]> code.delx.au - bg-scripts/blob - randombg.py
Move the PIL imports to the module scope, and add a warning if they are not found
[bg-scripts] / randombg.py
1 #!/usr/bin/env python
2
3 VERSION = "2.0"
4
5
6 import asyncore, asynchat, socket
7 import os, os.path, random, sys, time
8 from optparse import OptionParser
9 import logging
10 try:
11 logging.basicConfig(format="%(levelname)s: %(message)s")
12 except TypeError:
13 # Python 2.3's logging.basicConfig does not support parameters
14 logging.basicConfig()
15
16 try:
17 import cPickle as pickle
18 except ImportError:
19 import pickle
20
21 try:
22 # Required libraries
23 import asyncsched
24 import wallchanger
25 except ImportError, e:
26 logging.critical("Missing libraries! Exiting...", exc_info=1)
27 sys.exit(1)
28
29
30
31
32 def filter_images(filenames):
33 extensions = ('.jpg', '.jpe', '.jpeg', '.png', '.gif', '.bmp')
34 for filename in filenames:
35 _, ext = os.path.splitext(filename)
36 if ext.lower() in extensions:
37 yield filename
38
39 class BaseFileList(object):
40 """Base file list implementation"""
41 def __init__(self):
42 self.paths = []
43 self.favourites = []
44
45 def add_path(self, path):
46 self.paths.append(path)
47
48 def store_cache(self, filename):
49 try:
50 logging.debug("Attempting to store cache")
51 fd = open(filename, 'wb')
52 pickle.dump(self, fd, 2)
53 logging.debug("Cache successfully stored")
54 except Exception, e:
55 warning("Storing cache: %s" % e)
56
57 def load_cache(self, filename):
58 try:
59 logging.debug("Attempting to load cache from: %s" % filename)
60 self.paths.sort()
61
62 fd = open(filename, 'rb')
63 tmp = pickle.load(fd)
64
65 if tmp.__class__ != self.__class__:
66 raise ValueError("Using different file list type")
67
68 tmp.paths.sort()
69 if self.paths != tmp.paths:
70 raise ValueError, "Path list changed"
71
72 # Overwrite this object with the other
73 for attr, value in tmp.__dict__.items():
74 setattr(self, attr, value)
75
76 return True
77
78 except Exception, e:
79 logging.warning("Loading cache: %s" % e)
80 return False
81
82 def add_to_favourites(self):
83 '''Adds the current image to the list of favourites'''
84 self.favourites.append(self.get_current_image())
85
86 def scan_paths(self):
87 raise NotImplementedError()
88
89 def get_next_image(self):
90 raise NotImplementedError()
91
92 def get_prev_image(self):
93 raise NotImplementedError()
94
95 def get_current_image(self):
96 raise NotImplementedError()
97
98 def is_empty(self):
99 return True
100
101
102 class RandomFileList(BaseFileList):
103 def __init__(self):
104 super(RandomFileList, self).__init__()
105 self.list = []
106 self.last_image = None
107
108 def scan_paths(self):
109 for path in self.paths:
110 for dirpath, dirsnames, filenames in os.walk(path):
111 for filename in filter_images(filenames):
112 self.list.append(os.path.join(dirpath, filename))
113
114 def add_path(self, path):
115 self.paths.append(path)
116 logging.debug('Added path "%s" to the list' % path)
117
118 def get_next_image(self):
119 n = random.randint(0, len(self.list)-1)
120 self.last_image = self.list[n]
121 logging.debug("Picked file '%s' from list" % self.last_image)
122 return self.last_image
123
124 def get_current_image(self):
125 if self.last_image:
126 return self.last_image
127 else:
128 return self.get_next_image()
129
130 def is_empty(self):
131 return len(self.list) == 0
132
133
134 class AllRandomFileList(BaseFileList):
135 def __init__(self):
136 super(AllRandomFileList, self).__init__()
137 self.list = None
138 self.imagePointer = 0
139
140 # Scan the input directory, and then randomize the file list
141 def scan_paths(self):
142 logging.debug("Scanning paths")
143
144 self.list = []
145 for path in self.paths:
146 logging.debug('Scanning "%s"' % path)
147 for dirpath, dirsnames, filenames in os.walk(path):
148 for filename in filter_images(filenames):
149 logging.debug('Adding file "%s"' % filename)
150 self.list.append(os.path.join(dirpath, filename))
151
152 random.shuffle(self.list)
153
154 def add_path(self, path):
155 self.paths.append(path)
156 logging.debug('Added path "%s" to the list' % path)
157
158 def store_cache(self, filename):
159 try:
160 fd = open(filename, 'wb')
161 pickle.dump(self, fd, 2)
162 logging.debug("Cache successfully stored")
163 except Exception, e:
164 logging.warning("Storing cache", exc_info=1)
165
166 def get_current_image(self):
167 return self.list[self.imagePointer]
168
169 def __inc_in_range(self, n, amount = 1, rangeMax = None, rangeMin = 0):
170 if rangeMax == None: rangeMax = len(self.list)
171 assert rangeMax > 0
172 return (n + amount) % rangeMax
173
174 def get_next_image(self):
175 self.imagePointer = self.__inc_in_range(self.imagePointer)
176 imageName = self.list[self.imagePointer]
177 logging.debug("Picked file '%s' (pointer=%d) from list" % (imageName, self.imagePointer))
178 return imageName
179
180 def get_prev_image(self):
181 self.imagePointer = self.__inc_in_range(self.imagePointer, amount=-1)
182 imageName = self.list[self.imagePointer]
183 logging.debug("Picked file '%s' (pointer=%d) from list" % (imageName, self.imagePointer))
184 return imageName
185
186 def is_empty(self):
187 return len(self.list) == 0
188
189
190 class FolderRandomFileList(BaseFileList):
191 """A file list that will pick a file randomly within a directory. Each
192 directory has the same chance of being chosen."""
193 def __init__(self):
194 super(FolderRandomFileList, self).__init__()
195 self.directories = {}
196 self.last_image = None
197
198 def scan_paths(self):
199 pass
200
201 def add_path(self, path):
202 logging.debug('Added path "%s" to the list' % path)
203 for dirpath, dirs, filenames in os.walk(path):
204 logging.debug('Scanning "%s" for images' % dirpath)
205 if self.directories.has_key(dirpath):
206 continue
207 filenames = list(filter_images(filenames))
208 if len(filenames):
209 self.directories[dirpath] = filenames
210 logging.debug('Adding "%s" to "%s"' % (filenames, dirpath))
211 else:
212 logging.debug("No images found in '%s'" % dirpath)
213
214 def get_next_image(self):
215 directory = random.choice(self.directories.keys())
216 logging.debug('directory: "%s"' % directory)
217 filename = random.choice(self.directories[directory])
218 logging.debug('filename: "%s"' % filename)
219 return os.path.join(directory, filename)
220
221 def get_current_image(self):
222 if self.last_image:
223 return self.last_image
224 else:
225 return self.get_next_image()
226
227 def is_empty(self):
228 return len(self.directories.values()) == 0
229
230
231 class Cycler(object):
232 def init(self, options, paths, oneshot=False):
233 self.cycle_time = options.cycle_time
234 self.history_filename = options.history_filename
235
236 logging.debug("Initialising wallchanger")
237 wallchanger.init(options.background_colour, options.permanent, options.convert)
238
239 logging.debug("Initialising file list")
240 if options.all_random:
241 self.filelist = AllRandomFileList()
242 elif options.folder_random:
243 self.filelist = FolderRandomFileList()
244 else:
245 self.filelist = RandomFileList()
246
247 for path in paths:
248 self.filelist.add_path(path)
249
250 if self.filelist.load_cache(self.history_filename):
251 logging.debug("Loaded cache successfully")
252 else:
253 logging.debug("Could not load cache")
254 self.filelist.scan_paths()
255
256 if self.filelist.is_empty():
257 logging.error("No images were found. Exiting...")
258 sys.exit(1)
259
260 self.task = None
261 if oneshot:
262 self.cmd_next()
263 else:
264 self.cmd_reload()
265
266 def finish(self):
267 self.filelist.store_cache(self.history_filename)
268
269 def find_files(self, options, paths):
270 return filelist
271
272 def cmd_reset(self):
273 def next():
274 image = self.filelist.get_next_image()
275 wallchanger.set_image(image)
276 self.task = None
277 self.cmd_reset()
278
279 if self.task is not None:
280 self.task.cancel()
281 self.task = asyncsched.schedule(self.cycle_time, next)
282 logging.debug("Reset timer for %s seconds" % self.cycle_time)
283 self.filelist.store_cache(self.history_filename)
284
285 def cmd_reload(self):
286 image = self.filelist.get_current_image()
287 wallchanger.set_image(image)
288 self.cmd_reset()
289
290 def cmd_next(self):
291 image = self.filelist.get_next_image()
292 wallchanger.set_image(image)
293 self.cmd_reset()
294
295 def cmd_prev(self):
296 image = self.filelist.get_prev_image()
297 wallchanger.set_image(image)
298 self.cmd_reset()
299
300 def cmd_rescan(self):
301 self.filelist.scan_paths()
302
303 def cmd_pause(self):
304 if self.task is not None:
305 self.task.cancel()
306 self.task = None
307
308 def cmd_exit(self):
309 asyncsched.exit()
310
311 def cmd_favourite(self):
312 self.filelist.add_to_favourites()
313
314 class Server(asynchat.async_chat):
315 def __init__(self, cycler, conn, addr):
316 asynchat.async_chat.__init__(self, conn=conn)
317 self.cycler = cycler
318 self.ibuffer = []
319 self.set_terminator("\n")
320
321 def collect_incoming_data(self, data):
322 self.ibuffer.append(data)
323
324 def found_terminator(self):
325 line = "".join(self.ibuffer).lower()
326 self.ibuffer = []
327 prefix, cmd = line.split(None, 1)
328 if prefix != "cmd":
329 logging.debug('Bad line received "%s"' % line)
330 return
331 if hasattr(self.cycler, "cmd_" + cmd):
332 logging.debug('Executing command "%s"' % cmd)
333 getattr(self.cycler, "cmd_" + cmd)()
334 else:
335 logging.debug('Unknown command received "%s"' % cmd)
336
337
338 class Listener(asyncore.dispatcher):
339 def __init__(self, socket_filename, cycler):
340 asyncore.dispatcher.__init__(self)
341 self.cycler = cycler
342 self.create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
343 self.bind(socket_filename)
344 self.listen(2) # Backlog = 2
345
346 def handle_accept(self):
347 conn, addr = self.accept()
348 Server(self.cycler, conn, addr)
349
350 def writable(self):
351 return False
352
353
354 def do_server(options, paths):
355 try:
356 cycler = Cycler()
357 listener = Listener(options.socket_filename, cycler)
358 # Initialisation of Cycler delayed so we grab the socket quickly
359 cycler.init(options, paths)
360 try:
361 asyncsched.loop()
362 except KeyboardInterrupt:
363 print
364 cycler.finish()
365 finally:
366 # Make sure that the socket is cleaned up
367 try:
368 os.unlink(options.socket_filename)
369 except:
370 pass
371
372 def do_client(options, args):
373 if len(args) == 0:
374 args = ["next"]
375 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
376 sock.connect(options.socket_filename)
377 sock = sock.makefile()
378 for i, cmd in enumerate(args):
379 sock.write("cmd %s\n" % cmd)
380 if i < len(args) - 1:
381 time.sleep(options.cycle_time)
382 sock.close()
383
384 def do_oneshot(options, paths):
385 cycler = Cycler()
386 cycler.init(options, paths, oneshot=True)
387
388 def build_parser():
389 parser = OptionParser(version="%prog " + VERSION,
390 description = "Cycles through random background images.",
391 usage =
392 "\n(server) %prog [options] dir [dir2 ...]"
393 "\n(client) %prog [options] [next|prev|rescan|reload|pause] [...]"
394 "\nThe first instance to be run will be the server.\n"
395 )
396 parser.add_option("-p", "--permanent",
397 action="store_true", dest="permanent", default=False,
398 help="Make the background permanent. Note: This will cause all machines logged in with this account to simultaneously change background [Default: %default]")
399 parser.add_option("-v", '-d', "--verbose", "--debug",
400 action="count", dest="verbose", default=0,
401 help="Make the louder (good for debugging, or those who are curious)")
402 parser.add_option("-b", "--background-colour",
403 action="store", type="string", dest="background_colour", default="black",
404 help="Change the default background colour that is displayed if the image is not in the correct aspect ratio [Default: %default]")
405 parser.add_option("--all-random",
406 action="store_true", dest="all_random", default=False,
407 help="Make sure that all images have been displayed before repeating an image")
408 parser.add_option("-1", "--oneshot",
409 action="store_true", dest="oneshot", default=False,
410 help="Set one random image and terminate immediately.")
411 parser.add_option("--folder-random",
412 action="store_true", dest="folder_random", default=False,
413 help="Give each folder an equal chance of having an image selected from it")
414 parser.add_option("--convert",
415 action="store_true", dest="convert", default=False,
416 help="Do conversions using ImageMagick or PIL, don't rely on the window manager")
417 parser.add_option("--cycle-time",
418 action="store", type="int", default=1800, dest="cycle_time",
419 help="Cause the image to cycle every X seconds")
420 parser.add_option("--socket",
421 action="store", type="string", dest="socket_filename", default=os.path.expanduser('~/.randombg_socket'),
422 help="Location of the command/control socket.")
423 parser.add_option("--history-file",
424 action="store", type="string", dest="history_filename", default=os.path.expanduser('~/.randombg_historyfile'),
425 help="Stores the location of the last image to be loaded.")
426 return parser
427
428 def main():
429 parser = build_parser()
430 options, args = parser.parse_args(sys.argv[1:])
431
432 if options.verbose == 1:
433 logging.getLogger().setLevel(logging.INFO)
434 elif options.verbose >= 2:
435 logging.getLogger().setLevel(logging.DEBUG)
436
437 if options.oneshot:
438 do_oneshot(options, args)
439 else:
440 if os.path.exists(options.socket_filename):
441 do_client(options, args)
442 else:
443 do_server(options, args)
444
445
446 if __name__ == "__main__":
447 main()