]> code.delx.au - bg-scripts/blob - wallchanger.py
rename runProgram
[bg-scripts] / wallchanger.py
1 #!/usr/bin/env python
2 # Copyright 2008 Greg Darke <greg@tsukasa.net.au>
3 # Copyright 2008 James Bunton <jamesbunton@fastmail.fm>
4 # Licensed for distribution under the GPL version 2, check COPYING for details
5 # This is a cross platform/cross window manager way to change your wallpaper
6
7 import commands, sys, os, os.path, time
8 import logging
9 try:
10 import PIL, PIL.Image
11 except ImportError:
12 PIL = None
13
14 __all__ = ("init", "set_image")
15
16
17 changers = []
18
19 def set_image(filename):
20 logging.info("Setting image: %s", filename)
21 for changer in changers:
22 if not changer.set_image(filename):
23 logging.warning("Failed to set background: wallchanger.set_image(%s), changer=%s", filename, changer)
24
25 def init(*args, **kwargs):
26 """Desktop Changer factory"""
27
28 if sys.platform == "win32":
29 changers.append(WIN32Changer(*args, **kwargs))
30 return
31
32 logging.debug("Testing for OSX (NonX11)")
33 if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
34 changers.append(OSXChanger(*args, **kwargs))
35
36 if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
37 # X11 is not running
38 return
39 else:
40 if os.uname()[0] == 'Darwin':
41 # Try to detect if the X11 server is running on OSX
42 if commands.getstatusoutput("ps ax -o command|grep -q '^/.*X11 .* %s'" % os.environ['DISPLAY'])[0] != 0:
43 # X11 is not running for this display
44 return
45
46 logging.debug("Testing for KDE")
47 if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
48 changers.append(KDEChanger(*args, **kwargs))
49
50 logging.debug("Testing for Unity")
51 if commands.getstatusoutput("xlsclients | grep -qi unity")[0] == 0:
52 changers.append(UnityChanger(*args, **kwargs))
53
54 logging.debug("Testing for Gnome")
55 if commands.getstatusoutput("xwininfo -name 'gnome-settings-daemon'")[0] == 0:
56 changers.append(GnomeChanger(*args, **kwargs))
57
58 logging.debug("Testing for WMaker")
59 if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
60 changers.append(WMakerChanger(*args, **kwargs))
61
62 if len(changers) == 0:
63 raise Exception("Unknown window manager")
64
65
66 class BaseChanger(object):
67 name = "undefined"
68 def __init__(self, background_color='black', permanent=False, convert=False):
69 logging.info('Determined the window manager is "%s"', self.name)
70 self.background_color = background_color
71 self.permanent = permanent
72 self.convert = convert
73
74 try:
75 def _exec_cmd(self, cmd):
76 import subprocess
77 return subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
78
79 except ImportError:
80 # A simple implementation of subprocess for python2.4
81 def _exec_cmd(self, cmd):
82 """Runs a program given in cmd"""
83 return os.spawnvp(os.P_WAIT, cmd[0], cmd)
84
85 def set_image(self, filename):
86 raise NotImplementedError()
87
88 def convert_image_format(self, filename, format='BMP', allowAlpha=False, extension='.bmp'):
89 """Convert the image to another format, and store it in a local place"""
90 if not os.path.exists(filename):
91 logger.warn('The input file "%s" does not exist, so it will not be converted', filename)
92 return filename, False
93 if PIL is None:
94 logger.warn('PIL could not be found, not converting image format')
95 return filename, False
96
97 self.remove_old_image_cache()
98 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s%s' % (time.time(), extension))
99 img = PIL.Image.open(filename)
100
101 # Remove the alpha channel if the user doens't want it
102 if not allowAlpha and img.mode == 'RGBA':
103 img = img.convert('RGB')
104 img.save(output_name, format)
105
106 return output_name, True
107
108
109 class WMakerChanger(BaseChanger):
110 name = "WindowMaker"
111 _ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
112 def remove_old_image_cache(self):
113 """Cleans up any old temp images"""
114 if not os.path.isdir(self._ConvertedWallpaperLocation):
115 os.mkdir(self._ConvertedWallpaperLocation)
116 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
117 for filename in filenames:
118 os.unlink(os.path.join(fullpath, filename))
119 for dirname in dirnames:
120 os.unlink(os.path.join(fullpath, dirname))
121
122 def convert_image_format(self, file):
123 """Convert the image to a png, and store it in a local place"""
124 self.remove_old_image_cache()
125 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
126 cmd = ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name]
127 logging.debug("""Convert command: '"%s"'""", '" "'.join(cmd))
128 return output_name, self._exec_cmd(cmd)
129
130 def set_image(self, file):
131 if self.convert:
132 file, convert_status = self.convert_image_format(file)
133 if convert_status:
134 logging.debug('Convert failed')
135 cmd = ["wmsetbg",
136 "-b", self.background_color, # Sets the background colour to be what the user specified
137 "-S", # 'Smooth' (WTF?)
138 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
139 ### "-a", # scale the image, keeping the aspect ratio
140 "-u", # Force this to be the default background
141 "-d" # dither
142 ]
143 if self.permanent:
144 cmd += ["-u"] # update the wmaker database
145 cmd += [file]
146 logging.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd))
147 return not self._exec_cmd(cmd)
148
149 class OSXChanger(BaseChanger):
150 name = "Mac OS X"
151 _ConvertedWallpaperLocation = '/tmp/wallpapers/'
152 _DesktopPlistLocation = os.path.expanduser('~/Library/Preferences/com.apple.desktop.plist')
153
154 def __init__(self, *args, **kwargs):
155 BaseChanger.__init__(self, *args, **kwargs)
156
157 def remove_old_image_cache(self):
158 """Cleans up any old temp images"""
159 if not os.path.isdir(self._ConvertedWallpaperLocation):
160 os.mkdir(self._ConvertedWallpaperLocation)
161 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
162 for filename in filenames:
163 os.unlink(os.path.join(fullpath, filename))
164 for dirname in dirnames:
165 os.unlink(os.path.join(fullpath, dirname))
166
167 def convert_image_format(self, file):
168 """Convert the image to a png, and store it in a local place"""
169 self.remove_old_image_cache()
170 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
171 try:
172 return super(OSXChanger, self).convert_image_format(file, format='PNG', extension='.png')
173 except ImportError:
174 logging.debug('Could not load PIL, going to try just copying the image')
175 import shutil
176 output_name = os.path.join(self._ConvertedWallpaperLocation, os.path.basename(file))
177 shutil.copyfile(file, output_name)
178 return output_name, True
179
180 def fix_desktop_plist(self):
181 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
182 try:
183 import Foundation
184 desktop_plist = Foundation.NSMutableDictionary.dictionaryWithContentsOfFile_(self._DesktopPlistLocation)
185 # Remove all but the 'default' entry
186 for k in desktop_plist['Background'].keys():
187 if k == 'default':
188 continue
189 desktop_plist['Background'].removeObjectForKey_(k)
190 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
191 desktop_plist.writeToFile_atomically_(self._DesktopPlistLocation, True)
192 except ImportError:
193 logging.debug('Could not import the Foundation module, you may have problems with dual screens')
194
195 def set_image(self, filename):
196 self.fix_desktop_plist()
197 if self.convert:
198 filename, ret = self.convert_image_format(filename)
199 if not ret:
200 logging.debug("Convert failed")
201 return False
202 cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
203 logging.debug(cmd)
204 return not commands.getstatusoutput(cmd)[0]
205
206 class WIN32Changer(BaseChanger):
207 name = "Windows"
208 _ConvertedWallpaperLocation = os.path.join(os.environ.get('APPDATA', os.path.expanduser('~')), 'wallchanger')
209
210 def __init__(self, *args, **kwargs):
211 BaseChanger.__init__(self, *args, **kwargs)
212 if not self.convert:
213 logging.warn('Running on windows, but convert is not set')
214
215 def remove_old_image_cache(self):
216 """Cleans up any old temp images"""
217 if not os.path.isdir(self._ConvertedWallpaperLocation):
218 os.mkdir(self._ConvertedWallpaperLocation)
219 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
220 for filename in filenames:
221 os.unlink(os.path.join(fullpath, filename))
222 for dirname in dirnames:
223 os.unlink(os.path.join(fullpath, dirname))
224
225 def set_image(self, filename):
226 import ctypes
227 user32 = ctypes.windll.user32
228
229 # Taken from the Platform SDK
230 SPI_SETDESKWALLPAPER = 20
231 SPIF_SENDWININICHANGE = 2
232
233 if self.convert:
234 filename, ret = self.convert_image_format(filename)
235 if not ret:
236 logging.debug("Convert failed")
237 return False
238
239 # Parameters for SystemParametersInfoA are:
240 # (UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni)
241 user32.SystemParametersInfoA(
242 SPI_SETDESKWALLPAPER,
243 0,
244 filename,
245 SPIF_SENDWININICHANGE,
246 )
247 return True
248
249 class GnomeChanger(BaseChanger):
250 name = "Gnome"
251 def set_image(self, file):
252 cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
253 logging.debug(cmd)
254 return not self._exec_cmd(cmd)
255
256 class UnityChanger(BaseChanger):
257 name = "Unity"
258 def set_image(self, file):
259 cmd = ['gsettings', 'set', 'org.gnome.desktop.background', 'picture-uri', 'file://'+file]
260 logging.debug(cmd)
261 return not self._exec_cmd(cmd)
262
263 class KDEChanger(BaseChanger):
264 name = "KDE"
265 def set_image(self, file):
266 cmds = []
267 for group in ('Desktop0', 'Desktop0Screen0'):
268 base = ['kwriteconfig', '--file', 'kdesktoprc', '--group', group, '--key']
269 cmds.append(base + ['Wallpaper', file])
270 cmds.append(base + ['UseSHM', '--type', 'bool', 'true'])
271 cmds.append(base + ['WallpaperMode', 'ScaleAndCrop'])
272 cmds.append(base + ['MultiWallpaperMode', 'NoMulti'])
273
274 cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
275 for cmd in cmds:
276 logging.debug(cmd)
277 if self._exec_cmd(cmd) != 0:
278 return False
279
280 return True
281
282
283 def main(filename):
284 logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
285 init()
286 set_image(filename)
287
288 if __name__ == "__main__":
289 try:
290 filename = sys.argv[1]
291 except:
292 print >>sys.stderr, "Usage: %s filename" % sys.argv[0]
293 sys.exit(1)
294
295 main(filename)
296
297