]> git.phdru.name Git - xsetbg.git/blob - xsetbg.py
"BroytMann" => "Broytman".
[xsetbg.git] / xsetbg.py
1 #! /usr/bin/env python
2 """Set a random background image (XWin)
3
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)
6 using xli or xsetbg programs.
7
8 """
9
10 __version__ = "$Revision$"[11:-2]
11 __revision__ = "$Id$"[5:-2]
12 __date__ = "$Date$"[7:-2]
13
14 __author__ = "Oleg Broytman <phd@phd.pp.ru>"
15 __copyright__ = "Copyright (C) 2000-2009 PhiloSoft Design"
16 __license__ = "GNU GPL"
17
18
19 import sys, os
20
21
22 def usage():
23    sys.stderr.write("%s version %s\n" % (sys.argv[0], __version__))
24    sys.stderr.write("Usage: %s [force]\n" % sys.argv[0])
25    sys.exit(0)
26
27 def error(error_str, error_code=1):
28    sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
29    sys.exit(error_code)
30
31
32 from ConfigParser import SafeConfigParser
33
34 xsetbg_dir = os.path.join(os.environ["HOME"], "lib", "xsetbg")
35 os.chdir(xsetbg_dir)
36
37 config = SafeConfigParser()
38 config.read("xsetbg.conf")
39
40 if config.has_option("images", "directory") or \
41    config.has_option("images", "directory0") or \
42    config.has_option("images", "directory1"):
43    image_dirs = []
44    if config.has_option("images", "directory"):
45       image_dirs.append(config.get("images", "directory"))
46    if config.has_option("images", "directory0"):
47       image_dirs.append(config.get("images", "directory0"))
48    if config.has_option("images", "directory1"):
49       image_dirs.append(config.get("images", "directory1"))
50    i = 2
51    while True:
52       option = "directory%d" % i
53       if config.has_option("images", option):
54          image_dirs.append(config.get("images", option))
55          i += 1
56       else:
57          break
58 else:
59    image_dirs = ["images"]
60
61 image_dirs = [os.path.join(xsetbg_dir,
62    os.path.expandvars(os.path.expanduser(dirname)))
63       for dirname in image_dirs
64 ]
65
66 # minimum time in seconds between background image changes
67 if config.has_option("xsetbg", "min_pause"):
68    min_pause = config.getint("xsetbg", "min_pause")
69 else:
70    min_pause = 60
71
72 borders = config.get("xsetbg", "borders").split(',')
73 if config.has_option("xsetbg", "borders"):
74    borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
75 else:
76    borders = ["darkcyan", "steelblue", "midnightblue"]
77
78 # minimum time in seconds between occurences of the same image
79 if config.has_option("xsetbg", "min_delay"):
80    min_delay = config.getint("xsetbg", "min_delay")
81 else:
82    min_delay = 3600*24 # 24 hours
83
84 del config
85
86
87 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
88                # readable only by the user
89 global_db_name = "xsetbg.db"
90
91
92 # DB keys
93 timestamp_key = "timestamp"
94 filename_key = "filename"
95 old_filename_key = "old_filename"
96
97
98 import random
99 import anydbm, shelve
100 from time import time
101 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
102
103 # Import pickle and all anydbm/shelve internal machinery, so that
104 # when ReadyExec forks they will be ready.
105 # Also create the database if it is not exists yet.
106
107 try:
108    global_db = shelve.open(global_db_name, flag='c')
109 except anydbm.error, msg:
110    if str(msg) == "db type could not be determined":
111       os.remove(global_db_name)
112       global_db = shelve.open(global_db_name, flag='c')
113
114 # Remove old filenames
115 old_time = time() - min_delay
116
117 to_delete = [timestamp_key]
118 for key in global_db.keys():
119    if key.startswith('/') and global_db[key] < old_time:
120       to_delete.append(key)
121
122 for key in to_delete:
123    try:
124       del global_db[key]
125    except KeyError:
126       pass
127
128 global_db.close() # Close DB in the parent process
129
130
131 images = []
132
133 for image_dir in image_dirs:
134    # List images in all subdirectories
135    for dirpath, dirs, files in os.walk(image_dir):
136       images.extend([os.path.join(dirpath, file) for file in files])
137
138 if not images:
139    error("No images found. Abort.")
140
141
142 def run():
143    if len(sys.argv) not in (1, 2):
144       usage()
145
146    force = False
147    if len(sys.argv) == 2:
148       if sys.argv[1] == "force":
149          force = True
150       else:
151          usage()
152
153    # Use the program's file as the lock file:
154    # lock it to prevent two processes run in parallel.
155    lock_file = open("xsetbg.py", 'r')
156    try:
157       flock(lock_file, LOCK_EX|LOCK_NB)
158    except IOError: # already locked
159       lock_file.close()
160       return
161
162
163    global_db = None
164    try:
165       # Re-seed the RNG; this is neccessary because ReadyExecd forks
166       # and RNG in a child process got the same seed from the parent
167       # after every fork.
168       random.seed()
169
170       # Reopen the global persistent dictionary
171       global_db = shelve.open(global_db_name, 'w')
172
173       timestamp = global_db.get(timestamp_key)
174       current_time = time()
175
176       if not force and timestamp is not None and \
177          current_time - timestamp < min_pause: # Too early to change background
178             return
179
180       # Save current time
181       global_db[timestamp_key] = current_time
182
183       # Select a random image and check if we've seen it recently;
184       # loop until we can find a new image (never seen before) or old enough.
185       for i in xrange(len(images)): # ensure the loop is not infinite
186          image_name = random.choice(images)
187          if global_db.has_key(image_name):
188             image_time = global_db[image_name]
189             if current_time - image_time > min_delay:
190                break
191          else:
192             break
193       global_db[image_name] = current_time
194
195       # Save filename
196       if global_db.has_key(filename_key):
197          global_db[old_filename_key] = global_db[filename_key]
198       global_db[filename_key] = image_name
199
200    finally:
201       # Unlock and close the lock file
202       flock(lock_file, LOCK_UN)
203       lock_file.close()
204       # Flush and close the global persistent dictionary
205       if global_db: global_db.close()
206
207    program_options = ["xli", "xli", "-onroot", "-quiet"] + \
208       ["-center", "-border", random.choice(borders), "-zoom", "auto",
209          image_name]
210
211    os.execlp(*program_options)
212    error("cannot execute xli!")
213
214
215 if __name__ == "__main__":
216    run()