2 """Set a random background image (XWin)
4 Select a random image from a (list of) directory(s)
5 and set it as the desktop wallpaper (display it in the root window)
10 __version__ = "$Revision$"[11:-2]
11 __revision__ = "$Id$"[5:-2]
12 __date__ = "$Date$"[7:-2]
14 __author__ = "Oleg Broytman <phd@phdru.name>"
15 __copyright__ = "Copyright (C) 2000-2011 PhiloSoft Design"
16 __license__ = "GNU GPL"
18 __all__ = ['host', 'port', 'change']
22 from ConfigParser import SafeConfigParser
29 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
32 def error(error_str, error_code=1):
33 sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
37 xsetbg_dir = os.path.dirname(os.path.abspath(__file__))
40 config = SafeConfigParser()
41 config.read("xsetbg.conf")
43 if config.has_option("images", "directory") or \
44 config.has_option("images", "directory0") or \
45 config.has_option("images", "directory1"):
47 if config.has_option("images", "directory"):
48 image_dirs.append(config.get("images", "directory"))
49 if config.has_option("images", "directory0"):
50 image_dirs.append(config.get("images", "directory0"))
51 if config.has_option("images", "directory1"):
52 image_dirs.append(config.get("images", "directory1"))
55 option = "directory%d" % i
56 if config.has_option("images", option):
57 image_dirs.append(config.get("images", option))
62 image_dirs = ["images"]
64 image_dirs = [os.path.join(xsetbg_dir,
65 os.path.expandvars(os.path.expanduser(dirname)))
66 for dirname in image_dirs
69 # minimum time in seconds between background image changes
70 if config.has_option("xsetbg", "min_pause"):
71 min_pause = config.getint("xsetbg", "min_pause")
75 borders = config.get("xsetbg", "borders").split(',')
76 if config.has_option("xsetbg", "borders"):
77 borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
79 borders = ["darkcyan", "steelblue", "midnightblue"]
81 # minimum time in seconds between occurences of the same image
82 if config.has_option("xsetbg", "min_delay"):
83 min_delay = config.getint("xsetbg", "min_delay")
85 min_delay = 3600*24 # 24 hours
88 if config.has_option("httpd", "host"):
89 host = config.get("httpd", "host")
93 if config.has_option("httpd", "port"):
94 port = config.getint("httpd", "port")
96 error("Config must specify a port to listen. Abort.")
101 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
102 # readable only by the user
103 global_db_name = "xsetbg.db"
107 timestamp_key = "timestamp"
108 filename_key = "filename"
109 old_filename_key = "old_filename"
112 # Create the database if it is not exists yet.
115 global_db = shelve.open(global_db_name, flag='c')
116 except anydbm.error, msg:
117 if str(msg) == "db type could not be determined":
118 os.remove(global_db_name)
119 global_db = shelve.open(global_db_name, flag='c')
121 # Remove old filenames
122 old_time = time() - min_delay
124 to_delete = [timestamp_key]
125 for key in global_db.keys():
126 if key.startswith('/') and global_db[key] < old_time:
127 to_delete.append(key)
129 for key in to_delete:
135 global_db.close() # Close DB in the parent process
140 for image_dir in image_dirs:
141 # List images in all subdirectories
142 for dirpath, dirs, files in os.walk(image_dir):
143 images.extend([os.path.join(dirpath, file) for file in files])
146 error("No images found. Abort.")
149 def change(force=False):
150 # Use the program's file as the lock file:
151 # lock it to prevent two processes run in parallel.
152 lock_file = open("xsetbg.py", 'r')
154 flock(lock_file, LOCK_EX|LOCK_NB)
155 except IOError: # already locked
162 # Reopen the global persistent dictionary
163 global_db = shelve.open(global_db_name, 'w')
165 timestamp = global_db.get(timestamp_key)
166 current_time = time()
168 if not force and timestamp is not None and \
169 current_time - timestamp < min_pause: # Too early to change background
173 global_db[timestamp_key] = current_time
175 # Select a random image and check if we've seen it recently;
176 # loop until we can find a new image (never seen before) or old enough.
177 for i in xrange(len(images)): # ensure the loop is not infinite
178 image_name = random.choice(images)
179 if global_db.has_key(image_name):
180 image_time = global_db[image_name]
181 if current_time - image_time > min_delay:
185 global_db[image_name] = current_time
188 if global_db.has_key(filename_key):
189 global_db[old_filename_key] = global_db[filename_key]
190 global_db[filename_key] = image_name
192 program_options = ["xli", "-onroot", "-quiet"] + \
193 ["-center", "-border", random.choice(borders), "-zoom", "auto",
196 rc = subprocess.call(program_options)
198 error("cannot execute xli!")
201 # Unlock and close the lock file
202 flock(lock_file, LOCK_UN)
204 # Flush and close the global persistent dictionary
205 if global_db: global_db.close()