]> git.phdru.name Git - xsetbg.git/blob - xsetbg.py
ce3ffad81a0c3db08c712e9802191703da30c108
[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 # Import pickle and all anydbm/shelve internal machinery, so that
111 # when ReadyExec forks they will be ready.
112 # Also create the database if it is not exists yet.
113
114 try:
115    global_db = shelve.open(global_db_name, flag='c')
116 except anydbm.error, msg:
117    if str(msg) == "db type could not be determined":
118       os.remove(global_db_name)
119       global_db = shelve.open(global_db_name, flag='c')
120
121 # Remove old filenames
122 old_time = time() - min_delay
123
124 to_delete = [timestamp_key]
125 for key in global_db.keys():
126    if key.startswith('/') and global_db[key] < old_time:
127       to_delete.append(key)
128
129 for key in to_delete:
130    try:
131       del global_db[key]
132    except KeyError:
133       pass
134
135 global_db.close() # Close DB in the parent process
136
137
138 images = []
139
140 for image_dir in image_dirs:
141    # List images in all subdirectories
142    for dirpath, dirs, files in os.walk(image_dir):
143       images.extend([os.path.join(dirpath, file) for file in files])
144
145 if not images:
146    error("No images found. Abort.")
147
148
149 def published(func):
150     func._wsgi_published = True
151     return func
152
153 @published
154 def ping(force=False):
155    # Use the program's file as the lock file:
156    # lock it to prevent two processes run in parallel.
157    lock_file = open("xsetbg.py", 'r')
158    try:
159       flock(lock_file, LOCK_EX|LOCK_NB)
160    except IOError: # already locked
161       lock_file.close()
162       return
163
164
165    global_db = None
166    try:
167       # Reopen the global persistent dictionary
168       global_db = shelve.open(global_db_name, 'w')
169
170       timestamp = global_db.get(timestamp_key)
171       current_time = time()
172
173       if not force and timestamp is not None and \
174          current_time - timestamp < min_pause: # Too early to change background
175             return
176
177       # Save current time
178       global_db[timestamp_key] = current_time
179
180       # Select a random image and check if we've seen it recently;
181       # loop until we can find a new image (never seen before) or old enough.
182       for i in xrange(len(images)): # ensure the loop is not infinite
183          image_name = random.choice(images)
184          if global_db.has_key(image_name):
185             image_time = global_db[image_name]
186             if current_time - image_time > min_delay:
187                break
188          else:
189             break
190       global_db[image_name] = current_time
191
192       # Save filename
193       if global_db.has_key(filename_key):
194          global_db[old_filename_key] = global_db[filename_key]
195       global_db[filename_key] = image_name
196
197       program_options = ["xli", "-onroot", "-quiet"] + \
198          ["-center", "-border", random.choice(borders), "-zoom", "auto",
199             image_name]
200
201       rc = subprocess.call(program_options)
202       if rc:
203          error("cannot execute xli!")
204
205    finally:
206       # Unlock and close the lock file
207       flock(lock_file, LOCK_UN)
208       lock_file.close()
209       # Flush and close the global persistent dictionary
210       if global_db: global_db.close()
211
212 @published
213 def force():
214     ping(force=True)
215
216 @published
217 def stop():
218     QuitWSGIServer._quit_flag = True
219
220
221 from wsgiref.handlers import SimpleHandler
222 from wsgiref import simple_server
223 simple_server.ServerHandler = SimpleHandler # Stop logging to stdout
224 from wsgiref.simple_server import WSGIServer, make_server
225
226 g = globals().copy()
227 commands = dict([(name, g[name]) for name in g
228     if getattr(g[name], '_wsgi_published', False)])
229 del g
230
231 class QuitWSGIServer(WSGIServer):
232     _quit_flag = False
233
234     def serve_forever(self):
235         while not self._quit_flag:
236             self.handle_request()
237
238 def app(env, start_response):
239     command = env['PATH_INFO'][1:] # Remove the leading slash
240     if command not in commands:
241         status = '404 Not found'
242         response_headers = [('Content-type', 'text/plain')]
243         start_response(status, response_headers)
244         return ['The command was not found.\n']
245
246     try:
247         commands[command]()
248     except:
249         status = '500 Error'
250         response_headers = [('Content-type', 'text/plain')]
251         start_response(status, response_headers)
252         return ['Error occured!\n']
253
254     status = '200 OK'
255     response_headers = [('Content-type', 'text/plain')]
256     start_response(status, response_headers)
257     return ['Ok\n']
258
259 httpd = make_server(host, port, app, server_class=QuitWSGIServer)
260 httpd.serve_forever()