-
Notifications
You must be signed in to change notification settings - Fork 13
/
cplay
executable file
·1681 lines (1455 loc) · 56.3 KB
/
cplay
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- python -*-
__version__ = "cplay 1.47pre5"
"""
cplay - A curses front-end for various audio players
Copyright (C) 1998-2003 Ulf Betlehem <flu@iki.fi>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""
# ------------------------------------------
from types import *
import os
import sys
import time
import getopt
import signal
import string
import select
import re
try: from ncurses import curses
except ImportError: import curses
try: import tty
except ImportError: tty = None
try: import locale; locale.setlocale(locale.LC_ALL, "")
except: pass
# ------------------------------------------
_locale_domain = "cplay"
_locale_dir = "/usr/local/share/locale"
try:
import gettext # python 2.0
gettext.install(_locale_domain, _locale_dir)
except ImportError:
try:
import fintl
fintl.bindtextdomain(_locale_domain, _locale_dir)
fintl.textdomain(_locale_domain)
_ = fintl.gettext
except ImportError:
def _(s): return s
except:
def _(s): return s
# ------------------------------------------
XTERM = re.search("rxvt|xterm", os.environ["TERM"])
RETRY = 2.0
MIXER_IOCTL = [["MASTER", 0x80044d00, 0xc0044d00],
["PCM", 0x80044d04, 0xc0044d04]]
for DSP in ["/dev/sound/dsp", "/dev/dsp"]:
if os.path.exists(DSP): break
for MIXER in ["/dev/sound/mixer", "/dev/mixer"]:
if os.path.exists(MIXER): break
CONTROL_FIFO = "/var/tmp/cplay_control"
# ------------------------------------------
def which(program):
for path in string.split(os.environ["PATH"], ":"):
if os.path.exists(os.path.join(path, program)):
return os.path.join(path, program)
# ------------------------------------------
def cut(s, n, left=0):
if left: return len(s) > n and "<%s" % s[-n+1:] or s
else: return len(s) > n and "%s>" % s[:n-1] or s
# ------------------------------------------
#def log(msg):
# open("log", "a").write("%.02f %s\n" % (time.time(), msg))
# ------------------------------------------
class Stack:
def __init__(self):
self.items = ()
def push(self, item):
self.items = (item,) + self.items
def pop(self):
self.items, item = self.items[1:], self.items[0]
return item
# ------------------------------------------
class KeymapStack(Stack):
def process(self, code):
for keymap in self.items:
if keymap and keymap.process(code):
break
# ------------------------------------------
class Keymap:
def __init__(self):
self.methods = [None] * curses.KEY_MAX
def bind(self, key, method, args=None):
if type(key) in (TupleType, ListType):
for i in key: self.bind(i, method, args)
return
if type(key) is StringType:
key = ord(key)
self.methods[key] = (method, args)
def process(self, key):
if self.methods[key] is None: return 0
method, args = self.methods[key]
if args is None:
apply(method, (key,))
else:
apply(method, args)
return 1
# ------------------------------------------
class Window:
string.punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' # 1.5 kludge
chars = string.letters+string.digits+string.punctuation+string.whitespace
t = ['?'] * 256
for c in chars: t[ord(c)] = c
translationTable = string.join(t, ""); del t
def __init__(self, parent):
self.parent = parent
self.children = []
self.name = None
self.keymap = None
self.visible = 1
self.resize()
if parent: parent.children.append(self)
def insstr(self, s):
if not s: return
self.w.addstr(s[:-1])
self.w.hline(ord(s[-1]), 1) # insch() work-around
def __getattr__(self, name):
return getattr(self.w, name)
def getmaxyx(self):
y, x = self.w.getmaxyx()
try: curses.version # tested with 1.2 and 1.6
except AttributeError:
# pyncurses - emulate traditional (silly) behavior
y, x = y+1, x+1
return y, x
def touchwin(self):
try: self.w.touchwin()
except AttributeError: self.touchln(0, self.getmaxyx()[0])
def attron(self, attr):
try: self.w.attron(attr)
except AttributeError: self.w.attr_on(attr)
def attroff(self, attr):
try: self.w.attroff(attr)
except AttributeError: self.w.attr_off(attr)
def newwin(self):
return curses.newwin(0, 0, 0, 0)
def resize(self):
self.w = self.newwin()
self.ypos, self.xpos = self.getbegyx()
self.rows, self.cols = self.getmaxyx()
self.keypad(1)
self.leaveok(0)
self.scrollok(0)
for child in self.children:
child.resize()
def update(self):
self.clear()
self.refresh()
for child in self.children:
child.update()
# ------------------------------------------
class ProgressWindow(Window):
def __init__(self, parent):
Window.__init__(self, parent)
self.value = 0
def newwin(self):
return curses.newwin(1, self.parent.cols, self.parent.rows-2, 0)
def update(self):
self.move(0, 0)
self.hline(ord('-'), self.cols)
if self.value > 0:
self.move(0, 0)
x = int(self.value * self.cols) # 0 to cols-1
x and self.hline(ord('='), x)
self.move(0, x)
self.insstr('|')
self.touchwin()
self.refresh()
def progress(self, value):
self.value = min(value, 0.99)
self.update()
# ------------------------------------------
class StatusWindow(Window):
def __init__(self, parent):
Window.__init__(self, parent)
self.default_message = ''
self.current_message = ''
self.tid = None
def newwin(self):
return curses.newwin(1, self.parent.cols-12, self.parent.rows-1, 0)
def update(self):
msg = string.translate(self.current_message, Window.translationTable)
self.move(0, 0)
self.clrtoeol()
self.insstr(cut(msg, self.cols))
self.touchwin()
self.refresh()
def status(self, message, duration = 0):
self.current_message = str(message)
if self.tid: app.timeout.remove(self.tid)
if duration: self.tid = app.timeout.add(duration, self.timeout)
else: self.tid = None
self.update()
def timeout(self):
self.tid = None
self.restore_default_status()
def set_default_status(self, message):
if self.current_message == self.default_message: self.status(message)
self.default_message = message
XTERM and sys.stderr.write("\033]0;%s\a" % (message or "cplay"))
def restore_default_status(self):
self.status(self.default_message)
# ------------------------------------------
class CounterWindow(Window):
def __init__(self, parent):
Window.__init__(self, parent)
self.values = [0, 0]
self.mode = 1
def newwin(self):
return curses.newwin(1, 11, self.parent.rows-1, self.parent.cols-11)
def update(self):
h, s = divmod(self.values[self.mode], 3600)
m, s = divmod(s, 60)
self.move(0, 0)
self.attron(curses.A_BOLD)
self.insstr("%02dh %02dm %02ds" % (h, m, s))
self.attroff(curses.A_BOLD)
self.touchwin()
self.refresh()
def counter(self, values):
self.values = values
self.update()
def toggle_mode(self):
self.mode = not self.mode
tmp = [_("elapsed"), _("remaining")][self.mode]
app.status(_("Counting %s time") % tmp, 1)
self.update()
# ------------------------------------------
class RootWindow(Window):
def __init__(self, parent):
Window.__init__(self, parent)
keymap = Keymap()
app.keymapstack.push(keymap)
self.win_progress = ProgressWindow(self)
self.win_status = StatusWindow(self)
self.win_counter = CounterWindow(self)
self.win_tab = TabWindow(self)
keymap.bind(12, self.update, ()) # C-l
keymap.bind([curses.KEY_LEFT, 2], app.seek, (-1, 1)) # C-b
keymap.bind([curses.KEY_RIGHT, 6], app.seek, (1, 1)) # C-f
keymap.bind([1, '^'], app.seek, (0, 0)) # C-a
keymap.bind([5, '$'], app.seek, (-1, 0)) # C-e
keymap.bind(range(48,58), app.key_volume) # 0123456789
keymap.bind(['+', '='], app.inc_volume, ())
keymap.bind('-', app.dec_volume, ())
keymap.bind('n', app.next_song, ())
keymap.bind('p', app.prev_song, ())
keymap.bind('z', app.toggle_pause, ())
keymap.bind('x', app.toggle_stop, ())
keymap.bind('c', self.win_counter.toggle_mode, ())
keymap.bind('Q', self.command_quit, (1,))
keymap.bind('q', self.command_quit, ())
keymap.bind('v', app.toggle_mixer, ())
def command_quit(self, seriously=0):
if app.quit_silently or seriously: app.quit()
app.do_input_hook = self.do_quit
app.start_input(_("Quit? (y/N)"))
def do_quit(self, ch):
if chr(ch) == 'y': app.quit()
app.stop_input()
# ------------------------------------------
class TabWindow(Window):
def __init__(self, parent):
Window.__init__(self, parent)
self.active_child = 0
self.win_filelist = self.add(FilelistWindow)
self.win_playlist = self.add(PlaylistWindow)
self.win_help = self.add(HelpWindow)
keymap = Keymap()
keymap.bind('\t', self.change_window, ()) # Tab
keymap.bind('h', self.help, ())
app.keymapstack.push(keymap)
app.keymapstack.push(self.children[self.active_child].keymap)
def newwin(self):
return curses.newwin(self.parent.rows-2, self.parent.cols, 0, 0)
def update(self):
self.update_title()
self.move(1, 0)
self.hline(ord('-'), self.cols)
self.move(2, 0)
self.clrtobot()
self.refresh()
child = self.children[self.active_child]
child.visible = 1
child.update()
def update_title(self, refresh = 1):
child = self.children[self.active_child]
self.move(0, 0)
self.clrtoeol()
self.attron(curses.A_BOLD)
self.insstr(child.get_title())
self.attroff(curses.A_BOLD)
if refresh: self.refresh()
def add(self, Class):
win = Class(self)
win.visible = 0
return win
def change_window(self, window = None):
app.keymapstack.pop()
self.children[self.active_child].visible = 0
if window:
self.active_child = self.children.index(window)
else:
# toggle windows 0 and 1
self.active_child = not self.active_child
app.keymapstack.push(self.children[self.active_child].keymap)
self.update()
def help(self):
if self.children[self.active_child] == self.win_help:
self.change_window(self.win_last)
else:
self.win_last = self.children[self.active_child]
self.change_window(self.win_help)
app.status(__version__, 2)
# ------------------------------------------
class ListWindow(Window):
def __init__(self, parent):
Window.__init__(self, parent)
self.buffer = []
self.bufptr = self.scrptr = 0
self.search_direction = 0
self.last_search = ""
self.keymap = Keymap()
self.keymap.bind(['k', curses.KEY_UP, 16], self.cursor_move, (-1,))
self.keymap.bind(['j', curses.KEY_DOWN, 14], self.cursor_move, (1,))
self.keymap.bind(['K', curses.KEY_PPAGE], self.cursor_ppage, ())
self.keymap.bind(['J', curses.KEY_NPAGE], self.cursor_npage, ())
self.keymap.bind(['g', curses.KEY_HOME], self.cursor_home, ())
self.keymap.bind(['G', curses.KEY_END], self.cursor_end, ())
self.keymap.bind(['?', 18], self.start_search,
(_("backward-isearch"), -1))
self.keymap.bind(['/', 19], self.start_search,
(_("forward-isearch"), 1))
def newwin(self):
return curses.newwin(self.parent.rows-2, self.parent.cols,
self.parent.ypos+2, self.parent.xpos)
def update(self, force = 1):
self.bufptr = max(0, min(self.bufptr, len(self.buffer) - 1))
scrptr = (self.bufptr / self.rows) * self.rows
if force or self.scrptr != scrptr:
self.scrptr = scrptr
self.move(0, 0)
self.clrtobot()
i = 0
for entry in self.buffer[self.scrptr:]:
self.move(i, 0)
i = i + 1
self.putstr(entry)
if self.getyx()[0] == self.rows - 1: break
if self.visible:
self.refresh()
self.parent.update_title()
self.update_line(curses.A_REVERSE)
def update_line(self, attr = None, refresh = 1):
if not self.buffer: return
ypos = self.bufptr - self.scrptr
if attr: self.attron(attr)
self.move(ypos, 0)
self.hline(ord(' '), self.cols)
self.putstr(self.current())
if attr: self.attroff(attr)
if self.visible and refresh: self.refresh()
def get_title(self, data=""):
pos = "%s-%s/%s" % (self.scrptr+min(1, len(self.buffer)),
min(self.scrptr+self.rows, len(self.buffer)),
len(self.buffer))
width = self.cols-len(pos)-2
data = cut(data, width-len(self.name), 1)
return "%-*s %s" % (width, cut(self.name+data, width), pos)
def putstr(self, entry, *pos):
s = string.translate(str(entry), Window.translationTable)
pos and apply(self.move, pos)
self.insstr(cut(s, self.cols))
def current(self):
if self.bufptr >= len(self.buffer): self.bufptr = len(self.buffer) - 1
return self.buffer[self.bufptr]
def cursor_move(self, ydiff):
if app.input_mode: app.cancel_input()
if not self.buffer: return
self.update_line(refresh = 0)
self.bufptr = (self.bufptr + ydiff) % len(self.buffer)
self.update(force = 0)
def cursor_ppage(self):
tmp = self.bufptr % self.rows
if tmp == self.bufptr:
self.cursor_move(-(tmp+(len(self.buffer) % self.rows) or self.rows))
else:
self.cursor_move(-(tmp+self.rows))
def cursor_npage(self):
tmp = self.rows - self.bufptr % self.rows
if self.bufptr + tmp > len(self.buffer):
self.cursor_move(len(self.buffer) - self.bufptr)
else:
self.cursor_move(tmp)
def cursor_home(self): self.cursor_move(-self.bufptr)
def cursor_end(self): self.cursor_move(-self.bufptr - 1)
def start_search(self, type, direction):
self.search_direction = direction
self.not_found = 0
if not app.input_mode:
app.do_input_hook = self.do_search
app.stop_input_hook = self.stop_search
app.start_input(type)
else:
app.input_prompt = type
self.do_search(advance = direction)
def stop_search(self):
self.last_search = app.input_string
app.status(_("ok"), 1)
def do_search(self, ch = None, advance = 0):
if ch in [8, 127]: app.input_string = app.input_string[:-1]
elif ch: app.input_string = "%s%c" % (app.input_string, ch)
else: app.input_string = app.input_string or self.last_search
index = self.bufptr + advance
while 1:
if not 0 <= index < len(self.buffer):
app.status(_("Not found: %s ") % app.input_string)
self.not_found = 1
break
line = string.lower(str(self.buffer[index]))
if string.find(line, string.lower(app.input_string)) != -1:
app.status("%s%s " % (app.input_prompt, app.input_string))
self.update_line(refresh = 0)
self.bufptr = index
self.update(force = 0)
self.not_found = 0
break
if self.not_found:
app.status(_("Not found: %s ") % app.input_string)
break
index = index + self.search_direction
# ------------------------------------------
class HelpWindow(ListWindow):
def __init__(self, parent):
ListWindow.__init__(self, parent)
self.name = _("Help")
self.keymap.bind('q', self.parent.help, ())
self.buffer = string.split(_("""\
Global Space : tag/untag current
------ t, T : tag current/regex
Up/C-p/k, Down/C-n/j, u, U : untag current/regex
PgUp/K, PgDn/J, Home/g, End/G i : invert tags
: movement
Enter : chdir or play Filelist
Tab : filelist/playlist --------
n, p : next/prev track BkSpc : parent dir
z, x : toggle pause/stop o, s : goto, search recursively
Left, Right, a : add (tagged) to playlist
C-b, C-f : seek backward/forward
c : toggle counter mode Playlist
C-s, C-r, / : isearch --------
C-g, Esc : cancel d, D : delete (tagged) tracks/playlist
1..9, +, - : volume control m, M : move tagged tracks after/before
v : PCM or MASTER volume r, R : toggle repeat/Random mode
C-l, l : refresh, list mode s, S : shuffle/Sort playlist
h, q, Q : help, quit?, Quit! w, @ : write playlist, jump to current
Undocumented
------------
b, ' : set/get filelist bookmark
X : stop playlist after each track
<, > : scroll horizontally (not implemented)
C-a, ^ : seek to beginning of current track (restart)
C-e, $ : seek to end of current track (useless?)
! : shell command ($@ = tagged or current)
"""), "\n")
# ------------------------------------------
class ListEntry:
def __init__(self, pathname, dir=0):
self.filename = os.path.basename(pathname)
self.pathname = pathname
self.slash = dir and "/" or ""
self.tagged = 0
self.active = 0
def set_tagged(self, value):
self.tagged = value
def is_tagged(self):
return self.tagged == 1
def set_active(self, value):
self.active = value
def is_active(self):
return self.active == 1
def __str__(self):
mark = self.is_tagged() and "#" or " "
return "%s %s%s" % (mark, self.vp(), self.slash)
def vp(self):
return self.vps[0][1](self)
def vp_filename(self):
return self.filename or self.vp_pathname() # todo
def vp_pathname(self):
return self.pathname
vps = [[_("filename"), vp_filename],
[_("pathname"), vp_pathname]]
# ------------------------------------------
class PlaylistEntry(ListEntry):
def __init__(self, pathname):
ListEntry.__init__(self, pathname)
self.metadata = None
def vp_metadata(self):
return self.metadata or self.read_metadata()
def read_metadata(self):
self.metadata = get_tag(self.pathname)
return self.metadata
vps = ListEntry.vps[:]
# ------------------------------------------
class TagListWindow(ListWindow):
def __init__(self, parent):
ListWindow.__init__(self, parent)
self.keymap.bind(' ', self.command_tag_untag, ())
self.keymap.bind('i', self.command_invert_tags, ())
self.keymap.bind('t', self.command_tag, (1,))
self.keymap.bind('u', self.command_tag, (0,))
self.keymap.bind('T', self.command_tag_regexp, (1,))
self.keymap.bind('U', self.command_tag_regexp, (0,))
self.keymap.bind('l', self.command_change_viewpoint, ())
def command_change_viewpoint(self, klass=ListEntry):
klass.vps.append(klass.vps.pop(0))
app.status(_("Listing %s") % klass.vps[0][0], 1)
self.update()
def command_invert_tags(self):
for i in self.buffer:
i.set_tagged(not i.is_tagged())
self.update()
def command_tag_untag(self):
if not self.buffer: return
tmp = self.buffer[self.bufptr]
tmp.set_tagged(not tmp.is_tagged())
self.cursor_move(1)
def command_tag(self, value):
if not self.buffer: return
self.buffer[self.bufptr].set_tagged(value)
self.cursor_move(1)
def command_tag_regexp(self, value):
self.tag_value = value
app.stop_input_hook = self.stop_tag_regexp
app.start_input(value and _("Tag regexp") or _("Untag regexp"))
def stop_tag_regexp(self):
try:
r = re.compile(app.input_string, re.I)
for entry in self.buffer:
if r.search(str(entry)):
entry.set_tagged(self.tag_value)
self.update()
app.status(_("ok"), 1)
except re.error, e:
app.status(e, 2)
def get_tagged(self):
return filter(lambda x: x.is_tagged(), self.buffer)
# ------------------------------------------
class FilelistWindow(TagListWindow):
def __init__(self, parent):
TagListWindow.__init__(self, parent)
self.oldposition = {}
try: self.chdir(os.getcwd())
except OSError: self.chdir(os.environ['HOME'])
self.mtime_when = 0
self.mtime = None
self.keymap.bind('\n', self.command_chdir_or_play, ())
self.keymap.bind(['.', curses.KEY_BACKSPACE],
self.command_chparentdir, ())
self.keymap.bind('a', self.command_add_recursively, ())
self.keymap.bind('o', self.command_goto, ())
self.keymap.bind('s', self.command_search_recursively, ())
self.keymap.bind('b', self.command_set_bookmark, ())
self.keymap.bind("'", self.command_get_bookmark, ())
self.keymap.bind('!', self.command_shell, ())
self.bookmarks = { 39: [self.cwd, 0] }
def command_shell(self):
app.stop_input_hook = self.stop_shell
app.complete_input_hook = self.complete_shell
app.start_input(_("shell$ "), colon=0)
def stop_shell(self):
s = app.input_string
curses.endwin()
sys.stderr.write("\n")
argv = map(lambda x: x.pathname, self.get_tagged() or [self.current()])
argv = ["/bin/sh", "-c", s, "--"] + argv
pid = os.fork()
if pid == 0:
try: os.execv(argv[0], argv)
except: os._exit(1)
pid, r = os.waitpid(pid, 0)
sys.stderr.write("\nshell returned %s, press return!\n" % r)
sys.stdin.readline()
app.win_root.update()
app.restore_default_status()
def complete_shell(self, line):
return self.complete_generic(line, quote=1)
def complete_generic(self, line, quote=0):
import fnmatch
if quote:
s = re.sub('.*[^\\\\][ \'"()\[\]{}$`]', '', line)
s, part = re.sub('\\\\', '', s), line[:len(line)-len(s)]
else:
s, part = line, ""
s = os.path.expanduser(s)
head, tail = os.path.split(s)
results = fnmatch.filter(os.listdir(head or "."), tail+"*")
if len(results) == 0:
return line
if len(results) == 1:
s = os.path.join(head, results[0])
s = s + (os.path.isdir(s) and "/" or "")
else:
lm = results[0]
for result in results:
for i in range(min(len(result), len(lm))):
if result[i] != lm[i]:
lm = lm[:i]
break
s = os.path.join(head, lm)
if quote: s = re.sub('([ \'"()\[\]{}$`])', '\\\\\\1', s)
return part + s
def command_get_bookmark(self):
app.do_input_hook = self.do_get_bookmark
app.start_input(_("bookmark"))
def do_get_bookmark(self, ch):
app.input_string = ch
bookmark = self.bookmarks.get(ch)
if bookmark:
self.bookmarks[39] = [self.cwd, self.bufptr]
dir, pos = bookmark
self.chdir(dir)
self.listdir()
self.update()
# todo - goto pos in listdir?
self.bufptr = pos
self.update()
app.status(_("ok"), 1)
else:
app.status(_("Not found!"), 1)
app.stop_input()
def command_set_bookmark(self):
app.do_input_hook = self.do_set_bookmark
app.start_input(_("set bookmark"))
def do_set_bookmark(self, ch):
app.input_string = ch
self.bookmarks[ch] = [self.cwd, self.bufptr]
ch and app.status(_("ok"), 1) or app.stop_input()
def command_search_recursively(self):
app.stop_input_hook = self.stop_search_recursively
app.start_input(_("search"))
def stop_search_recursively(self):
try: re_tmp = re.compile(app.input_string, re.I)
except re.error, e:
app.status(e, 2)
return
app.status(_("Searching..."))
results = []
for entry in self.buffer:
if entry.filename == "..":
continue
if re_tmp.search(entry.filename):
results.append(entry)
elif os.path.isdir(entry.pathname):
try: self.search_recursively(re_tmp, entry.pathname, results)
except: pass
if not self.search_mode:
self.chdir(os.path.join(self.cwd,_("search results")))
self.search_mode = 1
self.buffer = results
self.bufptr = 0
self.parent.update_title()
self.update()
app.restore_default_status()
def search_recursively(self, re_tmp, dir, results):
for filename in os.listdir(dir):
pathname = os.path.join(dir, filename)
if re_tmp.search(filename):
if os.path.isdir(pathname):
results.append(ListEntry(pathname, 1))
elif VALID_PLAYLIST(filename) or VALID_SONG(filename):
results.append(ListEntry(pathname))
elif os.path.isdir(pathname):
self.search_recursively(re_tmp, pathname, results)
def get_title(self):
self.name = _("Filelist: ")
return ListWindow.get_title(self, re.sub("/?$", "/", self.cwd))
def listdir_maybe(self, now=0):
if now < self.mtime_when+2: return
self.mtime_when = now
self.oldposition[self.cwd] = self.bufptr
try: self.mtime == os.stat(self.cwd)[8] or self.listdir(quiet=1)
except os.error: pass
def listdir(self, quiet=0, prevdir=None):
quiet or app.status(_("Reading directory..."))
self.search_mode = 0
dirs = []
files = []
try:
self.mtime = os.stat(self.cwd)[8]
self.mtime_when = time.time()
filenames = os.listdir(self.cwd)
filenames.sort()
for filename in filenames:
if filename[0] == ".": continue
pathname = os.path.join(self.cwd, filename)
if os.path.isdir(pathname): dirs.append(pathname)
elif VALID_SONG(filename): files.append(pathname)
elif VALID_PLAYLIST(filename): files.append(pathname)
except os.error: pass
dots = ListEntry(os.path.join(self.cwd, ".."), 1)
self.buffer = [[dots], []][self.cwd == "/"]
for i in dirs: self.buffer.append(ListEntry(i, 1))
for i in files: self.buffer.append(ListEntry(i))
if prevdir:
for self.bufptr in range(len(self.buffer)):
if self.buffer[self.bufptr].filename == prevdir: break
else: self.bufptr = 0
elif self.oldposition.has_key(self.cwd):
self.bufptr = self.oldposition[self.cwd]
else: self.bufptr = 0
self.parent.update_title()
self.update()
quiet or app.restore_default_status()
def chdir(self, dir):
if hasattr(self, "cwd"): self.oldposition[self.cwd] = self.bufptr
self.cwd = os.path.normpath(dir)
try: os.chdir(self.cwd)
except: pass
def command_chdir_or_play(self):
if not self.buffer: return
if self.current().filename == "..":
self.command_chparentdir()
elif os.path.isdir(self.current().pathname):
self.chdir(self.current().pathname)
self.listdir()
elif VALID_SONG(self.current().filename):
app.play(self.current().pathname)
def command_chparentdir(self):
dir = os.path.basename(self.cwd)
self.chdir(os.path.dirname(self.cwd))
self.listdir(prevdir=dir)
def command_goto(self):
app.stop_input_hook = self.stop_goto
app.complete_input_hook = self.complete_generic
app.start_input(_("goto"))
def stop_goto(self):
dir = os.path.expanduser(app.input_string)
if dir[0] != '/': dir = os.path.join(self.cwd, dir)
if not os.path.isdir(dir):
app.status(_("Not a directory!"), 1)
return
self.chdir(dir)
self.listdir()
def command_add_recursively(self):
l = self.get_tagged()
if not l:
app.win_playlist.add(self.current().pathname)
self.cursor_move(1)
return
for entry in l:
app.win_playlist.add(entry.pathname)
entry.set_tagged(0)
self.update()
# ------------------------------------------
class PlaylistWindow(TagListWindow):
def __init__(self, parent):
TagListWindow.__init__(self, parent)
self.pathname = None
self.repeat = 0
self.random = 0
self.random_prev = []
self.random_next = []
self.random_unplayed = []
self.stop = 0
self.keymap.bind('\n', self.command_play, ())
self.keymap.bind('d', self.command_delete, ())
self.keymap.bind('D', self.command_delete_all, ())
self.keymap.bind('m', self.command_move, (1,))
self.keymap.bind('M', self.command_move, (0,))
self.keymap.bind('s', self.command_shuffle, ())
self.keymap.bind('S', self.command_sort, ())
self.keymap.bind('r', self.command_toggle_repeat, ())
self.keymap.bind('R', self.command_toggle_random, ())
self.keymap.bind('X', self.command_toggle_stop, ())
self.keymap.bind('w', self.command_save_playlist, ())
self.keymap.bind('@', self.command_jump_to_active, ())
self.keymap.bind('f', self.command_filter, ())
def command_filter(self):
None
def command_change_viewpoint(self, klass=PlaylistEntry):
if not globals().get("ID3"):
try:
global ID3, ogg, codecs
import ID3, ogg.vorbis, codecs
klass.vps.append([_("metadata"), klass.vp_metadata])
except ImportError: pass
TagListWindow.command_change_viewpoint(self, klass)
def get_title(self):
space_out = lambda value, s: value and s or " "*len(s)
self.name = _("Playlist %s %s %s") % (
space_out(self.repeat, _("[repeat]")),
space_out(self.random, _("[random]")),
space_out(self.stop, _("[stop]")))
return ListWindow.get_title(self)
def append(self, item):
self.buffer.append(item)
self.random_unplayed.append(item)
def remove(self, item):
self.buffer.remove(item)
if self.random:
try: self.random_prev.remove(item)
except ValueError: pass
try: self.random_next.remove(item)
except ValueError: pass
try: self.random_unplayed.remove(item)
except ValueError: pass
def add_dir(self, dir):
filenames = os.listdir(dir)
filenames.sort()
subdirs = []
for filename in filenames:
pathname = os.path.join(dir, filename)
if VALID_SONG(filename):
self.append(PlaylistEntry(pathname))
if os.path.isdir(pathname):
subdirs.append(pathname)
map(self.add_dir, subdirs)
def add_m3u(self, line):
if re.match("^(#.*)?$", line): return
if re.match("^(/|http://)", line):
self.append(PlaylistEntry(self.fix_url(line)))
else:
dirname = os.path.dirname(self.pathname)
self.append(PlaylistEntry(os.path.join(dirname, line)))
def add_pls(self, line):
# todo: support title & length
m = re.match("File(\d+)=(.*)", line)
if not m: return
self.append(PlaylistEntry(self.fix_url(m.group(2))))
def add_playlist(self, pathname):
self.pathname = pathname
if re.search("\.m3u$", pathname, re.I): f = self.add_m3u
if re.search("\.pls$", pathname, re.I): f = self.add_pls
file = open(pathname)
map(f, map(string.strip, file.readlines()))
file.close()
def add(self, pathname):
try:
if os.path.isdir(pathname):
app.status(_("Working..."))
self.add_dir(pathname)
elif VALID_PLAYLIST(pathname):
self.add_playlist(pathname)
else:
pathname = self.fix_url(pathname)
self.append(PlaylistEntry(pathname))
# todo - refactor