]> code.delx.au - bg-scripts/blob - wallchanger.py
Automated merge with ssh://hg@kagami.tsukasa.net.au/bg_scripts/
[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
10 __all__ = ("init", "set_image")
11
12
13 changers = []
14
15 def set_image(filename):
16 logging.info("Setting image: %s", filename)
17 for changer in changers:
18 if not changer.set_image(filename):
19 logging.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 logging.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 logging.debug("Testing for KDE")
39 if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
40 changers.append(KDEChanger(*args, **kwargs))
41
42 logging.debug("Testing for Gnome")
43 if commands.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
44 changers.append(GnomeChanger(*args, **kwargs))
45
46 logging.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, convert=False):
57 logging.info('Determined the window manager is "%s"', self.name)
58 self.background_color = background_color
59 self.permanent = permanent
60 self.convert = convert
61
62 try:
63 import subprocess
64 except ImportError:
65 self._runProgram = self._runProgram_command
66 else:
67 self._runProgram = self._runProgram_subprocess
68
69 def _runProgram_subprocess(self, cmd):
70 import subprocess
71 return subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
72
73 # A simple implementation of subprocess for python2.4
74 def _runProgram_command(self, cmd):
75 """Runs a program given in cmd"""
76 return os.spawnvp(os.P_WAIT, cmd[0], cmd)
77
78 def set_image(self, filename):
79 raise NotImplementedError()
80
81 class WMakerChanger(BaseChanger):
82 name = "WindowMaker"
83 _ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
84 def remove_old_image_cache(self):
85 """Cleans up any old temp images"""
86 if not os.path.isdir(self._ConvertedWallpaperLocation):
87 os.mkdir(self._ConvertedWallpaperLocation)
88 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
89 for filename in filenames:
90 os.unlink(os.path.join(fullpath, filename))
91 for dirname in dirnames:
92 os.unlink(os.path.join(fullpath, dirname))
93
94 def convert_image_format(self, file):
95 """Convert the image to a png, and store it in a local place"""
96 self.remove_old_image_cache()
97 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
98 cmd = ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name]
99 logging.debug("""Convert command: '"%s"'""", '" "'.join(cmd))
100 return output_name, self._runProgram(cmd)
101
102 def set_image(self, file):
103 if self.convert:
104 file, convert_status = self.convert_image_format(file)
105 if convert_status:
106 logging.debug('Convert failed')
107 cmd = ["wmsetbg",
108 "-b", self.background_color, # Sets the background colour to be what the user specified
109 "-S", # 'Smooth' (WTF?)
110 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
111 ### "-a", # scale the image, keeping the aspect ratio
112 "-u", # Force this to be the default background
113 "-d" # dither
114 ]
115 if self.permanent:
116 cmd += ["-u"] # update the wmaker database
117 cmd += [file]
118 logging.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd))
119 return not self._runProgram(cmd)
120
121 class OSXChanger(BaseChanger):
122 name = "Mac OS X"
123 _ConvertedWallpaperLocation = '/tmp/wallpapers/'
124 _DesktopPlistLocation = os.path.expanduser('~/Library/Preferences/com.apple.desktop.plist')
125
126 def __init__(self, *args, **kwargs):
127 BaseChanger.__init__(self, *args, **kwargs)
128
129 def remove_old_image_cache(self):
130 """Cleans up any old temp images"""
131 if not os.path.isdir(self._ConvertedWallpaperLocation):
132 os.mkdir(self._ConvertedWallpaperLocation)
133 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
134 for filename in filenames:
135 os.unlink(os.path.join(fullpath, filename))
136 for dirname in dirnames:
137 os.unlink(os.path.join(fullpath, dirname))
138
139 def convert_image_format(self, file):
140 """Convert the image to a png, and store it in a local place"""
141 self.remove_old_image_cache()
142 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
143 try:
144 import PIL, PIL.Image
145 img = PIL.Image.open(file)
146 img.save(output_name, "PNG")
147 return output_name, True
148 except ImportError:
149 logging.debug('Could not load PIL, going to try just copying the image')
150 import shutil
151 output_name = os.path.join(self._ConvertedWallpaperLocation, os.path.basename(file))
152 shutil.copyfile(file, output_name)
153 return output_name, True
154
155 def fix_desktop_plist(self):
156 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
157 try:
158 import Foundation
159 desktop_plist = Foundation.NSMutableDictionary.dictionaryWithContentsOfFile_(self._DesktopPlistLocation)
160 # Remove all but the 'default' entry
161 for k in desktop_plist['Background'].keys():
162 if k == 'default':
163 continue
164 desktop_plist['Background'].removeObjectForKey_(k)
165 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
166 desktop_plist.writeToFile_atomically_(self._DesktopPlistLocation, True)
167 except ImportError:
168 logging.debug('Could not import the Foundation module, you may have problems with dual screens')
169
170 def set_image(self, filename):
171 self.fix_desktop_plist()
172 if self.convert:
173 filename, ret = self.convert_image_format(filename)
174 if not ret:
175 logging.debug("Convert failed")
176 return False
177 cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
178 logging.debug(cmd)
179 return not commands.getstatusoutput(cmd)[0]
180
181 class GnomeChanger(BaseChanger):
182 name = "Gnome"
183 def set_image(self, file):
184 cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
185 logging.debug(cmd)
186 return not self._runProgram(cmd)
187
188 class KDEChanger(BaseChanger):
189 name = "KDE"
190 def set_image(self, file):
191 cmds = []
192 for group in ('Desktop0', 'Desktop0Screen0'):
193 base = ['kwriteconfig', '--file', 'kdesktoprc', '--group', group, '--key']
194 cmds.append(base + ['Wallpaper', file])
195 cmds.append(base + ['UseSHM', '--type', 'bool', 'true'])
196 cmds.append(base + ['WallpaperMode', 'ScaleAndCrop'])
197 cmds.append(base + ['MultiWallpaperMode', 'NoMulti'])
198
199 cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
200 for cmd in cmds:
201 logging.debug(cmd)
202 if self._runProgram(cmd) != 0:
203 return False
204
205 return True
206
207
208 def main(filename):
209 logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
210 init()
211 set_image(filename)
212
213 if __name__ == "__main__":
214 try:
215 filename = sys.argv[1]
216 except:
217 print >>sys.stderr, "Usage: %s filename" % sys.argv[0]
218 sys.exit(1)
219
220 main(filename)
221
222