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