]> code.delx.au - bg-scripts/blob - bin/randombg2_ipc.py
Initial import
[bg-scripts] / bin / randombg2_ipc.py
1 #!/usr/bin/env python
2
3 import sys, os, os.path, socket
4 from optparse import OptionParser, Values
5
6 VERSION = "1.1"
7 CACHE_LOCATION = os.path.expanduser('~/.randombg2_filelist_cache')
8 SOCKET_FILE = os.path.expanduser('~/tmp/tmp_socket')
9
10 try:
11 # These are my libraries...
12 import GregDebug, AsyncSocket, WallChanger, SigHandler
13
14 from GregDebug import debug, setDebugLevel, DEBUG_LEVEL_DEBUG, DEBUG_LEVEL_LOW, DEBUG_LEVEL_MEDIUM, DEBUG_LEVEL_HIGH, DEBUG_INCREMENT
15
16 from FileLists import *
17 except ImportError, e:
18 print >>sys.stderr, "Missing libraries!\nExiting..."
19 sys.exit(1)
20
21 def buildparser():
22 def buildOptions():
23 pass
24 def addfilestolist(optclass, opt, value, parser, fileList):
25 fo = open(value)
26 for line in fo:
27 fileList.list.append(line.strip())
28 fo.close()
29 fileList.allowAllRandom = False
30
31 parser = OptionParser(version="%prog " + VERSION,
32 description = "Picks a random background image",
33 usage = "%prog [options] dir [dir2 ...]")
34 parser.add_option("-p", "--permanent",
35 action="store_true", dest="permanent", default=False,
36 help="Make the background permanent. Note: This will cause all machines logged in with this account to simultaneously change background [Default: %default]")
37 parser.add_option("-q", "--quiet", "--silent",
38 action="count", dest="quiet", default=0,
39 help="Make the script quiet (good for running from a shell script)")
40 parser.add_option("-v", '-d', "--verbose", "--debug",
41 action="count", dest="verbose", default=0,
42 help="Make the louder (good for debugging, or those who are curious)")
43 parser.add_option("-b", "--background-colour",
44 action="store", type="string", dest="background_colour", default="black",
45 help="Change the default background colour that is displayed if the image is not in the correct aspect ratio [Default: %default]")
46 parser.add_option("--all-random",
47 action="store_true", dest="all_random", default=False,
48 help="Make sure that all images have been displayed before repeating an image")
49 parser.add_option("--folder-random",
50 action="store_true", dest="folder_random", default=False,
51 help="Give each folder an equal chance of having an image selected from it")
52 #parser.add_option("--file-list",
53 # action="callback", callback=addfilestolist, type="string", callback_args=(fileList,),
54 # help="Adds the list of images from the external file")
55 parser.add_option("--cycle",
56 action="store", type="int", default=0, dest="cycle_time",
57 help="Cause the image to cycle every X seconds")
58 return parser
59
60
61 def createIPCClient(domainSocketName):
62 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
63 sock.connect(domainSocketName)
64 sock_file = sock.makefile()
65 return sock_file
66
67 def main():
68 if os.path.exists(SOCKET_FILE):
69 # We are the client
70 sock = createIPCClient(SOCKET_FILE)
71 print >>sock, "CMD NEXT"
72 ### print >>sock, "CMD PREVIOUS"
73 ### print >>sock, "CMD PAUSE"
74 sock.close()
75 else:
76 # We are the server
77 try:
78 Server(SOCKET_FILE)()
79 finally:
80 # Make sure that the socket is cleaned up
81 os.unlink(SOCKET_FILE)
82
83 class Server(object):
84 def __init__(self, domainSocketName):
85 self.socketHandler = self._createIPCServer(domainSocketName)
86 self.callbackObj = None
87
88 parser = buildparser()
89 useroptions, paths = parser.parse_args(sys.argv[1:])
90
91 setDebugLevel(DEBUG_INCREMENT * (useroptions.quiet - useroptions.verbose))
92 debug("Just set GregDebug.DEBUG_LEVEL to %d" % GregDebug.DEBUG_LEVEL, DEBUG_LEVEL_LOW)
93
94 self.filelist = self.__getFileList(useroptions, paths)
95
96 if not self.filelist.hasImages():
97 print >>sys.stderr, "No files!"
98 parser.print_help()
99 sys.exit(1)
100
101 debug("Initilizing RandomBG", DEBUG_LEVEL_DEBUG)
102 self.randombg = WallChanger.RandomBG(self.filelist, useroptions.background_colour, useroptions.permanent)
103
104 # Store some of the other useful options
105 self.cycle_time = useroptions.cycle_time
106
107 def __getFileList(self, useroptions, paths):
108 if useroptions.all_random:
109 filelist = AllRandomFileList()
110 elif useroptions.folder_random:
111 filelist = FolderRandomFileList()
112 else:
113 filelist = RandomFileList()
114
115 for path in paths:
116 filelist.doAddPath(path)
117
118 if filelist.attemptCacheLoad(CACHE_LOCATION):
119 debug("Loaded cache successfully", DEBUG_LEVEL_LOW)
120 else:
121 debug("Could not load cache")
122 filelist.doScanPaths()
123 return filelist
124
125 def cycle_reload(self):
126 debug("Reloading wallpaper", DEBUG_LEVEL_LOW)
127 ret = self.randombg.cycleReload()
128 if not ret:
129 debug('Could not set wallpaper. Returned "%s"' % ret)
130 debug('About to sleep for "%d" seconds' % self.cycle_time, DEBUG_LEVEL_LOW)
131 self.callbackObj = self.socketHandler.addCallback(self.cycle_time, self.cycle_next)
132 return ret
133
134 def cycle_next(self):
135 debug("Cycling wallpaper", DEBUG_LEVEL_LOW)
136 ret = self.randombg.cycleNext()
137 if not ret:
138 debug('Could not set wallpaper. Returned "%s"' % ret)
139 debug('About to sleep for "%d" seconds' % self.cycle_time, DEBUG_LEVEL_LOW)
140 self.callbackObj = self.socketHandler.addCallback(self.cycle_time, self.cycle_next)
141 return ret
142
143 def cycle_prev(self):
144 debug("Cycling wallpaper", DEBUG_LEVEL_LOW)
145 ret = self.randombg.cyclePrev()
146 if not ret:
147 debug('Could not set wallpaper. Returned "%s"' % ret)
148 debug('About to sleep for "%d" seconds' % self.cycle_time, DEBUG_LEVEL_LOW)
149 # Yes this is ment to be cycle_next
150 self.callbackObj = self.socketHandler.addCallback(self.cycle_time, self.cycle_next)
151 return ret
152
153 def _finished(self):
154 self.filelist.doStoreCache(CACHE_LOCATION)
155
156 def __call__(self):
157 # Callback immediatly
158 self.socketHandler.addCallback(0.0, self.cycle_reload)
159 # Now go into the main loop
160 self.socketHandler.mainLoop()
161 # Clean up time
162 self._finished()
163
164 def _createIPCServer(self, domainSocketName):
165 """Create the Server socket, and start listening for clients"""
166
167 class Handler(object):
168 def __init__(self, parent):
169 self.parent = parent
170 def _removeOldTimer(self):
171 if self.parent.callbackObj:
172 self.parent.socketHandler.removeCallback(self.parent.callbackObj)
173 def _cmd_PAUSE(self):
174 debug("Pausing randombg")
175 self._removeOldTimer()
176 def _cmd_NEXT(self):
177 self._removeOldTimer()
178 self.parent.cycle_next()
179 def _cmd_PREVIOUS(self):
180 self._removeOldTimer()
181 self.parent.cycle_prev()
182 def _cmd_RESCAN(self):
183 self.parent.filelist.doScanPaths()
184 self._cmd_NEXT()
185 def _processLine(self, line):
186 prefix, cmd = line.split(None, 1)
187 if prefix != 'CMD':
188 debug('Unknown command received "%s"' % line)
189 return
190 if hasattr(self, '_cmd_%s' % cmd):
191 getattr(self, '_cmd_%s' % cmd)()
192 else:
193 debug('Unknown command received "%s"' % cmd)
194 def __call__(self, lineReader):
195 try:
196 while lineReader.hasLine():
197 self._processLine(lineReader.readline())
198 except Exception, e:
199 debug(str(e))
200
201 def handleClient(sock):
202 conn, address = sock.accept()
203 async_handler.addLineBufferedSocket(conn, Handler(self) )
204
205 async_handler = AsyncSocket.AsyncSocketOwner()
206
207 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
208 sock.bind(domainSocketName)
209 sock.listen(2) # Backlog = 2
210
211 async_handler.addSocket(sock, handleClient)
212
213 return async_handler
214
215 if __name__ == "__main__":
216 main()