From: Oleg Broytman Date: Sat, 25 Jul 2015 22:25:36 +0000 (+0300) Subject: Convert xsetbg.py X-Git-Tag: v5.0.0~3 X-Git-Url: https://git.phdru.name/?p=xsetbg.git;a=commitdiff_plain;h=2f99c9bc2e47a031db73de534ff56fec6788854e Convert xsetbg.py --- diff --git a/xsetbg.py b/xsetbg.py old mode 100755 new mode 100644 index 37bd04c..8f4f6c8 --- a/xsetbg.py +++ b/xsetbg.py @@ -1,4 +1,3 @@ -#! /usr/bin/env python """Set a random background image (XWin) Select a random image from a (list of) directory(s) @@ -8,192 +7,129 @@ using xli program. """ __author__ = "Oleg Broytman " -__copyright__ = "Copyright (C) 2000-2014 PhiloSoft Design" +__copyright__ = "Copyright (C) 2000-2015 PhiloSoft Design" __license__ = "GNU GPL" __all__ = ['change'] - -import anydbm from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB from datetime import timedelta import os import random import re -import shelve import subprocess import sys from time import time from xsetbg_conf import xsetbg_dir, xsetbg_conf -from xsetbg_db import xsetbg_db_path - - -def error(error_str, error_code=1): - sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str)) - sys.exit(error_code) - - -if xsetbg_conf.has_option("images", "directory") or \ - xsetbg_conf.has_option("images", "directory0") or \ - xsetbg_conf.has_option("images", "directory1"): - image_dirs = [] - if xsetbg_conf.has_option("images", "directory"): - image_dirs.append(xsetbg_conf.get("images", "directory")) - if xsetbg_conf.has_option("images", "directory0"): - image_dirs.append(xsetbg_conf.get("images", "directory0")) - if xsetbg_conf.has_option("images", "directory1"): - image_dirs.append(xsetbg_conf.get("images", "directory1")) - i = 2 - while True: - option = "directory%d" % i - if xsetbg_conf.has_option("images", option): - image_dirs.append(xsetbg_conf.get("images", option)) - i += 1 - else: - break -else: - image_dirs = ["images"] +from xsetbg_db import xsetbg_db + + +def error(error_str): + sys.exit("%s: Error: %s\n" % (sys.argv[0], error_str)) + + +if not xsetbg_db: + error("No database found. Run rescan_fs.py. Abort.") + +if xsetbg_db.select().count() == 0: + error("No images found. Run rescan_fs.py. Abort.") -image_dirs = [os.path.join(xsetbg_dir, - os.path.expandvars(os.path.expanduser(dirname))) - for dirname in image_dirs -] # minimum time in seconds between background image changes if xsetbg_conf.has_option("xsetbg", "min_pause"): - min_pause = xsetbg_conf.getint("xsetbg", "min_pause") + min_pause = xsetbg_conf.getint("xsetbg", "min_pause") else: - min_pause = 60 + min_pause = 60 borders = xsetbg_conf.get("xsetbg", "borders").split(',') if xsetbg_conf.has_option("xsetbg", "borders"): - borders = [border.strip() for border in xsetbg_conf.get("xsetbg", "borders").split(',')] + borders = [border.strip() for border in + xsetbg_conf.get("xsetbg", "borders").split(',')] else: - borders = ["darkcyan", "steelblue", "midnightblue"] + borders = ["darkcyan", "steelblue", "midnightblue"] # minimum time in seconds between occurences of the same image if xsetbg_conf.has_option("xsetbg", "min_delay"): - min_delay = xsetbg_conf.get("xsetbg", "min_delay") - - # Borrowed from http://stackoverflow.com/a/2765366 - td_re = re.compile('(?:(?P\d+)y)?(?:(?P\d+)m)?(?:(?P\d+)d)?(?:T(?:(?P\d+)h)?(?:(?P\d+)m)?(?:(?P\d+)s)?)?') - td_dict = td_re.match(min_delay).groupdict(0) - delta = timedelta(days=int(td_dict['days']) + (int(td_dict['months']) * 30) + (int(td_dict['years']) * 365), - hours=int(td_dict['hours']), - minutes=int(td_dict['minutes']), - seconds=int(td_dict['seconds'])) - - if delta: - min_delay = delta.days * 24*3600 + delta.seconds - else: - min_delay = int(min_delay) + min_delay = xsetbg_conf.get("xsetbg", "min_delay") + + # Borrowed from http://stackoverflow.com/a/2765366 + td_re = re.compile('(?:(?P\d+)y)?' + '(?:(?P\d+)m)?' + '(?:(?P\d+)d)?' + '(?:T(?:(?P\d+)h)?' + '(?:(?P\d+)m)?(?:(?P\d+)s)?)?') + td_dict = td_re.match(min_delay).groupdict(0) + delta = timedelta(days=int(td_dict['days']) + + (int(td_dict['months']) * 30) + + (int(td_dict['years']) * 365), + hours=int(td_dict['hours']), + minutes=int(td_dict['minutes']), + seconds=int(td_dict['seconds'])) + + if delta: + min_delay = delta.days * 24*3600 + delta.seconds + else: + min_delay = int(min_delay) else: - min_delay = 3600*24 # 24 hours - - -# DB keys -timestamp_key = "timestamp" -filename_key = "filename" -old_filename_key = "old_filename" - - -# Create the database if it is not exists yet. + min_delay = 3600*24 # 24 hours -os.umask(0066) # octal; -rw-------; make the global persistent dictionary - # readable only by the user -try: - xsetbg_db = shelve.open(xsetbg_db_path, flag='c') -except anydbm.error, msg: - if str(msg) == "db type could not be determined": - os.remove(xsetbg_db_path) - xsetbg_db = shelve.open(xsetbg_db_path, flag='c') - -# Remove old filenames -old_time = time() - min_delay - -to_delete = [timestamp_key] -for key in xsetbg_db.keys(): - if key.startswith('/') and xsetbg_db[key] < old_time: - to_delete.append(key) - -for key in to_delete: - try: - del xsetbg_db[key] - except KeyError: - pass - -xsetbg_db.close() # Close DB in the parent process - - -images = [] - -for image_dir in image_dirs: - # List images in all subdirectories - for dirpath, dirs, files in os.walk(image_dir): - images.extend([os.path.join(dirpath, file) for file in files]) - -if not images: - error("No images found. Abort.") +if xsetbg_db.select('last_shown IS NULL OR last_shown < %d' % + (time() - min_delay)).count() == 0: + error("No unshown images found. Run rescan_fs.py " + "or decrease min_delay. Abort.") def change(force=False): - # Use the program's file as the lock file: - # lock it to prevent two processes run in parallel. - lock_file = open(os.path.join(xsetbg_dir, 'xsetbg.py'), 'r') - - try: - flock(lock_file, LOCK_EX|LOCK_NB) - except IOError: # already locked - lock_file.close() - return - - - xsetbg_db = None - try: - # Reopen the global persistent dictionary - xsetbg_db = shelve.open(xsetbg_db_path, 'w') - - timestamp = xsetbg_db.get(timestamp_key) - current_time = time() - - if not force and timestamp is not None and \ - current_time - timestamp < min_pause: # Too early to change background + # Use the program's file as the lock file: + # lock it to prevent two processes run in parallel. + lock_file = open(os.path.join(xsetbg_dir, 'xsetbg.py'), 'r') + + try: + flock(lock_file, LOCK_EX | LOCK_NB) + except IOError: # already locked + lock_file.close() + return + + try: + timestamp = xsetbg_db.select('last_shown IS NOT NULL', + orderBy='-last_shown')[0].last_shown + current_time = time() + + if not force and timestamp is not None and \ + current_time - timestamp < min_pause: + # Too early to change background return - # Save current time - xsetbg_db[timestamp_key] = current_time - - # Select a random image and check if we've seen it recently; - # loop until we can find a new image (never seen before) or old enough. - for i in xrange(len(images)): # ensure the loop is not infinite - image_name = random.choice(images) - if xsetbg_db.has_key(image_name): - image_time = xsetbg_db[image_name] - if current_time - image_time > min_delay: - break - else: - break - xsetbg_db[image_name] = current_time - - # Save filename - if xsetbg_db.has_key(filename_key): - xsetbg_db[old_filename_key] = xsetbg_db[filename_key] - xsetbg_db[filename_key] = image_name - - program_options = ["xli", "-border", random.choice(borders), - "-center", "-onroot", "-quiet", "-zoom", "auto", - image_name] - - rc = subprocess.call(program_options) - if rc: - error("cannot execute xli!") - - finally: - # Unlock and close the lock file - flock(lock_file, LOCK_UN) - lock_file.close() - # Flush and close the global persistent dictionary - if xsetbg_db: xsetbg_db.close() + # Select a random image that has never been shown + not_shown_select = xsetbg_db.select('last_shown IS NULL') + not_shown_count = not_shown_select.count() + if not_shown_count: + row = not_shown_select[random.randint(0, not_shown_count - 1)] + else: + old_shown_select = xsetbg_db.select( + 'last_shown IS NOT NULL AND last_shown < %d' % + current_time - min_delay) + old_shown_count = old_shown_select.count() + if old_shown_count: + row = old_shown_select[random.randint(0, not_shown_count - 1)] + else: + error("No images to show found. Run rescan_fs.py " + "or decrease min_delay. Abort.") + + program_options = ["xli", "-border", random.choice(borders), + "-center", "-onroot", "-quiet", "-zoom", "auto", + row.full_name] + + rc = subprocess.call(program_options) + if rc: + error("cannot execute xli!") + else: + row.last_shown = current_time + + finally: + # Unlock and close the lock file + flock(lock_file, LOCK_UN) + lock_file.close()