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
7 import commands
, sys
, os
, os
.path
, time
14 __all__
= ("init", "set_image")
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
)
26 return commands
.getstatusoutput(cmd
)[0] == 0
28 def init(*args
, **kwargs
):
29 """Desktop Changer factory"""
33 if sys
.platform
== "win32":
34 classes
.append(WIN32Changer
)
37 logging
.debug("Testing for OSX (NonX11)")
38 if check_cmd("ps ax -o command -c|grep -q WindowServer"):
39 classes
.append(OSXChanger
)
41 if 'DISPLAY' not in os
.environ
or os
.environ
['DISPLAY'].startswith('/tmp/launch'):
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
51 logging
.debug("Testing for KDE")
52 if check_cmd("xwininfo -name 'KDE Desktop'"):
53 classes
.append(KDEChanger
)
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
)
60 classes
.append(Gnome2Changer
)
62 logging
.debug("Testing for WMaker")
63 if check_cmd("xlsclients | grep -qi wmaker"):
64 classes
.append(WMakerChanger
)
67 raise Exception("Unknown window manager")
70 changers
.append(klass(*args
, **kwargs
))
73 class BaseChanger(object):
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
82 def _exec_cmd(self
, cmd
):
84 return subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
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
)
92 def set_image(self
, filename
):
93 raise NotImplementedError()
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
101 logger
.warn('PIL could not be found, not converting image format')
102 return filename
, False
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
)
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
)
113 return output_name
, True
116 class WMakerChanger(BaseChanger
):
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
))
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
)
137 def set_image(self
, filename
):
139 filename
, convert_status
= self
.convert_image_format(filename
)
141 logging
.debug('Convert failed')
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
151 cmd
+= ["-u"] # update the wmaker database
153 logging
.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd
))
154 return not self
._exec
_cmd
(cmd
)
156 class OSXChanger(BaseChanger
):
158 _ConvertedWallpaperLocation
= '/tmp/wallpapers/'
159 _DesktopPlistLocation
= os
.path
.expanduser('~/Library/Preferences/com.apple.desktop.plist')
161 def __init__(self
, *args
, **kwargs
):
162 BaseChanger
.__init
__(self
, *args
, **kwargs
)
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
))
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())
179 return super(OSXChanger
, self
).convert_image_format(filename
, format
='PNG', extension
='.png')
181 logging
.debug('Could not load PIL, going to try just copying the image')
183 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, os
.path
.basename(filename
))
184 shutil
.copyfile(filename
, output_name
)
185 return output_name
, True
187 def fix_desktop_plist(self
):
188 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
191 desktop_plist
= Foundation
.NSMutableDictionary
.dictionaryWithContentsOfFile_(self
._DesktopPlistLocation
)
192 # Remove all but the 'default' entry
193 for k
in desktop_plist
['Background'].keys():
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)
200 logging
.debug('Could not import the Foundation module, you may have problems with dual screens')
202 def set_image(self
, filename
):
203 self
.fix_desktop_plist()
205 filename
, ret
= self
.convert_image_format(filename
)
207 logging
.debug("Convert failed")
209 cmd
= """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
211 return not commands
.getstatusoutput(cmd
)[0]
213 class WIN32Changer(BaseChanger
):
215 _ConvertedWallpaperLocation
= os
.path
.join(os
.environ
.get('APPDATA', os
.path
.expanduser('~')), 'wallchanger')
217 def __init__(self
, *args
, **kwargs
):
218 BaseChanger
.__init
__(self
, *args
, **kwargs
)
220 logging
.warn('Running on windows, but convert is not set')
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
))
232 def set_image(self
, filename
):
234 user32
= ctypes
.windll
.user32
236 # Taken from the Platform SDK
237 SPI_SETDESKWALLPAPER
= 20
238 SPIF_SENDWININICHANGE
= 2
241 filename
, ret
= self
.convert_image_format(filename
)
243 logging
.debug("Convert failed")
246 # Parameters for SystemParametersInfoA are:
247 # (UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni)
248 user32
.SystemParametersInfoA(
249 SPI_SETDESKWALLPAPER
,
252 SPIF_SENDWININICHANGE
,
256 class Gnome2Changer(BaseChanger
):
258 def set_image(self
, filename
):
259 cmd
= ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', filename
]
261 return not self
._exec
_cmd
(cmd
)
263 class Gnome3Changer(BaseChanger
):
265 def set_image(self
, filename
):
266 cmd
= ['gsettings', 'set', 'org.gnome.desktop.background', 'picture-uri', 'file://'+filename
]
268 return not self
._exec
_cmd
(cmd
)
270 class KDEChanger(BaseChanger
):
272 def set_image(self
, filename
):
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'])
281 cmds
.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
284 if self
._exec
_cmd
(cmd
) != 0:
291 logging
.basicConfig(level
=logging
.DEBUG
, format
="%(levelname)s: %(message)s")
295 if __name__
== "__main__":
297 filename
= sys
.argv
[1]
299 print >>sys
.stderr
, "Usage: %s filename" % sys
.argv
[0]