]>
code.delx.au - bg-scripts/blob - randombg.py
6 import asyncore
, asynchat
, socket
7 import os
, os
. path
, random
, sys
, time
8 from optparse
import OptionParser
11 logging
. basicConfig ( format
= " %(levelname)s : %(message)s " )
13 # Python 2.3's logging.basicConfig does not support parameters
17 import cPickle
as pickle
25 except ImportError , e
:
26 logging
. critical ( "Missing libraries! Exiting..." , exc_info
= 1 )
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
:
39 class BaseFileList ( object ):
40 """Base file list implementation"""
44 def add_path ( self
, path
):
45 self
. paths
. append ( path
)
47 def store_cache ( self
, filename
):
49 logging
. debug ( "Attempting to store cache" )
50 fd
= open ( filename
, 'wb' )
51 pickle
. dump ( obj
= self
, file = fd
, protocol
= 2 )
52 logging
. debug ( "Cache successfully stored" )
54 warning ( "Storing cache: %s " % e
)
56 def load_cache ( self
, filename
):
58 logging
. debug ( "Attempting to load cache from: %s " % filename
)
61 fd
= open ( filename
, 'rb' )
64 if tmp
.__ class
__ != self
.__ class
__ :
65 raise ValueError ( "Using different file list type" )
68 if self
. paths
!= getattr ( tmp
, "paths" ):
69 raise ValueError ( "Path list changed" )
71 for attr
, value
in tmp
.__ dict
__ . items ():
72 setattr ( self
, attr
, value
)
77 logging
. warning ( "Loading cache: %s " % e
)
81 raise NotImplementedError ()
83 def get_next_image ( self
):
84 raise NotImplementedError ()
86 def get_prev_image ( self
):
87 raise NotImplementedError ()
89 def get_current_image ( self
):
90 raise NotImplementedError ()
96 class RandomFileList ( BaseFileList
):
98 super ( RandomFileList
, self
) .__ init
__ ()
100 self
. last_image
= None
102 def scan_paths ( self
):
103 for path
in self
. paths
:
104 for dirpath
, dirsnames
, filenames
in os
. walk ( path
):
105 for filename
in filter_images ( filenames
):
106 self
. list . append ( os
. path
. join ( dirpath
, filename
))
108 def add_path ( self
, path
):
109 self
. paths
. append ( path
)
110 logging
. debug ( 'Added path " %s " to the list' % path
)
112 def get_next_image ( self
):
113 n
= random
. randint ( 0 , len ( self
. list )- 1 )
114 self
. last_image
= self
. list [ n
]
115 logging
. debug ( "Picked file ' %s ' from list" % self
. last_image
)
116 return self
. last_image
118 def get_current_image ( self
):
120 return self
. last_image
122 return self
. get_next_image ()
125 return len ( self
. list ) == 0
128 class AllRandomFileList ( BaseFileList
):
130 super ( AllRandomFileList
, self
) .__ init
__ ()
132 self
. imagePointer
= 0
134 # Scan the input directory, and then randomize the file list
135 def scan_paths ( self
):
136 logging
. debug ( "Scanning paths" )
139 for path
in self
. paths
:
140 logging
. debug ( 'Scanning " %s "' % path
)
141 for dirpath
, dirsnames
, filenames
in os
. walk ( path
):
142 for filename
in filter_images ( filenames
):
143 logging
. debug ( 'Adding file " %s "' % filename
)
144 self
. list . append ( os
. path
. join ( dirpath
, filename
))
146 random
. shuffle ( self
. list )
148 def add_path ( self
, path
):
149 self
. paths
. append ( path
)
150 logging
. debug ( 'Added path " %s " to the list' % path
)
152 def store_cache ( self
, filename
):
154 fd
= open ( filename
, 'wb' )
155 pickle
. dump ( self
, fd
, 2 )
156 logging
. debug ( "Cache successfully stored" )
158 logging
. warning ( "Storing cache" , exc_info
= 1 )
160 def load_cache ( self
, filename
, rescanPaths
= False ):
161 logging
. debug ( 'Attempting to load cache from " %s "' % filename
)
164 fd
= open ( filename
, 'rb' )
165 tmp
= pickle
. load ( fd
)
166 if self
. paths
== tmp
. paths
:
167 logging
. debug ( "Path lists match, copying properties" )
168 # Overwrite this object with the other
169 for attr
in ( 'list' , 'imagePointer' ):
170 setattr ( self
, attr
, getattr ( tmp
, attr
))
172 logging
. debug ( "Ignoring cache, path lists do not match" )
174 logging
. warning ( "Loading cache" , exc_info
= 1 )
178 def get_current_image ( self
):
179 return self
. list [ self
. imagePointer
]
181 def __inc_in_range ( self
, n
, amount
= 1 , rangeMax
= None , rangeMin
= 0 ):
182 if rangeMax
== None : rangeMax
= len ( self
. list )
184 return ( n
+ amount
) % rangeMax
186 def get_next_image ( self
):
187 self
. imagePointer
= self
.__ inc
_ in
_ range
( self
. imagePointer
)
188 imageName
= self
. list [ self
. imagePointer
]
189 logging
. debug ( "Picked file ' %s ' (pointer= %d ) from list" % ( imageName
, self
. imagePointer
))
192 def get_prev_image ( self
):
193 self
. imagePointer
= self
.__ inc
_ in
_ range
( self
. imagePointer
, amount
=- 1 )
194 imageName
= self
. list [ self
. imagePointer
]
195 logging
. debug ( "Picked file ' %s ' (pointer= %d ) from list" % ( imageName
, self
. imagePointer
))
199 return len ( self
. list ) == 0
201 class FolderRandomFileList ( BaseFileList
):
202 """A file list that will pick a file randomly within a directory. Each
203 directory has the same chance of being chosen."""
205 super ( FolderRandomFileList
, self
) .__ init
__ ()
206 self
. directories
= {}
207 self
. last_image
= None
209 def scan_paths ( self
):
212 def add_path ( self
, path
):
213 logging
. debug ( 'Added path " %s " to the list' % path
)
214 for dirpath
, dirs
, filenames
in os
. walk ( path
):
215 logging
. debug ( 'Scanning " %s " for images' % dirpath
)
216 if self
. directories
. has_key ( dirpath
):
218 filenames
= list ( filter_images ( filenames
))
220 self
. directories
[ dirpath
] = filenames
221 logging
. debug ( 'Adding " %s " to " %s "' % ( filenames
, dirpath
))
223 logging
. debug ( "No images found in ' %s '" % dirpath
)
225 def get_next_image ( self
):
226 directory
= random
. choice ( self
. directories
. keys ())
227 logging
. debug ( 'directory: " %s "' % directory
)
228 filename
= random
. choice ( self
. directories
[ directory
])
229 logging
. debug ( 'filename: " %s "' % filename
)
230 return os
. path
. join ( directory
, filename
)
232 def get_current_image ( self
):
234 return self
. last_image
236 return self
. get_next_image ()
239 return len ( self
. directories
. values ()) == 0
242 class Cycler ( object ):
243 def init ( self
, options
, paths
):
244 self
. cycle_time
= options
. cycle_time
245 self
. history_filename
= options
. history_filename
247 logging
. debug ( "Initialising wallchanger" )
248 wallchanger
. init ( options
. background_colour
, options
. permanent
)
250 logging
. debug ( "Initialising file list" )
251 if options
. all_random
:
252 self
. filelist
= AllRandomFileList ()
253 elif options
. folder_random
:
254 self
. filelist
= FolderRandomFileList ()
256 self
. filelist
= RandomFileList ()
259 self
. filelist
. add_path ( path
)
261 if self
. filelist
. load_cache ( self
. history_filename
):
262 logging
. debug ( "Loaded cache successfully" )
264 logging
. debug ( "Could not load cache" )
265 self
. filelist
. scan_paths ()
267 if self
. filelist
. is_empty ():
268 logging
. error ( "No images were found. Exiting..." )
275 self
. filelist
. store_cache ( self
. history_filename
)
277 def find_files ( self
, options
, paths
):
282 image
= self
. filelist
. get_next_image ()
283 wallchanger
. set_image ( image
)
287 if self
. task
is not None :
289 self
. task
= asyncsched
. schedule ( self
. cycle_time
, next
)
290 logging
. debug ( "Reset timer for %s seconds" % self
. cycle_time
)
292 def cmd_reload ( self
):
293 image
= self
. filelist
. get_current_image ()
294 wallchanger
. set_image ( image
)
298 image
= self
. filelist
. get_next_image ()
299 wallchanger
. set_image ( image
)
303 image
= self
. filelist
. get_prev_image ()
304 wallchanger
. set_image ( image
)
307 def cmd_rescan ( self
):
308 self
. filelist
. scan_paths ()
311 if self
. task
is not None :
318 class Server ( asynchat
. async_chat
):
319 def __init__ ( self
, cycler
, conn
, addr
):
320 asynchat
. async_chat
.__ init
__ ( self
, conn
= conn
)
323 self
. set_terminator ( " \n " )
325 def collect_incoming_data ( self
, data
):
326 self
. ibuffer
. append ( data
)
328 def found_terminator ( self
):
329 line
= "" . join ( self
. ibuffer
). lower ()
331 prefix
, cmd
= line
. split ( None , 1 )
333 logging
. debug ( 'Bad line received " %s "' % line
)
335 if hasattr ( self
. cycler
, "cmd_" + cmd
):
336 logging
. debug ( 'Executing command " %s "' % cmd
)
337 getattr ( self
. cycler
, "cmd_" + cmd
)()
339 logging
. debug ( 'Unknown command received " %s "' % cmd
)
343 class Listener ( asyncore
. dispatcher
):
344 def __init__ ( self
, socket_filename
, cycler
):
345 asyncore
. dispatcher
.__ init
__ ( self
)
347 self
. create_socket ( socket
. AF_UNIX
, socket
. SOCK_STREAM
)
348 self
. bind ( socket_filename
)
349 self
. listen ( 2 ) # Backlog = 2
351 def handle_accept ( self
):
352 conn
, addr
= self
. accept ()
353 Server ( self
. cycler
, conn
, addr
)
359 def do_server ( options
, paths
):
362 listener
= Listener ( options
. socket_filename
, cycler
)
363 # Initialisation of Cycler delayed so we grab the socket quickly
364 cycler
. init ( options
, paths
)
367 except KeyboardInterrupt :
371 # Make sure that the socket is cleaned up
373 os
. unlink ( options
. socket_filename
)
377 def do_client ( options
, args
):
380 sock
= socket
. socket ( socket
. AF_UNIX
, socket
. SOCK_STREAM
)
381 sock
. connect ( options
. socket_filename
)
382 sock
= sock
. makefile ()
383 for i
, cmd
in enumerate ( args
):
384 sock
. write ( "cmd %s \n " % cmd
)
385 if i
< len ( args
) - 1 :
386 time
. sleep ( options
. cycle_time
)
389 def do_oneshot ( options
, paths
):
391 cycler
. init ( options
, paths
)
394 parser
= OptionParser ( version
= "%prog " + VERSION
,
395 description
= "Cycles through random background images." ,
397 " \n (server) %prog [options] dir [dir2 ...]"
398 " \n (client) %prog [options] [next|prev|rescan|reload|pause] [...]"
399 " \n The first instance to be run will be the server. \n "
401 parser
. add_option ( "-p" , "--permanent" ,
402 action
= "store_true" , dest
= "permanent" , default
= False ,
403 help = "Make the background permanent. Note: This will cause all machines logged in with this account to simultaneously change background [Default: %def ault]" )
404 parser
. add_option ( "-v" , '-d' , "--verbose" , "--debug" ,
405 action
= "count" , dest
= "verbose" , default
= 0 ,
406 help = "Make the louder (good for debugging, or those who are curious)" )
407 parser
. add_option ( "-b" , "--background-colour" ,
408 action
= "store" , type = "string" , dest
= "background_colour" , default
= "black" ,
409 help = "Change the default background colour that is displayed if the image is not in the correct aspect ratio [Default: %def ault]" )
410 parser
. add_option ( "--all-random" ,
411 action
= "store_true" , dest
= "all_random" , default
= False ,
412 help = "Make sure that all images have been displayed before repeating an image" )
413 parser
. add_option ( "-1" , "--oneshot" ,
414 action
= "store_true" , dest
= "oneshot" , default
= False ,
415 help = "Set one random image and terminate immediately." )
416 parser
. add_option ( "--folder-random" ,
417 action
= "store_true" , dest
= "folder_random" , default
= False ,
418 help = "Give each folder an equal chance of having an image selected from it" )
419 parser
. add_option ( "--convert" ,
420 action
= "store_true" , dest
= "convert" , default
= False ,
421 help = "Do conversions using ImageMagick or PIL, don't rely on the window manager" )
422 parser
. add_option ( "--cycle-time" ,
423 action
= "store" , type = "int" , default
= 1800 , dest
= "cycle_time" ,
424 help = "Cause the image to cycle every X seconds" )
425 parser
. add_option ( "--socket" ,
426 action
= "store" , type = "string" , dest
= "socket_filename" , default
= os
. path
. expanduser ( '~/.randombg_socket' ),
427 help = "Location of the command/control socket." )
428 parser
. add_option ( "--history-file" ,
429 action
= "store" , type = "string" , dest
= "history_filename" , default
= os
. path
. expanduser ( '~/.randombg_historyfile' ),
430 help = "Stores the location of the last image to be loaded." )
434 parser
= build_parser ()
435 options
, args
= parser
. parse_args ( sys
. argv
[ 1 :])
437 if options
. verbose
== 1 :
438 logging
. getLogger (). setLevel ( logging
. INFO
)
439 elif options
. verbose
>= 2 :
440 logging
. getLogger (). setLevel ( logging
. DEBUG
)
443 do_oneshot ( options
, args
)
445 if os
. path
. exists ( options
. socket_filename
):
446 do_client ( options
, args
)
448 do_server ( options
, args
)
451 if __name__
== "__main__" :