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