]>
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
10 logging
. basicConfig ( format
= " %(levelname)s : %(message)s " )
12 import cPickle
as pickle
20 except ImportError , e
:
21 logging
. critical ( "Missing libraries! Exiting..." )
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
:
34 class BaseFileList ( object ):
35 """Base file list implementation"""
37 raise NotImplementedError ()
39 def add_path ( self
, path
):
40 raise NotImplementedError ()
42 def store_cache ( self
, path
):
45 def load_cache ( self
, filename
, rescanPaths
= False ):
48 def get_next_image ( self
):
49 raise NotImplementedError ()
51 def get_prev_image ( self
):
52 raise NotImplementedError ()
54 def get_current_image ( self
):
55 raise NotImplementedError ()
61 class RandomFileList ( BaseFileList
):
65 self
. last_image
= None
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
))
73 def add_path ( self
, path
):
74 self
. paths
. append ( path
)
75 logging
. debug ( 'Added path " %s " to the list' % path
)
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
84 return len ( self
. list ) == 0
87 class AllRandomFileList ( BaseFileList
):
93 # Scan the input directory, and then randomize the file list
95 logging
. debug ( "Scanning paths" )
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
))
105 random
. shuffle ( self
. list )
107 def add_path ( self
, path
):
108 self
. paths
. append ( path
)
109 logging
. debug ( 'Added path " %s " to the list' % path
)
111 def store_cache ( self
, filename
):
113 fd
= open ( filename
, 'wb' )
114 pickle
. dump ( obj
= self
, file = fd
, protocol
= 2 )
115 logging
. debug ( "Cache successfully stored" )
117 logging
. warning ( "Storing cache" , exc_info
= 1 )
119 def load_cache ( self
, filename
, rescanPaths
= False ):
120 logging
. debug ( 'Attempting to load cache from " %s "' % filename
)
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
))
131 logging
. debug ( "Ignoring cache, path lists do not match" )
133 logging
. warning ( "Loading cache" , exc_info
= 1 )
135 def get_current_image ( self
):
136 return self
. list [ self
. imagePointer
]
138 def __inc_in_range ( self
, n
, amount
= 1 , rangeMax
= None , rangeMin
= 0 ):
139 if rangeMax
== None : rangeMax
= len ( self
. list )
141 return ( n
+ amount
) % rangeMax
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
))
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
))
156 return len ( self
. list ) == 0
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."""
162 self
. directories
= {}
164 def scan_paths ( self
):
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
):
173 filenames
= list ( filter_images ( filenames
))
175 self
. directories
[ dirpath
] = filenames
176 logging
. debug ( 'Adding " %s " to " %s "' % ( filenames
, dirpath
))
178 logging
. debug ( "No images found in ' %s '" % dirpath
)
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
)
188 return len ( self
. directories
. values ()) == 0
191 class Cycler ( object ):
192 def init ( self
, options
, paths
):
193 self
. cycle_time
= options
. cycle_time
194 self
. history_filename
= options
. history_filename
196 logging
. debug ( "Initialising wallchanger" )
197 wallchanger
. init ( options
. background_colour
, options
. permanent
)
199 logging
. debug ( "Initialising file list" )
200 if options
. all_random
:
201 self
. filelist
= AllRandomFileList ()
202 elif options
. folder_random
:
203 self
. filelist
= FolderRandomFileList ()
205 self
. filelist
= RandomFileList ()
208 self
. filelist
. add_path ( path
)
210 if self
. filelist
. load_cache ( self
. history_filename
):
211 logging
. debug ( "Loaded cache successfully" )
213 logging
. debug ( "Could not load cache" )
214 self
. filelist
. scan_paths ()
216 if self
. filelist
. is_empty ():
217 logging
. error ( "No images were found. Exiting..." )
224 self
. filelist
. store_cache ( self
. history_filename
)
226 def find_files ( self
, options
, paths
):
231 image
= self
. filelist
. get_next_image ()
232 wallchanger
. set_image ( image
)
236 if self
. task
is not None :
238 self
. task
= asyncsched
. schedule ( self
. cycle_time
, next
)
239 logging
. debug ( "Reset timer for %s seconds" % self
. cycle_time
)
241 def cmd_reload ( self
):
242 image
= self
. filelist
. get_current_image ()
243 wallchanger
. set_image ( image
)
247 image
= self
. filelist
. get_next_image ()
248 wallchanger
. set_image ( image
)
252 image
= self
. filelist
. get_prev_image ()
253 wallchanger
. set_image ( image
)
256 def cmd_rescan ( self
):
257 self
. filelist
. scan_paths ()
261 if self
. task
is not None :
268 class Server ( asynchat
. async_chat
):
269 def __init__ ( self
, cycler
, conn
, addr
):
270 asynchat
. async_chat
.__ init
__ ( self
, conn
= conn
)
273 self
. set_terminator ( " \n " )
275 def collect_incoming_data ( self
, data
):
276 self
. ibuffer
. append ( data
)
278 def found_terminator ( self
):
279 line
= "" . join ( self
. ibuffer
). lower ()
281 prefix
, cmd
= line
. split ( None , 1 )
283 logging
. debug ( 'Bad line received " %s "' % line
)
285 if hasattr ( self
. cycler
, "cmd_" + cmd
):
286 logging
. debug ( 'Executing command " %s "' % cmd
)
287 getattr ( self
. cycler
, "cmd_" + cmd
)()
289 logging
. debug ( 'Unknown command received " %s "' % cmd
)
293 class Listener ( asyncore
. dispatcher
):
294 def __init__ ( self
, socket_filename
, cycler
):
295 asyncore
. dispatcher
.__ init
__ ( self
)
297 self
. create_socket ( socket
. AF_UNIX
, socket
. SOCK_STREAM
)
298 self
. bind ( socket_filename
)
299 self
. listen ( 2 ) # Backlog = 2
301 def handle_accept ( self
):
302 conn
, addr
= self
. accept ()
303 Server ( self
. cycler
, conn
, addr
)
309 def do_server ( options
, paths
):
312 listener
= Listener ( options
. socket_filename
, cycler
)
313 # Initialisation of Cycler delayed so we grab the socket quickly
314 cycler
. init ( options
, paths
)
317 except KeyboardInterrupt :
321 # Make sure that the socket is cleaned up
323 os
. unlink ( options
. socket_filename
)
327 def do_client ( options
, args
):
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
)
339 def do_oneshot ( options
, paths
):
341 cycler
. init ( options
, paths
)
344 parser
= OptionParser ( version
= "%prog " + VERSION
,
345 description
= "Cycles through random background images." ,
347 " \n (server) %prog [options] dir [dir2 ...]"
348 " \n (client) %prog [options] [next|prev|rescan|reload|pause] [...]"
349 " \n The first instance to be run will be the server. \n "
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: %def ault]" )
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: %def ault]" )
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." )
384 parser
= build_parser ()
385 options
, args
= parser
. parse_args ( sys
. argv
[ 1 :])
387 if options
. verbose
== 1 :
388 logging
. getLogger (). setLevel ( logging
. INFO
)
389 elif options
. verbose
>= 2 :
390 logging
. getLogger (). setLevel ( logging
. DEBUG
)
393 do_oneshot ( options
, args
)
395 if os
. path
. exists ( options
. socket_filename
):
396 do_client ( options
, args
)
398 do_server ( options
, args
)
401 if __name__
== "__main__" :