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