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