]>
code.delx.au - bg-scripts/blob - randombg.py
fff408f3b6d6cacf6fe77487986d5dc1551294b7
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"""
45 def add_path ( self
, path
):
46 self
. paths
. append ( path
)
48 def store_cache ( self
, filename
):
50 logging
. debug ( "Attempting to store cache" )
51 fd
= open ( filename
, 'wb' )
52 pickle
. dump ( self
, fd
, 2 )
53 logging
. debug ( "Cache successfully stored" )
55 warning ( "Storing cache: %s " % e
)
57 def load_cache ( self
, filename
):
59 logging
. debug ( "Attempting to load cache from: %s " % filename
)
62 fd
= open ( filename
, 'rb' )
65 if tmp
.__ class
__ != self
.__ class
__ :
66 raise ValueError ( "Using different file list type" )
69 if self
. paths
!= getattr ( tmp
, "paths" ):
70 raise ValueError ( "Path list changed" )
72 for attr
, value
in tmp
.__ dict
__ . items ():
73 setattr ( self
, attr
, value
)
78 logging
. warning ( "Loading cache: %s " % e
)
81 def add_to_favourites ( self
):
82 '''Adds the current image to the list of favourites'''
83 self
. favourites
. append ( self
. get_current_image ())
86 raise NotImplementedError ()
88 def get_next_image ( self
):
89 raise NotImplementedError ()
91 def get_prev_image ( self
):
92 raise NotImplementedError ()
94 def get_current_image ( self
):
95 raise NotImplementedError ()
101 class RandomFileList ( BaseFileList
):
103 super ( RandomFileList
, self
) .__ init
__ ()
105 self
. last_image
= None
107 def scan_paths ( self
):
108 for path
in self
. paths
:
109 for dirpath
, dirsnames
, filenames
in os
. walk ( path
):
110 for filename
in filter_images ( filenames
):
111 self
. list . append ( os
. path
. join ( dirpath
, filename
))
113 def add_path ( self
, path
):
114 self
. paths
. append ( path
)
115 logging
. debug ( 'Added path " %s " to the list' % path
)
117 def get_next_image ( self
):
118 n
= random
. randint ( 0 , len ( self
. list )- 1 )
119 self
. last_image
= self
. list [ n
]
120 logging
. debug ( "Picked file ' %s ' from list" % self
. last_image
)
121 return self
. last_image
123 def get_current_image ( self
):
125 return self
. last_image
127 return self
. get_next_image ()
130 return len ( self
. list ) == 0
133 class AllRandomFileList ( BaseFileList
):
135 super ( AllRandomFileList
, self
) .__ init
__ ()
137 self
. imagePointer
= 0
139 # Scan the input directory, and then randomize the file list
140 def scan_paths ( self
):
141 logging
. debug ( "Scanning paths" )
144 for path
in self
. paths
:
145 logging
. debug ( 'Scanning " %s "' % path
)
146 for dirpath
, dirsnames
, filenames
in os
. walk ( path
):
147 for filename
in filter_images ( filenames
):
148 logging
. debug ( 'Adding file " %s "' % filename
)
149 self
. list . append ( os
. path
. join ( dirpath
, filename
))
151 random
. shuffle ( self
. list )
153 def add_path ( self
, path
):
154 self
. paths
. append ( path
)
155 logging
. debug ( 'Added path " %s " to the list' % path
)
157 def store_cache ( self
, filename
):
159 fd
= open ( filename
, 'wb' )
160 pickle
. dump ( self
, fd
, 2 )
161 logging
. debug ( "Cache successfully stored" )
163 logging
. warning ( "Storing cache" , exc_info
= 1 )
165 def load_cache ( self
, filename
, rescanPaths
= False ):
166 logging
. debug ( 'Attempting to load cache from " %s "' % filename
)
169 fd
= open ( filename
, 'rb' )
170 tmp
= pickle
. load ( fd
)
171 if self
. paths
== tmp
. paths
:
172 logging
. debug ( "Path lists match, copying properties" )
173 # Overwrite this object with the other
174 for attr
in ( 'list' , 'imagePointer' , 'favourites' ):
175 setattr ( self
, attr
, getattr ( tmp
, attr
))
177 logging
. debug ( "Ignoring cache, path lists do not match" )
179 logging
. warning ( "Loading cache" , exc_info
= 1 )
183 def get_current_image ( self
):
184 return self
. list [ self
. imagePointer
]
186 def __inc_in_range ( self
, n
, amount
= 1 , rangeMax
= None , rangeMin
= 0 ):
187 if rangeMax
== None : rangeMax
= len ( self
. list )
189 return ( n
+ amount
) % rangeMax
191 def get_next_image ( self
):
192 self
. imagePointer
= self
.__ inc
_ in
_ range
( self
. imagePointer
)
193 imageName
= self
. list [ self
. imagePointer
]
194 logging
. debug ( "Picked file ' %s ' (pointer= %d ) from list" % ( imageName
, self
. imagePointer
))
197 def get_prev_image ( self
):
198 self
. imagePointer
= self
.__ inc
_ in
_ range
( self
. imagePointer
, amount
=- 1 )
199 imageName
= self
. list [ self
. imagePointer
]
200 logging
. debug ( "Picked file ' %s ' (pointer= %d ) from list" % ( imageName
, self
. imagePointer
))
204 return len ( self
. list ) == 0
206 class FolderRandomFileList ( BaseFileList
):
207 """A file list that will pick a file randomly within a directory. Each
208 directory has the same chance of being chosen."""
210 super ( FolderRandomFileList
, self
) .__ init
__ ()
211 self
. directories
= {}
212 self
. last_image
= None
214 def scan_paths ( self
):
217 def add_path ( self
, path
):
218 logging
. debug ( 'Added path " %s " to the list' % path
)
219 for dirpath
, dirs
, filenames
in os
. walk ( path
):
220 logging
. debug ( 'Scanning " %s " for images' % dirpath
)
221 if self
. directories
. has_key ( dirpath
):
223 filenames
= list ( filter_images ( filenames
))
225 self
. directories
[ dirpath
] = filenames
226 logging
. debug ( 'Adding " %s " to " %s "' % ( filenames
, dirpath
))
228 logging
. debug ( "No images found in ' %s '" % dirpath
)
230 def get_next_image ( self
):
231 directory
= random
. choice ( self
. directories
. keys ())
232 logging
. debug ( 'directory: " %s "' % directory
)
233 filename
= random
. choice ( self
. directories
[ directory
])
234 logging
. debug ( 'filename: " %s "' % filename
)
235 return os
. path
. join ( directory
, filename
)
237 def get_current_image ( self
):
239 return self
. last_image
241 return self
. get_next_image ()
244 return len ( self
. directories
. values ()) == 0
247 class Cycler ( object ):
248 def init ( self
, options
, paths
, oneshot
= False ):
249 self
. cycle_time
= options
. cycle_time
250 self
. history_filename
= options
. history_filename
252 logging
. debug ( "Initialising wallchanger" )
253 wallchanger
. init ( options
. background_colour
, options
. permanent
, options
. convert
)
255 logging
. debug ( "Initialising file list" )
256 if options
. all_random
:
257 self
. filelist
= AllRandomFileList ()
258 elif options
. folder_random
:
259 self
. filelist
= FolderRandomFileList ()
261 self
. filelist
= RandomFileList ()
264 self
. filelist
. add_path ( path
)
266 if self
. filelist
. load_cache ( self
. history_filename
):
267 logging
. debug ( "Loaded cache successfully" )
269 logging
. debug ( "Could not load cache" )
270 self
. filelist
. scan_paths ()
272 if self
. filelist
. is_empty ():
273 logging
. error ( "No images were found. Exiting..." )
283 self
. filelist
. store_cache ( self
. history_filename
)
285 def find_files ( self
, options
, paths
):
290 image
= self
. filelist
. get_next_image ()
291 wallchanger
. set_image ( image
)
295 if self
. task
is not None :
297 self
. task
= asyncsched
. schedule ( self
. cycle_time
, next
)
298 logging
. debug ( "Reset timer for %s seconds" % self
. cycle_time
)
299 self
. filelist
. store_cache ( self
. history_filename
)
301 def cmd_reload ( self
):
302 image
= self
. filelist
. get_current_image ()
303 wallchanger
. set_image ( image
)
307 image
= self
. filelist
. get_next_image ()
308 wallchanger
. set_image ( image
)
312 image
= self
. filelist
. get_prev_image ()
313 wallchanger
. set_image ( image
)
316 def cmd_rescan ( self
):
317 self
. filelist
. scan_paths ()
320 if self
. task
is not None :
327 def cmd_favourite ( self
):
328 self
. filelist
. add_to_favourites ()
330 class Server ( asynchat
. async_chat
):
331 def __init__ ( self
, cycler
, conn
, addr
):
332 asynchat
. async_chat
.__ init
__ ( self
, conn
= conn
)
335 self
. set_terminator ( " \n " )
337 def collect_incoming_data ( self
, data
):
338 self
. ibuffer
. append ( data
)
340 def found_terminator ( self
):
341 line
= "" . join ( self
. ibuffer
). lower ()
343 prefix
, cmd
= line
. split ( None , 1 )
345 logging
. debug ( 'Bad line received " %s "' % line
)
347 if hasattr ( self
. cycler
, "cmd_" + cmd
):
348 logging
. debug ( 'Executing command " %s "' % cmd
)
349 getattr ( self
. cycler
, "cmd_" + cmd
)()
351 logging
. debug ( 'Unknown command received " %s "' % cmd
)
355 class Listener ( asyncore
. dispatcher
):
356 def __init__ ( self
, socket_filename
, cycler
):
357 asyncore
. dispatcher
.__ init
__ ( self
)
359 self
. create_socket ( socket
. AF_UNIX
, socket
. SOCK_STREAM
)
360 self
. bind ( socket_filename
)
361 self
. listen ( 2 ) # Backlog = 2
363 def handle_accept ( self
):
364 conn
, addr
= self
. accept ()
365 Server ( self
. cycler
, conn
, addr
)
371 def do_server ( options
, paths
):
374 listener
= Listener ( options
. socket_filename
, cycler
)
375 # Initialisation of Cycler delayed so we grab the socket quickly
376 cycler
. init ( options
, paths
)
379 except KeyboardInterrupt :
383 # Make sure that the socket is cleaned up
385 os
. unlink ( options
. socket_filename
)
389 def do_client ( options
, args
):
392 sock
= socket
. socket ( socket
. AF_UNIX
, socket
. SOCK_STREAM
)
393 sock
. connect ( options
. socket_filename
)
394 sock
= sock
. makefile ()
395 for i
, cmd
in enumerate ( args
):
396 sock
. write ( "cmd %s \n " % cmd
)
397 if i
< len ( args
) - 1 :
398 time
. sleep ( options
. cycle_time
)
401 def do_oneshot ( options
, paths
):
403 cycler
. init ( options
, paths
, oneshot
= True )
406 parser
= OptionParser ( version
= "%prog " + VERSION
,
407 description
= "Cycles through random background images." ,
409 " \n (server) %prog [options] dir [dir2 ...]"
410 " \n (client) %prog [options] [next|prev|rescan|reload|pause] [...]"
411 " \n The first instance to be run will be the server. \n "
413 parser
. add_option ( "-p" , "--permanent" ,
414 action
= "store_true" , dest
= "permanent" , default
= False ,
415 help = "Make the background permanent. Note: This will cause all machines logged in with this account to simultaneously change background [Default: %def ault]" )
416 parser
. add_option ( "-v" , '-d' , "--verbose" , "--debug" ,
417 action
= "count" , dest
= "verbose" , default
= 0 ,
418 help = "Make the louder (good for debugging, or those who are curious)" )
419 parser
. add_option ( "-b" , "--background-colour" ,
420 action
= "store" , type = "string" , dest
= "background_colour" , default
= "black" ,
421 help = "Change the default background colour that is displayed if the image is not in the correct aspect ratio [Default: %def ault]" )
422 parser
. add_option ( "--all-random" ,
423 action
= "store_true" , dest
= "all_random" , default
= False ,
424 help = "Make sure that all images have been displayed before repeating an image" )
425 parser
. add_option ( "-1" , "--oneshot" ,
426 action
= "store_true" , dest
= "oneshot" , default
= False ,
427 help = "Set one random image and terminate immediately." )
428 parser
. add_option ( "--folder-random" ,
429 action
= "store_true" , dest
= "folder_random" , default
= False ,
430 help = "Give each folder an equal chance of having an image selected from it" )
431 parser
. add_option ( "--convert" ,
432 action
= "store_true" , dest
= "convert" , default
= False ,
433 help = "Do conversions using ImageMagick or PIL, don't rely on the window manager" )
434 parser
. add_option ( "--cycle-time" ,
435 action
= "store" , type = "int" , default
= 1800 , dest
= "cycle_time" ,
436 help = "Cause the image to cycle every X seconds" )
437 parser
. add_option ( "--socket" ,
438 action
= "store" , type = "string" , dest
= "socket_filename" , default
= os
. path
. expanduser ( '~/.randombg_socket' ),
439 help = "Location of the command/control socket." )
440 parser
. add_option ( "--history-file" ,
441 action
= "store" , type = "string" , dest
= "history_filename" , default
= os
. path
. expanduser ( '~/.randombg_historyfile' ),
442 help = "Stores the location of the last image to be loaded." )
446 parser
= build_parser ()
447 options
, args
= parser
. parse_args ( sys
. argv
[ 1 :])
449 if options
. verbose
== 1 :
450 logging
. getLogger (). setLevel ( logging
. INFO
)
451 elif options
. verbose
>= 2 :
452 logging
. getLogger (). setLevel ( logging
. DEBUG
)
455 do_oneshot ( options
, args
)
457 if os
. path
. exists ( options
. socket_filename
):
458 do_client ( options
, args
)
460 do_server ( options
, args
)
463 if __name__
== "__main__" :