]>
code.delx.au - bg-scripts/blob - bin/randombg.py
6 import asyncore
, asynchat
, socket
7 import os
, os
. path
, random
, sys
, time
8 from optparse
import OptionParser
10 from logging
import debug
, info
, warning
, error
, critical
11 logging
. basicConfig ( format
= " %(levelname)s : %(message)s " )
13 import cPickle
as pickle
21 except ImportError , e
:
22 critical ( "Missing libraries! Exiting..." )
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
:
35 class BaseFileList ( object ):
36 """Base file list implementation"""
38 raise NotImplementedError ()
40 def add_path ( self
, path
):
41 raise NotImplementedError ()
43 def store_cache ( self
, path
):
46 def load_cache ( self
, filename
, rescanPaths
= False ):
49 def get_next_image ( self
):
50 raise NotImplementedError ()
52 def get_prev_image ( self
):
53 raise NotImplementedError ()
55 def get_current_image ( self
):
56 raise NotImplementedError ()
62 class RandomFileList ( BaseFileList
):
66 self
. last_image
= None
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
))
74 def add_path ( self
, path
):
75 self
. paths
. append ( path
)
76 debug ( 'Added path " %s " to the list' % path
)
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
85 return len ( self
. list ) == 0
88 class AllRandomFileList ( BaseFileList
):
94 # Scan the input directory, and then randomize the file list
96 debug ( "Scanning paths" )
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
))
106 random
. shuffle ( self
. list )
108 def add_path ( self
, path
):
109 self
. paths
. append ( path
)
110 debug ( 'Added path " %s " to the list' % path
)
112 def store_cache ( self
, filename
):
114 fd
= open ( filename
, 'wb' )
115 pickle
. dump ( obj
= self
, file = fd
, protocol
= 2 )
116 debug ( "Cache successfully stored" )
118 warning ( "Storing cache: %s " % e
)
120 def load_cache ( self
, filename
, rescanPaths
= False ):
121 debug ( 'Attempting to load cache from " %s "' % filename
)
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
))
132 debug ( "Ignoring cache, path lists do not match" )
134 warning ( "Loading cache: %s " % e
)
136 def get_current_image ( self
):
137 return self
. list [ self
. imagePointer
]
139 def __inc_in_range ( self
, n
, amount
= 1 , rangeMax
= None , rangeMin
= 0 ):
140 if rangeMax
== None : rangeMax
= len ( self
. list )
142 return ( n
+ amount
) % rangeMax
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
))
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
))
157 return len ( self
. list ) == 0
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."""
163 self
. directories
= {}
165 def scan_paths ( self
):
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
):
174 filenames
= list ( filter_images ( filenames
))
176 self
. directories
[ dirpath
] = filenames
177 debug ( 'Adding " %s " to " %s "' % ( filenames
, dirpath
))
179 debug ( "No images found in ' %s '" % dirpath
)
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
)
189 return len ( self
. directories
. values ()) == 0
192 class Cycler ( object ):
193 def init ( self
, options
, paths
):
194 self
. cycle_time
= options
. cycle_time
195 self
. history_filename
= options
. history_filename
197 debug ( "Initialising wallchanger" )
198 wallchanger
. init ( options
. background_colour
, options
. permanent
)
200 debug ( "Initialising file list" )
201 if options
. all_random
:
202 self
. filelist
= AllRandomFileList ()
203 elif options
. folder_random
:
204 self
. filelist
= FolderRandomFileList ()
206 self
. filelist
= RandomFileList ()
209 self
. filelist
. add_path ( path
)
211 if self
. filelist
. load_cache ( self
. history_filename
):
212 debug ( "Loaded cache successfully" )
214 debug ( "Could not load cache" )
215 self
. filelist
. scan_paths ()
217 if self
. filelist
. is_empty ():
218 error ( "No images were found. Exiting..." )
225 self
. filelist
. store_cache ( self
. history_filename
)
227 def find_files ( self
, options
, paths
):
232 image
= self
. filelist
. get_next_image ()
233 wallchanger
. set_image ( image
)
237 if self
. task
is not None :
239 self
. task
= asyncsched
. schedule ( self
. cycle_time
, next
)
240 debug ( "Reset timer for %s seconds" % self
. cycle_time
)
242 def cmd_reload ( self
):
243 image
= self
. filelist
. get_current_image ()
244 wallchanger
. set_image ( image
)
248 image
= self
. filelist
. get_next_image ()
249 wallchanger
. set_image ( image
)
253 image
= self
. filelist
. get_prev_image ()
254 wallchanger
. set_image ( image
)
257 def cmd_rescan ( self
):
258 self
. filelist
. scan_paths ()
262 if self
. task
is not None :
269 class Server ( asynchat
. async_chat
):
270 def __init__ ( self
, cycler
, conn
, addr
):
271 asynchat
. async_chat
.__ init
__ ( self
, conn
= conn
)
274 self
. set_terminator ( " \n " )
276 def collect_incoming_data ( self
, data
):
277 self
. ibuffer
. append ( data
)
279 def found_terminator ( self
):
280 line
= "" . join ( self
. ibuffer
). lower ()
282 prefix
, cmd
= line
. split ( None , 1 )
284 debug ( 'Bad line received " %s "' % line
)
286 if hasattr ( self
. cycler
, "cmd_" + cmd
):
287 debug ( 'Executing command " %s "' % cmd
)
288 getattr ( self
. cycler
, "cmd_" + cmd
)()
290 debug ( 'Unknown command received " %s "' % cmd
)
294 class Listener ( asyncore
. dispatcher
):
295 def __init__ ( self
, socket_filename
, cycler
):
296 asyncore
. dispatcher
.__ init
__ ( self
)
298 self
. create_socket ( socket
. AF_UNIX
, socket
. SOCK_STREAM
)
299 self
. bind ( socket_filename
)
300 self
. listen ( 2 ) # Backlog = 2
302 def handle_accept ( self
):
303 conn
, addr
= self
. accept ()
304 Server ( self
. cycler
, conn
, addr
)
310 def do_server ( options
, paths
):
313 listener
= Listener ( options
. socket_filename
, cycler
)
314 # Initialisation of Cycler delayed so we grab the socket quickly
315 cycler
. init ( options
, paths
)
318 except KeyboardInterrupt :
322 # Make sure that the socket is cleaned up
324 os
. unlink ( options
. socket_filename
)
328 def do_client ( options
, args
):
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
)
337 time
. sleep ( options
. cycle_time
)
340 def do_oneshot ( options
, paths
):
342 cycler
. init ( options
, paths
)
345 parser
= OptionParser ( version
= "%prog " + VERSION
,
346 description
= "Cycles through random background images." ,
348 " \n (server) %prog [options] dir [dir2 ...]"
349 " \n (client) %prog [options] [next|prev|rescan|reload|pause] [...]"
350 " \n The first instance to be run will be the server. \n "
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: %def ault]" )
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: %def ault]" )
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." )
385 parser
= build_parser ()
386 options
, args
= parser
. parse_args ( sys
. argv
[ 1 :])
388 if options
. verbose
== 1 :
389 logging
. getLogger (). setLevel ( logging
. INFO
)
390 elif options
. verbose
>= 2 :
391 logging
. getLogger (). setLevel ( logging
. DEBUG
)
394 do_oneshot ( options
, args
)
396 if os
. path
. exists ( options
. socket_filename
):
397 do_client ( options
, args
)
399 do_server ( options
, args
)
402 if __name__
== "__main__" :