]> code.delx.au - bg-scripts/blob - bin/wallchanger.py
1ac5dcff2955c198dfa105d5a6220c92f42f629b
[bg-scripts] / bin / 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, subprocess, time
8 from logging import debug, info, warning
9
10 __all__ = ("init", "set_image")
11
12
13 changers = []
14
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))
20
21 def init(*args, **kwargs):
22 """Desktop Changer factory"""
23
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))
27
28 if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
29 # X11 is not running
30 return
31 else:
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
36 return
37
38 debug("Testing for KDE")
39 if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
40 changers.append(KDEChanger(*args, **kwargs))
41
42 debug("Testing for Gnome")
43 if commands.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
44 changers.append(GnomeChanger(*args, **kwargs))
45
46 debug("Testing for WMaker")
47 if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
48 changers.append(WMakerChanger(*args, **kwargs))
49
50 if len(changers) == 0:
51 raise Exception("Unknown window manager")
52
53
54 class BaseChanger(object):
55 name = "undefined"
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
60
61 def set_image(self, filename):
62 raise NotImplementedError()
63
64 class WMakerChanger(BaseChanger):
65 name = "WindowMaker"
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))
76
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()
84
85 def set_image(self, file):
86 file, convert_status = self.convert_image_format(file)
87 if convert_status:
88 debug('Convert failed')
89 cmd = ["wmsetbg",
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
95 "-d" # dither
96 ]
97 if self.permanent:
98 cmd += ["-u"] # update the wmaker database
99 cmd += [file]
100 debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd))
101 return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
102
103 class OSXChanger(BaseChanger):
104 name = "Mac OS X"
105 _ConvertedWallpaperLocation = '/tmp/wallpapers/'
106 _DesktopPlistLocation = os.path.expanduser('~/Library/Preferences/com.apple.desktop.plist')
107
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))
117
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())
122 try:
123 import PIL, PIL.Image
124 img = PIL.Image.open(file)
125 img.save(output_name, "PNG")
126 return output_name, True
127 except ImportError:
128 debug('Could not load PIL, going to try just copying the image')
129 import shutil
130 output_name = os.path.join(self._ConvertedWallpaperLocation, os.path.basename(file))
131 shutil.copyfile(file, output_name)
132 return output_name, True
133
134 def fix_desktop_plist(self):
135 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
136 try:
137 import Foundation
138 desktop_plist = Foundation.NSMutableDictionary.dictionaryWithContentsOfFile_(self._DesktopPlistLocation)
139 # Remove all but the 'default' entry
140 for k in desktop_plist['Background'].keys():
141 if k == 'default':
142 continue
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)
146 except ImportError:
147 debug('Could not import the Foundation module, you may have problems with dual screens')
148
149 def set_image(self, file):
150 output_name, ret = self.convert_image_format(file)
151 if not ret:
152 debug("Convert failed")
153 return False
154 self.fix_desktop_plist()
155 cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % output_name
156 debug(cmd)
157 return not commands.getstatusoutput(cmd)[0]
158
159 class GnomeChanger(BaseChanger):
160 name = "Gnome"
161 def set_image(self, file):
162 cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
163 debug(cmd)
164 return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
165
166 class KDEChanger(BaseChanger):
167 name = "KDE"
168 def set_image(self, file):
169 cmds = []
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'])
176
177 cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
178 for cmd in cmds:
179 debug(cmd)
180 if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0:
181 return False
182
183 return True
184
185
186 def main(filename):
187 import logging
188 logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
189 init()
190 set_image(filename)
191
192 if __name__ == "__main__":
193 try:
194 filename = sys.argv[1]
195 except:
196 print >>sys.stderr, "Usage: %s filename" % sys.argv[0]
197 sys.exit(1)
198
199 main(filename)
200
201