Advertisement
Guest User

bg_slideshow.py modified

a guest
Apr 30th, 2012
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.47 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #
  3. # bg_slideshow.py
  4. # (c) 2012 MB http://somethingididnotknow.wordpress.com
  5. #
  6. # This script is released under WTFPL, but it's heavily inspired from Romano
  7. # Giannetti's original bg_slideshow.py
  8. # See http://rlog.rgtti.com/software/linux/wallpaper-slideshow-for-gnome3/
  9. #
  10. # A simple wallpaper changer for GNOME desktop.
  11. # List your wallpapers folders in file ~/.bg_slideshow.conf and run the script:
  12. #
  13. # python bg_slideshow.py &
  14. #
  15. # or add a startup entry using gnome-session-properties
  16. import signal
  17. import sys
  18. import os
  19. import random
  20. from time import gmtime, sleep, strftime
  21.  
  22. class WallpaperChanger:
  23.     # conf file is in ~/.bg_slideshow.conf change it here if you want
  24.     conf_file = os.path.join(os.getenv("HOME"), '.bg_slideshow.conf')
  25.     mode = "zoom" # one of none, centered, wallpaper, scaled, stretched, zoom, spanned
  26.     delay = 3 * 60 # in seconds
  27.     formats = [".jpg", ".png", ".gif", ".jpeg"] # accepted formats
  28.     files = []
  29.     pid_file = os.path.join('/','var','run','bg_slideshow','bg_slideshow.pid')
  30.     all_files = set()
  31.    
  32.     def __init__(self):
  33.         self.index = 0
  34.         self.parse_conf()
  35.  
  36.     def parse_conf(self):
  37.         """parses the configuration file, interpreting every non-commented line
  38.        as a directory into which wallpaper images reside.
  39.        In case no images are found, the script exits"""
  40.         self.bad_folders = []
  41.         if not os.path.isfile(self.conf_file):
  42.             with open(self.conf_file, 'w') as conf:
  43.                 self.append_error(conf, 'List your wallpapers folder here')
  44.                 print 'List your wallpapers folders in configuration file ', self.conf_file
  45.                 sys.exit(1)
  46.         self.conf_last_modified = os.path.getmtime(self.conf_file)
  47.         self.files = self.get_all_files()
  48.         if not self.files:
  49.             self.append_error(conf, 'No images found!')
  50.             sys.exit(1)
  51.         self.all_files = set(self.files)
  52.         random.shuffle(self.files)
  53.        
  54.     def get_all_files(self):
  55.         """adds all files in all directories found in the configuration file to
  56.        a list containing all wallpapers to be shown with no duplicates (based
  57.        on complete file name)"""
  58.         files = []
  59.         with open(self.conf_file, 'r+') as conf:
  60.              # trim whitespaces and newlines
  61.             for line in [x.strip() for x in conf.readlines()]:
  62.                 if not line.startswith('#'):
  63.                     if os.path.isdir(line):
  64.                         try:
  65.                             files.extend([os.path.join(line, file) for file in os.listdir(line) if os.path.splitext(file)[1] in self.formats])
  66.                         except OSError, e:
  67.                             # deal with bad folders later...
  68.                             self.bad_folders.append('%s: %s' % (line, e.strerror))
  69.             if self.bad_folders:
  70.                 for folder in self.bad_folders:
  71.                     self.append_error(conf, folder)
  72.         return self.remove_duplicates(files)
  73.        
  74.     def remove_duplicates(self, files):
  75.         seen = set()
  76.         seen_add = seen.add
  77.         return [x for x in files if x not in seen and not seen.add(x)]
  78.            
  79.     def append_error(self, conf, line):
  80.         # go to the end of conf file and append messages there
  81.         conf.seek(0, 2)
  82.         conf.write('# %s - %s%s' % (strftime("%Y-%m-%d %H:%M:%S", gmtime()), line, os.linesep))
  83.        
  84.     def poll_for_new_files(self):
  85.         """checks whether new files have been added to the configured folders"""
  86.         all_files = set(self.get_all_files())
  87.         new_files = all_files - self.all_files
  88.         if new_files:
  89.             shown = set(self.files[:self.index])
  90.             self.files = list(all_files - shown)
  91.             self.all_files = all_files
  92.             random.shuffle(self.files)
  93.             self.index = 0
  94.  
  95.     def write_pid(self, pid_path):
  96.         if os.path.isfile(pid_path):
  97.             return False
  98.  
  99.         f = open(pid_path, 'w')
  100.         f.write(str(os.getpid()))
  101.         f.close()
  102.         return True
  103.  
  104.     def remove_pid(self):
  105.         os.remove(self.pid_file)
  106.  
  107.     def proc_exit(self, signum, frame):
  108.         self.remove_pid()
  109.         sys.exit(0)
  110.  
  111.     def install_traps(self):
  112.         signal.signal(signal.SIGINT, self.proc_exit)
  113.  
  114.     def run(self):
  115.         if (not self.write_pid(self.pid_file)):
  116.             print "bg_slideshow: Failed to start, check",self.pid_file
  117.             sys.exit(1)
  118.  
  119.         self.install_traps()
  120.  
  121.         sleep(self.delay) # this seems to be needed to avoid gnome-shell crashes
  122.         while True:
  123.             last_edit = os.path.getmtime(self.conf_file)
  124.             if last_edit != self.conf_last_modified:
  125.                 self.parse_conf()
  126.             next_bg = self.files[self.index]
  127.             if os.path.isfile(next_bg):
  128.                 os.system('/usr/bin/gsettings set org.gnome.desktop.background picture-uri file://%s' % self.files[self.index])
  129.                 os.system('/usr/bin/gsettings set org.gnome.desktop.background picture-options %s' % self.mode)
  130.                 sleep(self.delay)
  131.             self.index += 1
  132.             self.poll_for_new_files()
  133.             if self.index >= len(self.files):
  134.                 self.index = 0
  135.                 self.parse_conf() # this also checks that at least a bg exists!
  136.                 random.shuffle(self.files)
  137.            
  138. if __name__ == "__main__":
  139.     changer = WallpaperChanger()
  140.     changer.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement