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