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