]> code.delx.au - bg-scripts/blob - lib/WallChanger.py
Fixed Gnome
[bg-scripts] / lib / WallChanger.py
1 #! python
2
3 import commands, sys, os, os.path, subprocess, time
4 from GregDebug import debug, setDebugLevel, DEBUG_LEVEL_DEBUG, DEBUG_LEVEL_LOW, DEBUG_LEVEL_MEDIUM, DEBUG_LEVEL_HIGH, DEBUG_INCREMENT
5
6 import python24_adapter # NB: Must be imported before collections
7 import collections
8
9 """This is a cross platform/cross window manager way to change your current
10 desktop image."""
11
12 __all__ = ('RandomBG')
13
14 def RandomBG(*args, **kwargs):
15 """Desktop Changer factory"""
16
17 ret = None
18
19 debug("Testing for OSX (NonX11)", DEBUG_LEVEL_LOW)
20 if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
21 ret = __OSXChanger(*args, **kwargs)
22
23 if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
24 # X11 is not running
25 return ret
26 else:
27 if os.uname()[0] == 'Darwin':
28 # Try to detect if the X11 server is running on OSX
29 if commands.getstatusoutput("ps ax -o command|grep -q '/.*X11 .* %s'" % os.environ['DISPLAY'])[0] != 0:
30 # X11 is not running for this display
31 return ret
32
33 debug("Testing for KDE", DEBUG_LEVEL_LOW)
34 if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
35 if ret is not None:
36 ret.nextChanger = __KDEChanger(*args, **kwargs)
37 else:
38 ret = __KDEChanger(*args, **kwargs)
39
40 debug("Testing for Gnome", DEBUG_LEVEL_LOW)
41 if commands.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
42 if ret is not None:
43 ret.nextChanger = __GnomeChanger(*args, **kwargs)
44 else:
45 ret = __GnomeChanger(*args, **kwargs)
46
47 debug("Testing for WMaker", DEBUG_LEVEL_LOW)
48 if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
49 if ret is not None:
50 ret.nextChanger = __WMakerChanger(*args, **kwargs)
51 else:
52 ret = __WMakerChanger(*args, **kwargs)
53
54 if ret is None:
55 raise Exception("Unknown window manager")
56 else:
57 return ret
58
59 class __BaseChanger(object):
60 def __init__(self, filelist, backgroundColour='black', permanent=False):
61 debug('Determined the window manager is "%s"' % self.__class__.__name__, DEBUG_LEVEL_MEDIUM)
62 self.backgroundColour = backgroundColour
63 self.permanent = permanent
64 self.filelist = filelist
65 # Used to 'chain' background changers
66 self.nextChanger = None
67
68 def callChained(self, filename):
69 if self.nextChanger is None:
70 return True
71 else:
72 return self.nextChanger.changeTo(filename)
73
74 def cycleNext(self):
75 file = self.filelist.getNextRandomImage()
76 return self.changeTo(file) and self.callChained(file)
77
78 def cyclePrev(self):
79 file = self.filelist.getPrevRandomImage()
80 return self.changeTo(file) and self.callChained(file)
81
82 def cycleReload(self):
83 file = self.filelist.getCurrentImage()
84 return self.changeTo(file) and self.callChained(file)
85
86
87 class __WMakerChanger(__BaseChanger):
88 _ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
89 def _removeOldImageCache(self):
90 """Cleans up any old temp images"""
91 if not os.path.isdir(self._ConvertedWallpaperLocation):
92 os.mkdir(self._ConvertedWallpaperLocation)
93 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
94 for filename in filenames:
95 os.unlink(os.path.join(fullpath, filename))
96 for dirname in dirnames:
97 os.unlink(os.path.join(fullpath, dirname))
98
99 def _convertImageFormat(self, file):
100 """Convert the image to a png, and store it in a local place"""
101 self._removeOldImageCache()
102 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
103 cmd = ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name]
104 debug("""Convert command: '"%s"'""" % '" "'.join(cmd), DEBUG_LEVEL_DEBUG)
105 return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
106 def changeTo(self, file):
107 file, convert_status = self._convertImageFormat(file)
108 if convert_status:
109 debug('Convert failed')
110 cmd = ["wmsetbg",
111 "-b", self.backgroundColour, # Sets the background colour to be what the user specified
112 "-S", # 'Smooth' (WTF?)
113 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
114 ### "-a", # scale the image, keeping the aspect ratio
115 "-u", # Force this to be the default background
116 "-d" # dither
117 ]
118 if self.permanent:
119 cmd += ["-u"] # update the wmaker database
120 cmd += [file]
121 debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd), DEBUG_LEVEL_DEBUG)
122 return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
123
124 class __OSXChanger(__BaseChanger):
125 _ConvertedWallpaperLocation = '/tmp/wallpapers/'
126 def _removeOldImageCache(self):
127 """Cleans up any old temp images"""
128 if not os.path.isdir(self._ConvertedWallpaperLocation):
129 os.mkdir(self._ConvertedWallpaperLocation)
130 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
131 for filename in filenames:
132 os.unlink(os.path.join(fullpath, filename))
133 for dirname in dirnames:
134 os.unlink(os.path.join(fullpath, dirname))
135
136 def _convertImageFormat(self, file):
137 """Convert the image to a png, and store it in a local place"""
138 self._removeOldImageCache()
139 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
140 cmd = ["convert", file, output_name]
141 debug("""Convert command: '"%s"'""" % '" "'.join(cmd), DEBUG_LEVEL_DEBUG)
142 return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
143
144 def changeTo(self, file):
145 output_name, ret = self._convertImageFormat(file)
146 if ret: # Since 0 indicates success
147 debug("Convert failed %s" % ret)
148 return False
149 cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % output_name
150 debug(cmd, DEBUG_LEVEL_DEBUG)
151 return not commands.getstatusoutput(cmd)[0]
152
153 class __GnomeChanger(__BaseChanger):
154 def changeTo(self, file):
155 cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
156 debug(cmd, DEBUG_LEVEL_DEBUG)
157 return subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
158
159 class __KDEChanger(__BaseChanger):
160 def changeTo(self, file):
161 cmds = []
162 for group in ('Desktop0', 'Desktop0Screen0'):
163 base = ['kwriteconfig', '--file', 'kdesktoprc', '--group', group, '--key']
164 cmds.append(base + ['Wallpaper', file])
165 cmds.append(base + ['UseSHM', '--type', 'bool', 'true'])
166 cmds.append(base + ['WallpaperMode', 'ScaleAndCrop'])
167 cmds.append(base + ['MultiWallpaperMode', 'NoMulti'])
168
169 cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
170 for cmd in cmds:
171 debug(cmd, DEBUG_LEVEL_DEBUG)
172 if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0:
173 return 1 # Fail
174
175 return 0 # Success
176