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