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