]> git.phdru.name Git - xsetbg.git/blob - xsetbg.py
XSetBg: select a random image and set it as the desktop wallpaper (display it in...
[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__ = "2.17.0"
10 __author__ = "Oleg BroytMann <phd@phd.pp.ru>"
11 __copyright__ = "Copyright (C) 2000-2006 PhiloSoft Design"
12 __revision__ = "$Id$"[5:-2]
13 __date__ = "$Date$"[7:-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 del config
95
96
97 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
98                # readable only by the user
99 global_db_name = "xsetbg.db"
100
101
102 import random
103 import anydbm, shelve
104 from time import time
105 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
106
107 # Import pickle and all anydbm/shelve internal machinery, so that
108 # when ReadyExec forks they will be ready.
109 # Also create the database if it is not exists yet.
110
111 try:
112    global_db = shelve.open(global_db_name, flag='c')
113 except anydbm.error, msg:
114    if str(msg) == "db type could not be determined":
115       os.remove(global_db_name)
116       global_db = shelve.open(global_db_name, flag='c')
117
118 global_db.close() # Close DB in parent process
119
120
121 # DB keys
122 timestamp_key = "timestamp"
123 filename_key = "filename"
124 old_filename_key = "old_filename"
125
126
127 images = []
128
129 for image_dir in image_dirs:
130    # List images in all subdirectories
131    for dirpath, dirs, files in os.walk(image_dir):
132       images.extend([os.path.join(dirpath, file) for file in files])
133
134 if not images:
135    error("No images found. Abort.")
136
137
138 try:
139    from PIL import Image
140    use_PIL = True
141 except ImportError:
142    use_PIL = False
143
144
145 def run():
146    if len(sys.argv) not in (1, 2):
147       usage()
148
149    force = False
150    if len(sys.argv) == 2:
151       if sys.argv[1] == "force":
152          force = True
153       else:
154          usage()
155
156    # Use the program's file as the lock file:
157    # lock it to prevent two processes run in parallel.
158    lock_file = open("xsetbg.py", 'r')
159    try:
160       flock(lock_file , LOCK_EX|LOCK_NB)
161    except IOError: # already locked
162       lock_file.close()
163       return
164
165
166    global_db = None
167    try:
168       # Re-seed the RNG; this is neccessary because ReadyExecd forks
169       # and RNG in a child process got the same seed from the parent
170       # after every fork.
171       random.seed()
172
173       # Reopen the global persistent dictionary
174       global_db = shelve.open(global_db_name, 'w')
175
176       timestamp = global_db.get(timestamp_key)
177       current_time = time()
178
179       if not force and timestamp is not None and \
180          current_time - timestamp < min_pause: # Too early to change background
181             return
182
183       # Save current time
184       global_db[timestamp_key] = current_time
185
186       border = random.choice(borders)
187       image_name = random.choice(images)
188       root, ext = os.path.splitext(image_name)
189
190       # Save filename
191       if global_db.has_key(filename_key):
192          global_db[old_filename_key] = global_db[filename_key]
193       global_db[filename_key] = image_name
194
195       placement_options = []
196       if use_PIL:
197          image = Image.open(image_name, 'r')
198          im_w, im_h = image.size
199          del image
200          if (im_w > screen_width) or (im_h > screen_height):
201             zoom = min(screen_width*100//im_w, screen_height*100//im_h)
202             if zoom > 0: placement_options = ["-zoom", str(zoom)]
203
204    finally:
205       # Unlock and close the lock file
206       flock(lock_file , LOCK_UN)
207       lock_file.close()
208       # Flush and close the global persistent dictionary
209       if global_db: global_db.close()
210
211
212    if ext.lower() in (".bmp", ".png"):
213       # xsetbg does not recognize BMP files.
214       # PNG files have gamma settings, and xli can adapt it to the display gamma;
215       # xloadimage/xview/xsetbg display them with wrong gamma.
216       program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
217          ["-center", "-border", border, image_name]
218       os.execlp(*program_options)
219       error("cannot execute xli!")
220    else:
221       # ...but xli failed to load many image types, use xsetbg for them
222       program_options = ["xsetbg", "xsetbg"] + placement_options + \
223          ["-center", "-border", border, image_name]
224       os.execlp(*program_options)
225       error("cannot execute xsetbg!")
226
227
228 if __name__ == "__main__":
229    run()