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
, subprocess
, time
8 from logging
import debug
, info
, warning
10 __all__
= ("init", "set_image")
15 def set_image(filename
):
16 info("Setting image: %s" % filename
)
17 for changer
in changers
:
18 if not changer
.set_image(filename
):
19 warning("Failed to set background: wallchanger.set_image(%s), changer=%s" % (filename
, changer
))
21 def init(*args
, **kwargs
):
22 """Desktop Changer factory"""
24 debug("Testing for OSX (NonX11)")
25 if commands
.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
26 changers
.append(OSXChanger(*args
, **kwargs
))
28 if 'DISPLAY' not in os
.environ
or os
.environ
['DISPLAY'].startswith('/tmp/launch'):
32 if os
.uname()[0] == 'Darwin':
33 # Try to detect if the X11 server is running on OSX
34 if commands
.getstatusoutput("ps ax -o command|grep -q '/.*X11 .* %s'" % os
.environ
['DISPLAY'])[0] != 0:
35 # X11 is not running for this display
38 debug("Testing for KDE")
39 if commands
.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
40 changers
.append(KDEChanger(*args
, **kwargs
))
42 debug("Testing for Gnome")
43 if commands
.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
44 changers
.append(GnomeChanger(*args
, **kwargs
))
46 debug("Testing for WMaker")
47 if commands
.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
48 changers
.append(WMakerChanger(*args
, **kwargs
))
50 if len(changers
) == 0:
51 raise Exception("Unknown window manager")
54 class BaseChanger(object):
56 def __init__(self
, background_color
='black', permanent
=False, convert
=False):
57 info('Determined the window manager is "%s"' % self
.name
)
58 self
.background_color
= background_color
59 self
.permanent
= permanent
60 self
.convert
= convert
62 def set_image(self
, filename
):
63 raise NotImplementedError()
65 class WMakerChanger(BaseChanger
):
67 _ConvertedWallpaperLocation
= '/tmp/wallpapers_wmaker/'
68 def remove_old_image_cache(self
):
69 """Cleans up any old temp images"""
70 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
71 os
.mkdir(self
._ConvertedWallpaperLocation
)
72 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
73 for filename
in filenames
:
74 os
.unlink(os
.path
.join(fullpath
, filename
))
75 for dirname
in dirnames
:
76 os
.unlink(os
.path
.join(fullpath
, dirname
))
78 def convert_image_format(self
, file):
79 """Convert the image to a png, and store it in a local place"""
80 self
.remove_old_image_cache()
81 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
82 cmd
= ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name
]
83 debug("""Convert command: '"%s"'""" % '" "'.join(cmd
))
84 return output_name
, subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
86 def set_image(self
, file):
88 file, convert_status
= self
.convert_image_format(file)
90 debug('Convert failed')
92 "-b", self
.background_color
, # Sets the background colour to be what the user specified
93 "-S", # 'Smooth' (WTF?)
94 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
95 ### "-a", # scale the image, keeping the aspect ratio
96 "-u", # Force this to be the default background
100 cmd
+= ["-u"] # update the wmaker database
102 debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd
))
103 return not subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
105 class OSXChanger(BaseChanger
):
107 _ConvertedWallpaperLocation
= '/tmp/wallpapers/'
108 _DesktopPlistLocation
= os
.path
.expanduser('~/Library/Preferences/com.apple.desktop.plist')
110 def __init__(self
, *args
, **kwargs
):
111 BaseChanger
.__init
__(self
, *args
, **kwargs
)
112 self
.fix_desktop_plist()
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
))
124 def convert_image_format(self
, file):
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())
129 import PIL
, PIL
.Image
130 img
= PIL
.Image
.open(file)
131 img
.save(output_name
, "PNG")
132 return output_name
, True
134 debug('Could not load PIL, going to try just copying the image')
136 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, os
.path
.basename(file))
137 shutil
.copyfile(file, output_name
)
138 return output_name
, True
140 def fix_desktop_plist(self
):
141 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
144 desktop_plist
= Foundation
.NSMutableDictionary
.dictionaryWithContentsOfFile_(self
._DesktopPlistLocation
)
145 # Remove all but the 'default' entry
146 for k
in desktop_plist
['Background'].keys():
149 desktop_plist
['Background'].removeObjectForKey_(k
)
150 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
151 desktop_plist
.writeToFile_atomically_(self
._DesktopPlistLocation
, True)
153 debug('Could not import the Foundation module, you may have problems with dual screens')
155 def set_image(self
, filename
):
157 filename
, ret
= self
.convert_image_format(filename
)
159 debug("Convert failed")
161 cmd
= """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
163 return not commands
.getstatusoutput(cmd
)[0]
165 class GnomeChanger(BaseChanger
):
167 def set_image(self
, file):
168 cmd
= ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
170 return not subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
172 class KDEChanger(BaseChanger
):
174 def set_image(self
, file):
176 for group
in ('Desktop0', 'Desktop0Screen0'):
177 base
= ['kwriteconfig', '--file', 'kdesktoprc', '--group', group
, '--key']
178 cmds
.append(base
+ ['Wallpaper', file])
179 cmds
.append(base
+ ['UseSHM', '--type', 'bool', 'true'])
180 cmds
.append(base
+ ['WallpaperMode', 'ScaleAndCrop'])
181 cmds
.append(base
+ ['MultiWallpaperMode', 'NoMulti'])
183 cmds
.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
186 if subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait() != 0:
194 logging
.basicConfig(level
=logging
.DEBUG
, format
="%(levelname)s: %(message)s")
198 if __name__
== "__main__":
200 filename
= sys
.argv
[1]
202 print >>sys
.stderr
, "Usage: %s filename" % sys
.argv
[0]