cplay

view cplay @ 2:c7d8ec7da73b

Add mplayer as a backend player Plus: exchange PCM and Master mixer.
author markus schnalke <meillo@marmaro.de>
date Thu, 27 Jul 2017 07:08:00 +0200
parents aa5f022eac8a
children
line source
1 #!/usr/bin/env python
2 # -*- python -*-
4 __version__ = "cplay 1.49-meillo"
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.setlength()
1210 self.update_status()
1212 def stop(self, quiet=0):
1213 self.paused and self.toggle_pause(quiet)
1214 try:
1215 while 1:
1216 try: os.kill(-self.pid, signal.SIGINT)
1217 except os.error: pass
1218 os.waitpid(self.pid, os.WNOHANG)
1219 except Exception: pass
1220 self.stopped = 1
1221 quiet or self.update_status()
1223 def toggle_pause(self, quiet=0):
1224 try: os.kill(-self.pid, [signal.SIGSTOP, signal.SIGCONT][self.paused])
1225 except os.error: return
1226 self.paused = not self.paused
1227 quiet or self.update_status()
1229 def parse_progress(self):
1230 if self.stopped or self.step: self.tid = None
1231 else:
1232 self.parse_buf()
1233 self.tid = app.timeout.add(1.0, self.parse_progress)
1235 def read_fd(self, fd):
1236 self.buf = os.read(fd, 512)
1237 self.tid or self.parse_progress()
1239 def poll(self):
1240 try: os.waitpid(self.pid, os.WNOHANG)
1241 except:
1242 # something broken? try again
1243 if self.time_setup and (time.time() - self.time_setup) < 2.0:
1244 self.play()
1245 return 0
1246 app.set_default_status("")
1247 app.counter([0,0])
1248 app.progress(0)
1249 return 1
1251 def seek(self, offset, relative):
1252 if relative:
1253 d = offset * self.length * 0.002
1254 self.step = self.step * (self.step * d > 0) + d
1255 self.offset = min(self.length, max(0, self.offset+self.step))
1256 else:
1257 self.step = 1
1258 self.offset = (offset < 0) and self.length+offset or offset
1259 self.show_position()
1261 def set_position(self, offset, length, values):
1262 self.offset = offset
1263 self.length = length
1264 self.values = values
1265 self.show_position()
1267 def show_position(self):
1268 app.counter(self.values)
1269 app.progress(self.length and (float(self.offset) / self.length))
1271 def update_status(self):
1272 if not self.entry:
1273 app.set_default_status("")
1274 elif self.stopped:
1275 app.set_default_status(_("Stopped: %s") % self.entry.vp())
1276 elif self.paused:
1277 app.set_default_status(_("Paused: %s") % self.entry.vp())
1278 else:
1279 app.set_default_status(_("Playing: %s") % self.entry.vp())
1281 def setlength(self):
1282 return
1284 # ------------------------------------------
1285 class FrameOffsetPlayer(Player):
1286 re_progress = re.compile("Time.*\s(\d+):(\d+).*\[(\d+):(\d+)")
1288 def parse_buf(self):
1289 match = self.re_progress.search(self.buf)
1290 if match:
1291 m1, s1, m2, s2 = map(string.atoi, match.groups())
1292 head, tail = m1*60+s1, m2*60+s2
1293 self.set_position(head, head+tail, [head, tail])
1295 # ------------------------------------------
1296 class TimeOffsetPlayer(Player):
1297 re_progress = re.compile("(\d+):(\d+):(\d+)")
1299 def parse_buf(self):
1300 match = self.re_progress.search(self.buf)
1301 if match:
1302 h, m, s = map(string.atoi, match.groups())
1303 tail = h*3600+m*60+s
1304 head = max(self.length, tail) - tail
1305 self.set_position(head, head+tail, [head, tail])
1307 # ------------------------------------------
1308 class TimeOffsetMplayer(Player):
1309 re_progress = re.compile("A: *(\d+)")
1311 def parse_buf(self):
1312 match = self.re_progress.search(self.buf)
1313 if match:
1314 head = string.atoi(match.groups()[0])
1315 tail = max(self.length, head) - head
1316 self.set_position(head, head+tail, [head, tail])
1318 def setlength(self):
1319 while 1:
1320 self.buf = os.read(self.stdout_r, 512)
1321 re_length = re.compile("ID_LENGTH=(\d+)")
1322 match = re_length.search(self.buf)
1323 if match:
1324 self.length = string.atoi(match.groups()[0])
1325 break
1327 # ------------------------------------------
1328 class NoOffsetPlayer(Player):
1330 def parse_buf(self):
1331 head = self.offset+1
1332 self.set_position(head, 0, [head, head])
1334 def seek(self, *dummy):
1335 return 1
1337 # ------------------------------------------
1338 class Timeout:
1339 def __init__(self):
1340 self.next = 0
1341 self.dict = {}
1343 def add(self, timeout, func, args=()):
1344 tid = self.next = self.next + 1
1345 self.dict[tid] = (func, args, time.time() + timeout)
1346 return tid
1348 def remove(self, tid):
1349 del self.dict[tid]
1351 def check(self, now):
1352 for tid, (func, args, timeout) in self.dict.items():
1353 if now >= timeout:
1354 self.remove(tid)
1355 apply(func, args)
1356 return len(self.dict) and 0.2 or None
1358 # ------------------------------------------
1359 class FIFOControl:
1360 def __init__(self):
1361 try: self.fd = open(CONTROL_FIFO, "rb+", 0)
1362 except: self.fd = None
1363 self.commands = {"pause" : app.toggle_pause,
1364 "next" : app.next_song,
1365 "prev" : app.prev_song,
1366 "forward" : self.forward,
1367 "backward" : self.backward,
1368 "play" : app.toggle_stop,
1369 "stop" : app.toggle_stop,
1370 "volup" : app.inc_volume,
1371 "voldown" : app.dec_volume,
1372 "quit" : app.quit}
1374 def handle_command(self):
1375 command = string.strip(self.fd.readline())
1376 if command in self.commands.keys():
1377 self.commands[command]()
1379 def forward(self):
1380 app.seek(1, 1)
1382 def backward(self):
1383 app.seek(-1, 1)
1385 # ------------------------------------------
1386 class Application:
1387 def __init__(self):
1388 self.keymapstack = KeymapStack()
1389 self.input_mode = 0
1390 self.input_prompt = ""
1391 self.input_string = ""
1392 self.do_input_hook = None
1393 self.stop_input_hook = None
1394 self.complete_input_hook = None
1395 self.channels = []
1396 self.restricted = 0
1397 self.input_keymap = Keymap()
1398 self.input_keymap.bind(list(Window.chars), self.do_input)
1399 self.input_keymap.bind(curses.KEY_BACKSPACE, self.do_input, (8,))
1400 self.input_keymap.bind([21, 23], self.do_input)
1401 self.input_keymap.bind(['\a', 27], self.cancel_input, ())
1402 self.input_keymap.bind(['\n', curses.KEY_ENTER],
1403 self.stop_input, ())
1405 def setup(self):
1406 if tty:
1407 self.tcattr = tty.tcgetattr(sys.stdin.fileno())
1408 tcattr = tty.tcgetattr(sys.stdin.fileno())
1409 tcattr[0] = tcattr[0] & ~(tty.IXON)
1410 tty.tcsetattr(sys.stdin.fileno(), tty.TCSANOW, tcattr)
1411 self.w = curses.initscr()
1412 curses.cbreak()
1413 curses.noecho()
1414 try: curses.meta(1)
1415 except: pass
1416 self.cursor(0)
1417 signal.signal(signal.SIGCHLD, signal.SIG_IGN)
1418 signal.signal(signal.SIGHUP, self.handler_quit)
1419 signal.signal(signal.SIGINT, self.handler_quit)
1420 signal.signal(signal.SIGTERM, self.handler_quit)
1421 signal.signal(signal.SIGWINCH, self.handler_resize)
1422 self.win_root = RootWindow(None)
1423 self.win_root.update()
1424 self.win_tab = self.win_root.win_tab
1425 self.win_filelist = self.win_root.win_tab.win_filelist
1426 self.win_playlist = self.win_root.win_tab.win_playlist
1427 self.win_status = self.win_root.win_status
1428 self.status = self.win_status.status
1429 self.set_default_status = self.win_status.set_default_status
1430 self.restore_default_status = self.win_status.restore_default_status
1431 self.counter = self.win_root.win_counter.counter
1432 self.progress = self.win_root.win_progress.progress
1433 self.player = PLAYERS[0]
1434 self.timeout = Timeout()
1435 self.play_tid = None
1436 self.kludge = 0
1437 self.win_filelist.listdir()
1438 self.control = FIFOControl()
1440 def cleanup(self):
1441 try: curses.endwin()
1442 except curses.error: return
1443 XTERM and sys.stderr.write("\033]0;%s\a" % "xterm")
1444 tty and tty.tcsetattr(sys.stdin.fileno(), tty.TCSADRAIN, self.tcattr)
1445 print
1447 def run(self):
1448 while 1:
1449 now = time.time()
1450 timeout = self.timeout.check(now)
1451 self.win_filelist.listdir_maybe(now)
1452 if not self.player.stopped:
1453 timeout = 0.5
1454 if self.kludge and self.player.poll():
1455 self.player.stopped = 1 # end of playlist hack
1456 if not self.win_playlist.stop:
1457 entry = self.win_playlist.change_active_entry(1)
1458 entry and self.play(entry)
1459 R = [sys.stdin, self.player.stdout_r, self.player.stderr_r]
1460 self.control.fd and R.append(self.control.fd)
1461 try: r, w, e = select.select(R, [], [], timeout)
1462 except select.error: continue
1463 self.kludge = 1
1464 # user
1465 if sys.stdin in r:
1466 c = self.win_root.getch()
1467 self.keymapstack.process(c)
1468 # player
1469 if self.player.stderr_r in r:
1470 self.player.read_fd(self.player.stderr_r)
1471 # player
1472 if self.player.stdout_r in r:
1473 self.player.read_fd(self.player.stdout_r)
1474 # remote
1475 if self.control.fd in r:
1476 self.control.handle_command()
1478 def play(self, entry, offset = 0):
1479 self.kludge = 0
1480 self.play_tid = None
1481 if entry is None or offset is None: return
1482 self.player.stop(quiet=1)
1483 for self.player in PLAYERS:
1484 if self.player.re_files.search(entry.pathname):
1485 if self.player.setup(entry, offset): break
1486 else:
1487 app.status(_("Player not found!"), 1)
1488 self.player.stopped = 0 # keep going
1489 return
1490 self.player.play()
1492 def delayed_play(self, entry, offset):
1493 if self.play_tid: self.timeout.remove(self.play_tid)
1494 self.play_tid = self.timeout.add(0.5, self.play, (entry, offset))
1496 def next_song(self):
1497 self.delayed_play(self.win_playlist.change_active_entry(1), 0)
1499 def prev_song(self):
1500 self.delayed_play(self.win_playlist.change_active_entry(-1), 0)
1502 def seek(self, offset, relative):
1503 if not self.player.entry: return
1504 self.player.seek(offset, relative)
1505 self.delayed_play(self.player.entry, self.player.offset)
1507 def toggle_pause(self):
1508 if not self.player.entry: return
1509 if not self.player.stopped: self.player.toggle_pause()
1511 def toggle_stop(self):
1512 if not self.player.entry: return
1513 if not self.player.stopped: self.player.stop()
1514 else: self.play(self.player.entry, self.player.offset)
1516 def inc_volume(self):
1517 self.mixer("cue", 1)
1519 def dec_volume(self):
1520 self.mixer("cue", -1)
1522 def key_volume(self, ch):
1523 self.mixer("set", (ch & 0x0f)*10)
1525 def mixer(self, cmd=None, arg=None):
1526 try: self._mixer(cmd, arg)
1527 except Exception, e: app.status(e, 2)
1529 def _mixer(self, cmd, arg):
1530 try:
1531 import ossaudiodev
1532 mixer = ossaudiodev.openmixer()
1533 get, set = mixer.get, mixer.set
1534 self.channels = self.channels or \
1535 [['PCM', ossaudiodev.SOUND_MIXER_PCM],
1536 ['MASTER', ossaudiodev.SOUND_MIXER_VOLUME]]
1537 except ImportError:
1538 import oss
1539 mixer = oss.open_mixer()
1540 get, set = mixer.read_channel, mixer.write_channel
1541 self.channels = self.channels or \
1542 [['PCM', oss.SOUND_MIXER_PCM],
1543 ['MASTER', oss.SOUND_MIXER_VOLUME]]
1544 if cmd is "toggle": self.channels.insert(0, self.channels.pop())
1545 name, channel = self.channels[0]
1546 if cmd is "cue": arg = min(100, max(0, get(channel)[0] + arg))
1547 if cmd in ["set", "cue"]: set(channel, (arg, arg))
1548 app.status(_("%s volume %s%%") % (name, get(channel)[0]), 1)
1549 mixer.close()
1551 def show_input(self):
1552 n = len(self.input_prompt)+1
1553 s = cut(self.input_string, self.win_status.cols-n, left=1)
1554 app.status("%s%s " % (self.input_prompt, s))
1556 def start_input(self, prompt="", data="", colon=1):
1557 self.input_mode = 1
1558 self.cursor(1)
1559 app.keymapstack.push(self.input_keymap)
1560 self.input_prompt = prompt + (colon and ": " or "")
1561 self.input_string = data
1562 self.show_input()
1564 def do_input(self, *args):
1565 if self.do_input_hook:
1566 return apply(self.do_input_hook, args)
1567 ch = args and args[0] or None
1568 if ch in [8, 127]: # backspace
1569 self.input_string = self.input_string[:-1]
1570 elif ch == 9 and self.complete_input_hook:
1571 self.input_string = self.complete_input_hook(self.input_string)
1572 elif ch == 21: # C-u
1573 self.input_string = ""
1574 elif ch == 23: # C-w
1575 self.input_string = re.sub("((.* )?)\w.*", "\\1", self.input_string)
1576 elif ch:
1577 self.input_string = "%s%c" % (self.input_string, ch)
1578 self.show_input()
1580 def stop_input(self, *args):
1581 self.input_mode = 0
1582 self.cursor(0)
1583 app.keymapstack.pop()
1584 if not self.input_string:
1585 app.status(_("cancel"), 1)
1586 elif self.stop_input_hook:
1587 apply(self.stop_input_hook, args)
1588 self.do_input_hook = None
1589 self.stop_input_hook = None
1590 self.complete_input_hook = None
1592 def cancel_input(self):
1593 self.input_string = ""
1594 self.stop_input()
1596 def cursor(self, visibility):
1597 try: curses.curs_set(visibility)
1598 except: pass
1600 def quit(self):
1601 self.player.stop(quiet=1)
1602 sys.exit(0)
1604 def handler_resize(self, sig, frame):
1605 # curses trickery
1606 while 1:
1607 try: curses.endwin(); break
1608 except: time.sleep(1)
1609 self.w.refresh()
1610 self.win_root.resize()
1611 self.win_root.update()
1613 def handler_quit(self, sig, frame):
1614 self.quit()
1616 # ------------------------------------------
1617 def main():
1618 try:
1619 opts, args = getopt.getopt(sys.argv[1:], "nrRv")
1620 except:
1621 usage = _("Usage: %s [-nrRv] [ file | dir | playlist ] ...\n")
1622 sys.stderr.write(usage % sys.argv[0])
1623 sys.exit(1)
1625 global app
1626 app = Application()
1628 playlist = []
1629 if not sys.stdin.isatty():
1630 playlist = map(string.strip, sys.stdin.readlines())
1631 os.close(0)
1632 os.open("/dev/tty", 0)
1633 try:
1634 app.setup()
1635 for opt, optarg in opts:
1636 if opt == "-n": app.restricted = 1
1637 if opt == "-r": app.win_playlist.command_toggle_repeat()
1638 if opt == "-R": app.win_playlist.command_toggle_random()
1639 if opt == "-v": app.mixer("toggle")
1640 if args or playlist:
1641 for i in args or playlist:
1642 app.win_playlist.add(os.path.abspath(i))
1643 app.win_tab.change_window()
1644 app.run()
1645 except SystemExit:
1646 app.cleanup()
1647 except Exception:
1648 app.cleanup()
1649 import traceback
1650 traceback.print_exc()
1652 # ------------------------------------------
1653 PLAYERS = [
1654 TimeOffsetMplayer("mplayer -vo null -identify -ss %d %s", "(^http://|\.(mp[1-4]|flv|mkv|m4a)$)"),
1655 FrameOffsetPlayer("ogg123 -q -v -k %d %s", "\.ogg$"),
1656 FrameOffsetPlayer("splay -f -k %d %s", "(^http://|\.mp[123]$)", 38.28),
1657 FrameOffsetPlayer("mpg123 -q -v -k %d %s", "(^http://|\.mp[123]$)", 38.28),
1658 FrameOffsetPlayer("mpg321 -q -v -k %d %s", "(^http://|\.mp[123]$)", 38.28),
1659 TimeOffsetPlayer("madplay -v --display-time=remaining -s %d %s", "\.mp[123]$"),
1660 NoOffsetPlayer("mikmod -q -p0 %s", "\.(mod|xm|fm|s3m|med|col|669|it|mtm)$"),
1661 NoOffsetPlayer("xmp -q %s", "\.(mod|xm|fm|s3m|med|col|669|it|mtm|stm)$"),
1662 NoOffsetPlayer("play %s", "\.(aiff|au|cdr|mp3|ogg|wav)$"),
1663 NoOffsetPlayer("speexdec %s", "\.spx$")
1666 def VALID_SONG(name):
1667 for player in PLAYERS:
1668 if player.re_files.search(name):
1669 return 1
1671 def VALID_PLAYLIST(name):
1672 if re.search("\.(m3u|pls)$", name, re.I):
1673 return 1
1675 for rc in [os.path.expanduser("~/.cplayrc"), "/etc/cplayrc"]:
1676 try: execfile(rc); break
1677 except IOError: pass
1679 # ------------------------------------------
1680 if __name__ == "__main__": main()