3 # Copyright (C) 2004, 2005 Richard Kettlewell
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 """Graphical user interface for DisOrder"""
34 ########################################################################
38 # The main (initial) thread of the program runs all GUI code. The GUI is only
39 # directly modified from inside this thread. We sometimes call this the
42 # We have a background thread, MonitorStateThread, which waits for changes to
43 # the server's state which we care about. Whenever such a change occurs it
44 # notifies all the widgets which care about it (and possibly other widgets;
45 # the current implementation is unsophisticated.)
47 # Widget poll() methods usually, but NOT ALWAYS, called in the
48 # MonitorStateThread. Other widget methods are call in the master thread.
50 # We have a separate disorder.client for each thread rather than locking a
51 # single client. MonitorStateThread also has a private disorder.client that
52 # it uses to watch for server state changes.
54 ########################################################################
57 # communication queue into thread containing Tk event loop
59 # Sets up a callback on the event loop (in this thread) which periodically
60 # checks the queue for elements; if any are found they are executed.
61 def __init__(self, master):
62 self.q = Queue.Queue();
68 item = self.q.get_nowait()
70 self.master.after_idle(self.poll)
72 self.master.after(100, self.poll)
77 ########################################################################
79 class ProgressBar(Canvas):
81 def __init__(self, master=None, **kw):
82 Canvas.__init__(self, master, highlightthickness=0, **kw)
83 self.outer = self.create_rectangle(0, 0, 0, 0,
87 self.bar = self.create_rectangle(0, 0, 0, 0,
93 self.bind("<Configure>", lambda e: self.redisplay())
95 def update(self, current, total):
96 self.current = current
110 w, h = self.winfo_width(), self.winfo_height()
112 self.coords(self.outer, 0, 0, w - 1, h - 1)
114 bw = int((w - 2) * self.current / self.total)
115 self.itemconfig(self.bar,
118 self.coords(self.bar, 1, 1, bw, h - 2)
120 self.itemconfig(self.bar,
123 self.coords(self.bar, 1, 1, w - 2, h - 2)
125 # look up a track's name part, using client c. Maintains a cache.
127 def part(c, track, context, part):
128 key = "%s-%s-%s" % (part, context, track)
130 if not part_cache.has_key(key) or part_cache[key]['when'] < now - 3600:
131 part_cache[key] = {'when': now,
132 'what': c.part(track, context, part)}
133 return part_cache[key]['what']
135 class PlayingWidget(Frame):
136 # widget that always displays information about what's
138 def __init__(self, master=None, **kw):
139 Frame.__init__(self, master, **kw)
140 # column 0 is descriptions, column 1 is the values
141 self.columnconfigure(0,weight=0)
142 self.columnconfigure(1,weight=1)
144 self.field(0, 0, "artist", "Artist")
145 self.field(1, 0, "album", "Album")
146 self.field(2, 0, "title", "Title")
147 # column 1 also has the progress bar in it
148 self.p = ProgressBar(self, height=20)
149 self.p.grid(row=3, column=1, sticky=E+W)
150 # column 2 has operation buttons
151 b = Button(self, text="Quit", command=self.quit)
152 b.grid(row=0, column=2, sticky=E+W)
153 b = Button(self, text="Scratch", command=self.scratch)
154 b.grid(row=1, column=2, sticky=E+W)
155 b = Button(self, text="Recent", command=self.recent)
156 b.grid(row=2, column=2, sticky=E+W)
162 def field(self, row, column, name, label):
164 Label(self, text=label).grid(row=row, column=column, sticky=E)
165 self.fields[name] = Text(self, height=1, state=DISABLED)
166 self.fields[name].grid(row=row, column=column + 1, sticky=W+E);
168 def set(self, name, value):
169 # set a field's value
170 f = self.fields[name]
171 f.config(state=NORMAL)
174 f.config(state=DISABLED)
176 def playing(self, p):
177 # called with new what's-playing information
180 for tpart in ['artist', 'album', 'title']:
181 values[tpart] = part(client, p['track'], 'display', tpart)
183 self.length = client.length(p['track'])
184 except disorder.operationError:
186 self.started = int(p['played'])
189 for k in self.fields.keys():
191 self.set(k, values[k])
196 def length_bar(self):
197 if self.length and self.length > 0:
198 self.p.update(time.time() - self.started, self.length)
202 def update_length(self):
204 self.after(1000, self.update_length)
209 intercom.put(lambda: self.playing(p))
218 def recent_close(self):
219 self.recentw.destroy()
224 self.recentw.deiconify()
227 w = 80*tracklistFont.measure('A')
228 h = 40*tracklistFont.metrics("linespace")
229 self.recentw = Toplevel()
230 self.recentw.protocol("WM_DELETE_WINDOW", self.recent_close)
231 self.recentw.title("Recently Played")
232 # XXX for some reason Toplevel(width=w,height=h) doesn't seem to work
233 self.recentw.geometry("%dx%d" % (w,h))
234 w = RecentWidget(self.recentw)
235 w.pack(fill=BOTH, expand=1)
238 class TrackListWidget(Frame):
239 def __init__(self, master=None, **kw):
240 Frame.__init__(self, master, **kw)
241 self.yscrollbar = Scrollbar(self)
242 self.xscrollbar = Scrollbar(self, orient=HORIZONTAL)
243 self.canvas = Canvas(self,
244 xscrollcommand=self.xscrollbar.set,
245 yscrollcommand=self.yscrollbar.set)
246 self.xscrollbar.config(command=self.canvas.xview)
247 self.yscrollbar.config(command=self.canvas.yview)
248 self.canvas.grid(row=0, column=0, sticky=N+S+E+W)
249 self.yscrollbar.grid(row=0, column=1, sticky=N+S)
250 self.xscrollbar.grid(row=1, column=0, sticky=E+W)
251 self.columnconfigure(0,weight=1)
252 self.rowconfigure(0,weight=1)
254 self.default_cursor = self['cursor']
255 self.configure(cursor="watch")
257 def queue(self, q, w_artists, w_albums, w_titles, artists, albums, titles):
258 # called with new queue state
259 # delete old contents
261 for i in self.canvas.find_all():
262 self.canvas.delete(i)
264 # if the call was queued but not received before the window was deleted
265 # we might get an error from Tcl/Tk, which no longer knows the window,
268 w = tracklistHFont.measure("Artist")
271 w = tracklistHFont.measure("Album")
274 w = tracklistHFont.measure("Title")
277 hheading = tracklistHFont.metrics("linespace")
278 h = tracklistFont.metrics('linespace')
280 x_album = x_artist + w_artists + 16
281 x_title = x_album + w_albums + 16
282 w = x_title + w_titles + 8
283 self.canvas['scrollregion'] = (0, 0, w, h * len(artists) + hheading)
284 self.canvas.create_text(x_artist, 0, text="Artist",
287 self.canvas.create_text(x_album, 0, text="Album",
290 self.canvas.create_text(x_title, 0, text="Title",
294 for n in range(0,len(artists)):
299 self.canvas.create_text(x_artist, y, text=artist,
303 self.canvas.create_text(x_album, y, text=album,
307 self.canvas.create_text(x_title, y, text=title,
312 self.configure(cursor=self.default_cursor)
317 # we do the track name calculation in the background thread so that
318 # the gui can still be responsive
322 w_artists = w_albums = w_titles = 16
324 artist = part(c, t['track'], 'display', 'artist')
325 album = part(c, t['track'], 'display', 'album')
326 title = part(c, t['track'], 'display', 'title')
327 w = tracklistFont.measure(artist)
330 w = tracklistFont.measure(album)
333 w = tracklistFont.measure(title)
336 artists.append(artist)
339 intercom.put(lambda: self.queue(q, w_artists, w_albums, w_titles,
340 artists, albums, titles))
343 class QueueWidget(TrackListWidget):
344 def __init__(self, master=None, **kw):
345 TrackListWidget.__init__(self, master, **kw)
347 def getqueue(self, c):
350 class RecentWidget(TrackListWidget):
351 def __init__(self, master=None, **kw):
352 TrackListWidget.__init__(self, master, **kw)
354 def getqueue(self, c):
359 class MonitorStateThread:
360 # thread to pick up current server state and publish it
362 # Creates a client and monitors it in a daemon thread for state changes.
363 # Whenever one occurs, call w.poll(c) for every member w of widgets with
364 # a client owned by the thread in which the call occurs.
365 def __init__(self, widgets, masterclient=None):
366 self.logclient = disorder.client()
367 self.client = disorder.client()
368 self.clientlock = threading.Lock()
370 masterclient = disorder.client()
371 self.masterclient = masterclient
372 self.widgets = widgets
373 self.lock = threading.Lock()
375 self.thread = threading.Thread(target=self.run)
376 self.thread.setDaemon(True)
378 # spare thread for processing additions
379 self.adderq = Queue.Queue()
380 self.adder = threading.Thread(target=self.runadder)
381 self.adder.setDaemon(True)
384 def notify(self, line):
386 widgets = self.widgets
389 self.clientlock.acquire()
391 self.clientlock.release()
396 self.widgets.append(w)
398 self.adderq.put(lambda client: w.poll(client))
400 def remove(self, what):
402 self.widgets.remove(what)
407 self.logclient.log(lambda client, line: self.notify(line))
411 item = self.adderq.get()
412 self.clientlock.acquire()
414 self.clientlock.release()
416 ########################################################################
427 -h, --help Display this message
428 -V, --version Display version number
430 tkdisorder is copyright (c) 2004, 2005 Richard Kettlewell.
433 ########################################################################
436 opts, rest = getopt.getopt(sys.argv[1:], "Vh", ["version", "help"])
437 except getopt.GetoptError, e:
438 sys.stderr.write("ERROR: %s, try --help for help\n" % e.msg)
441 if o in ('-V', '--version'):
442 print "%s" % disorder.version
445 if o in ('h', '--help'):
450 client = disorder.client() # master thread's client
453 root.title("DisOrder")
455 tracklistFont = tkFont.Font(family='Helvetica', size=10)
456 tracklistHFont = tracklistFont.copy()
457 tracklistHFont.config(weight="bold")
459 p = PlayingWidget(root)
460 p.pack(fill=BOTH, expand=1)
462 q = QueueWidget(root)
463 q.pack(fill=BOTH, expand=1)
465 intercom = Intercom(root) # only need a single intercom
466 mst = MonitorStateThread([p, q], client)