]> code.delx.au - bg-scripts/blob - bin/randombg2_ipc.py
Various bug fixes.
[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 self.filelist.doStoreCache(CACHE_LOCATION)
142 return ret
143
144 def cycle_prev(self):
145 debug("Cycling wallpaper", DEBUG_LEVEL_LOW)
146 ret = self.randombg.cyclePrev()
147 if not ret:
148 debug('Could not set wallpaper. Returned "%s"' % ret)
149 debug('About to sleep for "%d" seconds' % self.cycle_time, DEBUG_LEVEL_LOW)
150 # Yes this is ment to be cycle_next
151 self.callbackObj = self.socketHandler.addCallback(self.cycle_time, self.cycle_next)
152 self.filelist.doStoreCache(CACHE_LOCATION)
153 return ret
154
155 def _finished(self):
156 self.filelist.doStoreCache(CACHE_LOCATION)
157
158 def __call__(self):
159 # Callback immediatly
160 self.socketHandler.addCallback(0.0, self.cycle_reload)
161 # Now go into the main loop
162 self.socketHandler.mainLoop()
163 # Clean up time
164 self._finished()
165
166 def _createIPCServer(self, domainSocketName):
167 """Create the Server socket, and start listening for clients"""
168
169 class Handler(object):
170 def __init__(self, parent):
171 self.parent = parent
172 def _removeOldTimer(self):
173 if self.parent.callbackObj:
174 self.parent.socketHandler.removeCallback(self.parent.callbackObj)
175 def _cmd_PAUSE(self):
176 debug("Pausing randombg")
177 self._removeOldTimer()
178 def _cmd_NEXT(self):
179 self._removeOldTimer()
180 self.parent.cycle_next()
181 def _cmd_PREVIOUS(self):
182 self._removeOldTimer()
183 self.parent.cycle_prev()
184 def _cmd_RESCAN(self):
185 self.parent.filelist.doScanPaths()
186 self._cmd_NEXT()
187 def _cmd_RELOAD(self):
188 self._removeOldTimer()
189 self.parent.cycle_reload()
190 def _processLine(self, line):
191 prefix, cmd = line.split(None, 1)
192 if prefix != 'CMD':
193 debug('Unknown command received "%s"' % line)
194 return
195 if hasattr(self, '_cmd_%s' % cmd):
196 getattr(self, '_cmd_%s' % cmd)()
197 else:
198 debug('Unknown command received "%s"' % cmd)
199 def __call__(self, lineReader):
200 try:
201 while lineReader.hasLine():
202 self._processLine(lineReader.readline())
203 except Exception, e:
204 debug(str(e))
205
206 def handleClient(sock):
207 conn, address = sock.accept()
208 async_handler.addLineBufferedSocket(conn, Handler(self) )
209
210 async_handler = AsyncSocket.AsyncSocketOwner()
211
212 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
213 sock.bind(domainSocketName)
214 sock.listen(2) # Backlog = 2
215
216 async_handler.addSocket(sock, handleClient)
217
218 return async_handler
219
220 if __name__ == "__main__":
221 main()