cplay

view cplay @ 0:aa5f022eac8a

Use upstream cplay-1.49 as a start
author markus schnalke <meillo@marmaro.de>
date Wed, 27 Sep 2017 09:22:32 +0200
parents
children c7d8ec7da73b
line source
1 #!/usr/bin/env python
2 # -*- python -*-
4 __version__ = "cplay 1.49"
6 """
7 cplay - A curses front-end for various audio players
8 Copyright (C) 1998-2003 Ulf Betlehem <flu@iki.fi>
10 This program is free software; you can redistribute it and/or
11 modify it under the terms of the GNU General Public License
12 as published by the Free Software Foundation; either version 2
13 of the License, or (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 """
25 # ------------------------------------------
26 from types import *
28 import os
29 import sys
30 import time
31 import getopt
32 import signal
33 import string
34 import select
35 import re
37 try: from ncurses import curses
38 except ImportError: import curses
40 try: import tty
41 except ImportError: tty = None
43 try: import locale; locale.setlocale(locale.LC_ALL, "")
44 except: pass
46 # ------------------------------------------
47 _locale_domain = "cplay"
48 _locale_dir = "/usr/local/share/locale"
50 try:
51 import gettext # python 2.0
52 gettext.install(_locale_domain, _locale_dir)
53 except ImportError:
54 try:
55 import fintl
56 fintl.bindtextdomain(_locale_domain, _locale_dir)
57 fintl.textdomain(_locale_domain)
58 _ = fintl.gettext
59 except ImportError:
60 def _(s): return s
61 except:
62 def _(s): return s
64 # ------------------------------------------
65 XTERM = re.search("rxvt|xterm", os.environ["TERM"])
66 CONTROL_FIFO = "/var/tmp/cplay_control"
68 # ------------------------------------------
69 def which(program):
70 for path in string.split(os.environ["PATH"], ":"):
71 if os.path.exists(os.path.join(path, program)):
72 return os.path.join(path, program)
74 # ------------------------------------------
75 def cut(s, n, left=0):
76 if left: return len(s) > n and "<%s" % s[-n+1:] or s
77 else: return len(s) > n and "%s>" % s[:n-1] or s
79 # ------------------------------------------
80 class Stack:
81 def __init__(self):
82 self.items = ()
84 def push(self, item):
85 self.items = (item,) + self.items
87 def pop(self):
88 self.items, item = self.items[1:], self.items[0]
89 return item
91 # ------------------------------------------
92 class KeymapStack(Stack):
93 def process(self, code):
94 for keymap in self.items:
95 if keymap and keymap.process(code):
96 break
98 # ------------------------------------------
99 class Keymap:
100 def __init__(self):
101 self.methods = [None] * curses.KEY_MAX
103 def bind(self, key, method, args=None):
104 if type(key) in (TupleType, ListType):
105 for i in key: self.bind(i, method, args)
106 return
107 if type(key) is StringType:
108 key = ord(key)
109 self.methods[key] = (method, args)
111 def process(self, key):
112 if self.methods[key] is None: return 0
113 method, args = self.methods[key]
114 if args is None:
115 apply(method, (key,))
116 else:
117 apply(method, args)
118 return 1
120 # ------------------------------------------
121 class Window:
122 chars = string.letters+string.digits+string.punctuation+string.whitespace
124 t = ['?'] * 256
125 for c in chars: t[ord(c)] = c
126 translationTable = string.join(t, ""); del t
128 def __init__(self, parent):
129 self.parent = parent
130 self.children = []
131 self.name = None
132 self.keymap = None
133 self.visible = 1
134 self.resize()
135 if parent: parent.children.append(self)
137 def insstr(self, s):
138 if not s: return
139 self.w.addstr(s[:-1])
140 self.w.hline(ord(s[-1]), 1) # insch() work-around
142 def __getattr__(self, name):
143 return getattr(self.w, name)
145 def getmaxyx(self):
146 y, x = self.w.getmaxyx()
147 try: curses.version # tested with 1.2 and 1.6
148 except AttributeError:
149 # pyncurses - emulate traditional (silly) behavior
150 y, x = y+1, x+1
151 return y, x
153 def touchwin(self):
154 try: self.w.touchwin()
155 except AttributeError: self.touchln(0, self.getmaxyx()[0])
157 def attron(self, attr):
158 try: self.w.attron(attr)
159 except AttributeError: self.w.attr_on(attr)
161 def attroff(self, attr):
162 try: self.w.attroff(attr)
163 except AttributeError: self.w.attr_off(attr)
165 def newwin(self):
166 return curses.newwin(0, 0, 0, 0)
168 def resize(self):
169 self.w = self.newwin()
170 self.ypos, self.xpos = self.getbegyx()
171 self.rows, self.cols = self.getmaxyx()
172 self.keypad(1)
173 self.leaveok(0)
174 self.scrollok(0)
175 for child in self.children:
176 child.resize()
178 def update(self):
179 self.clear()
180 self.refresh()
181 for child in self.children:
182 child.update()
184 # ------------------------------------------
185 class ProgressWindow(Window):
186 def __init__(self, parent):
187 Window.__init__(self, parent)
188 self.value = 0
190 def newwin(self):
191 return curses.newwin(1, self.parent.cols, self.parent.rows-2, 0)
193 def update(self):
194 self.move(0, 0)
195 self.hline(ord('-'), self.cols)
196 if self.value > 0:
197 self.move(0, 0)
198 x = int(self.value * self.cols) # 0 to cols-1
199 x and self.hline(ord('='), x)
200 self.move(0, x)
201 self.insstr('|')
202 self.touchwin()
203 self.refresh()
205 def progress(self, value):
206 self.value = min(value, 0.99)
207 self.update()
209 # ------------------------------------------
210 class StatusWindow(Window):
211 def __init__(self, parent):
212 Window.__init__(self, parent)
213 self.default_message = ''
214 self.current_message = ''
215 self.tid = None
217 def newwin(self):
218 return curses.newwin(1, self.parent.cols-12, self.parent.rows-1, 0)
220 def update(self):
221 msg = string.translate(self.current_message, Window.translationTable)
222 self.move(0, 0)
223 self.clrtoeol()
224 self.insstr(cut(msg, self.cols))
225 self.touchwin()
226 self.refresh()
228 def status(self, message, duration = 0):
229 self.current_message = str(message)
230 if self.tid: app.timeout.remove(self.tid)
231 if duration: self.tid = app.timeout.add(duration, self.timeout)
232 else: self.tid = None
233 self.update()
235 def timeout(self):
236 self.tid = None
237 self.restore_default_status()
239 def set_default_status(self, message):
240 if self.current_message == self.default_message: self.status(message)
241 self.default_message = message
242 XTERM and sys.stderr.write("\033]0;%s\a" % (message or "cplay"))
244 def restore_default_status(self):
245 self.status(self.default_message)
247 # ------------------------------------------
248 class CounterWindow(Window):
249 def __init__(self, parent):
250 Window.__init__(self, parent)
251 self.values = [0, 0]
252 self.mode = 1
254 def newwin(self):
255 return curses.newwin(1, 11, self.parent.rows-1, self.parent.cols-11)
257 def update(self):
258 h, s = divmod(self.values[self.mode], 3600)
259 m, s = divmod(s, 60)
260 self.move(0, 0)
261 self.attron(curses.A_BOLD)
262 self.insstr("%02dh %02dm %02ds" % (h, m, s))
263 self.attroff(curses.A_BOLD)
264 self.touchwin()
265 self.refresh()
267 def counter(self, values):
268 self.values = values
269 self.update()
271 def toggle_mode(self):
272 self.mode = not self.mode
273 tmp = [_("elapsed"), _("remaining")][self.mode]
274 app.status(_("Counting %s time") % tmp, 1)
275 self.update()
277 # ------------------------------------------
278 class RootWindow(Window):
279 def __init__(self, parent):
280 Window.__init__(self, parent)
281 keymap = Keymap()
282 app.keymapstack.push(keymap)
283 self.win_progress = ProgressWindow(self)
284 self.win_status = StatusWindow(self)
285 self.win_counter = CounterWindow(self)
286 self.win_tab = TabWindow(self)
287 keymap.bind(12, self.update, ()) # C-l
288 keymap.bind([curses.KEY_LEFT, 2], app.seek, (-1, 1)) # C-b
289 keymap.bind([curses.KEY_RIGHT, 6], app.seek, (1, 1)) # C-f
290 keymap.bind([1, '^'], app.seek, (0, 0)) # C-a
291 keymap.bind([5, '$'], app.seek, (-1, 0)) # C-e
292 keymap.bind(range(48,58), app.key_volume) # 0123456789
293 keymap.bind(['+', '='], app.inc_volume, ())
294 keymap.bind('-', app.dec_volume, ())
295 keymap.bind('n', app.next_song, ())
296 keymap.bind('p', app.prev_song, ())
297 keymap.bind('z', app.toggle_pause, ())
298 keymap.bind('x', app.toggle_stop, ())
299 keymap.bind('c', self.win_counter.toggle_mode, ())
300 keymap.bind('Q', app.quit, ())
301 keymap.bind('q', self.command_quit, ())
302 keymap.bind('v', app.mixer, ("toggle",))
304 def command_quit(self):
305 app.do_input_hook = self.do_quit
306 app.start_input(_("Quit? (y/N)"))
308 def do_quit(self, ch):
309 if chr(ch) == 'y': app.quit()
310 app.stop_input()
312 # ------------------------------------------
313 class TabWindow(Window):
314 def __init__(self, parent):
315 Window.__init__(self, parent)
316 self.active_child = 0
318 self.win_filelist = self.add(FilelistWindow)
319 self.win_playlist = self.add(PlaylistWindow)
320 self.win_help = self.add(HelpWindow)
322 keymap = Keymap()
323 keymap.bind('\t', self.change_window, ()) # tab
324 keymap.bind('h', self.help, ())
325 app.keymapstack.push(keymap)
326 app.keymapstack.push(self.children[self.active_child].keymap)
328 def newwin(self):
329 return curses.newwin(self.parent.rows-2, self.parent.cols, 0, 0)
331 def update(self):
332 self.update_title()
333 self.move(1, 0)
334 self.hline(ord('-'), self.cols)
335 self.move(2, 0)
336 self.clrtobot()
337 self.refresh()
338 child = self.children[self.active_child]
339 child.visible = 1
340 child.update()
342 def update_title(self, refresh = 1):
343 child = self.children[self.active_child]
344 self.move(0, 0)
345 self.clrtoeol()
346 self.attron(curses.A_BOLD)
347 self.insstr(child.get_title())
348 self.attroff(curses.A_BOLD)
349 if refresh: self.refresh()
351 def add(self, Class):
352 win = Class(self)
353 win.visible = 0
354 return win
356 def change_window(self, window = None):
357 app.keymapstack.pop()
358 self.children[self.active_child].visible = 0
359 if window:
360 self.active_child = self.children.index(window)
361 else:
362 # toggle windows 0 and 1
363 self.active_child = not self.active_child
364 app.keymapstack.push(self.children[self.active_child].keymap)
365 self.update()
367 def help(self):
368 if self.children[self.active_child] == self.win_help:
369 self.change_window(self.win_last)
370 else:
371 self.win_last = self.children[self.active_child]
372 self.change_window(self.win_help)
373 app.status(__version__, 2)
375 # ------------------------------------------
376 class ListWindow(Window):
377 def __init__(self, parent):
378 Window.__init__(self, parent)
379 self.buffer = []
380 self.bufptr = self.scrptr = 0
381 self.search_direction = 0
382 self.last_search = ""
383 self.hoffset = 0
384 self.keymap = Keymap()
385 self.keymap.bind(['k', curses.KEY_UP, 16], self.cursor_move, (-1,))
386 self.keymap.bind(['j', curses.KEY_DOWN, 14], self.cursor_move, (1,))
387 self.keymap.bind(['K', curses.KEY_PPAGE], self.cursor_ppage, ())
388 self.keymap.bind(['J', curses.KEY_NPAGE], self.cursor_npage, ())
389 self.keymap.bind(['g', curses.KEY_HOME], self.cursor_home, ())
390 self.keymap.bind(['G', curses.KEY_END], self.cursor_end, ())
391 self.keymap.bind(['?', 18], self.start_search,
392 (_("backward-isearch"), -1))
393 self.keymap.bind(['/', 19], self.start_search,
394 (_("forward-isearch"), 1))
395 self.keymap.bind(['>'], self.hscroll, (8,))
396 self.keymap.bind(['<'], self.hscroll, (-8,))
398 def newwin(self):
399 return curses.newwin(self.parent.rows-2, self.parent.cols,
400 self.parent.ypos+2, self.parent.xpos)
402 def update(self, force = 1):
403 self.bufptr = max(0, min(self.bufptr, len(self.buffer) - 1))
404 scrptr = (self.bufptr / self.rows) * self.rows
405 if force or self.scrptr != scrptr:
406 self.scrptr = scrptr
407 self.move(0, 0)
408 self.clrtobot()
409 i = 0
410 for entry in self.buffer[self.scrptr:]:
411 self.move(i, 0)
412 i = i + 1
413 self.putstr(entry)
414 if self.getyx()[0] == self.rows - 1: break
415 if self.visible:
416 self.refresh()
417 self.parent.update_title()
418 self.update_line(curses.A_REVERSE)
420 def update_line(self, attr = None, refresh = 1):
421 if not self.buffer: return
422 ypos = self.bufptr - self.scrptr
423 if attr: self.attron(attr)
424 self.move(ypos, 0)
425 self.hline(ord(' '), self.cols)
426 self.putstr(self.current())
427 if attr: self.attroff(attr)
428 if self.visible and refresh: self.refresh()
430 def get_title(self, data=""):
431 pos = "%s-%s/%s" % (self.scrptr+min(1, len(self.buffer)),
432 min(self.scrptr+self.rows, len(self.buffer)),
433 len(self.buffer))
434 width = self.cols-len(pos)-2
435 data = cut(data, width-len(self.name), 1)
436 return "%-*s %s" % (width, cut(self.name+data, width), pos)
438 def putstr(self, entry, *pos):
439 s = string.translate(str(entry), Window.translationTable)
440 pos and apply(self.move, pos)
441 if self.hoffset: s = "<%s" % s[self.hoffset+1:]
442 self.insstr(cut(s, self.cols))
444 def current(self):
445 if self.bufptr >= len(self.buffer): self.bufptr = len(self.buffer) - 1
446 return self.buffer[self.bufptr]
448 def cursor_move(self, ydiff):
449 if app.input_mode: app.cancel_input()
450 if not self.buffer: return
451 self.update_line(refresh = 0)
452 self.bufptr = (self.bufptr + ydiff) % len(self.buffer)
453 self.update(force = 0)
455 def cursor_ppage(self):
456 tmp = self.bufptr % self.rows
457 if tmp == self.bufptr:
458 self.cursor_move(-(tmp+(len(self.buffer) % self.rows) or self.rows))
459 else:
460 self.cursor_move(-(tmp+self.rows))
462 def cursor_npage(self):
463 tmp = self.rows - self.bufptr % self.rows
464 if self.bufptr + tmp > len(self.buffer):
465 self.cursor_move(len(self.buffer) - self.bufptr)
466 else:
467 self.cursor_move(tmp)
469 def cursor_home(self): self.cursor_move(-self.bufptr)
471 def cursor_end(self): self.cursor_move(-self.bufptr - 1)
473 def start_search(self, type, direction):
474 self.search_direction = direction
475 self.not_found = 0
476 if app.input_mode:
477 app.input_prompt = "%s: " % type
478 self.do_search(advance = direction)
479 else:
480 app.do_input_hook = self.do_search
481 app.stop_input_hook = self.stop_search
482 app.start_input(type)
484 def stop_search(self):
485 self.last_search = app.input_string
486 app.status(_("ok"), 1)
488 def do_search(self, ch = None, advance = 0):
489 if ch in [8, 127]: app.input_string = app.input_string[:-1]
490 elif ch: app.input_string = "%s%c" % (app.input_string, ch)
491 else: app.input_string = app.input_string or self.last_search
492 index = self.bufptr + advance
493 while 1:
494 if not 0 <= index < len(self.buffer):
495 app.status(_("Not found: %s ") % app.input_string)
496 self.not_found = 1
497 break
498 line = string.lower(str(self.buffer[index]))
499 if string.find(line, string.lower(app.input_string)) != -1:
500 app.show_input()
501 self.update_line(refresh = 0)
502 self.bufptr = index
503 self.update(force = 0)
504 self.not_found = 0
505 break
506 if self.not_found:
507 app.status(_("Not found: %s ") % app.input_string)
508 break
509 index = index + self.search_direction
511 def hscroll(self, value):
512 self.hoffset = max(0, self.hoffset + value)
513 self.update()
515 # ------------------------------------------
516 class HelpWindow(ListWindow):
517 def __init__(self, parent):
518 ListWindow.__init__(self, parent)
519 self.name = _("Help")
520 self.keymap.bind('q', self.parent.help, ())
521 self.buffer = string.split(_("""\
522 Global t, T : tag current/regex
523 ------ u, U : untag current/regex
524 Up, Down, k, j, C-p, C-n, Sp, i : invert current/all
525 PgUp, PgDn, K, J, ! : shell ($@ = tagged or current)
526 Home, End, g, G : movement
527 Enter : chdir or play Filelist
528 Tab : filelist/playlist --------
529 n, p : next/prev track a : add (tagged) to playlist
530 z, x : toggle pause/stop s : recursive search
531 BS, o : goto parent/specified dir
532 Left, Right, m, ' : set/get bookmark
533 C-f, C-b : seek forward/backward
534 C-a, C-e : restart/end track Playlist
535 C-s, C-r, / : isearch --------
536 C-g, Esc : cancel d, D : delete (tagged) tracks/playlist
537 1..9, +, - : volume control m, M : move tagged tracks after/before
538 c, v : counter/volume mode r, R : toggle repeat/Random mode
539 <, > : horizontal scrolling s, S : shuffle/Sort playlist
540 C-l, l : refresh, list mode w, @ : write playlist, jump to active
541 h, q, Q : help, quit?, Quit! X : stop playlist after each track
542 """), "\n")
544 # ------------------------------------------
545 class ListEntry:
546 def __init__(self, pathname, dir=0):
547 self.filename = os.path.basename(pathname)
548 self.pathname = pathname
549 self.slash = dir and "/" or ""
550 self.tagged = 0
552 def set_tagged(self, value):
553 self.tagged = value
555 def is_tagged(self):
556 return self.tagged == 1
558 def __str__(self):
559 mark = self.is_tagged() and "#" or " "
560 return "%s %s%s" % (mark, self.vp(), self.slash)
562 def vp(self):
563 return self.vps[0][1](self)
565 def vp_filename(self):
566 return self.filename or self.pathname
568 def vp_pathname(self):
569 return self.pathname
571 vps = [[_("filename"), vp_filename],
572 [_("pathname"), vp_pathname]]
574 # ------------------------------------------
575 class PlaylistEntry(ListEntry):
576 def __init__(self, pathname):
577 ListEntry.__init__(self, pathname)
578 self.metadata = None
579 self.active = 0
581 def set_active(self, value):
582 self.active = value
584 def is_active(self):
585 return self.active == 1
587 def vp_metadata(self):
588 return self.metadata or self.read_metadata()
590 def read_metadata(self):
591 self.metadata = get_tag(self.pathname)
592 return self.metadata
594 vps = ListEntry.vps[:]
596 # ------------------------------------------
597 class TagListWindow(ListWindow):
598 def __init__(self, parent):
599 ListWindow.__init__(self, parent)
600 self.keymap.bind(' ', self.command_tag_untag, ())
601 self.keymap.bind('i', self.command_invert_tags, ())
602 self.keymap.bind('t', self.command_tag, (1,))
603 self.keymap.bind('u', self.command_tag, (0,))
604 self.keymap.bind('T', self.command_tag_regexp, (1,))
605 self.keymap.bind('U', self.command_tag_regexp, (0,))
606 self.keymap.bind('l', self.command_change_viewpoint, ())
608 def command_change_viewpoint(self, klass=ListEntry):
609 klass.vps.append(klass.vps.pop(0))
610 app.status(_("Listing %s") % klass.vps[0][0], 1)
611 app.player.update_status()
612 self.update()
614 def command_invert_tags(self):
615 for i in self.buffer:
616 i.set_tagged(not i.is_tagged())
617 self.update()
619 def command_tag_untag(self):
620 if not self.buffer: return
621 tmp = self.buffer[self.bufptr]
622 tmp.set_tagged(not tmp.is_tagged())
623 self.cursor_move(1)
625 def command_tag(self, value):
626 if not self.buffer: return
627 self.buffer[self.bufptr].set_tagged(value)
628 self.cursor_move(1)
630 def command_tag_regexp(self, value):
631 self.tag_value = value
632 app.stop_input_hook = self.stop_tag_regexp
633 app.start_input(value and _("Tag regexp") or _("Untag regexp"))
635 def stop_tag_regexp(self):
636 try:
637 r = re.compile(app.input_string, re.I)
638 for entry in self.buffer:
639 if r.search(str(entry)):
640 entry.set_tagged(self.tag_value)
641 self.update()
642 app.status(_("ok"), 1)
643 except re.error, e:
644 app.status(e, 2)
646 def get_tagged(self):
647 return filter(lambda x: x.is_tagged(), self.buffer)
649 def not_tagged(self, l):
650 return filter(lambda x: not x.is_tagged(), l)
652 # ------------------------------------------
653 class FilelistWindow(TagListWindow):
654 def __init__(self, parent):
655 TagListWindow.__init__(self, parent)
656 self.oldposition = {}
657 try: self.chdir(os.getcwd())
658 except OSError: self.chdir(os.environ['HOME'])
659 self.startdir = self.cwd
660 self.mtime_when = 0
661 self.mtime = None
662 self.keymap.bind(['\n', curses.KEY_ENTER],
663 self.command_chdir_or_play, ())
664 self.keymap.bind(['.', curses.KEY_BACKSPACE],
665 self.command_chparentdir, ())
666 self.keymap.bind('a', self.command_add_recursively, ())
667 self.keymap.bind('o', self.command_goto, ())
668 self.keymap.bind('s', self.command_search_recursively, ())
669 self.keymap.bind('m', self.command_set_bookmark, ())
670 self.keymap.bind("'", self.command_get_bookmark, ())
671 self.keymap.bind('!', self.command_shell, ())
672 self.bookmarks = { 39: [self.cwd, 0] }
674 def command_shell(self):
675 if app.restricted: return
676 app.stop_input_hook = self.stop_shell
677 app.complete_input_hook = self.complete_shell
678 app.start_input(_("shell$ "), colon=0)
680 def stop_shell(self):
681 s = app.input_string
682 curses.endwin()
683 sys.stderr.write("\n")
684 argv = map(lambda x: x.pathname, self.get_tagged() or [self.current()])
685 argv = ["/bin/sh", "-c", s, "--"] + argv
686 pid = os.fork()
687 if pid == 0:
688 try: os.execv(argv[0], argv)
689 except: os._exit(1)
690 pid, r = os.waitpid(pid, 0)
691 sys.stderr.write("\nshell returned %s, press return!\n" % r)
692 sys.stdin.readline()
693 app.win_root.update()
694 app.restore_default_status()
695 app.cursor(0)
697 def complete_shell(self, line):
698 return self.complete_generic(line, quote=1)
700 def complete_generic(self, line, quote=0):
701 import glob
702 if quote:
703 s = re.sub('.*[^\\\\][ \'"()\[\]{}$`]', '', line)
704 s, part = re.sub('\\\\', '', s), line[:len(line)-len(s)]
705 else:
706 s, part = line, ""
707 results = glob.glob(os.path.expanduser(s)+"*")
708 if len(results) == 0:
709 return line
710 if len(results) == 1:
711 lm = results[0]
712 lm = lm + (os.path.isdir(lm) and "/" or "")
713 else:
714 lm = results[0]
715 for result in results:
716 for i in range(min(len(result), len(lm))):
717 if result[i] != lm[i]:
718 lm = lm[:i]
719 break
720 if quote: lm = re.sub('([ \'"()\[\]{}$`])', '\\\\\\1', lm)
721 return part + lm
723 def command_get_bookmark(self):
724 app.do_input_hook = self.do_get_bookmark
725 app.start_input(_("bookmark"))
727 def do_get_bookmark(self, ch):
728 app.input_string = ch
729 bookmark = self.bookmarks.get(ch)
730 if bookmark:
731 self.bookmarks[39] = [self.cwd, self.bufptr]
732 dir, pos = bookmark
733 self.chdir(dir)
734 self.listdir()
735 self.bufptr = pos
736 self.update()
737 app.status(_("ok"), 1)
738 else:
739 app.status(_("Not found!"), 1)
740 app.stop_input()
742 def command_set_bookmark(self):
743 app.do_input_hook = self.do_set_bookmark
744 app.start_input(_("set bookmark"))
746 def do_set_bookmark(self, ch):
747 app.input_string = ch
748 self.bookmarks[ch] = [self.cwd, self.bufptr]
749 ch and app.status(_("ok"), 1) or app.stop_input()
751 def command_search_recursively(self):
752 app.stop_input_hook = self.stop_search_recursively
753 app.start_input(_("search"))
755 def stop_search_recursively(self):
756 try: re_tmp = re.compile(app.input_string, re.I)
757 except re.error, e:
758 app.status(e, 2)
759 return
760 app.status(_("Searching..."))
761 results = []
762 for entry in self.buffer:
763 if entry.filename == "..":
764 continue
765 if re_tmp.search(entry.filename):
766 results.append(entry)
767 elif os.path.isdir(entry.pathname):
768 try: self.search_recursively(re_tmp, entry.pathname, results)
769 except: pass
770 if not self.search_mode:
771 self.chdir(os.path.join(self.cwd,_("search results")))
772 self.search_mode = 1
773 self.buffer = results
774 self.bufptr = 0
775 self.parent.update_title()
776 self.update()
777 app.restore_default_status()
779 def search_recursively(self, re_tmp, dir, results):
780 for filename in os.listdir(dir):
781 pathname = os.path.join(dir, filename)
782 if re_tmp.search(filename):
783 if os.path.isdir(pathname):
784 results.append(ListEntry(pathname, 1))
785 elif VALID_PLAYLIST(filename) or VALID_SONG(filename):
786 results.append(ListEntry(pathname))
787 elif os.path.isdir(pathname):
788 self.search_recursively(re_tmp, pathname, results)
790 def get_title(self):
791 self.name = _("Filelist: ")
792 return ListWindow.get_title(self, re.sub("/?$", "/", self.cwd))
794 def listdir_maybe(self, now=0):
795 if now < self.mtime_when+2: return
796 self.mtime_when = now
797 self.oldposition[self.cwd] = self.bufptr
798 try: self.mtime == os.stat(self.cwd)[8] or self.listdir(quiet=1)
799 except os.error: pass
801 def listdir(self, quiet=0, prevdir=None):
802 quiet or app.status(_("Reading directory..."))
803 self.search_mode = 0
804 dirs = []
805 files = []
806 try:
807 self.mtime = os.stat(self.cwd)[8]
808 self.mtime_when = time.time()
809 filenames = os.listdir(self.cwd)
810 filenames.sort()
811 for filename in filenames:
812 if filename[0] == ".": continue
813 pathname = os.path.join(self.cwd, filename)
814 if os.path.isdir(pathname): dirs.append(pathname)
815 elif VALID_SONG(filename): files.append(pathname)
816 elif VALID_PLAYLIST(filename): files.append(pathname)
817 except os.error: pass
818 dots = ListEntry(os.path.join(self.cwd, ".."), 1)
819 self.buffer = [[dots], []][self.cwd == "/"]
820 for i in dirs: self.buffer.append(ListEntry(i, 1))
821 for i in files: self.buffer.append(ListEntry(i))
822 if prevdir:
823 for self.bufptr in range(len(self.buffer)):
824 if self.buffer[self.bufptr].filename == prevdir: break
825 else: self.bufptr = 0
826 elif self.oldposition.has_key(self.cwd):
827 self.bufptr = self.oldposition[self.cwd]
828 else: self.bufptr = 0
829 self.parent.update_title()
830 self.update()
831 quiet or app.restore_default_status()
833 def chdir(self, dir):
834 if hasattr(self, "cwd"): self.oldposition[self.cwd] = self.bufptr
835 self.cwd = os.path.normpath(dir)
836 try: os.chdir(self.cwd)
837 except: pass
839 def command_chdir_or_play(self):
840 if not self.buffer: return
841 if self.current().filename == "..":
842 self.command_chparentdir()
843 elif os.path.isdir(self.current().pathname):
844 self.chdir(self.current().pathname)
845 self.listdir()
846 elif VALID_SONG(self.current().filename):
847 app.play(self.current())
849 def command_chparentdir(self):
850 if app.restricted and self.cwd == self.startdir: return
851 dir = os.path.basename(self.cwd)
852 self.chdir(os.path.dirname(self.cwd))
853 self.listdir(prevdir=dir)
855 def command_goto(self):
856 if app.restricted: return
857 app.stop_input_hook = self.stop_goto
858 app.complete_input_hook = self.complete_generic
859 app.start_input(_("goto"))
861 def stop_goto(self):
862 dir = os.path.expanduser(app.input_string)
863 if dir[0] != '/': dir = os.path.join(self.cwd, dir)
864 if not os.path.isdir(dir):
865 app.status(_("Not a directory!"), 1)
866 return
867 self.chdir(dir)
868 self.listdir()
870 def command_add_recursively(self):
871 l = self.get_tagged()
872 if not l:
873 app.win_playlist.add(self.current().pathname)
874 self.cursor_move(1)
875 return
876 app.status(_("Adding tagged files"), 1)
877 for entry in l:
878 app.win_playlist.add(entry.pathname, quiet=1)
879 entry.set_tagged(0)
880 self.update()
882 # ------------------------------------------
883 class PlaylistWindow(TagListWindow):
884 def __init__(self, parent):
885 TagListWindow.__init__(self, parent)
886 self.pathname = None
887 self.repeat = 0
888 self.random = 0
889 self.random_prev = []
890 self.random_next = []
891 self.random_left = []
892 self.stop = 0
893 self.keymap.bind(['\n', curses.KEY_ENTER],
894 self.command_play, ())
895 self.keymap.bind('d', self.command_delete, ())
896 self.keymap.bind('D', self.command_delete_all, ())
897 self.keymap.bind('m', self.command_move, (1,))
898 self.keymap.bind('M', self.command_move, (0,))
899 self.keymap.bind('s', self.command_shuffle, ())
900 self.keymap.bind('S', self.command_sort, ())
901 self.keymap.bind('r', self.command_toggle_repeat, ())
902 self.keymap.bind('R', self.command_toggle_random, ())
903 self.keymap.bind('X', self.command_toggle_stop, ())
904 self.keymap.bind('w', self.command_save_playlist, ())
905 self.keymap.bind('@', self.command_jump_to_active, ())
907 def command_change_viewpoint(self, klass=PlaylistEntry):
908 if not globals().get("ID3"):
909 try:
910 global ID3, ogg, codecs
911 import ID3, ogg.vorbis, codecs
912 klass.vps.append([_("metadata"), klass.vp_metadata])
913 except ImportError: pass
914 TagListWindow.command_change_viewpoint(self, klass)
916 def get_title(self):
917 space_out = lambda value, s: value and s or " "*len(s)
918 self.name = _("Playlist %s %s %s") % (
919 space_out(self.repeat, _("[repeat]")),
920 space_out(self.random, _("[random]")),
921 space_out(self.stop, _("[stop]")))
922 return ListWindow.get_title(self)
924 def append(self, item):
925 self.buffer.append(item)
926 if self.random: self.random_left.append(item)
928 def add_dir(self, dir):
929 filenames = os.listdir(dir)
930 filenames.sort()
931 subdirs = []
932 for filename in filenames:
933 pathname = os.path.join(dir, filename)
934 if VALID_SONG(filename):
935 self.append(PlaylistEntry(pathname))
936 if os.path.isdir(pathname):
937 subdirs.append(pathname)
938 map(self.add_dir, subdirs)
940 def add_m3u(self, line):
941 if re.match("^(#.*)?$", line): return
942 if re.match("^(/|http://)", line):
943 self.append(PlaylistEntry(self.fix_url(line)))
944 else:
945 dirname = os.path.dirname(self.pathname)
946 self.append(PlaylistEntry(os.path.join(dirname, line)))
948 def add_pls(self, line):
949 # todo - support title & length
950 m = re.match("File(\d+)=(.*)", line)
951 if m: self.append(PlaylistEntry(self.fix_url(m.group(2))))
953 def add_playlist(self, pathname):
954 self.pathname = pathname
955 if re.search("\.m3u$", pathname, re.I): f = self.add_m3u
956 if re.search("\.pls$", pathname, re.I): f = self.add_pls
957 file = open(pathname)
958 map(f, map(string.strip, file.readlines()))
959 file.close()
961 def add(self, pathname, quiet=0):
962 try:
963 if os.path.isdir(pathname):
964 app.status(_("Working..."))
965 self.add_dir(pathname)
966 elif VALID_PLAYLIST(pathname):
967 self.add_playlist(pathname)
968 else:
969 pathname = self.fix_url(pathname)
970 self.append(PlaylistEntry(pathname))
971 # todo - refactor
972 filename = os.path.basename(pathname) or pathname
973 quiet or app.status(_("Added: %s") % filename, 1)
974 except Exception, e:
975 app.status(e, 2)
977 def fix_url(self, url):
978 return re.sub("(http://[^/]+)/?(.*)", "\\1/\\2", url)
980 def putstr(self, entry, *pos):
981 if entry.is_active(): self.attron(curses.A_BOLD)
982 apply(ListWindow.putstr, (self, entry) + pos)
983 if entry.is_active(): self.attroff(curses.A_BOLD)
985 def change_active_entry(self, direction):
986 if not self.buffer: return
987 old = self.get_active_entry()
988 new = None
989 if self.random:
990 if direction > 0:
991 if self.random_next: new = self.random_next.pop()
992 elif self.random_left: pass
993 elif self.repeat: self.random_left = self.buffer[:]
994 else: return
995 if not new:
996 import random
997 new = random.choice(self.random_left)
998 self.random_left.remove(new)
999 try: self.random_prev.remove(new)
1000 except ValueError: pass
1001 self.random_prev.append(new)
1002 else:
1003 if len(self.random_prev) > 1:
1004 self.random_next.append(self.random_prev.pop())
1005 new = self.random_prev[-1]
1006 else: return
1007 old and old.set_active(0)
1008 elif old:
1009 index = self.buffer.index(old)+direction
1010 if not (0 <= index < len(self.buffer) or self.repeat): return
1011 old.set_active(0)
1012 new = self.buffer[index % len(self.buffer)]
1013 else:
1014 new = self.buffer[0]
1015 new.set_active(1)
1016 self.update()
1017 return new
1019 def get_active_entry(self):
1020 for entry in self.buffer:
1021 if entry.is_active(): return entry
1023 def command_jump_to_active(self):
1024 entry = self.get_active_entry()
1025 if not entry: return
1026 self.bufptr = self.buffer.index(entry)
1027 self.update()
1029 def command_play(self):
1030 if not self.buffer: return
1031 entry = self.get_active_entry()
1032 entry and entry.set_active(0)
1033 entry = self.current()
1034 entry.set_active(1)
1035 self.update()
1036 app.play(entry)
1038 def command_delete(self):
1039 if not self.buffer: return
1040 current_entry, n = self.current(), len(self.buffer)
1041 self.buffer = self.not_tagged(self.buffer)
1042 if n > len(self.buffer):
1043 try: self.bufptr = self.buffer.index(current_entry)
1044 except ValueError: pass
1045 else:
1046 current_entry.set_tagged(1)
1047 del self.buffer[self.bufptr]
1048 if self.random:
1049 self.random_prev = self.not_tagged(self.random_prev)
1050 self.random_next = self.not_tagged(self.random_next)
1051 self.random_left = self.not_tagged(self.random_left)
1052 self.update()
1054 def command_delete_all(self):
1055 self.buffer = []
1056 self.random_prev = []
1057 self.random_next = []
1058 self.random_left = []
1059 app.status(_("Deleted playlist"), 1)
1060 self.update()
1062 def command_move(self, after):
1063 if not self.buffer: return
1064 current_entry, l = self.current(), self.get_tagged()
1065 if not l or current_entry.is_tagged(): return
1066 self.buffer = self.not_tagged(self.buffer)
1067 self.bufptr = self.buffer.index(current_entry)+after
1068 self.buffer[self.bufptr:self.bufptr] = l
1069 self.update()
1071 def command_shuffle(self):
1072 import random
1073 l = []
1074 n = len(self.buffer)
1075 while n > 0:
1076 n = n-1
1077 r = random.randint(0, n)
1078 l.append(self.buffer[r])
1079 del self.buffer[r]
1080 self.buffer = l
1081 self.bufptr = 0
1082 self.update()
1083 app.status(_("Shuffled playlist... Oops?"), 1)
1085 def command_sort(self):
1086 app.status(_("Working..."))
1087 self.buffer.sort(lambda x, y: x.vp() > y.vp() or -1)
1088 self.bufptr = 0
1089 self.update()
1090 app.status(_("Sorted playlist"), 1)
1092 def command_toggle_repeat(self):
1093 self.toggle("repeat", _("Repeat: %s"))
1095 def command_toggle_random(self):
1096 self.toggle("random", _("Random: %s"))
1097 self.random_prev = []
1098 self.random_next = []
1099 self.random_left = self.buffer[:]
1101 def command_toggle_stop(self):
1102 self.toggle("stop", _("Stop playlist: %s"))
1104 def toggle(self, attr, format):
1105 setattr(self, attr, not getattr(self, attr))
1106 app.status(format % (getattr(self, attr) and _("on") or _("off")), 1)
1107 self.parent.update_title()
1109 def command_save_playlist(self):
1110 if app.restricted: return
1111 default = self.pathname or "%s/" % app.win_filelist.cwd
1112 app.stop_input_hook = self.stop_save_playlist
1113 app.start_input(_("Save playlist"), default)
1115 def stop_save_playlist(self):
1116 pathname = app.input_string
1117 if pathname[0] != '/':
1118 pathname = os.path.join(app.win_filelist.cwd, pathname)
1119 if not re.search("\.m3u$", pathname, re.I):
1120 pathname = "%s%s" % (pathname, ".m3u")
1121 try:
1122 file = open(pathname, "w")
1123 for entry in self.buffer:
1124 file.write("%s\n" % entry.pathname)
1125 file.close()
1126 self.pathname = pathname
1127 app.status(_("ok"), 1)
1128 except IOError, e:
1129 app.status(e, 2)
1131 # ------------------------------------------
1132 def get_tag(pathname):
1133 if re.compile("^http://").match(pathname) or not os.path.exists(pathname):
1134 return pathname
1135 tags = {}
1136 # FIXME: use magic instead of file extensions to identify OGGs and MP3s
1137 if re.compile(".*\.ogg$", re.I).match(pathname):
1138 try:
1139 vf = ogg.vorbis.VorbisFile(pathname)
1140 vc = vf.comment()
1141 tags = vc.as_dict()
1142 except NameError: pass
1143 except (IOError, UnicodeError): return os.path.basename(pathname)
1144 elif re.compile(".*\.mp3$", re.I).match(pathname):
1145 try:
1146 vc = ID3.ID3(pathname, as_tuple=1)
1147 tags = vc.as_dict()
1148 except NameError: pass
1149 except (IOError, ID3.InvalidTagError): return os.path.basename(pathname)
1150 else:
1151 return os.path.basename(pathname)
1153 artist = tags.get("ARTIST", [""])[0]
1154 title = tags.get("TITLE", [""])[0]
1155 tag = os.path.basename(pathname)
1156 try:
1157 if artist and title:
1158 tag = codecs.latin_1_encode(artist)[0] + " - " + codecs.latin_1_encode(title)[0]
1159 elif artist:
1160 tag = artist
1161 elif title:
1162 tag = title
1163 return codecs.latin_1_encode(tag)[0]
1164 except (NameError, UnicodeError): return tag
1166 # ------------------------------------------
1167 class Player:
1168 def __init__(self, commandline, files, fps=1):
1169 self.commandline = commandline
1170 self.re_files = re.compile(files, re.I)
1171 self.fps = fps
1172 self.stdin_r, self.stdin_w = os.pipe()
1173 self.stdout_r, self.stdout_w = os.pipe()
1174 self.stderr_r, self.stderr_w = os.pipe()
1175 self.entry = None
1176 self.stopped = 0
1177 self.paused = 0
1178 self.time_setup = None
1179 self.buf = ''
1180 self.tid = None
1182 def setup(self, entry, offset):
1183 self.argv = string.split(self.commandline)
1184 self.argv[0] = which(self.argv[0])
1185 for i in range(len(self.argv)):
1186 if self.argv[i] == "%s": self.argv[i] = entry.pathname
1187 if self.argv[i] == "%d": self.argv[i] = str(offset*self.fps)
1188 self.entry = entry
1189 if offset == 0:
1190 app.progress(0)
1191 self.offset = 0
1192 self.length = 0
1193 self.values = [0, 0]
1194 self.time_setup = time.time()
1195 return self.argv[0]
1197 def play(self):
1198 self.pid = os.fork()
1199 if self.pid == 0:
1200 os.dup2(self.stdin_w, sys.stdin.fileno())
1201 os.dup2(self.stdout_w, sys.stdout.fileno())
1202 os.dup2(self.stderr_w, sys.stderr.fileno())
1203 os.setpgrp()
1204 try: os.execv(self.argv[0], self.argv)
1205 except: os._exit(1)
1206 self.stopped = 0
1207 self.paused = 0
1208 self.step = 0
1209 self.update_status()
1211 def stop(self, quiet=0):
1212 self.paused and self.toggle_pause(quiet)
1213 try:
1214 while 1:
1215 try: os.kill(-self.pid, signal.SIGINT)
1216 except os.error: pass
1217 os.waitpid(self.pid, os.WNOHANG)
1218 except Exception: pass
1219 self.stopped = 1
1220 quiet or self.update_status()
1222 def toggle_pause(self, quiet=0):
1223 try: os.kill(-self.pid, [signal.SIGSTOP, signal.SIGCONT][self.paused])
1224 except os.error: return
1225 self.paused = not self.paused
1226 quiet or self.update_status()
1228 def parse_progress(self):
1229 if self.stopped or self.step: self.tid = None
1230 else:
1231 self.parse_buf()
1232 self.tid = app.timeout.add(1.0, self.parse_progress)
1234 def read_fd(self, fd):
1235 self.buf = os.read(fd, 512)
1236 self.tid or self.parse_progress()
1238 def poll(self):
1239 try: os.waitpid(self.pid, os.WNOHANG)
1240 except:
1241 # something broken? try again
1242 if self.time_setup and (time.time() - self.time_setup) < 2.0:
1243 self.play()
1244 return 0
1245 app.set_default_status("")
1246 app.counter([0,0])
1247 app.progress(0)
1248 return 1
1250 def seek(self, offset, relative):
1251 if relative:
1252 d = offset * self.length * 0.002
1253 self.step = self.step * (self.step * d > 0) + d
1254 self.offset = min(self.length, max(0, self.offset+self.step))
1255 else:
1256 self.step = 1
1257 self.offset = (offset < 0) and self.length+offset or offset
1258 self.show_position()
1260 def set_position(self, offset, length, values):
1261 self.offset = offset
1262 self.length = length
1263 self.values = values
1264 self.show_position()
1266 def show_position(self):
1267 app.counter(self.values)
1268 app.progress(self.length and (float(self.offset) / self.length))
1270 def update_status(self):
1271 if not self.entry:
1272 app.set_default_status("")
1273 elif self.stopped:
1274 app.set_default_status(_("Stopped: %s") % self.entry.vp())
1275 elif self.paused:
1276 app.set_default_status(_("Paused: %s") % self.entry.vp())
1277 else:
1278 app.set_default_status(_("Playing: %s") % self.entry.vp())
1280 # ------------------------------------------
1281 class FrameOffsetPlayer(Player):
1282 re_progress = re.compile("Time.*\s(\d+):(\d+).*\[(\d+):(\d+)")
1284 def parse_buf(self):
1285 match = self.re_progress.search(self.buf)
1286 if match:
1287 m1, s1, m2, s2 = map(string.atoi, match.groups())
1288 head, tail = m1*60+s1, m2*60+s2
1289 self.set_position(head, head+tail, [head, tail])
1291 # ------------------------------------------
1292 class TimeOffsetPlayer(Player):
1293 re_progress = re.compile("(\d+):(\d+):(\d+)")
1295 def parse_buf(self):
1296 match = self.re_progress.search(self.buf)
1297 if match:
1298 h, m, s = map(string.atoi, match.groups())
1299 tail = h*3600+m*60+s
1300 head = max(self.length, tail) - tail
1301 self.set_position(head, head+tail, [head, tail])
1303 # ------------------------------------------
1304 class NoOffsetPlayer(Player):
1306 def parse_buf(self):
1307 head = self.offset+1
1308 self.set_position(head, 0, [head, head])
1310 def seek(self, *dummy):
1311 return 1
1313 # ------------------------------------------
1314 class Timeout:
1315 def __init__(self):
1316 self.next = 0
1317 self.dict = {}
1319 def add(self, timeout, func, args=()):
1320 tid = self.next = self.next + 1
1321 self.dict[tid] = (func, args, time.time() + timeout)
1322 return tid
1324 def remove(self, tid):
1325 del self.dict[tid]
1327 def check(self, now):
1328 for tid, (func, args, timeout) in self.dict.items():
1329 if now >= timeout:
1330 self.remove(tid)
1331 apply(func, args)
1332 return len(self.dict) and 0.2 or None
1334 # ------------------------------------------
1335 class FIFOControl:
1336 def __init__(self):
1337 try: self.fd = open(CONTROL_FIFO, "rb+", 0)
1338 except: self.fd = None
1339 self.commands = {"pause" : app.toggle_pause,
1340 "next" : app.next_song,
1341 "prev" : app.prev_song,
1342 "forward" : self.forward,
1343 "backward" : self.backward,
1344 "play" : app.toggle_stop,
1345 "stop" : app.toggle_stop,
1346 "volup" : app.inc_volume,
1347 "voldown" : app.dec_volume,
1348 "quit" : app.quit}
1350 def handle_command(self):
1351 command = string.strip(self.fd.readline())
1352 if command in self.commands.keys():
1353 self.commands[command]()
1355 def forward(self):
1356 app.seek(1, 1)
1358 def backward(self):
1359 app.seek(-1, 1)
1361 # ------------------------------------------
1362 class Application:
1363 def __init__(self):
1364 self.keymapstack = KeymapStack()
1365 self.input_mode = 0
1366 self.input_prompt = ""
1367 self.input_string = ""
1368 self.do_input_hook = None
1369 self.stop_input_hook = None
1370 self.complete_input_hook = None
1371 self.channels = []
1372 self.restricted = 0
1373 self.input_keymap = Keymap()
1374 self.input_keymap.bind(list(Window.chars), self.do_input)
1375 self.input_keymap.bind(curses.KEY_BACKSPACE, self.do_input, (8,))
1376 self.input_keymap.bind([21, 23], self.do_input)
1377 self.input_keymap.bind(['\a', 27], self.cancel_input, ())
1378 self.input_keymap.bind(['\n', curses.KEY_ENTER],
1379 self.stop_input, ())
1381 def setup(self):
1382 if tty:
1383 self.tcattr = tty.tcgetattr(sys.stdin.fileno())
1384 tcattr = tty.tcgetattr(sys.stdin.fileno())
1385 tcattr[0] = tcattr[0] & ~(tty.IXON)
1386 tty.tcsetattr(sys.stdin.fileno(), tty.TCSANOW, tcattr)
1387 self.w = curses.initscr()
1388 curses.cbreak()
1389 curses.noecho()
1390 try: curses.meta(1)
1391 except: pass
1392 self.cursor(0)
1393 signal.signal(signal.SIGCHLD, signal.SIG_IGN)
1394 signal.signal(signal.SIGHUP, self.handler_quit)
1395 signal.signal(signal.SIGINT, self.handler_quit)
1396 signal.signal(signal.SIGTERM, self.handler_quit)
1397 signal.signal(signal.SIGWINCH, self.handler_resize)
1398 self.win_root = RootWindow(None)
1399 self.win_root.update()
1400 self.win_tab = self.win_root.win_tab
1401 self.win_filelist = self.win_root.win_tab.win_filelist
1402 self.win_playlist = self.win_root.win_tab.win_playlist
1403 self.win_status = self.win_root.win_status
1404 self.status = self.win_status.status
1405 self.set_default_status = self.win_status.set_default_status
1406 self.restore_default_status = self.win_status.restore_default_status
1407 self.counter = self.win_root.win_counter.counter
1408 self.progress = self.win_root.win_progress.progress
1409 self.player = PLAYERS[0]
1410 self.timeout = Timeout()
1411 self.play_tid = None
1412 self.kludge = 0
1413 self.win_filelist.listdir()
1414 self.control = FIFOControl()
1416 def cleanup(self):
1417 try: curses.endwin()
1418 except curses.error: return
1419 XTERM and sys.stderr.write("\033]0;%s\a" % "xterm")
1420 tty and tty.tcsetattr(sys.stdin.fileno(), tty.TCSADRAIN, self.tcattr)
1421 print
1423 def run(self):
1424 while 1:
1425 now = time.time()
1426 timeout = self.timeout.check(now)
1427 self.win_filelist.listdir_maybe(now)
1428 if not self.player.stopped:
1429 timeout = 0.5
1430 if self.kludge and self.player.poll():
1431 self.player.stopped = 1 # end of playlist hack
1432 if not self.win_playlist.stop:
1433 entry = self.win_playlist.change_active_entry(1)
1434 entry and self.play(entry)
1435 R = [sys.stdin, self.player.stdout_r, self.player.stderr_r]
1436 self.control.fd and R.append(self.control.fd)
1437 try: r, w, e = select.select(R, [], [], timeout)
1438 except select.error: continue
1439 self.kludge = 1
1440 # user
1441 if sys.stdin in r:
1442 c = self.win_root.getch()
1443 self.keymapstack.process(c)
1444 # player
1445 if self.player.stderr_r in r:
1446 self.player.read_fd(self.player.stderr_r)
1447 # player
1448 if self.player.stdout_r in r:
1449 self.player.read_fd(self.player.stdout_r)
1450 # remote
1451 if self.control.fd in r:
1452 self.control.handle_command()
1454 def play(self, entry, offset = 0):
1455 self.kludge = 0
1456 self.play_tid = None
1457 if entry is None or offset is None: return
1458 self.player.stop(quiet=1)
1459 for self.player in PLAYERS:
1460 if self.player.re_files.search(entry.pathname):
1461 if self.player.setup(entry, offset): break
1462 else:
1463 app.status(_("Player not found!"), 1)
1464 self.player.stopped = 0 # keep going
1465 return
1466 self.player.play()
1468 def delayed_play(self, entry, offset):
1469 if self.play_tid: self.timeout.remove(self.play_tid)
1470 self.play_tid = self.timeout.add(0.5, self.play, (entry, offset))
1472 def next_song(self):
1473 self.delayed_play(self.win_playlist.change_active_entry(1), 0)
1475 def prev_song(self):
1476 self.delayed_play(self.win_playlist.change_active_entry(-1), 0)
1478 def seek(self, offset, relative):
1479 if not self.player.entry: return
1480 self.player.seek(offset, relative)
1481 self.delayed_play(self.player.entry, self.player.offset)
1483 def toggle_pause(self):
1484 if not self.player.entry: return
1485 if not self.player.stopped: self.player.toggle_pause()
1487 def toggle_stop(self):
1488 if not self.player.entry: return
1489 if not self.player.stopped: self.player.stop()
1490 else: self.play(self.player.entry, self.player.offset)
1492 def inc_volume(self):
1493 self.mixer("cue", 1)
1495 def dec_volume(self):
1496 self.mixer("cue", -1)
1498 def key_volume(self, ch):
1499 self.mixer("set", (ch & 0x0f)*10)
1501 def mixer(self, cmd=None, arg=None):
1502 try: self._mixer(cmd, arg)
1503 except Exception, e: app.status(e, 2)
1505 def _mixer(self, cmd, arg):
1506 try:
1507 import ossaudiodev
1508 mixer = ossaudiodev.openmixer()
1509 get, set = mixer.get, mixer.set
1510 self.channels = self.channels or \
1511 [['MASTER', ossaudiodev.SOUND_MIXER_VOLUME],
1512 ['PCM', ossaudiodev.SOUND_MIXER_PCM]]
1513 except ImportError:
1514 import oss
1515 mixer = oss.open_mixer()
1516 get, set = mixer.read_channel, mixer.write_channel
1517 self.channels = self.channels or \
1518 [['MASTER', oss.SOUND_MIXER_VOLUME],
1519 ['PCM', oss.SOUND_MIXER_PCM]]
1520 if cmd is "toggle": self.channels.insert(0, self.channels.pop())
1521 name, channel = self.channels[0]
1522 if cmd is "cue": arg = min(100, max(0, get(channel)[0] + arg))
1523 if cmd in ["set", "cue"]: set(channel, (arg, arg))
1524 app.status(_("%s volume %s%%") % (name, get(channel)[0]), 1)
1525 mixer.close()
1527 def show_input(self):
1528 n = len(self.input_prompt)+1
1529 s = cut(self.input_string, self.win_status.cols-n, left=1)
1530 app.status("%s%s " % (self.input_prompt, s))
1532 def start_input(self, prompt="", data="", colon=1):
1533 self.input_mode = 1
1534 self.cursor(1)
1535 app.keymapstack.push(self.input_keymap)
1536 self.input_prompt = prompt + (colon and ": " or "")
1537 self.input_string = data
1538 self.show_input()
1540 def do_input(self, *args):
1541 if self.do_input_hook:
1542 return apply(self.do_input_hook, args)
1543 ch = args and args[0] or None
1544 if ch in [8, 127]: # backspace
1545 self.input_string = self.input_string[:-1]
1546 elif ch == 9 and self.complete_input_hook:
1547 self.input_string = self.complete_input_hook(self.input_string)
1548 elif ch == 21: # C-u
1549 self.input_string = ""
1550 elif ch == 23: # C-w
1551 self.input_string = re.sub("((.* )?)\w.*", "\\1", self.input_string)
1552 elif ch:
1553 self.input_string = "%s%c" % (self.input_string, ch)
1554 self.show_input()
1556 def stop_input(self, *args):
1557 self.input_mode = 0
1558 self.cursor(0)
1559 app.keymapstack.pop()
1560 if not self.input_string:
1561 app.status(_("cancel"), 1)
1562 elif self.stop_input_hook:
1563 apply(self.stop_input_hook, args)
1564 self.do_input_hook = None
1565 self.stop_input_hook = None
1566 self.complete_input_hook = None
1568 def cancel_input(self):
1569 self.input_string = ""
1570 self.stop_input()
1572 def cursor(self, visibility):
1573 try: curses.curs_set(visibility)
1574 except: pass
1576 def quit(self):
1577 self.player.stop(quiet=1)
1578 sys.exit(0)
1580 def handler_resize(self, sig, frame):
1581 # curses trickery
1582 while 1:
1583 try: curses.endwin(); break
1584 except: time.sleep(1)
1585 self.w.refresh()
1586 self.win_root.resize()
1587 self.win_root.update()
1589 def handler_quit(self, sig, frame):
1590 self.quit()
1592 # ------------------------------------------
1593 def main():
1594 try:
1595 opts, args = getopt.getopt(sys.argv[1:], "nrRv")
1596 except:
1597 usage = _("Usage: %s [-nrRv] [ file | dir | playlist ] ...\n")
1598 sys.stderr.write(usage % sys.argv[0])
1599 sys.exit(1)
1601 global app
1602 app = Application()
1604 playlist = []
1605 if not sys.stdin.isatty():
1606 playlist = map(string.strip, sys.stdin.readlines())
1607 os.close(0)
1608 os.open("/dev/tty", 0)
1609 try:
1610 app.setup()
1611 for opt, optarg in opts:
1612 if opt == "-n": app.restricted = 1
1613 if opt == "-r": app.win_playlist.command_toggle_repeat()
1614 if opt == "-R": app.win_playlist.command_toggle_random()
1615 if opt == "-v": app.mixer("toggle")
1616 if args or playlist:
1617 for i in args or playlist:
1618 app.win_playlist.add(os.path.abspath(i))
1619 app.win_tab.change_window()
1620 app.run()
1621 except SystemExit:
1622 app.cleanup()
1623 except Exception:
1624 app.cleanup()
1625 import traceback
1626 traceback.print_exc()
1628 # ------------------------------------------
1629 PLAYERS = [
1630 FrameOffsetPlayer("ogg123 -q -v -k %d %s", "\.ogg$"),
1631 FrameOffsetPlayer("splay -f -k %d %s", "(^http://|\.mp[123]$)", 38.28),
1632 FrameOffsetPlayer("mpg123 -q -v -k %d %s", "(^http://|\.mp[123]$)", 38.28),
1633 FrameOffsetPlayer("mpg321 -q -v -k %d %s", "(^http://|\.mp[123]$)", 38.28),
1634 TimeOffsetPlayer("madplay -v --display-time=remaining -s %d %s", "\.mp[123]$"),
1635 NoOffsetPlayer("mikmod -q -p0 %s", "\.(mod|xm|fm|s3m|med|col|669|it|mtm)$"),
1636 NoOffsetPlayer("xmp -q %s", "\.(mod|xm|fm|s3m|med|col|669|it|mtm|stm)$"),
1637 NoOffsetPlayer("play %s", "\.(aiff|au|cdr|mp3|ogg|wav)$"),
1638 NoOffsetPlayer("speexdec %s", "\.spx$")
1641 def VALID_SONG(name):
1642 for player in PLAYERS:
1643 if player.re_files.search(name):
1644 return 1
1646 def VALID_PLAYLIST(name):
1647 if re.search("\.(m3u|pls)$", name, re.I):
1648 return 1
1650 for rc in [os.path.expanduser("~/.cplayrc"), "/etc/cplayrc"]:
1651 try: execfile(rc); break
1652 except IOError: pass
1654 # ------------------------------------------
1655 if __name__ == "__main__": main()