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):
57 info('Determined the window manager is "%s"' % self
.name
)
58 self
.background_color
= background_color
59 self
.permanent
= permanent
61 def set_image(self
, filename
):
62 raise NotImplementedError()
64 class WMakerChanger(BaseChanger
):
66 _ConvertedWallpaperLocation
= '/tmp/wallpapers_wmaker/'
67 def remove_old_image_cache(self
):
68 """Cleans up any old temp images"""
69 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
70 os
.mkdir(self
._ConvertedWallpaperLocation
)
71 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
72 for filename
in filenames
:
73 os
.unlink(os
.path
.join(fullpath
, filename
))
74 for dirname
in dirnames
:
75 os
.unlink(os
.path
.join(fullpath
, dirname
))
77 def convert_image_format(self
, file):
78 """Convert the image to a png, and store it in a local place"""
79 self
.remove_old_image_cache()
80 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
81 cmd
= ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name
]
82 debug("""Convert command: '"%s"'""" % '" "'.join(cmd
))
83 return output_name
, subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
85 def set_image(self
, file):
86 file, convert_status
= self
.convert_image_format(file)
88 debug('Convert failed')
90 "-b", self
.background_color
, # Sets the background colour to be what the user specified
91 "-S", # 'Smooth' (WTF?)
92 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
93 ### "-a", # scale the image, keeping the aspect ratio
94 "-u", # Force this to be the default background
98 cmd
+= ["-u"] # update the wmaker database
100 debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd
))
101 return not subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
103 class OSXChanger(BaseChanger
):
105 _ConvertedWallpaperLocation
= '/tmp/wallpapers/'
106 _DesktopPlistLocation
= os
.path
.expanduser('~/Library/Preferences/com.apple.desktop.plist')
108 def remove_old_image_cache(self
):
109 """Cleans up any old temp images"""
110 if not os
.path
.isdir(self
._ConvertedWallpaperLocation
):
111 os
.mkdir(self
._ConvertedWallpaperLocation
)
112 for fullpath
, filenames
, dirnames
in os
.walk(self
._ConvertedWallpaperLocation
, topdown
=False):
113 for filename
in filenames
:
114 os
.unlink(os
.path
.join(fullpath
, filename
))
115 for dirname
in dirnames
:
116 os
.unlink(os
.path
.join(fullpath
, dirname
))
118 def convert_image_format(self
, file):
119 """Convert the image to a png, and store it in a local place"""
120 self
.remove_old_image_cache()
121 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, '%s.png' % time
.time())
123 import PIL
, PIL
.Image
124 img
= PIL
.Image
.open(file)
125 img
.save(output_name
, "PNG")
126 return output_name
, True
128 debug('Could not load PIL, going to try just copying the image')
130 output_name
= os
.path
.join(self
._ConvertedWallpaperLocation
, os
.path
.basename(file))
131 shutil
.copyfile(file, output_name
)
132 return output_name
, True
134 def fix_desktop_plist(self
):
135 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
138 desktop_plist
= Foundation
.NSMutableDictionary
.dictionaryWithContentsOfFile_(self
._DesktopPlistLocation
)
139 # Remove all but the 'default' entry
140 for k
in desktop_plist
['Background'].keys():
143 desktop_plist
['Background'].removeObjectForKey_(k
)
144 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
145 desktop_plist
.writeToFile_atomically_(self
._DesktopPlistLocation
, True)
147 debug('Could not import the Foundation module, you may have problems with dual screens')
149 def set_image(self
, file):
150 output_name
, ret
= self
.convert_image_format(file)
152 debug("Convert failed")
154 self
.fix_desktop_plist()
155 cmd
= """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % output_name
157 return not commands
.getstatusoutput(cmd
)[0]
159 class GnomeChanger(BaseChanger
):
161 def set_image(self
, file):
162 cmd
= ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
164 return not subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait()
166 class KDEChanger(BaseChanger
):
168 def set_image(self
, file):
170 for group
in ('Desktop0', 'Desktop0Screen0'):
171 base
= ['kwriteconfig', '--file', 'kdesktoprc', '--group', group
, '--key']
172 cmds
.append(base
+ ['Wallpaper', file])
173 cmds
.append(base
+ ['UseSHM', '--type', 'bool', 'true'])
174 cmds
.append(base
+ ['WallpaperMode', 'ScaleAndCrop'])
175 cmds
.append(base
+ ['MultiWallpaperMode', 'NoMulti'])
177 cmds
.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
180 if subprocess
.Popen(cmd
, stdout
=sys
.stdout
, stderr
=sys
.stderr
, stdin
=None).wait() != 0:
188 logging
.basicConfig(level
=logging
.DEBUG
, format
="%(levelname)s: %(message)s")
192 if __name__
== "__main__":
194 filename
= sys
.argv
[1]
196 print >>sys
.stderr
, "Usage: %s filename" % sys
.argv
[0]