]> git.phdru.name Git - xsetbg.git/blob - xsetbg.py
More comments.
[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 global_db.close() # Close DB in parent process
127
128
129 # DB keys
130 timestamp_key = "timestamp"
131 filename_key = "filename"
132 old_filename_key = "old_filename"
133
134
135 images = []
136
137 for image_dir in image_dirs:
138    # List images in all subdirectories
139    for dirpath, dirs, files in os.walk(image_dir):
140       images.extend([os.path.join(dirpath, file) for file in files])
141
142 if not images:
143    error("No images found. Abort.")
144
145
146 try:
147    from PIL import Image
148    use_PIL = True
149 except ImportError:
150    use_PIL = False
151
152
153 def run():
154    if len(sys.argv) not in (1, 2):
155       usage()
156
157    force = False
158    if len(sys.argv) == 2:
159       if sys.argv[1] == "force":
160          force = True
161       else:
162          usage()
163
164    # Use the program's file as the lock file:
165    # lock it to prevent two processes run in parallel.
166    lock_file = open("xsetbg.py", 'r')
167    try:
168       flock(lock_file , LOCK_EX|LOCK_NB)
169    except IOError: # already locked
170       lock_file.close()
171       return
172
173
174    global_db = None
175    try:
176       # Re-seed the RNG; this is neccessary because ReadyExecd forks
177       # and RNG in a child process got the same seed from the parent
178       # after every fork.
179       random.seed()
180
181       # Reopen the global persistent dictionary
182       global_db = shelve.open(global_db_name, 'w')
183
184       timestamp = global_db.get(timestamp_key)
185       current_time = time()
186
187       if not force and timestamp is not None and \
188          current_time - timestamp < min_pause: # Too early to change background
189             return
190
191       # Save current time
192       global_db[timestamp_key] = current_time
193
194       # Select a random image and check if we've seen it recently;
195       # loop until we can find a new image (never seen before) or old enough.
196       for i in xrange(len(images)): # ensure the loop is not infinite
197          image_name = random.choice(images)
198          if global_db.has_key(image_name):
199             image_time = global_db[image_name]
200             if current_time - image_time > min_delay:
201                break
202          else:
203             break
204       global_db[image_name] = current_time
205
206       border = random.choice(borders)
207       root, ext = os.path.splitext(image_name)
208
209       # Save filename
210       if global_db.has_key(filename_key):
211          global_db[old_filename_key] = global_db[filename_key]
212       global_db[filename_key] = image_name
213
214       placement_options = []
215       if use_PIL:
216          image = Image.open(image_name, 'r')
217          im_w, im_h = image.size
218          del image
219          if (im_w > screen_width) or (im_h > screen_height):
220             zoom = min(screen_width*100//im_w, screen_height*100//im_h)
221             if zoom > 0: placement_options = ["-zoom", str(zoom)]
222
223    finally:
224       # Unlock and close the lock file
225       flock(lock_file , LOCK_UN)
226       lock_file.close()
227       # Flush and close the global persistent dictionary
228       if global_db: global_db.close()
229
230
231    if ext.lower() in (".bmp", ".png"):
232       # xsetbg does not recognize BMP files.
233       # PNG files have gamma settings, and xli can adapt it to the display gamma;
234       # xloadimage/xview/xsetbg display them with wrong gamma.
235       program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
236          ["-center", "-border", border, image_name]
237       os.execlp(*program_options)
238       error("cannot execute xli!")
239    else:
240       # ...but xli failed to load many image types, use xsetbg for them
241       program_options = ["xsetbg", "xsetbg"] + placement_options + \
242          ["-center", "-border", border, image_name]
243       os.execlp(*program_options)
244       error("cannot execute xsetbg!")
245
246
247 if __name__ == "__main__":
248    run()