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