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