]> git.phdru.name Git - xsetbg.git/blob - xsetbg.py
Removed last traces of ReadyExec.
[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 Broytman <phd@phd.pp.ru>"
15 __copyright__ = "Copyright (C) 2000-2010 PhiloSoft Design"
16 __license__ = "GNU GPL"
17
18
19 import sys, os
20 import subprocess
21
22
23 def error(error_str, error_code=1):
24    sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
25    sys.exit(error_code)
26
27
28 from ConfigParser import SafeConfigParser
29
30 xsetbg_dir = os.path.dirname(os.path.abspath(__file__))
31 os.chdir(xsetbg_dir)
32
33 config = SafeConfigParser()
34 config.read("xsetbg.conf")
35
36 if config.has_option("images", "directory") or \
37    config.has_option("images", "directory0") or \
38    config.has_option("images", "directory1"):
39    image_dirs = []
40    if config.has_option("images", "directory"):
41       image_dirs.append(config.get("images", "directory"))
42    if config.has_option("images", "directory0"):
43       image_dirs.append(config.get("images", "directory0"))
44    if config.has_option("images", "directory1"):
45       image_dirs.append(config.get("images", "directory1"))
46    i = 2
47    while True:
48       option = "directory%d" % i
49       if config.has_option("images", option):
50          image_dirs.append(config.get("images", option))
51          i += 1
52       else:
53          break
54 else:
55    image_dirs = ["images"]
56
57 image_dirs = [os.path.join(xsetbg_dir,
58    os.path.expandvars(os.path.expanduser(dirname)))
59       for dirname in image_dirs
60 ]
61
62 # minimum time in seconds between background image changes
63 if config.has_option("xsetbg", "min_pause"):
64    min_pause = config.getint("xsetbg", "min_pause")
65 else:
66    min_pause = 60
67
68 borders = config.get("xsetbg", "borders").split(',')
69 if config.has_option("xsetbg", "borders"):
70    borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
71 else:
72    borders = ["darkcyan", "steelblue", "midnightblue"]
73
74 # minimum time in seconds between occurences of the same image
75 if config.has_option("xsetbg", "min_delay"):
76    min_delay = config.getint("xsetbg", "min_delay")
77 else:
78    min_delay = 3600*24 # 24 hours
79
80 # httpd settings
81 if config.has_option("httpd", "host"):
82    host = config.get("httpd", "host")
83 else:
84    host = 'localhost'
85
86 if config.has_option("httpd", "port"):
87    port = config.getint("httpd", "port")
88 else:
89    error("Config must specify a port to listen. Abort.")
90
91 del config
92
93
94 os.umask(0066) # octal; -rw-------; make the global persistent dictionary
95                # readable only by the user
96 global_db_name = "xsetbg.db"
97
98
99 # DB keys
100 timestamp_key = "timestamp"
101 filename_key = "filename"
102 old_filename_key = "old_filename"
103
104
105 import random
106 import anydbm, shelve
107 from time import time
108 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
109
110 # Create the database if it is not exists yet.
111
112 try:
113    global_db = shelve.open(global_db_name, flag='c')
114 except anydbm.error, msg:
115    if str(msg) == "db type could not be determined":
116       os.remove(global_db_name)
117       global_db = shelve.open(global_db_name, flag='c')
118
119 # Remove old filenames
120 old_time = time() - min_delay
121
122 to_delete = [timestamp_key]
123 for key in global_db.keys():
124    if key.startswith('/') and global_db[key] < old_time:
125       to_delete.append(key)
126
127 for key in to_delete:
128    try:
129       del global_db[key]
130    except KeyError:
131       pass
132
133 global_db.close() # Close DB in the parent process
134
135
136 images = []
137
138 for image_dir in image_dirs:
139    # List images in all subdirectories
140    for dirpath, dirs, files in os.walk(image_dir):
141       images.extend([os.path.join(dirpath, file) for file in files])
142
143 if not images:
144    error("No images found. Abort.")
145
146
147 def published(func):
148     func._wsgi_published = True
149     return func
150
151 @published
152 def ping(force=False):
153    # Use the program's file as the lock file:
154    # lock it to prevent two processes run in parallel.
155    lock_file = open("xsetbg.py", 'r')
156    try:
157       flock(lock_file, LOCK_EX|LOCK_NB)
158    except IOError: # already locked
159       lock_file.close()
160       return
161
162
163    global_db = None
164    try:
165       # Reopen the global persistent dictionary
166       global_db = shelve.open(global_db_name, 'w')
167
168       timestamp = global_db.get(timestamp_key)
169       current_time = time()
170
171       if not force and timestamp is not None and \
172          current_time - timestamp < min_pause: # Too early to change background
173             return
174
175       # Save current time
176       global_db[timestamp_key] = current_time
177
178       # Select a random image and check if we've seen it recently;
179       # loop until we can find a new image (never seen before) or old enough.
180       for i in xrange(len(images)): # ensure the loop is not infinite
181          image_name = random.choice(images)
182          if global_db.has_key(image_name):
183             image_time = global_db[image_name]
184             if current_time - image_time > min_delay:
185                break
186          else:
187             break
188       global_db[image_name] = current_time
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       program_options = ["xli", "-onroot", "-quiet"] + \
196          ["-center", "-border", random.choice(borders), "-zoom", "auto",
197             image_name]
198
199       rc = subprocess.call(program_options)
200       if rc:
201          error("cannot execute xli!")
202
203    finally:
204       # Unlock and close the lock file
205       flock(lock_file, LOCK_UN)
206       lock_file.close()
207       # Flush and close the global persistent dictionary
208       if global_db: global_db.close()
209
210 @published
211 def force():
212     ping(force=True)
213
214 @published
215 def stop():
216     QuitWSGIServer._quit_flag = True
217
218
219 from wsgiref.handlers import SimpleHandler
220 from wsgiref import simple_server
221 simple_server.ServerHandler = SimpleHandler # Stop logging to stdout
222 from wsgiref.simple_server import WSGIServer, make_server
223
224 g = globals().copy()
225 commands = dict([(name, g[name]) for name in g
226     if getattr(g[name], '_wsgi_published', False)])
227 del g
228
229 class QuitWSGIServer(WSGIServer):
230     _quit_flag = False
231
232     def serve_forever(self):
233         while not self._quit_flag:
234             self.handle_request()
235
236 def app(env, start_response):
237     command = env['PATH_INFO'][1:] # Remove the leading slash
238     if command not in commands:
239         status = '404 Not found'
240         response_headers = [('Content-type', 'text/plain')]
241         start_response(status, response_headers)
242         return ['The command was not found.\n']
243
244     try:
245         commands[command]()
246     except:
247         status = '500 Error'
248         response_headers = [('Content-type', 'text/plain')]
249         start_response(status, response_headers)
250         return ['Error occured!\n']
251
252     status = '200 OK'
253     response_headers = [('Content-type', 'text/plain')]
254     start_response(status, response_headers)
255     return ['Ok\n']
256
257 force()
258 httpd = make_server(host, port, app, server_class=QuitWSGIServer)
259 httpd.serve_forever()