-
Notifications
You must be signed in to change notification settings - Fork 28
/
lyvi
executable file
·860 lines (738 loc) · 31.1 KB
/
lyvi
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
from __future__ import unicode_literals
import os
import sys
import shlex
import locale
import curses
import socket
import codecs
import textwrap
from time import sleep
from shutil import copy2
from getpass import getuser
from threading import Thread, Lock
from subprocess import Popen, PIPE
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
import plyr
locale.setlocale(locale.LC_ALL, '')
VERSION = '0.1'
GLYR_VERSION = plyr.version().split()[1]
HOME = os.environ['HOME']
CFG_HOME = os.environ['XDG_CONFIG_HOME'] if 'XDG_CONFIG_HOME' in os.environ \
else os.environ['HOME'] + '/.config'
CACHE_HOME = os.environ['XDG_CACHE_HOME'] if 'XDG_CACHE_HOME' in os.environ \
else os.environ['HOME'] + '/.cache'
SETTINGS = {'lang': 'en',
'view': 'lyrics',
'key_quit': 'q',
'key_toggle': 'a',
'key_play': 'x',
'key_pause': 'c',
'key_next': 'b',
'key_prev': 'z',
'key_stop': 'v',
'key_volup': '=',
'key_voldn': '-',
'color_title': 7,
'color_text': -1,
'color_status': -1,
'color_buttons': -1,
'mpd_host': 'localhost',
'mpd_port': 6600,
'save_lyrics': False,
'bg': False,
'bg_opacity': 85,
'bg_path': None}
def parse_config(file):
settings = {}
try:
f = open(file, 'r')
except IOError:
pass
else:
for l in f.read().splitlines():
if not l.strip().startswith('#') and '=' in l:
key, value = [x.strip() for x in l.split('=', 1)]
if value == 'True':
value = True
elif value == 'False':
value = False
settings[key] = value
else:
continue
f.close()
return settings
def wrap(text, cols):
wt = ''
for l in text.splitlines():
while len(l) > cols:
wt += l[:cols - 1] + '→' + '\n '
l = l[cols - 1:]
wt += l + '\n '
wt = wt[:-2].encode('utf-8') if sys.version < '3' else wt[:-2]
return wt
def wrapwords(text, cols):
wt = ''
for l in text.split('\n'):
for wl in textwrap.wrap(l, cols):
wt += wl.strip() + '\n '
wt += '\n '
wt = wt.strip().encode('utf-8') if sys.version < '3' else wt.strip()
return wt
def process_socket(command, file):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(file)
s.send((command + '\n').encode())
s.close()
def process_fifo(command, file):
f = open(file, 'w')
f.write(command + '\n')
f.flush()
def get_output(command):
p = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE)
return p.communicate()[0].decode('utf-8').strip()
def running(process):
res = True if process in get_output('ps -C %s' % process) else False
return res
def bg_set(file, opacity):
os.system('convert -fill black -colorize %s%% %s %s'
% (opacity, file, file))
os.system('printf "\e]20;%s;100x100+50+50:op=keep-aspect\a"' % file)
def bg_unset():
# Ugly, but I can't find any way to unset urxvt background.
# So, we will create a transparent 1x1 gif image and set it as background.
f = open('/tmp/lyvi_blank.gif', 'wb')
f.write(b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\
\xFF\xFF\xFF\x21\xF9\x04\x01\x00\x00\x01\x00\x2C\x00\x00\x00\x00\x01\x00\x01\
\x00\x00\x02\x01\x4C\x00\x3B')
f.close()
os.system('printf "\e]20;/tmp/lyvi_blank.gif\a"')
for file in ['/tmp/lyvi_bg.jpg', '/tmp/lyvi_blank.gif']:
if os.path.exists(file):
os.remove(file)
def bg_setlocal():
bg_path = SETTINGS['bg_path'].replace('<artist>', p.artist) \
.replace('<artistinitial>', p.artist[0])
imgs = []
for root, subfolders, files in os.walk(bg_path):
for file in files:
if file.endswith('jpg') or file.endswith('jpeg') \
or file.endswith('png'):
imgs.append(os.path.abspath(os.path.join(root, file)))
if imgs:
tmp_img = '/tmp/lyvi_bg.' + imgs[0].split('.')[-1]
copy2(imgs[0], '/tmp')
os.rename('/tmp/' + imgs[0].split('/')[-1], tmp_img)
bg_set(tmp_img, SETTINGS['bg_opacity'])
else:
bg_unset()
def glyr_query(type, artist, title, lang):
cache_dir = CACHE_HOME + '/lyvi'
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
db = plyr.Database(cache_dir)
query = plyr.Query(artist=artist, title=title, get_type=type,
database=db, language=lang)
query.useragent = 'lyvi/%s' % VERSION
return query.commit()
def metadata_get(type, artist, title, lang):
if ((type == 'lyrics' and (artist == 'N/A' or title == 'N/A'))
or ((type == 'artistbio' or type == 'backdrops') and artist == 'N/A')
or (type == 'guitartabs' and (artist == 'N/A' or title == 'N/A'))):
return 'Missing tags'
elif type == 'backdrops':
img = None
try:
img = glyr_query(type, artist, title, lang)[0].data
except IndexError:
try:
img = glyr_query('artistphoto', artist, title, lang)[0].data
except IndexError:
pass
if img:
f = open('/tmp/lyvi_bg.jpg', 'wb')
f.write(img)
f.close()
bg_set('/tmp/lyvi_bg.jpg', SETTINGS['bg_opacity'])
else:
bg_unset()
else:
try:
m = glyr_query(type, artist, title, lang)[0].data.decode('utf-8')
except IndexError:
m = None
return m
def get_and_update(artist, title, data, types):
if 'backdrops' in types:
if SETTINGS['bg_path']:
bg_setlocal()
for type in types:
m = metadata_get(type, artist, title, SETTINGS['lang'])
data['lock'].acquire()
try:
if data['ui'].artist + data['ui'].title == artist + title:
setattr(data['ui'], type, m)
data['ui'].update_content()
finally:
data['lock'].release()
# Optionally save lyric to a file
if SETTINGS['save_lyrics'] and p.file and type == 'lyrics' \
and m and m != 'Missing tags':
f = codecs.open(p.file.rsplit('.')[0] + '.lyric', 'w', 'utf-8')
f.write(m)
f.close()
class DummyPlayer:
def status(self):
self.file = None
if self.run == None:
self.running = True
elif self.run['type'] == 'file':
self.running = os.path.exists(self.run['name'])
elif self.run['type'] == 'process':
self.running = running(self.run['name'])
if self.np['type'] == 'np_file' or self.np['type'] == 'np_command':
if self.np['type'] == 'np_file':
try:
f = codecs.open(self.np['name'], 'r', 'utf-8')
s = f.read()
f.close()
except IOError:
s = ''
elif self.np['type'] == 'np_command':
s = get_output(self.np['name'])
self.playing = True
s = s.strip().split('\\')
if len(s) < 2:
self.playing = False
else:
self.artist = s[0]
self.title = s[1]
if len(s) > 2:
self.file = s[2]
# mpd workaround
if self.__class__.__name__ == 'Mpd':
f = open(HOME + '/.mpdconf')
for line in f.read().splitlines():
if 'music_directory' in line:
music_dir = line.split('"')[1]
if not music_dir.endswith('/'):
music_dir += '/'
self.file = music_dir + self.file
# deadbeef workaround
if self.title == self.file.rsplit('.', 1)[0]:
self.title = 'N/A'
else:
if self.np['type'] == 'command':
s = get_output(self.np['name'])
elif self.np['type'] == 'log':
f = open(self.np['name'])
s = f.read().split(self.np['str']['beg'])[-1]
f.close()
elif self.np['type'] == 'url':
p = urlopen(self.np['name'])
s = p.read().decode()
p.close()
if self.np['str']['stopped'] in s:
self.playing = False
else:
self.playing = True
if self.np['str']['artist_beg'] in s:
self.artist = s.split(self.np['str']['artist_beg'])[1] \
.split(self.np['str']['artist_end'])[0]
else:
self.artist = 'N/A'
if self.np['str']['title_beg'] in s:
self.title = s.split(self.np['str']['title_beg'])[1] \
.split(self.np['str']['title_end'])[0]
else:
self.title = 'N/A'
if self.np['str']['file_beg'] in s:
self.file = s.split(self.np['str']['file_beg'])[1] \
.split(self.np['str']['file_end'])[0]
# guayadeque workaround
if self.__class__.__name__ == 'Guayadeque':
if self.file.startswith('file://'):
self.file = self.file.split('file://')[1]
else:
self.file = None
if self.playing == False:
self.artist = 'N/A'
self.title = 'N/A'
else:
missing_tag = ['', 'Unknown artist']
if self.artist in missing_tag:
self.artist = 'N/A'
if self.title in missing_tag:
self.title = 'N/A'
def command(self, command):
if command in self.ctl['commands']:
if self.ctl['type'] == 'socket':
process_socket(self.ctl['commands'][command], self.ctl['name'])
elif self.ctl['type'] == 'fifo':
process_fifo(self.ctl['commands'][command], self.ctl['name'])
elif self.ctl['type'] == 'command':
os.system(self.ctl['commands'][command])
class Cmus(DummyPlayer):
def __init__(self):
self.run = {'type': 'file',
'name': HOME + '/.cmus/socket'}
self.np = {'type': 'command',
'name': 'cmus-remote -Q',
'str': {'artist_beg': 'tag artist ',
'artist_end': '\n',
'title_beg': 'tag title ',
'title_end': '\n',
'file_beg': 'file ',
'file_end': '\n',
'stopped': 'status stopped'}}
self.ctl = {'type': 'command',
'commands': {'play': 'cmus-remote -p',
'pause': 'cmus-remote -u',
'next': 'cmus-remote -n',
'prev': 'cmus-remote -r',
'stop': 'cmus-remote -s',
'volup': 'cmus-remote -v +5%',
'voldn': 'cmus-remote -v -5%'}}
class Shellfm(DummyPlayer):
def __init__(self):
self.run = {'type': 'file',
'name': HOME + '/.shell-fm/session'}
self.np = {'type': 'np_file',
'name': HOME + '/.shell-fm/nowplaying'}
self.ctl = {'type': 'socket',
'name': HOME + '/.shell-fm/socket',
'commands': {'pause': 'pause',
'next': 'skip',
'stop': 'stop',
'volup': 'volume +5',
'voldn': 'volume -5'}}
class Pianobar(DummyPlayer):
def __init__(self):
config_dir = CFG_HOME + '/pianobar/'
# set default keys
settings = {'key_pause': 'p',
'key_next': 'n',
'key_stop': 'q',
'key_volup': ')',
'key_voldn': '('}
settings.update(parse_config(config_dir + 'config'))
self.run = {'type': 'process',
'name': 'pianobar'}
self.np = {'type': 'np_file',
'name': config_dir + 'nowplaying'}
self.ctl = {'type': 'fifo',
'name': config_dir + 'ctl',
'commands': {'play': settings['key_pause'],
'pause': settings['key_pause'],
'next': settings['key_next'],
'stop': settings['key_stop'],
'volup': settings['key_volup'],
'voldn': settings['key_voldn']}}
class Mpd(DummyPlayer):
def __init__(self, host, port):
local = ['localhost', '127.0.0.1']
mpc = 'mpc -h %s -p %s' % (host, port)
self.run = {'type': 'process',
'name': 'mpd'} if host in local else None
self.np = {'type': 'np_command'}
self.np['name'] = mpc + ' current -f "%artist%\\%title%\\%file%"'\
if host in local else mpc + ' current -f "%artist%\\%title%"'
self.ctl = {'type': 'command',
'commands': {'play': '%s play > /dev/null' % mpc,
'pause': '%s pause > /dev/null' % mpc,
'next': '%s next > /dev/null' % mpc,
'prev': '%s prev > /dev/null' % mpc,
'stop': '%s stop > /dev/null' % mpc,
'volup': '%s volume +5 > /dev/null' % mpc,
'voldn': '%s volume -5 > /dev/null' % mpc}}
class Moc(DummyPlayer):
def __init__(self):
self.run = {'type': 'file',
'name': HOME + '/.moc/pid'}
self.np = {'type': 'command',
'name': 'mocp -i',
'str': {'artist_beg': 'Artist: ',
'artist_end': '\n',
'title_beg': 'SongTitle: ',
'title_end': '\n',
'file_beg': 'File: ',
'file_end': '\n',
'stopped': 'State: STOP'}}
self.ctl = {'type': 'command',
'commands': {'play': 'mocp -U 2> /dev/null',
'pause': 'mocp -P 2> /dev/null',
'next': 'mocp -f 2> /dev/null',
'prev': 'mocp -r 2> /dev/null',
'stop': 'mocp -s 2> /dev/null',
'volup': 'mocp --volume +5 2> /dev/null',
'voldn': 'mocp --volume -5 2> /dev/null'}}
class Mplayer(DummyPlayer):
def __init__(self):
self.run = {'type': 'process',
'name': 'mplayer'}
self.np = {'type': 'log',
'name': HOME + '/.mplayer/log',
'str': {'beg': 'AUDIO_ID',
'artist_beg': 'VALUE1=',
'artist_end': '\n',
'title_beg': 'VALUE0=',
'title_end': '\n',
'file_beg': '||||',
'file_end': '||||',
'stopped': '||||'}}
self.ctl = {'type': 'fifo',
'name': HOME + '/.mplayer/fifo',
'commands': {'play': 'pause',
'pause': 'pause',
'next': 'pt_step 1',
'prev': 'pt_step -1',
'stop': 'stop',
'volup': 'volume +1',
'voldn': 'volume -1'}}
class Vlc(DummyPlayer):
def __init__(self):
self.run = {'type': 'file',
'name': '/tmp/vlc.sock'}
self.np = {'type': 'url',
'name': 'http://localhost:8080/requests/status.xml',
'str': {'artist_beg': 'name=\'artist\'>',
'artist_end': '</info>',
'title_beg': 'name=\'title\'>',
'title_end': '</info>',
'file_beg': '||||',
'file_end': '||||',
'stopped': '<state>stopped</state>'}}
self.ctl = {'type': 'socket',
'name': '/tmp/vlc.sock',
'commands': {'play': 'pause',
'pause': 'pause',
'next': 'next',
'prev': 'prev',
'stop': 'stop',
'volup': 'volup 1',
'voldn': 'voldown 1'}}
class Audacious(DummyPlayer):
def __init__(self):
config_dir = CFG_HOME + '/audacious/'
self.run = {'type': 'file',
'name': config_dir + 'lock'}
self.np = {'type': 'np_file',
'name': config_dir + 'nowplaying'}
self.ctl = {'type': 'command',
'commands': {'play': 'audtool --playback-playpause',
'pause': 'audtool --playback-playpause',
'next': 'audtool --playlist-advance',
'prev': 'audtool --playlist-reverse',
'stop': 'audtool --playback-stop',
'volup': 'audtool --set-volume +5',
'voldn': 'audtool --set-volume -5'}}
class Deadbeef(DummyPlayer):
def __init__(self):
self.run = {'type': 'process',
'name': 'deadbeef-main'}
self.np = {'type': 'np_command',
'name': 'deadbeef --nowplaying "%a%\\%t%\\%f%"'}
self.ctl = {'type': 'command',
'commands': {'play': 'deadbeef --play 2> /dev/null',
'pause': 'deadbeef --toggle-pause \
2> /dev/null',
'next': 'deadbeef --next 2> /dev/null',
'prev': 'deadbeef --prev 2> /dev/null',
'stop': 'deadbeef --stop 2> /dev/null'}}
class Qmmp(DummyPlayer):
def __init__(self):
self.run = {'type': 'file',
'name': '/tmp/qmmp.sock.1000'}
self.np = {'type': 'command',
'name': 'qmmp --status',
'str': {'artist_beg': 'ARTIST = ',
'artist_end': '\n',
'title_beg': 'TITLE = ',
'title_end': '\n',
'file_beg': '||||',
'file_end': '||||',
'stopped': '[stopped]'}}
self.ctl = {'type': 'command',
'commands': {'play': 'qmmp -t',
'pause': 'qmmp -t',
'next': 'qmmp --next',
'prev': 'qmmp --previous',
'stop': 'qmmp -s',
'volup': 'qmmp --volume-inc',
'voldn': 'qmmp --volume-dec'}}
class Guayadeque(DummyPlayer):
def __init__(self):
self.run = {'type': 'file',
'name': '%s/.guayadeque/.guayadeque-%s' %
(HOME, getuser())}
cmd_base = 'dbus-send --print-reply --type=method_call\
--dest=org.mpris.guayadeque /Player\
org.freedesktop.MediaPlayer.'
str_base = '"\n variant string "'
self.np = {'type': 'command',
'name': cmd_base + 'GetMetadata',
'str': {'artist_beg': 'artist' + str_base,
'artist_end': '"\n',
'title_beg': 'title' + str_base,
'title_end': '"\n',
'file_beg': 'location' + str_base,
'file_end': '"\n',
'stopped': '||||'}}
self.ctl = {'type': 'command',
'commands': {'play': cmd_base + 'Play &> /dev/null',
'pause': cmd_base + 'Play &> /dev/null',
'next': cmd_base + 'Next &> /dev/null',
'prev': cmd_base + 'Prev &> /dev/null',
'stop': cmd_base + 'Stop &> /dev/null'}}
class Gmusicbrowser(DummyPlayer):
def __init__(self):
config_dir = CFG_HOME + '/gmusicbrowser/'
self.run = {'type': 'file',
'name': config_dir + 'gmusicbrowser.fifo'}
self.np = {'type': 'np_file',
'name': config_dir + 'nowplaying'}
self.ctl = {'type': 'fifo',
'name': self.run['name'],
'commands': {'play': 'PlayPause',
'pause': 'PlayPause',
'next': 'NextSong',
'prev': 'PrevSong',
'stop': 'Stop'}}
class Ui:
def __init__(self, screen):
self.screen = screen
self.settings = SETTINGS
self.quit = False
self.artist = ''
curses.curs_set(0)
mousemask = curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION
curses.mousemask(mousemask)
curses.mouseinterval(0)
# init colors
curses.use_default_colors()
curses.init_pair(1, int(self.settings['color_title']), -1)
curses.init_pair(2, int(self.settings['color_text']), -1)
curses.init_pair(3, int(self.settings['color_status']), -1)
curses.init_pair(4, int(self.settings['color_buttons']), -1)
def update_content(self):
self.pos_y = 0
self.y, self.x = self.screen.getmaxyx()
if self.settings['view'] == 'lyrics':
self.header = self.artist + ' - ' + self.title
self.text = self.lyrics if self.lyrics \
else 'No lyrics found'
text_wrap = wrap(self.text, self.x - 2)
elif self.settings['view'] == 'artistbio':
self.header = self.artist
self.text = self.artistbio if self.artistbio \
else 'No artist info found'
text_wrap = wrapwords(self.text, self.x - 2)
elif self.settings['view'] == 'guitartabs':
self.header = self.artist + ' - ' + self.title
self.text = self.guitartabs if self.guitartabs \
else 'No guitar tabs found'
text_wrap = wrap(self.text, self.x - 2)
header_wrap = wrap(self.header, self.x - 2)
self.pad_lines = len(header_wrap.splitlines()) + \
len(text_wrap.splitlines()) + 1
# main window
self.pad = curses.newpad(self.pad_lines + self.y, self.x)
self.pad.addstr(0, 1, header_wrap,
curses.color_pair(1) | curses.A_BOLD)
self.pad.addstr(len(header_wrap.splitlines()) + 1, 1, text_wrap,
curses.color_pair(2))
# statusbar
self.statusbar = curses.newpad(1, self.x)
self.refresh()
def refresh(self):
self.pad.noutrefresh(self.pos_y, 0, 0, 0, self.y - 2, self.x)
self.statusbar.erase()
if self.pad_lines <= self.y - 1:
pos_perc = 'All'
elif self.pos_y == 0:
pos_perc = 'Top'
elif self.pos_y > self.pad_lines - self.y:
pos_perc = 'Bot'
else:
pos_perc = str(int((100 / float(self.pad_lines - self.y)) \
* self.pos_y - 1)) + '%'
self.statusbar.addstr(0, 1, '|< >> || >|', curses.color_pair(4))
self.statusbar.addstr(0, self.x - len(pos_perc) - 1, pos_perc,
curses.color_pair(3))
self.statusbar.addstr(0, self.x - len(self.settings['view']) - 10,
self.settings['view'], curses.color_pair(3))
self.statusbar.noutrefresh(0, 0, self.y - 1, 0, self.y, self.x)
curses.doupdate()
def toggle_views(self):
views = ['lyrics', 'artistbio', 'guitartabs']
i = views.index(self.settings['view']) + 1
if i >= len(views):
i = 0
self.settings['view'] = views[i]
self.update_content()
def scroll(self, i):
if i == 'top':
self.pos_y = 0
elif i == 'bot':
self.pos_y = self.pad_lines - self.y + 1
elif i == 'npage':
if self.pos_y + self.y - 1 <= self.pad_lines - 1:
self.pos_y += self.y - 1
elif i == 'ppage':
self.pos_y -= self.y - 1
if self.pos_y < 0:
self.pos_y = 0
else:
if i < 0:
self.pos_y += i
if self.pos_y < 0:
self.pos_y = 0
elif self.pos_y < self.pad_lines - self.y + 1:
self.pos_y += i
if self.pos_y > self.pad_lines - self.y + 1:
self.pos_y = self.pad_lines - self.y + 1
self.refresh()
def control(self):
commands = {ord(self.settings['key_play']): 'play',
ord(self.settings['key_pause']): 'pause',
ord(self.settings['key_next']): 'next',
ord(self.settings['key_prev']): 'prev',
ord(self.settings['key_stop']): 'stop',
ord(self.settings['key_volup']): 'volup',
ord(self.settings['key_voldn']): 'voldn'}
while True:
key = self.screen.getch()
x = y = bstate = None
if key == curses.KEY_MOUSE:
id, x, y, z, bstate = curses.getmouse()
if key == ord(self.settings['key_quit']):
self.quit = True
elif key == curses.KEY_RESIZE:
self.update_content()
elif bstate == curses.BUTTON1_PRESSED:
if y == self.y - 1:
if 1 <= x <= 2:
p.command('prev')
elif 5 <= x <= 6:
p.command('play')
elif 9 <= x <= 10:
p.command('pause')
elif 13 <= x <= 14:
p.command('next')
elif self.x - len(self.settings['view']) - 10 <= x\
and x < self.x - 10:
self.toggle_views()
elif key == ord(self.settings['key_toggle']):
self.toggle_views()
elif key in commands:
p.command(commands[key])
elif key == curses.KEY_DOWN or key == ord('j'):
self.scroll(1)
elif key == curses.KEY_UP or key == ord('k'):
self.scroll(-1)
elif bstate == curses.BUTTON2_PRESSED:
self.scroll(3)
elif bstate == curses.BUTTON4_PRESSED:
self.scroll(-3)
elif key == curses.KEY_NPAGE or key == curses.KEY_RIGHT:
self.scroll('npage')
elif key == curses.KEY_PPAGE or key == curses.KEY_LEFT:
self.scroll('ppage')
elif key == curses.KEY_END or key == ord('G'):
self.scroll('bot')
elif key == curses.KEY_HOME or key == ord('g'):
self.scroll('top')
def main(stdscr):
u = Ui(stdscr)
ui_control = Thread(target=u.control)
ui_control.daemon = True
ui_control.start()
lock = Lock()
data = {'ui': u, 'lock': lock}
while True:
p.status()
if u.quit == True or not p.running:
if not p.running:
if os.path.exists(p.np['name']):
os.remove(p.np['name'])
break
elif p.playing == True:
if p.artist != u.artist or p.title != u.title:
needsupdate = ['lyrics', 'guitartabs']
if p.artist != u.artist:
needsupdate.insert(1, 'artistbio')
if SETTINGS['bg']:
needsupdate.insert(0, 'backdrops')
elif u.artistbio == 'Searching artist info...':
needsupdate.insert(1, 'artistbio')
if u.settings['view'] in needsupdate:
needsupdate.insert(1 if 'backdrops' in needsupdate else 0,
needsupdate.pop(needsupdate.index(u.settings['view'])))
lock.acquire()
try:
u.artist = p.artist
u.title = p.title
if 'lyrics' in needsupdate:
u.lyrics = 'Searching lyrics...'
if 'artistbio' in needsupdate:
u.artistbio = 'Searching artist info...'
if 'guitartabs' in needsupdate:
u.guitartabs = 'Searching guitar tab...'
u.update_content()
finally:
lock.release()
worker = Thread(target=get_and_update,
args=(p.artist, p.title, data, needsupdate))
worker.daemon = True
worker.start()
else:
u.artist = p.artist
u.title = p.title
u.lyrics = 'Not playing'
u.artistbio = 'Not playing'
u.guitartabs = 'Not playing'
u.update_content()
sleep(1)
if SETTINGS['bg']:
bg_unset()
SETTINGS.update(parse_config(CFG_HOME + '/lyvi/rc'))
if __name__ == '__main__':
if '-v' in sys.argv:
print('Lyvi %s (libglyr %s)' % (VERSION, GLYR_VERSION))
sys.exit()
players = {'cmus': Cmus,
'shell-fm': Shellfm,
'pianobar': Pianobar,
'mocp': Moc,
'gmusicbrowser': Gmusicbrowser,
'mplayer': Mplayer,
'vlc': Vlc,
'audacious': Audacious,
'deadbeef-main': Deadbeef,
'qmmp': Qmmp,
'guayadeque': Guayadeque}
for player in players:
if running(player):
p = players[player]()
break
else:
local = ['localhost', '127.0.0.1']
if running('mpd') or SETTINGS['mpd_host'] not in local:
p = Mpd(SETTINGS['mpd_host'], SETTINGS['mpd_port'])
else:
print('No supported player found.')
sys.exit()
if len(sys.argv) > 1:
p.command(sys.argv[1])
else:
curses.wrapper(main)