]> code.delx.au - bg-scripts/blob - bin/randombg.py
RandomBG: More major cleanups.
[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 False
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("Exception while 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("Exception while 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 self.list
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 add_path(self, path):
166 debug('Added path "%s" to the list' % path)
167 for dirpath, dirs, filenames in os.walk(path):
168 debug('Scanning "%s" for images' % dirpath)
169 if self.directories.has_key(dirpath):
170 continue
171 filenames = filter_images(filenames)
172 if len(filenames):
173 self.directories[dirpath] = filenames
174 debug('Adding "%s" to "%s"' % (filenames, dirpath))
175 else:
176 debug("No images found in '%s'" % dirpath)
177
178 def get_next_image(self):
179 directory = random.choice(self.directories.keys())
180 debug('directory: "%s"' % directory)
181 filename = random.choice(self.directories[directory])
182 debug('filename: "%s"' % filename)
183 return os.path.join(directory, filename)
184
185 def is_empty(self):
186 return len(self.directories.values())
187
188
189 class Cycler(object):
190 def __init__(self, options, paths):
191 self.filelist = self.find_files(options, paths)
192 if not self.filelist.is_empty():
193 error("No images were found. Exiting...")
194 sys.exit(1)
195
196 debug("Initialising RandomBG")
197 self.randombg = WallChanger.RandomBG(options.background_colour, options.permanent)
198 self.cycle_time = options.cycle_time
199
200 self.task = None
201 self.cmd_next()
202
203 def find_files(self, options, paths):
204 if options.all_random:
205 filelist = AllRandomFileList()
206 elif options.folder_random:
207 filelist = FolderRandomFileList()
208 else:
209 filelist = RandomFileList()
210
211 for path in paths:
212 filelist.add_path(path)
213
214 if filelist.load_cache(options.history_filename):
215 debug("Loaded cache successfully")
216 else:
217 debug("Could not load cache")
218 filelist.scan_paths()
219 return filelist
220
221 def cmd_reset(self):
222 def next():
223 image = self.filelist.get_next_image()
224 self.randombg.setImage(image)
225 self.task = None
226 self.cmd_reset()
227
228 if self.task is not None:
229 self.task.cancel()
230 self.task = asyncsched.schedule(self.cycle_time, next)
231 debug("Reset timer for %s seconds" % self.cycle_time)
232
233 def cmd_reload(self):
234 image = self.filelist.get_current_image()
235 self.randombg.setImage(image)
236 self.cmd_reset()
237
238 def cmd_next(self):
239 image = self.filelist.get_next_image()
240 self.randombg.setImage(image)
241 self.cmd_reset()
242
243 def cmd_prev(self):
244 image = self.filelist.get_prev_image()
245 self.randombg.setImage(image)
246 self.cmd_reset()
247
248 def cmd_rescan(self):
249 self.filelist.scan_paths()
250 self.cmd_next()
251
252 def cmd_pause(self):
253 if self.task is not None:
254 self.task.cancel()
255 self.task = None
256
257 class Server(asynchat.async_chat):
258 def __init__(self, cycler, conn, addr):
259 asynchat.async_chat.__init__(self, conn=conn)
260 self.cycler = cycler
261 self.ibuffer = []
262 self.set_terminator("\n")
263
264 def collect_incoming_data(self, data):
265 self.ibuffer.append(data)
266
267 def found_terminator(self):
268 line = "".join(self.ibuffer).lower()
269 self.ibuffer = []
270 prefix, cmd = line.split(None, 1)
271 if prefix != "cmd":
272 debug('Bad line received "%s"' % line)
273 return
274 if hasattr(self.cycler, "cmd_" + cmd):
275 debug('Executing command "%s"' % cmd)
276 getattr(self.cycler, "cmd_" + cmd)()
277 else:
278 debug('Unknown command received "%s"' % cmd)
279
280
281
282 class Listener(asyncore.dispatcher):
283 def __init__(self, socket_filename, randombg):
284 asyncore.dispatcher.__init__(self)
285 self.randombg = randombg
286 self.create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
287 self.bind(socket_filename)
288 self.listen(2) # Backlog = 2
289
290 def handle_accept(self):
291 conn, addr = self.accept()
292 Server(self.randombg, conn, addr)
293
294
295 def do_server(options, paths):
296 try:
297 try:
298 cycler = Cycler(options, paths)
299 listener = Listener(options.socket_filename, cycler)
300 asyncsched.loop()
301 except KeyboardInterrupt:
302 print
303 finally:
304 # Make sure that the socket is cleaned up
305 try:
306 os.unlink(options.socket_filename)
307 except:
308 pass
309
310 def do_client(options, args):
311 if len(args) == 0:
312 args = ["next"]
313 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
314 sock.connect(options.socket_filename)
315 sock = sock.makefile()
316 for i, cmd in enumerate(args):
317 sock.write("cmd %s\n" % cmd)
318 if i+1 != len(args):
319 time.sleep(options.cycle_time)
320 sock.close()
321
322
323 def build_parser():
324 parser = OptionParser(version="%prog " + VERSION,
325 description = "Cycles through random background images.",
326 usage =
327 "\n(server) %prog [options] dir [dir2 ...]"
328 "\n(client) %prog [options] [next|prev|rescan|reload|pause] [...]"
329 "\nThe first instance to be run will be the server.\n"
330 )
331 parser.add_option("-p", "--permanent",
332 action="store_true", dest="permanent", default=False,
333 help="Make the background permanent. Note: This will cause all machines logged in with this account to simultaneously change background [Default: %default]")
334 parser.add_option("-v", '-d', "--verbose", "--debug",
335 action="count", dest="verbose", default=0,
336 help="Make the louder (good for debugging, or those who are curious)")
337 parser.add_option("-b", "--background-colour",
338 action="store", type="string", dest="background_colour", default="black",
339 help="Change the default background colour that is displayed if the image is not in the correct aspect ratio [Default: %default]")
340 parser.add_option("--all-random",
341 action="store_true", dest="all_random", default=False,
342 help="Make sure that all images have been displayed before repeating an image")
343 parser.add_option("--folder-random",
344 action="store_true", dest="folder_random", default=False,
345 help="Give each folder an equal chance of having an image selected from it")
346 parser.add_option("--cycle-time",
347 action="store", type="int", default=1800, dest="cycle_time",
348 help="Cause the image to cycle every X seconds")
349 parser.add_option("--socket",
350 action="store", type="string", dest="socket_filename", default=os.path.expanduser('~/tmp/tmp_socket'),
351 help="Location of the command/control socket.")
352 parser.add_option("--history-file",
353 action="store", type="string", dest="history_filename", default=os.path.expanduser('~/.randombg_historyfile'),
354 help="Stores the location of the last image to be loaded.")
355 return parser
356
357 def main():
358 parser = build_parser()
359 options, args = parser.parse_args(sys.argv[1:])
360
361 logging.basicConfig(level=10*options.verbose)
362
363 if os.path.exists(options.socket_filename):
364 do_client(options, args)
365 else:
366 do_server(options, args)
367
368
369 if __name__ == "__main__":
370 main()
371