]> code.delx.au - bg-scripts/blob - bin/wallchanger.py
WallChanger improvements
[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 for changer in changers:
17 if not changer.set_image(filename):
18 warning("Failed to set background: wallchanger.set_image(%s), changer=%s" % (filename, changer))
19
20 def init(*args, **kwargs):
21 """Desktop Changer factory"""
22
23 debug("Testing for OSX (NonX11)")
24 if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
25 changers.append(OSXChanger(*args, **kwargs))
26
27 if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
28 # X11 is not running
29 return
30 else:
31 if os.uname()[0] == 'Darwin':
32 # Try to detect if the X11 server is running on OSX
33 if commands.getstatusoutput("ps ax -o command|grep -q '/.*X11 .* %s'" % os.environ['DISPLAY'])[0] != 0:
34 # X11 is not running for this display
35 return
36
37 debug("Testing for KDE")
38 if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
39 changers.append(KDEChanger(*args, **kwargs))
40
41 debug("Testing for Gnome")
42 if commands.getstatusoutput("xwininfo -name 'gnome-session'")[0] == 0:
43 changers.append(GnomeChanger(*args, **kwargs))
44
45 debug("Testing for WMaker")
46 if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
47 changers.append(WMakerChanger(*args, **kwargs))
48
49 if len(changers) == 0:
50 raise Exception("Unknown window manager")
51
52
53 class BaseChanger(object):
54 name = "undefined"
55 def __init__(self, background_color='black', permanent=False):
56 info('Determined the window manager is "%s"' % self.name)
57 self.background_color = background_color
58 self.permanent = permanent
59
60 def set_image(self, filename):
61 raise NotImplementedError()
62
63 class WMakerChanger(BaseChanger):
64 name = "WindowMaker"
65 _ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
66 def remove_old_image_cache(self):
67 """Cleans up any old temp images"""
68 if not os.path.isdir(self._ConvertedWallpaperLocation):
69 os.mkdir(self._ConvertedWallpaperLocation)
70 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
71 for filename in filenames:
72 os.unlink(os.path.join(fullpath, filename))
73 for dirname in dirnames:
74 os.unlink(os.path.join(fullpath, dirname))
75
76 def convert_image_format(self, file):
77 """Convert the image to a png, and store it in a local place"""
78 self.remove_old_image_cache()
79 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
80 cmd = ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name]
81 debug("""Convert command: '"%s"'""" % '" "'.join(cmd))
82 return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
83
84 def set_image(self, file):
85 file, convert_status = self.convert_image_format(file)
86 if convert_status:
87 debug('Convert failed')
88 cmd = ["wmsetbg",
89 "-b", self.background_color, # Sets the background colour to be what the user specified
90 "-S", # 'Smooth' (WTF?)
91 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
92 ### "-a", # scale the image, keeping the aspect ratio
93 "-u", # Force this to be the default background
94 "-d" # dither
95 ]
96 if self.permanent:
97 cmd += ["-u"] # update the wmaker database
98 cmd += [file]
99 debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd))
100 return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
101
102 class OSXChanger(BaseChanger):
103 name = "Mac OS X"
104 _ConvertedWallpaperLocation = '/tmp/wallpapers/'
105 _DesktopPlistLocation = os.path.expanduser('~/Library/Preferences/com.apple.desktop.plist')
106
107 def remove_old_image_cache(self):
108 """Cleans up any old temp images"""
109 if not os.path.isdir(self._ConvertedWallpaperLocation):
110 os.mkdir(self._ConvertedWallpaperLocation)
111 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
112 for filename in filenames:
113 os.unlink(os.path.join(fullpath, filename))
114 for dirname in dirnames:
115 os.unlink(os.path.join(fullpath, dirname))
116
117 def convert_image_format(self, file):
118 """Convert the image to a png, and store it in a local place"""
119 self.remove_old_image_cache()
120 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
121 try:
122 import PIL, PIL.Image
123 img = PIL.Image.open(file)
124 img.save(output_name, "PNG")
125 return output_name, True
126 except ImportError:
127 debug('Could not load PIL, going to try just copying the image')
128 import shutil
129 output_name = os.path.join(self._ConvertedWallpaperLocation, os.path.basename(file))
130 shutil.copyfile(file, output_name)
131 return output_name, True
132
133 def fix_desktop_plist(self):
134 """Removes the entry in the desktop plist file that specifies the wallpaper for each monitor"""
135 try:
136 import Foundation
137 desktop_plist = Foundation.NSMutableDictionary.dictionaryWithContentsOfFile_(self._DesktopPlistLocation)
138 # Remove all but the 'default' entry
139 for k in desktop_plist['Background'].keys():
140 if k == 'default':
141 continue
142 desktop_plist['Background'].removeObjectForKey_(k)
143 # Store the plist again (Make sure we write it out atomically -- Don't want to break finder)
144 desktop_plist.writeToFile_atomically_(self._DesktopPlistLocation, True)
145 except ImportError:
146 debug('Could not import the Foundation module, you may have problems with dual screens')
147
148 def set_image(self, file):
149 output_name, ret = self.convert_image_format(file)
150 if not ret:
151 debug("Convert failed")
152 return False
153 self.fix_desktop_plist()
154 cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % output_name
155 debug(cmd)
156 return not commands.getstatusoutput(cmd)[0]
157
158 class GnomeChanger(BaseChanger):
159 name = "Gnome"
160 def set_image(self, file):
161 cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
162 debug(cmd)
163 return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
164
165 class KDEChanger(BaseChanger):
166 name = "KDE"
167 def set_image(self, file):
168 cmds = []
169 for group in ('Desktop0', 'Desktop0Screen0'):
170 base = ['kwriteconfig', '--file', 'kdesktoprc', '--group', group, '--key']
171 cmds.append(base + ['Wallpaper', file])
172 cmds.append(base + ['UseSHM', '--type', 'bool', 'true'])
173 cmds.append(base + ['WallpaperMode', 'ScaleAndCrop'])
174 cmds.append(base + ['MultiWallpaperMode', 'NoMulti'])
175
176 cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
177 for cmd in cmds:
178 debug(cmd)
179 if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0:
180 return False
181
182 return True
183
184
185 def main(filename):
186 import logging
187 logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
188 init()
189 set_image(filename)
190
191 if __name__ == "__main__":
192 try:
193 filename = sys.argv[1]
194 except:
195 print >>sys.stderr, "Usage: %s filename" % sys.argv[0]
196 sys.exit(1)
197
198 main(filename)
199
200