]>
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 )
137 def get_current_image ( self
):
138 return self
. list [ self
. imagePointer
]
140 def __inc_in_range ( self
, n
, amount
= 1 , rangeMax
= None , rangeMin
= 0 ):
141 if rangeMax
== None : rangeMax
= len ( self
. list )
143 return ( n
+ amount
) % rangeMax
145 def get_next_image ( self
):
146 self
. imagePointer
= self
.__ inc
_ in
_ range
( self
. imagePointer
)
147 imageName
= self
. list [ self
. imagePointer
]
148 logging
. debug ( "Picked file ' %s ' (pointer= %d ) from list" % ( imageName
, self
. imagePointer
))
151 def get_prev_image ( self
):
152 self
. imagePointer
= self
.__ inc
_ in
_ range
( self
. imagePointer
, amount
=- 1 )
153 imageName
= self
. list [ self
. imagePointer
]
154 logging
. debug ( "Picked file ' %s ' (pointer= %d ) from list" % ( imageName
, self
. imagePointer
))
158 return len ( self
. list ) == 0
160 class FolderRandomFileList ( BaseFileList
):
161 """A file list that will pick a file randomly within a directory. Each
162 directory has the same chance of being chosen."""
164 self
. directories
= {}
166 def scan_paths ( self
):
169 def add_path ( self
, path
):
170 logging
. debug ( 'Added path " %s " to the list' % path
)
171 for dirpath
, dirs
, filenames
in os
. walk ( path
):
172 logging
. debug ( 'Scanning " %s " for images' % dirpath
)
173 if self
. directories
. has_key ( dirpath
):
175 filenames
= list ( filter_images ( filenames
))
177 self
. directories
[ dirpath
] = filenames
178 logging
. debug ( 'Adding " %s " to " %s "' % ( filenames
, dirpath
))
180 logging
. debug ( "No images found in ' %s '" % dirpath
)
182 def get_next_image ( self
):
183 directory
= random
. choice ( self
. directories
. keys ())
184 logging
. debug ( 'directory: " %s "' % directory
)
185 filename
= random
. choice ( self
. directories
[ directory
])
186 logging
. debug ( 'filename: " %s "' % filename
)
187 return os
. path
. join ( directory
, filename
)
190 return len ( self
. directories
. values ()) == 0
193 class Cycler ( object ):
194 def init ( self
, options
, paths
):
195 self
. cycle_time
= options
. cycle_time
196 self
. history_filename
= options
. history_filename
198 logging
. debug ( "Initialising wallchanger" )
199 wallchanger
. init ( options
. background_colour
, options
. permanent
)
201 logging
. debug ( "Initialising file list" )
202 if options
. all_random
:
203 self
. filelist
= AllRandomFileList ()
204 elif options
. folder_random
:
205 self
. filelist
= FolderRandomFileList ()
207 self
. filelist
= RandomFileList ()
210 self
. filelist
. add_path ( path
)
212 if self
. filelist
. load_cache ( self
. history_filename
):
213 logging
. debug ( "Loaded cache successfully" )
215 logging
. debug ( "Could not load cache" )
216 self
. filelist
. scan_paths ()
218 if self
. filelist
. is_empty ():
219 logging
. error ( "No images were found. Exiting..." )
226 self
. filelist
. store_cache ( self
. history_filename
)
228 def find_files ( self
, options
, paths
):
233 image
= self
. filelist
. get_next_image ()
234 wallchanger
. set_image ( image
)
238 if self
. task
is not None :
240 self
. task
= asyncsched
. schedule ( self
. cycle_time
, next
)
241 logging
. debug ( "Reset timer for %s seconds" % self
. cycle_time
)
243 def cmd_reload ( self
):
244 image
= self
. filelist
. get_current_image ()
245 wallchanger
. set_image ( image
)
249 image
= self
. filelist
. get_next_image ()
250 wallchanger
. set_image ( image
)
254 image
= self
. filelist
. get_prev_image ()
255 wallchanger
. set_image ( image
)
258 def cmd_rescan ( self
):
259 self
. filelist
. scan_paths ()
263 if self
. task
is not None :
270 class Server ( asynchat
. async_chat
):
271 def __init__ ( self
, cycler
, conn
, addr
):
272 asynchat
. async_chat
.__ init
__ ( self
, conn
= conn
)
275 self
. set_terminator ( " \n " )
277 def collect_incoming_data ( self
, data
):
278 self
. ibuffer
. append ( data
)
280 def found_terminator ( self
):
281 line
= "" . join ( self
. ibuffer
). lower ()
283 prefix
, cmd
= line
. split ( None , 1 )
285 logging
. debug ( 'Bad line received " %s "' % line
)
287 if hasattr ( self
. cycler
, "cmd_" + cmd
):
288 logging
. debug ( 'Executing command " %s "' % cmd
)
289 getattr ( self
. cycler
, "cmd_" + cmd
)()
291 logging
. debug ( 'Unknown command received " %s "' % cmd
)
295 class Listener ( asyncore
. dispatcher
):
296 def __init__ ( self
, socket_filename
, cycler
):
297 asyncore
. dispatcher
.__ init
__ ( self
)
299 self
. create_socket ( socket
. AF_UNIX
, socket
. SOCK_STREAM
)
300 self
. bind ( socket_filename
)
301 self
. listen ( 2 ) # Backlog = 2
303 def handle_accept ( self
):
304 conn
, addr
= self
. accept ()
305 Server ( self
. cycler
, conn
, addr
)
311 def do_server ( options
, paths
):
314 listener
= Listener ( options
. socket_filename
, cycler
)
315 # Initialisation of Cycler delayed so we grab the socket quickly
316 cycler
. init ( options
, paths
)
319 except KeyboardInterrupt :
323 # Make sure that the socket is cleaned up
325 os
. unlink ( options
. socket_filename
)
329 def do_client ( options
, args
):
332 sock
= socket
. socket ( socket
. AF_UNIX
, socket
. SOCK_STREAM
)
333 sock
. connect ( options
. socket_filename
)
334 sock
= sock
. makefile ()
335 for i
, cmd
in enumerate ( args
):
336 sock
. write ( "cmd %s \n " % cmd
)
337 if i
< len ( args
) - 1 :
338 time
. sleep ( options
. cycle_time
)
341 def do_oneshot ( options
, paths
):
343 cycler
. init ( options
, paths
)
346 parser
= OptionParser ( version
= "%prog " + VERSION
,
347 description
= "Cycles through random background images." ,
349 " \n (server) %prog [options] dir [dir2 ...]"
350 " \n (client) %prog [options] [next|prev|rescan|reload|pause] [...]"
351 " \n The first instance to be run will be the server. \n "
353 parser
. add_option ( "-p" , "--permanent" ,
354 action
= "store_true" , dest
= "permanent" , default
= False ,
355 help = "Make the background permanent. Note: This will cause all machines logged in with this account to simultaneously change background [Default: %def ault]" )
356 parser
. add_option ( "-v" , '-d' , "--verbose" , "--debug" ,
357 action
= "count" , dest
= "verbose" , default
= 0 ,
358 help = "Make the louder (good for debugging, or those who are curious)" )
359 parser
. add_option ( "-b" , "--background-colour" ,
360 action
= "store" , type = "string" , dest
= "background_colour" , default
= "black" ,
361 help = "Change the default background colour that is displayed if the image is not in the correct aspect ratio [Default: %def ault]" )
362 parser
. add_option ( "--all-random" ,
363 action
= "store_true" , dest
= "all_random" , default
= False ,
364 help = "Make sure that all images have been displayed before repeating an image" )
365 parser
. add_option ( "-1" , "--oneshot" ,
366 action
= "store_true" , dest
= "oneshot" , default
= False ,
367 help = "Set one random image and terminate immediately." )
368 parser
. add_option ( "--folder-random" ,
369 action
= "store_true" , dest
= "folder_random" , default
= False ,
370 help = "Give each folder an equal chance of having an image selected from it" )
371 parser
. add_option ( "--convert" ,
372 action
= "store_true" , dest
= "convert" , default
= False ,
373 help = "Do conversions using ImageMagick or PIL, don't rely on the window manager" )
374 parser
. add_option ( "--cycle-time" ,
375 action
= "store" , type = "int" , default
= 1800 , dest
= "cycle_time" ,
376 help = "Cause the image to cycle every X seconds" )
377 parser
. add_option ( "--socket" ,
378 action
= "store" , type = "string" , dest
= "socket_filename" , default
= os
. path
. expanduser ( '~/.randombg_socket' ),
379 help = "Location of the command/control socket." )
380 parser
. add_option ( "--history-file" ,
381 action
= "store" , type = "string" , dest
= "history_filename" , default
= os
. path
. expanduser ( '~/.randombg_historyfile' ),
382 help = "Stores the location of the last image to be loaded." )
386 parser
= build_parser ()
387 options
, args
= parser
. parse_args ( sys
. argv
[ 1 :])
389 if options
. verbose
== 1 :
390 logging
. getLogger (). setLevel ( logging
. INFO
)
391 elif options
. verbose
>= 2 :
392 logging
. getLogger (). setLevel ( logging
. DEBUG
)
395 do_oneshot ( options
, args
)
397 if os
. path
. exists ( options
. socket_filename
):
398 do_client ( options
, args
)
400 do_server ( options
, args
)
403 if __name__
== "__main__" :