]> 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, subprocess, 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 def set_image(self, filename):
63 raise NotImplementedError()
64
65 class WMakerChanger(BaseChanger):
66 name = "WindowMaker"
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))
77
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 logging.debug("""Convert command: '"%s"'""", '" "'.join(cmd))
84 return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
85
86 def set_image(self, file):
87 if self.convert:
88 file, convert_status = self.convert_image_format(file)
89 if convert_status:
90 logging.debug('Convert failed')
91 cmd = ["wmsetbg",
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
97 "-d" # dither
98 ]
99 if self.permanent:
100 cmd += ["-u"] # update the wmaker database
101 cmd += [file]
102 logging.debug('''WMaker bgset command: "'%s'"''', "' '".join(cmd))
103 return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
104
105 class OSXChanger(BaseChanger):
106 name = "Mac OS X"
107 _ConvertedWallpaperLocation = '/tmp/wallpapers/'
108 _DesktopPlistLocation = os.path.expanduser('~/Library/Preferences/com.apple.desktop.plist')
109
110 def __init__(self, *args, **kwargs):
111 BaseChanger.__init__(self, *args, **kwargs)
112
113 def remove_old_image_cache(self):
114 """Cleans up any old temp images"""
115 if not os.path.isdir(self._ConvertedWallpaperLocation):
116 os.mkdir(self._ConvertedWallpaperLocation)
117 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
118 for filename in filenames:
119 os.unlink(os.path.join(fullpath, filename))
120 for dirname in dirnames:
121 os.unlink(os.path.join(fullpath, dirname))
122
123 def convert_image_format(self, file):
124 """Convert the image to a png, and store it in a local place"""
125 self.remove_old_image_cache()
126 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
127 try:
128 import PIL, PIL.Image
129 img = PIL.Image.open(file)
130 img.save(output_name, "PNG")
131 return output_name, True
132 except ImportError:
133 logging.debug('Could not load PIL, going to try just copying the image')
134 import shutil
135 output_name = os.path.join(self._ConvertedWallpaperLocation, os.path.basename(file))
136 shutil.copyfile(file, output_name)
137 return output_name, True
138
139 def fix_desktop_plist(self):
140 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
141 try:
142 import Foundation
143 desktop_plist = Foundation.NSMutableDictionary.dictionaryWithContentsOfFile_(self._DesktopPlistLocation)
144 # Remove all but the 'default' entry
145 for k in desktop_plist['Background'].keys():
146 if k == 'default':
147 continue
148 desktop_plist['Background'].removeObjectForKey_(k)
149 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
150 desktop_plist.writeToFile_atomically_(self._DesktopPlistLocation, True)
151 except ImportError:
152 logging.debug('Could not import the Foundation module, you may have problems with dual screens')
153
154 def set_image(self, filename):
155 self.fix_desktop_plist()
156 if self.convert:
157 filename, ret = self.convert_image_format(filename)
158 if not ret:
159 logging.debug("Convert failed")
160 return False
161 cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % filename
162 logging.debug(cmd)
163 return not commands.getstatusoutput(cmd)[0]
164
165 class GnomeChanger(BaseChanger):
166 name = "Gnome"
167 def set_image(self, file):
168 cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
169 logging.debug(cmd)
170 return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
171
172 class KDEChanger(BaseChanger):
173 name = "KDE"
174 def set_image(self, file):
175 cmds = []
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'])
182
183 cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
184 for cmd in cmds:
185 logging.debug(cmd)
186 if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0:
187 return False
188
189 return True
190
191
192 def main(filename):
193 logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
194 init()
195 set_image(filename)
196
197 if __name__ == "__main__":
198 try:
199 filename = sys.argv[1]
200 except:
201 print >>sys.stderr, "Usage: %s filename" % sys.argv[0]
202 sys.exit(1)
203
204 main(filename)
205
206