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