]> code.delx.au - bg-scripts/blob - lib/WallChanger.py
c6958a84dd958dada1418c3dd755c3968ded560b
[bg-scripts] / lib / WallChanger.py
1 #! python
2
3 import commands, sys, os, os.path, subprocess, time
4 from GregDebug import debug, setDebugLevel, DEBUG_LEVEL_DEBUG, DEBUG_LEVEL_LOW, DEBUG_LEVEL_MEDIUM, DEBUG_LEVEL_HIGH, DEBUG_INCREMENT
5
6 import python24_adapter # NB: Must be imported before collections
7 import collections
8
9 """This is a cross platform/cross window manager way to change your current
10 desktop image."""
11
12 __all__ = ('RandomBG')
13
14 def RandomBG(*args, **kwargs):
15 """Desktop Changer factory"""
16
17 ret = None
18
19 debug("Testing for OSX (NonX11)", DEBUG_LEVEL_LOW)
20 if commands.getstatusoutput("ps ax -o command -c|grep -q WindowServer")[0] == 0:
21 ret = __OSXChanger(*args, **kwargs)
22
23 if 'DISPLAY' not in os.environ or os.environ['DISPLAY'].startswith('/tmp/launch'):
24 # X11 is not running
25 return ret
26 else:
27 if os.uname()[0] == 'Darwin':
28 # Try to detect if the X11 server is running on OSX
29 if commands.getstatusoutput("ps ax -o command|grep -q '/.*X11 .* %s'" % os.environ['DISPLAY'])[0] != 0:
30 # X11 is not running for this display
31 return ret
32
33 debug("Testing for KDE", DEBUG_LEVEL_LOW)
34 if commands.getstatusoutput("xwininfo -name 'KDE Desktop'")[0] == 0:
35 if ret is not None:
36 ret.nextChanger = __KDEChanger(*args, **kwargs)
37 else:
38 ret = __KDEChanger(*args, **kwargs)
39
40 debug("Testing for WMaker", DEBUG_LEVEL_LOW)
41 if commands.getstatusoutput("xlsclients | grep -qi wmaker")[0] == 0:
42 if ret is not None:
43 ret.nextChanger = __WMakerChanger(*args, **kwargs)
44 else:
45 ret = __WMakerChanger(*args, **kwargs)
46
47 if ret is None:
48 raise Exception("Unknown window manager")
49 else:
50 return ret
51
52 class __BaseChanger(object):
53 def __init__(self, filelist, backgroundColour='black', permanent=False):
54 debug('Determined the window manager is "%s"' % self.__class__.__name__, DEBUG_LEVEL_MEDIUM)
55 self.backgroundColour = backgroundColour
56 self.permanent = permanent
57 self.filelist = filelist
58 # Used to 'chain' background changers
59 self.nextChanger = None
60
61 def callChained(self, filename):
62 if self.nextChanger is None:
63 return True
64 else:
65 return self.nextChanger.changeTo(filename)
66
67 def cycleNext(self):
68 file = self.filelist.getNextRandomImage()
69 return self.changeTo(file) and self.callChained(file)
70
71 def cyclePrev(self):
72 file = self.filelist.getPrevRandomImage()
73 return self.changeTo(file) and self.callChained(file)
74
75 def cycleReload(self):
76 file = self.filelist.getCurrentImage()
77 return self.changeTo(file) and self.callChained(file)
78
79
80 class __WMakerChanger(__BaseChanger):
81 _ConvertedWallpaperLocation = '/tmp/wallpapers_wmaker/'
82 def _removeOldImageCache(self):
83 """Cleans up any old temp images"""
84 if not os.path.isdir(self._ConvertedWallpaperLocation):
85 os.mkdir(self._ConvertedWallpaperLocation)
86 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
87 for filename in filenames:
88 os.unlink(os.path.join(fullpath, filename))
89 for dirname in dirnames:
90 os.unlink(os.path.join(fullpath, dirname))
91
92 def _convertImageFormat(self, file):
93 """Convert the image to a png, and store it in a local place"""
94 self._removeOldImageCache()
95 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
96 cmd = ["convert", '-resize', '1280', '-gravity', 'Center', '-crop', '1280x800+0+0', file, output_name]
97 debug("""Convert command: '"%s"'""" % '" "'.join(cmd), DEBUG_LEVEL_DEBUG)
98 return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
99 def changeTo(self, file):
100 file, convert_status = self._convertImageFormat(file)
101 if convert_status:
102 debug('Convert failed')
103 cmd = ["wmsetbg",
104 "-b", self.backgroundColour, # Sets the background colour to be what the user specified
105 "-S", # 'Smooth' (WTF?)
106 "-e", # Center the image on the screen (only affects when the image in no the in the correct aspect ratio
107 ### "-a", # scale the image, keeping the aspect ratio
108 "-u", # Force this to be the default background
109 "-d" # dither
110 ]
111 if self.permanent:
112 cmd += ["-u"] # update the wmaker database
113 cmd += [file]
114 debug('''WMaker bgset command: "'%s'"''' % "' '".join(cmd), DEBUG_LEVEL_DEBUG)
115 return not subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
116
117 class __OSXChanger(__BaseChanger):
118 _ConvertedWallpaperLocation = '/tmp/wallpapers/'
119 def _removeOldImageCache(self):
120 """Cleans up any old temp images"""
121 if not os.path.isdir(self._ConvertedWallpaperLocation):
122 os.mkdir(self._ConvertedWallpaperLocation)
123 for fullpath, filenames, dirnames in os.walk(self._ConvertedWallpaperLocation, topdown=False):
124 for filename in filenames:
125 os.unlink(os.path.join(fullpath, filename))
126 for dirname in dirnames:
127 os.unlink(os.path.join(fullpath, dirname))
128
129 def _convertImageFormat(self, file):
130 """Convert the image to a png, and store it in a local place"""
131 self._removeOldImageCache()
132 output_name = os.path.join(self._ConvertedWallpaperLocation, '%s.png' % time.time())
133 cmd = ["convert", file, output_name]
134 debug("""Convert command: '"%s"'""" % '" "'.join(cmd), DEBUG_LEVEL_DEBUG)
135 return output_name, subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
136
137 def changeTo(self, file):
138 output_name, ret = self._convertImageFormat(file)
139 if ret: # Since 0 indicates success
140 debug("Convert failed %s" % ret)
141 return False
142 cmd = """osascript -e 'tell application "finder" to set desktop picture to posix file "%s"'""" % output_name
143 debug(cmd, DEBUG_LEVEL_DEBUG)
144 return not commands.getstatusoutput(cmd)[0]
145
146 class __GnomeChanger(__BaseChanger):
147 def changeTo(self, file):
148 cmd = ['gconftool-2', '--type', 'string', '--set', '/desktop/gnome/background/picture_filename', file]
149 debug(cmd, DEBUG_LEVEL_DEBUG)
150 return subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
151
152 class __KDEChanger(__BaseChanger):
153 def changeTo(self, file):
154 cmds = []
155 for group in ('Desktop0', 'Desktop0Screen0'):
156 base = ['kwriteconfig', '--file', 'kdesktoprc', '--group', group, '--key']
157 cmds.append(base + ['Wallpaper', file])
158 cmds.append(base + ['UseSHM', '--type', 'bool', 'true'])
159 cmds.append(base + ['WallpaperMode', 'ScaleAndCrop'])
160 cmds.append(base + ['MultiWallpaperMode', 'NoMulti'])
161
162 cmds.append(['dcop', 'kdesktop', 'KBackgroundIface', 'configure'])
163 for cmd in cmds:
164 debug(cmd, DEBUG_LEVEL_DEBUG)
165 if subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait() != 0:
166 return 1 # Fail
167
168 return 0 # Success
169