]> git.phdru.name Git - xsetbg.git/commitdiff
XSetBg: select a random image and set it as the desktop wallpaper (display it in...
authorOleg Broytman <phd@phdru.name>
Fri, 27 Jan 2006 15:39:56 +0000 (15:39 +0000)
committerOleg Broytman <phd@phdru.name>
Fri, 27 Jan 2006 15:39:56 +0000 (15:39 +0000)
git-svn-id: file:///home/phd/archive/SVN/xsetbg/trunk@2 143022c7-580b-0410-bae3-87f2bf5d3141

print-filename.py [new file with mode: 0755]
xsetbg-ping [new file with mode: 0755]
xsetbg-start [new file with mode: 0755]
xsetbg-stop [new file with mode: 0755]
xsetbg.conf [new file with mode: 0644]
xsetbg.py [new file with mode: 0755]

diff --git a/print-filename.py b/print-filename.py
new file mode 100755 (executable)
index 0000000..63a1481
--- /dev/null
@@ -0,0 +1,86 @@
+#! /usr/local/bin/python -O
+"""This file is a part of XSetBg.
+Author: Oleg BroytMann <phd@phd.pp.ru>
+Copyright (C) 2004-2006 PhiloSoft Design
+"""
+
+__version__ = "1.3.0"
+__author__ = "Oleg BroytMann <phd@phd.pp.ru>"
+__copyright__ = "Copyright (C) 2004-2006 PhiloSoft Design"
+__revision__ = "$Id$"[5:-2]
+__date__ = "$Date$"[7:-2]
+
+
+import sys, os, shelve
+
+def usage(code=0):
+   sys.stderr.write("Usage: %s [-0|--null] [-o|--old] [-w|--width] [width]\n" % sys.argv[0])
+   sys.exit(code)
+
+
+def get_args():
+   from getopt import getopt, GetoptError
+
+   try:
+      options, arguments = getopt(sys.argv[1:], "0ow:",
+         ["null", "old", "width="])
+   except GetoptError:
+      usage(1)
+
+   print0 = False
+   old = False
+   width = None
+
+   for option, value in options:
+      if option in ("-h", "--help"):
+         usage()
+      elif option in ("-0", "--null"):
+         print0 = True
+      elif option in ("-o", "--old"):
+         old = True
+      elif option in ("-w", "--width"):
+         width = int(value)
+      else:
+         usage(2)
+
+   if arguments:
+      if width is not None:
+         usage(3)
+      elif len(arguments) > 1:
+         usage(4)
+      else:
+         width = int(arguments[0])
+
+   return print0, old, width
+
+print0, old, width = get_args()
+
+
+xsetbg_dir = os.path.join(os.environ["HOME"], "lib", "xsetbg")
+os.chdir(xsetbg_dir)
+
+global_db_name = "xsetbg.db"
+filename_key = "filename"
+old_filename_key = "old_filename"
+
+global_db = shelve.open(global_db_name, flag='r')
+if old:
+   key = old_filename_key
+else:
+   key = filename_key
+filename = global_db[key]
+global_db.close()
+
+if width is not None:
+   lines = []
+   while filename:
+      lines.append(filename[:width])
+      filename = filename[width:]
+   filename = "\n".join(lines)
+
+sys.stdout.write(filename)
+
+if print0:
+   sys.stdout.write('\0')
+else:
+   print
diff --git a/xsetbg-ping b/xsetbg-ping
new file mode 100755 (executable)
index 0000000..2fef273
--- /dev/null
@@ -0,0 +1,16 @@
+#! /bin/sh
+
+if [ -z "$DISPLAY" ]; then
+   exit 0
+fi
+
+if xscreensaver-command -time 2>/dev/null | grep -Eq 'screen (blanked|locked)'; then
+   exit 0
+fi
+
+if ps a | grep -v grep | grep -q mplayer; then
+   exit 0
+fi
+
+cd "$HOME/lib/xsetbg"
+exec readyexec xsetbg.sock
diff --git a/xsetbg-start b/xsetbg-start
new file mode 100755 (executable)
index 0000000..6254963
--- /dev/null
@@ -0,0 +1,7 @@
+#! /bin/sh
+
+umask 077
+cd "$HOME/lib/xsetbg"
+# Remove stale socket
+rm -f xsetbg.sock
+PYTHONPATH="`pwd`" python -O "`whence readyexecd.py`" xsetbg.sock xsetbg.run &
diff --git a/xsetbg-stop b/xsetbg-stop
new file mode 100755 (executable)
index 0000000..0623f20
--- /dev/null
@@ -0,0 +1,6 @@
+#! /bin/sh
+
+cd "$HOME/lib/xsetbg"
+readyexec --stop xsetbg.sock
+# Remove socket
+exec rm -f xsetbg.sock
diff --git a/xsetbg.conf b/xsetbg.conf
new file mode 100644 (file)
index 0000000..38342e8
--- /dev/null
@@ -0,0 +1,6 @@
+[images]
+directory0 = ~/lib/xsetbg/images
+
+[xsetbg]
+min_pause = 60 ; minimum time in seconds between background image changes
+borders = darkcyan, steelblue, midnightblue
diff --git a/xsetbg.py b/xsetbg.py
new file mode 100755 (executable)
index 0000000..0a4a3f9
--- /dev/null
+++ b/xsetbg.py
@@ -0,0 +1,229 @@
+#! /usr/local/bin/python -O
+"""Select a random image from $HOME/lib/xsetbg/images subdirectories
+and set it as the desktop wallpaper (display it in the root window).
+
+Author: Oleg BroytMann <phd@phd.pp.ru>
+Copyright (C) 2000-2006 PhiloSoft Design
+"""
+
+__version__ = "2.17.0"
+__author__ = "Oleg BroytMann <phd@phd.pp.ru>"
+__copyright__ = "Copyright (C) 2000-2006 PhiloSoft Design"
+__revision__ = "$Id$"[5:-2]
+__date__ = "$Date$"[7:-2]
+
+
+import sys, os
+
+
+def usage():
+   sys.stderr.write("%s version %s\n" % (sys.argv[0], __version__))
+   sys.stderr.write("Usage: %s [force]\n" % sys.argv[0])
+   sys.exit(0)
+
+def error(error_str, error_code=1):
+   sys.stderr.write("%s: Error: %s\n" % (sys.argv[0], error_str))
+   sys.exit(error_code)
+
+
+xwininfo = os.popen("xwininfo -root", 'r')
+xwininfo_lines = xwininfo.read()
+rc = xwininfo.close()
+if rc:
+   error("calling xwininfo", rc)
+
+screen_width = None
+screen_height = None
+for line in xwininfo_lines.split('\n'):
+   line = line.strip()
+   if line.startswith("Width: "):
+      screen_width = int(line[len("Width: "):])
+   elif line.startswith("Height: "):
+      screen_height = int(line[len("Height: "):])
+
+if not screen_width or not screen_height:
+   error("parsing xwininfo output")
+
+
+from ConfigParser import SafeConfigParser
+
+xsetbg_dir = os.path.join(os.environ["HOME"], "lib", "xsetbg")
+os.chdir(xsetbg_dir)
+
+config = SafeConfigParser()
+config.read("xsetbg.conf")
+
+if config.has_option("images", "directory") or \
+   config.has_option("images", "directory0") or \
+   config.has_option("images", "directory1"):
+   image_dirs = []
+   if config.has_option("images", "directory"):
+      image_dirs.append(config.get("images", "directory"))
+   if config.has_option("images", "directory0"):
+      image_dirs.append(config.get("images", "directory0"))
+   if config.has_option("images", "directory1"):
+      image_dirs.append(config.get("images", "directory1"))
+   i = 2
+   while True:
+      option = "directory%d" % i
+      if config.has_option("images", option):
+         image_dirs.append(config.get("images", option))
+         i += 1
+      else:
+         break
+else:
+   image_dirs = ["images"]
+
+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 config.has_option("xsetbg", "min_pause"):
+   min_pause = config.getint("xsetbg", "min_pause")
+else:
+   min_pause = 60
+
+borders = config.get("xsetbg", "borders").split(',')
+if config.has_option("xsetbg", "borders"):
+   borders = [border.strip() for border in config.get("xsetbg", "borders").split(',')]
+else:
+   borders = ["darkcyan", "steelblue", "midnightblue"]
+
+del config
+
+
+os.umask(0066) # octal; -rw-------; make the global persistent dictionary
+               # readable only by the user
+global_db_name = "xsetbg.db"
+
+
+import random
+import anydbm, shelve
+from time import time
+from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
+
+# Import pickle and all anydbm/shelve internal machinery, so that
+# when ReadyExec forks they will be ready.
+# Also create the database if it is not exists yet.
+
+try:
+   global_db = shelve.open(global_db_name, flag='c')
+except anydbm.error, msg:
+   if str(msg) == "db type could not be determined":
+      os.remove(global_db_name)
+      global_db = shelve.open(global_db_name, flag='c')
+
+global_db.close() # Close DB in parent process
+
+
+# DB keys
+timestamp_key = "timestamp"
+filename_key = "filename"
+old_filename_key = "old_filename"
+
+
+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.")
+
+
+try:
+   from PIL import Image
+   use_PIL = True
+except ImportError:
+   use_PIL = False
+
+
+def run():
+   if len(sys.argv) not in (1, 2):
+      usage()
+
+   force = False
+   if len(sys.argv) == 2:
+      if sys.argv[1] == "force":
+         force = True
+      else:
+         usage()
+
+   # Use the program's file as the lock file:
+   # lock it to prevent two processes run in parallel.
+   lock_file = open("xsetbg.py", 'r')
+   try:
+      flock(lock_file , LOCK_EX|LOCK_NB)
+   except IOError: # already locked
+      lock_file.close()
+      return
+
+
+   global_db = None
+   try:
+      # Re-seed the RNG; this is neccessary because ReadyExecd forks
+      # and RNG in a child process got the same seed from the parent
+      # after every fork.
+      random.seed()
+
+      # Reopen the global persistent dictionary
+      global_db = shelve.open(global_db_name, 'w')
+
+      timestamp = global_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
+            return
+
+      # Save current time
+      global_db[timestamp_key] = current_time
+
+      border = random.choice(borders)
+      image_name = random.choice(images)
+      root, ext = os.path.splitext(image_name)
+
+      # Save filename
+      if global_db.has_key(filename_key):
+         global_db[old_filename_key] = global_db[filename_key]
+      global_db[filename_key] = image_name
+
+      placement_options = []
+      if use_PIL:
+         image = Image.open(image_name, 'r')
+         im_w, im_h = image.size
+         del image
+         if (im_w > screen_width) or (im_h > screen_height):
+            zoom = min(screen_width*100//im_w, screen_height*100//im_h)
+            if zoom > 0: placement_options = ["-zoom", str(zoom)]
+
+   finally:
+      # Unlock and close the lock file
+      flock(lock_file , LOCK_UN)
+      lock_file.close()
+      # Flush and close the global persistent dictionary
+      if global_db: global_db.close()
+
+
+   if ext.lower() in (".bmp", ".png"):
+      # xsetbg does not recognize BMP files.
+      # PNG files have gamma settings, and xli can adapt it to the display gamma;
+      # xloadimage/xview/xsetbg display them with wrong gamma.
+      program_options = ["xli", "xli", "-onroot", "-quiet"] + placement_options + \
+         ["-center", "-border", border, image_name]
+      os.execlp(*program_options)
+      error("cannot execute xli!")
+   else:
+      # ...but xli failed to load many image types, use xsetbg for them
+      program_options = ["xsetbg", "xsetbg"] + placement_options + \
+         ["-center", "-border", border, image_name]
+      os.execlp(*program_options)
+      error("cannot execute xsetbg!")
+
+
+if __name__ == "__main__":
+   run()