-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
SpotifyLyrics.pyw
executable file
·839 lines (727 loc) · 38.7 KB
/
SpotifyLyrics.pyw
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
#!/usr/bin/env python3
import configparser
import getpass
import os
import platform
import re
import subprocess
import sys
import threading
import time
import webbrowser
import pathvalidate
import pylrc
import sentry_sdk
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtGui import QAction
from PyQt6.QtWidgets import QSystemTrayIcon, QMenu, QApplication, QMessageBox
import backend
from services import Config
if os.name == "nt":
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("spotifylyrics.version1")
class Communicate(QtCore.QObject):
signal = QtCore.pyqtSignal(str, str)
class LyricsTextBrowserWidget(QtWidgets.QTextBrowser):
wheelSignal = QtCore.pyqtSignal()
def wheelEvent(self, e):
try:
modifiers = e.modifiers()
if modifiers == QtCore.Qt.KeyboardModifier.ControlModifier:
num_pixels = e.pixelDelta()
num_degrees = e.angleDelta()
factor = 1
if not num_pixels.isNull():
sign = 1 if num_pixels.y() > 0 else -1
UI.change_fontsize(sign * factor)
elif not num_degrees.isNull():
sign = 1 if num_degrees.y() > 0 else -1
UI.change_fontsize(sign * factor)
else:
super(QtWidgets.QTextBrowser, self).wheelEvent(e)
except:
pass
BRACKETS = re.compile(r'\[.+?\]')
HTML_TAGS = re.compile(r'<.+?>')
class UiForm:
sync = False
ontop = False
open_spotify = False
changed = False
dark_theme = False
info = False
minimize_to_tray = False
tray_icon = None
streaming_services = [backend.SpotifyStreamingService(), backend.VlcMediaPlayer(), backend.TidalStreamingService()]
def __init__(self):
self.lyrics = ""
self.timed = False
self.is_loading_settings = False
self.comm = Communicate()
self.comm.signal.connect(self.refresh_lyrics)
FORM.setObjectName("Form")
FORM.resize(550, 610)
FORM.setMinimumSize(QtCore.QSize(350, 310))
self.grid_layout_2 = QtWidgets.QGridLayout(FORM)
self.grid_layout_2.setObjectName("gridLayout_2")
self.vertical_layout_2 = QtWidgets.QVBoxLayout()
self.vertical_layout_2.setObjectName("verticalLayout_2")
self.horizontal_layout_2 = QtWidgets.QHBoxLayout()
self.horizontal_layout_2.setObjectName("horizontalLayout_2")
self.horizontal_layout_1 = QtWidgets.QHBoxLayout()
self.horizontal_layout_1.setObjectName("horizontalLayout_1")
self.label_song_name = QtWidgets.QLabel(FORM)
self.label_song_name.setObjectName("label_song_name")
self.label_song_name.setOpenExternalLinks(True)
self.horizontal_layout_2.addWidget(self.label_song_name, 0,
QtCore.Qt.AlignmentFlag.AlignLeft | QtCore.Qt.AlignmentFlag.AlignVCenter)
spacer_item = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding,
QtWidgets.QSizePolicy.Policy.Minimum)
self.horizontal_layout_2.addItem(spacer_item)
self.streaming_services_box = QtWidgets.QComboBox(FORM)
self.streaming_services_box.setGeometry(QtCore.QRect(160, 120, 69, 22))
self.streaming_services_box.addItems(str(n) for n in self.streaming_services)
self.streaming_services_box.setCurrentIndex(0)
self.streaming_services_box.currentIndexChanged.connect(self.options_changed)
self.horizontal_layout_2.addWidget(self.streaming_services_box, 0,
QtCore.Qt.AlignmentFlag.AlignRight | QtCore.Qt.AlignmentFlag.AlignVCenter)
self.change_lyrics_button = QtWidgets.QPushButton(FORM)
self.change_lyrics_button.setObjectName("pushButton")
self.change_lyrics_button.setText("Change Lyrics")
self.change_lyrics_button.clicked.connect(self.change_lyrics)
self.horizontal_layout_2.addWidget(self.change_lyrics_button, 0,
QtCore.Qt.AlignmentFlag.AlignRight | QtCore.Qt.AlignmentFlag.AlignVCenter)
self.save_button = QtWidgets.QPushButton(FORM)
self.save_button.setObjectName("saveButton")
self.save_button.setText("Save Lyrics")
self.save_button.clicked.connect(self.save_lyrics)
self.horizontal_layout_2.addWidget(self.save_button, 0,
QtCore.Qt.AlignmentFlag.AlignRight | QtCore.Qt.AlignmentFlag.AlignVCenter)
# Open Tab Button
self.chords_button = QtWidgets.QPushButton(FORM)
self.chords_button.setObjectName("chordsButton")
self.chords_button.setText("Chords")
self.chords_button.clicked.connect(self.get_chords)
self.horizontal_layout_2.addWidget(self.chords_button, 0,
QtCore.Qt.AlignmentFlag.AlignRight | QtCore.Qt.AlignmentFlag.AlignVCenter)
self.options_combobox = QtWidgets.QComboBox(FORM)
self.options_combobox.setGeometry(QtCore.QRect(160, 120, 69, 22))
self.options_combobox.setObjectName("comboBox")
self.options_combobox.addItem("")
self.options_combobox.addItem("")
self.options_combobox.addItem("")
self.options_combobox.addItem("")
self.options_combobox.addItem("")
self.options_combobox.addItem("")
self.options_combobox.addItem("")
self.options_combobox.addItem("")
self.tray_icon = QSystemTrayIcon(FORM)
self.tray_icon.setIcon(QtGui.QIcon(self.get_resource_path('icon.png')))
show_action = QAction("Show", FORM)
quit_action = QAction("Exit", FORM)
show_action.triggered.connect(FORM.show)
quit_action.triggered.connect(QApplication.quit)
tray_menu = QMenu()
tray_menu.addAction(show_action)
tray_menu.addAction(quit_action)
self.tray_icon.setContextMenu(tray_menu)
self.tray_icon.show()
self.tray_icon.activated.connect(FORM.icon_activated)
if os.name == "nt":
self.options_combobox.addItem("")
self.horizontal_layout_2.addWidget(self.options_combobox, 0,
QtCore.Qt.AlignmentFlag.AlignRight | QtCore.Qt.AlignmentFlag.AlignVCenter)
self.font_size_box = QtWidgets.QSpinBox(FORM)
self.font_size_box.setMinimum(1)
self.font_size_box.setProperty("value", 10)
self.font_size_box.setObjectName("fontBox")
self.horizontal_layout_2.addWidget(self.font_size_box, 0,
QtCore.Qt.AlignmentFlag.AlignRight | QtCore.Qt.AlignmentFlag.AlignVCenter)
self.vertical_layout_2.addLayout(self.horizontal_layout_2)
self.sync_adjustment_slider = QtWidgets.QSlider(FORM)
self.sync_adjustment_slider.setInvertedAppearance(True)
self.sync_adjustment_slider.setMinimum(-60)
self.sync_adjustment_slider.setMaximum(60)
self.sync_adjustment_slider.setSingleStep(1)
self.sync_adjustment_slider.setToolTipDuration(5000)
self.sync_adjustment_slider.setFixedWidth(25)
self.sync_adjustment_slider.valueChanged.connect(self.changed_slider)
self.sync_adjustment_slider.setValue(0)
self.horizontal_layout_1.addWidget(self.sync_adjustment_slider)
self.text_browser = LyricsTextBrowserWidget(FORM)
self.text_browser.setObjectName("textBrowser")
self.text_browser.setAcceptRichText(True)
self.text_browser.setStyleSheet("font-size: %spt;" % self.font_size_box.value() * 2)
self.text_browser.setFontPointSize(self.font_size_box.value())
self.horizontal_layout_1.addWidget(self.text_browser)
self.info_table = QtWidgets.QTableWidget(FORM)
self.info_table.setStyleSheet("font-size: %spt;" % self.font_size_box.value() * 2)
self.info_table.setColumnCount(2)
self.info_table.setMaximumWidth(300)
self.info_table.verticalHeader().setVisible(False)
self.info_table.horizontalHeader().setVisible(False)
self.info_table.horizontalHeader().setStretchLastSection(True)
self.info_table.setVisible(False)
self.horizontal_layout_1.addWidget(self.info_table)
self.vertical_layout_2.addLayout(self.horizontal_layout_1)
self.grid_layout_2.addLayout(self.vertical_layout_2, 2, 0, 1, 1)
self.retranslate_ui(FORM)
self.font_size_box.valueChanged.connect(self.update_fontsize)
self.options_combobox.currentIndexChanged.connect(self.options_changed)
QtCore.QMetaObject.connectSlotsByName(FORM)
FORM.setTabOrder(self.text_browser, self.options_combobox)
FORM.setTabOrder(self.options_combobox, self.font_size_box)
self.current_line_size_ratio = 1.25
self.current_line_style = {
"font-size": f"{self.current_line_size_ratio * self.font_size_box.value()}pt"
}
self.set_style()
self.load_save_settings()
self.spotify()
self.start_thread()
self.song = None
def changed_slider(self, value) -> None:
self.sync_adjustment_slider.setToolTip("%d seconds shifted" % value)
def streaming_service_changed(self) -> None:
self.spotify()
self.load_save_settings(save=True)
def get_current_streaming_service(self) -> backend.StreamingService:
return self.streaming_services[self.streaming_services_box.currentIndex()]
def load_save_settings(self, save=False) -> None:
if self.is_loading_settings:
return
settings_file = Config.SETTINGS_DIR + "settings.ini"
section = "settings"
if not os.path.exists(settings_file):
directory = os.path.dirname(settings_file)
if not os.path.exists(directory):
os.makedirs(directory)
loaded_config = configparser.ConfigParser(strict=False)
if not save:
self.is_loading_settings = True
try:
loaded_config.read(settings_file)
except configparser.MissingSectionHeaderError:
pass
self.sync = loaded_config.getboolean(section, "syncedlyrics", fallback=False)
self.ontop = loaded_config.getboolean(section, "alwaysontop", fallback=False)
self.open_spotify = loaded_config.getboolean(section, "openspotify", fallback=False)
self.dark_theme = loaded_config.getboolean(section, "darktheme", fallback=False)
self.info = loaded_config.getboolean(section, "info", fallback=False)
self.minimize_to_tray = loaded_config.getboolean(section, "minimizetotray", fallback=False)
self.font_size_box.setValue(loaded_config.getint(section, "fontsize", fallback=10))
Config.LYRICS_DIR = loaded_config.get(section, "LyricsPath", fallback=Config.LYRICS_DIR)
streaming_service_name = loaded_config.get(section, "StreamingService", fallback=None)
if streaming_service_name:
for i in range(len(self.streaming_services)):
if str(self.streaming_services[i]) == streaming_service_name:
self.streaming_services_box.setCurrentIndex(i)
break
FORM.move(loaded_config.getint(section, "X", fallback=FORM.pos().x()),
loaded_config.getint(section, "Y", fallback=FORM.pos().y()))
if loaded_config.getboolean(section, "FullScreen", fallback=False):
FORM.showFullScreen()
elif loaded_config.getboolean(section, "Maximized", fallback=False):
FORM.showMaximized()
else:
FORM.resize(loaded_config.getint(section, "Width", fallback=FORM.width().real),
loaded_config.getint(section, "Height", fallback=FORM.height().real))
if loaded_config.getboolean(section, "disableErrorReporting", fallback=False):
self.disableErrorReporting = True
sentry_sdk.init()
self.options_combobox.setItemText(8, "Error reporting disabled")
else:
self.disableErrorReporting = False
if self.dark_theme:
self.set_dark_theme()
if self.sync:
self.options_combobox.setItemText(2, "Synced Lyrics (on)")
if self.ontop:
FORM.setWindowFlags(FORM.windowFlags() | QtCore.Qt.WindowType.WindowStaysOnTopHint)
self.options_combobox.setItemText(3, "Always on Top (on)")
FORM.show()
if self.open_spotify:
self.options_combobox.setItemText(4, "Open Spotify (on)")
if self.info:
self.options_combobox.setItemText(5, "Info (on)")
self.info_table.setVisible(True)
if self.minimize_to_tray:
self.options_combobox.setItemText(7, "Minimize to Tray (on)")
else:
loaded_config.add_section(section)
loaded_config[section]["SyncedLyrics"] = str(self.sync)
loaded_config[section]["AlwaysOnTop"] = str(self.ontop)
loaded_config[section]["OpenSpotify"] = str(self.open_spotify)
loaded_config[section]["DarkTheme"] = str(self.dark_theme)
loaded_config[section]["Info"] = str(self.info)
loaded_config[section]["MinimizeToTray"] = str(self.minimize_to_tray)
loaded_config[section]["FontSize"] = str(self.font_size_box.value())
loaded_config[section]["StreamingService"] = str(self.get_current_streaming_service())
loaded_config[section]["FullScreen"] = str(FORM.isFullScreen())
loaded_config[section]["Maximized"] = str(FORM.isMaximized())
loaded_config[section]["X"] = str(FORM.pos().x())
loaded_config[section]["Y"] = str(FORM.pos().y())
loaded_config[section]["Width"] = str(FORM.width().real)
loaded_config[section]["Height"] = str(FORM.height().real)
if self.disableErrorReporting:
loaded_config[section]["disableErrorReporting"] = str(self.disableErrorReporting)
if Config.LYRICS_DIR != Config.DEFAULT_LYRICS_DIR:
loaded_config[section]["LyricsPath"] = Config.LYRICS_DIR
with open(settings_file, 'w+') as settings:
loaded_config.write(settings)
self.is_loading_settings = False
def options_changed(self) -> None:
current_index = self.options_combobox.currentIndex()
if current_index == 1:
if self.dark_theme is False:
self.set_dark_theme()
else:
self.dark_theme = False
self.text_browser.setStyleSheet("")
self.label_song_name.setStyleSheet("")
self.options_combobox.setStyleSheet("")
self.font_size_box.setStyleSheet("")
self.sync_adjustment_slider.setStyleSheet("")
self.streaming_services_box.setStyleSheet("")
self.change_lyrics_button.setStyleSheet("")
self.save_button.setStyleSheet("")
self.chords_button.setStyleSheet("")
self.info_table.setStyleSheet("")
self.options_combobox.setItemText(1, "Dark Theme")
text = re.sub("color:.*?;", "color: black;", self.label_song_name.text())
self.label_song_name.setText(text)
FORM.setWindowOpacity(1.0)
FORM.setStyleSheet("")
self.set_style()
elif current_index == 2:
if self.sync:
self.options_combobox.setItemText(2, "Synced Lyrics")
else:
self.options_combobox.setItemText(2, "Synced Lyrics (on)")
self.sync = not self.sync
elif current_index == 3:
if self.ontop is False:
FORM.setWindowFlags(FORM.windowFlags() | QtCore.Qt.WindowType.WindowStaysOnTopHint)
self.options_combobox.setItemText(3, "Always on Top (on)")
FORM.show()
else:
FORM.setWindowFlags(FORM.windowFlags() & ~QtCore.Qt.WindowType.WindowStaysOnTopHint)
self.options_combobox.setItemText(3, "Always on Top")
FORM.show()
self.ontop = not self.ontop
elif current_index == 4:
if self.open_spotify:
self.options_combobox.setItemText(4, "Open Spotify")
else:
self.spotify()
self.options_combobox.setItemText(4, "Open Spotify (on)")
self.open_spotify = not self.open_spotify
elif current_index == 5:
if self.info:
self.options_combobox.setItemText(5, "Info")
self.info_table.setVisible(False)
else:
self.options_combobox.setItemText(5, "Info (on)")
self.info_table.setVisible(True)
self.info = not self.info
elif current_index == 6:
if os.name == "nt":
subprocess.Popen(r'explorer "' + Config.LYRICS_DIR + '"')
elif current_index == 7:
if self.minimize_to_tray:
self.options_combobox.setItemText(7, "Minimize to System Tray")
else:
self.options_combobox.setItemText(7, "Minimize to System Tray (on)")
self.minimize_to_tray = not self.minimize_to_tray
elif current_index == 8:
if self.disableErrorReporting:
self.options_combobox.setItemText(8, "Disable Error reporting")
else:
self.options_combobox.setItemText(8, "Error Reporting disabled")
self.disableErrorReporting = not self.disableErrorReporting
self.options_combobox.setCurrentIndex(0)
self.load_save_settings(save=True)
def set_style(self):
self.lyrics_text_align = QtCore.Qt.AlignmentFlag.AlignLeft
if os.path.exists(Config.SETTINGS_DIR + "theme.ini"):
theme_file = Config.SETTINGS_DIR + "theme.ini"
else:
theme_file = "theme.ini"
if not os.path.exists(theme_file):
self.label_song_name.setStyleSheet("color: black; text-decoration: underline;")
return
section = "theme"
style_config = configparser.ConfigParser()
with open(theme_file, 'r') as theme:
style_config.read_string(f"[{section}]\n{theme.read()}")
align = style_config.get(section, "lyricstextalign", fallback="")
if align:
if align == "center":
self.lyrics_text_align = QtCore.Qt.AlignmentFlag.AlignCenter
elif align == "right":
self.lyrics_text_align = QtCore.Qt.AlignmentFlag.AlignRight
FORM.setWindowOpacity(style_config.getfloat(section, "windowopacity", fallback=1))
background = style_config.get(section, "backgroundcolor", fallback="")
if background:
FORM.setStyleSheet(f"background-color: {background};")
style = self.text_browser.styleSheet()
text_background = style_config.get(section, "lyricsbackgroundcolor", fallback="")
if text_background:
style = f"{style}background-color: {text_background};"
text_color = style_config.get(section, "lyricstextcolor", fallback="")
if text_color:
style = f"{style}color: %s;" % text_color
text_font = style_config.get(section, "lyricsfont", fallback="")
if text_font:
style = f"{style}font-family: \"{text_font}\";"
self.text_browser.setStyleSheet(style)
style = self.label_song_name.styleSheet()
label_color = style_config.get(section, "songnamecolor", fallback="")
if label_color:
style = style + "color: %s;" % label_color
text = re.sub("color:.*?;", f"color: {label_color};", self.label_song_name.text())
self.label_song_name.setText(text)
label_underline = style_config.getboolean(section, "songnameunderline", fallback=False)
if label_underline:
style = f"{style}text-decoration: underline;"
self.label_song_name.setStyleSheet(style)
style = self.font_size_box.styleSheet()
font_size_background = style_config.get(section, "fontboxbackgroundcolor", fallback="")
if font_size_background:
style = f"{style}background-color: {font_size_background};"
font_size_color = style_config.get(section, "fontboxtextcolor", fallback="")
if font_size_color:
style = f"{style}color: {font_size_color};"
self.streaming_services_box.setStyleSheet(style)
self.options_combobox.setStyleSheet(style)
self.font_size_box.setStyleSheet(style)
self.change_lyrics_button.setStyleSheet(style)
self.save_button.setStyleSheet(style)
self.chords_button.setStyleSheet(style)
self.current_line_size_ratio = style_config.getfloat(section, "currentLineSizeRatio", fallback=1.25)
self.current_line_style["font-size"] = f"{self.current_line_size_ratio * self.font_size_box.value()}pt"
current_line_background_color = style_config.get(section, "currentLineBackgroundColor", fallback="")
if current_line_background_color:
self.current_line_style["background-color"] = current_line_background_color
def set_dark_theme(self):
self.dark_theme = True
self.text_browser.setStyleSheet("background-color: #181818; color: #ffffff;")
self.label_song_name.setStyleSheet("color: #9c9c9c; text-decoration: underline;")
text = re.sub("color:.*?;", "color: #9c9c9c;", self.label_song_name.text())
self.label_song_name.setText(text)
self.sync_adjustment_slider.setStyleSheet("background-color: #181818; color: #9c9c9c;")
self.streaming_services_box.setStyleSheet("background-color: #181818; color: #9c9c9c;")
self.options_combobox.setStyleSheet("background-color: #181818; color: #9c9c9c;")
self.font_size_box.setStyleSheet("background-color: #181818; color: #9c9c9c;")
self.change_lyrics_button.setStyleSheet("background-color: #181818; color: #9c9c9c;")
self.save_button.setStyleSheet("background-color: #181818; color: #9c9c9c;")
self.chords_button.setStyleSheet("background-color: #181818; color: #9c9c9c;")
self.info_table.setStyleSheet("background-color: #181818; color: #9c9c9c;")
self.options_combobox.setItemText(1, "Dark Theme (on)")
FORM.setWindowOpacity(1.0)
FORM.setStyleSheet("background-color: #282828;")
@staticmethod
def get_resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def set_lyrics_with_alignment(self, lyrics):
self.text_browser.clear()
for line in lyrics.splitlines():
self.text_browser.append(line)
self.text_browser.setAlignment(self.lyrics_text_align)
def change_fontsize(self, offset):
self.font_size_box.setValue(self.font_size_box.value() + offset)
def update_fontsize(self):
self.text_browser.setFontPointSize(self.font_size_box.value())
style = self.text_browser.styleSheet()
style = style.replace('%s' % style[style.find("font"):style.find("pt;") + 3], '')
style = style.replace('p ', '')
self.text_browser.setStyleSheet(f"{style}p font-size: {self.font_size_box.value() * 2}pt;")
lyrics = self.text_browser.toPlainText()
self.set_lyrics_with_alignment(lyrics)
self.current_line_style["font-size"] = f"{self.current_line_size_ratio * self.font_size_box.value()}pt"
self.load_save_settings(save=True)
def retranslate_ui(self, form):
_translate = QtCore.QCoreApplication.translate
form.setWindowTitle(_translate("Form", f"Spotify Lyrics - {backend.get_version()}"))
form.setWindowIcon(QtGui.QIcon(self.get_resource_path('icon.png')))
if backend.check_version():
self.label_song_name.setText(_translate("Form", "Spotify Lyrics"))
else:
self.label_song_name.setText(_translate("Form",
"Spotify Lyrics <style type=\"text/css\">a {text-decoration: "
"none}</style><a "
"href=\"https://github.com/SimonIT/spotifylyrics/releases\"><sup>("
"update)</sup></a>"))
update_dialog = QMessageBox()
update_dialog.setWindowIcon(FORM.windowIcon())
update_dialog.setIcon(QMessageBox.Icon.Information)
update_dialog.setText("A newer version of SpotifyLyrics is available!")
update_dialog.setInformativeText("Do you want to download the newer version?")
update_dialog.setWindowTitle("Update available")
update_dialog.setStandardButtons(QMessageBox.StandardButton.Open | QMessageBox.StandardButton.Close)
update_result = update_dialog.exec()
if update_result == QMessageBox.StandardButton.Open:
webbrowser.open("https://github.com/SimonIT/spotifylyrics/releases")
self.text_browser.setText(_translate("Form", "Play a song in Spotify to fetch lyrics."))
self.font_size_box.setToolTip(_translate("Form", "Font Size"))
self.options_combobox.setItemText(0, _translate("Form", "Options"))
self.options_combobox.setItemText(1, _translate("Form", "Dark Theme"))
self.options_combobox.setItemText(2, _translate("Form", "Synced Lyrics"))
self.options_combobox.setItemText(3, _translate("Form", "Always on Top"))
self.options_combobox.setItemText(4, _translate("Form", "Open Spotify"))
self.options_combobox.setItemText(5, _translate("Form", "Info"))
if os.name == "nt":
self.options_combobox.setItemText(6, _translate("Form", "Open Lyrics Directory"))
self.options_combobox.setItemText(7, _translate("Form", "Minimize to Tray"))
self.options_combobox.setItemText(8, _translate("Form", "Disable error reporting"))
def add_service_name_to_lyrics(self, lyrics, service_name):
return '''<span style="font-size:%spx; font-style:italic;">Lyrics loaded from: %s</span>\n\n%s''' % (
(self.font_size_box.value() - 2) * 2, service_name, lyrics)
def display_lyrics(self, comm):
old_song_name = ""
while True:
song_name = backend.get_window_title(self.get_current_streaming_service())
if (old_song_name != song_name or self.changed) \
and song_name not in self.get_current_streaming_service().get_not_playing_windows_title():
self.sync_adjustment_slider.setValue(0)
comm.signal.emit(song_name, "Loading...")
if not self.changed:
old_song_name = song_name
start = time.time()
self.song = backend.Song.get_from_string(song_name)
self.lyrics = ""
if self.info:
backend.load_info(self, self.song)
lyrics_metadata = backend.get_lyrics(song=self.song, sync=self.sync)
else:
lyrics_metadata = backend.next_lyrics(song=self.song, sync=self.sync)
self.changed = False
self.lyrics = lyrics_metadata.lyrics
self.timed = lyrics_metadata.timed
if not lyrics_metadata.url:
header = song_name
else:
style = self.label_song_name.styleSheet()
if style == "":
color = "color: black"
else:
color = style
header = '''<style type="text/css">a {text-decoration: none; %s}</style><a href="%s">%s</a>''' \
% (color, lyrics_metadata.url, song_name)
lyrics_clean = lyrics_metadata.lyrics
if lyrics_metadata.timed:
self.sync_adjustment_slider.setVisible(self.sync)
lrc = pylrc.parse(lyrics_metadata.lyrics)
if lrc.album:
self.song.album = lrc.album
lyrics_clean = '\n'.join(e.text for e in lrc)
comm.signal.emit(header,
self.add_service_name_to_lyrics(lyrics_clean, lyrics_metadata.service_name))
count = 0
line_changed = True
while self.sync and not self.changed:
time_title_start = time.time()
window_title = backend.get_window_title(self.get_current_streaming_service())
time_title_end = time.time()
if window_title in self.get_current_streaming_service().get_not_playing_windows_title():
time.sleep(0.2)
start += 0.2 + time_title_end - time_title_start
elif song_name != window_title or not count + 1 < len(lrc):
self.sync_adjustment_slider.setValue(0)
break
else:
if lrc[count + 1].time - self.sync_adjustment_slider.value() <= time.time() - start:
count += 1
line_changed = True
if line_changed:
lrc[count - 1].text = HTML_TAGS.sub("", lrc[count - 1].text)
lrc[count].text = \
f"<b style=\"{self.dict_to_style(self.current_line_style)}\">{lrc[count].text}</b>"
if count - 2 > 0:
lrc[count - 3].text = HTML_TAGS.sub("", lrc[count - 3].text)
lrc[count - 2].text = "<a name=\"#scrollHere\">%s</a>" % lrc[count - 2].text
bold_lyrics = '<style type="text/css">p {font-size: %spt}</style><p>%s</p>' % \
(
self.font_size_box.value(),
'<br>'.join(e.text for e in lrc)
)
comm.signal.emit(
header,
self.add_service_name_to_lyrics(bold_lyrics, lyrics_metadata.service_name)
)
line_changed = False
time.sleep(0.5)
else:
time.sleep(0.2)
else:
self.sync_adjustment_slider.setVisible(False)
comm.signal.emit(
header,
self.add_service_name_to_lyrics(lyrics_clean, lyrics_metadata.service_name))
time.sleep(1)
def start_thread(self):
lyrics_thread = threading.Thread(target=self.display_lyrics, args=(self.comm,))
lyrics_thread.daemon = True
lyrics_thread.start()
def refresh_lyrics(self, song_name, lyrics):
_translate = QtCore.QCoreApplication.translate
if backend.get_window_title(self.get_current_streaming_service()):
self.label_song_name.setText(_translate("Form", song_name))
self.set_lyrics_with_alignment(_translate("Form", lyrics))
self.text_browser.scrollToAnchor("#scrollHere")
self.refresh_info()
def refresh_info(self):
self.info_table.clearContents()
if not self.song:
return
self.info_table.setRowCount(8)
index = 0
self.info_table.setItem(index, 0, QtWidgets.QTableWidgetItem("Title"))
self.info_table.setItem(index, 1, QtWidgets.QTableWidgetItem(self.song.name))
index += 1
self.info_table.setItem(index, 0, QtWidgets.QTableWidgetItem("Artist"))
self.info_table.setItem(index, 1, QtWidgets.QTableWidgetItem(self.song.artist))
index += 1
if self.song.album != "UNKNOWN":
self.info_table.setItem(index, 0, QtWidgets.QTableWidgetItem("Album"))
self.info_table.setItem(index, 1, QtWidgets.QTableWidgetItem(self.song.album))
index += 1
if self.song.genre != "UNKNOWN":
self.info_table.setItem(index, 0, QtWidgets.QTableWidgetItem("Genre"))
self.info_table.setItem(index, 1, QtWidgets.QTableWidgetItem(self.song.genre))
index += 1
if self.song.year != -1:
self.info_table.setItem(index, 0, QtWidgets.QTableWidgetItem("Year"))
self.info_table.setItem(index, 1, QtWidgets.QTableWidgetItem(str(self.song.year)))
index += 1
if self.song.cycles_per_minute != -1:
self.info_table.setItem(index, 0, QtWidgets.QTableWidgetItem("Cycles Per Minute"))
self.info_table.setItem(index, 1, QtWidgets.QTableWidgetItem(str(self.song.cycles_per_minute)))
index += 1
if self.song.beats_per_minute != -1:
self.info_table.setItem(index, 0, QtWidgets.QTableWidgetItem("Beats Per Minute"))
self.info_table.setItem(index, 1, QtWidgets.QTableWidgetItem(str(self.song.beats_per_minute)))
index += 1
if self.song.dances:
self.info_table.setItem(index, 0, QtWidgets.QTableWidgetItem("Dances"))
self.info_table.setItem(index, 1, QtWidgets.QTableWidgetItem("\n".join(self.song.dances)))
self.info_table.resizeRowsToContents()
self.info_table.resizeColumnsToContents()
def get_chords(self):
_translate = QtCore.QCoreApplication.translate
if self.song:
backend.load_chords(self.song)
else:
self.text_browser.append(_translate("Form", "I'm sorry, Dave. I'm afraid I can't do that."))
def change_lyrics(self):
_translate = QtCore.QCoreApplication.translate
if self.song:
self.changed = True
else:
self.text_browser.append(_translate("Form", "I'm sorry, Dave. I'm afraid I can't do that."))
def save_lyrics(self):
if not self.song or not self.lyrics:
return
if not os.path.exists(Config.LYRICS_DIR):
os.makedirs(Config.LYRICS_DIR)
artist = pathvalidate.sanitize_filename(self.song.artist)
name = pathvalidate.sanitize_filename(self.song.name)
new_lyrics_file_name = None
for lyrics_file_name in os.listdir(Config.LYRICS_DIR):
lyrics_file_name = os.path.join(Config.LYRICS_DIR, lyrics_file_name)
if os.path.isfile(lyrics_file_name):
file_parts = os.path.splitext(lyrics_file_name)
file_extension = file_parts[1].lower()
if file_extension in (".txt", ".lrc"):
file_name = file_parts[0].lower()
if name.lower() in file_name and artist.lower() in file_name:
save_dialog = QMessageBox()
save_dialog.setWindowIcon(FORM.windowIcon())
save_dialog.setIcon(QMessageBox.Icon.Information)
save_dialog.setText("You got already saved lyrics for the song %s by %s!" %
(self.song.name, self.song.artist))
save_dialog.setInformativeText("Do you want overwrite them?")
save_dialog.setWindowTitle("Lyrics already saved")
save_dialog.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
save_anyway = save_dialog.exec()
if save_anyway == QMessageBox.StandardButton.Yes:
new_lyrics_file_name = file_parts[0]
break
else:
return
if not new_lyrics_file_name:
new_lyrics_file_name = os.path.join(Config.LYRICS_DIR, f"{artist} - {name}")
text = self.lyrics
if self.timed:
lyrics_file_name = new_lyrics_file_name + ".lrc"
if self.sync_adjustment_slider.value() != 0:
lrc = pylrc.parse(text)
lrc.offset -= self.sync_adjustment_slider.value() * 1000
text = lrc.toLRC()
else:
lyrics_file_name = new_lyrics_file_name + ".txt"
with open(lyrics_file_name, "w", encoding="utf-8") as lyrics_file:
lyrics_file.write(text)
def spotify(self) -> None:
if not self.open_spotify:
return
if not backend.open_spotify(self.get_current_streaming_service()):
save_dialog = QMessageBox()
save_dialog.setWindowIcon(FORM.windowIcon())
save_dialog.setIcon(QMessageBox.Icon.Warning)
save_dialog.setText("Couldn't open %s!" % str(self.get_current_streaming_service()))
save_dialog.setStandardButtons(QMessageBox.StandardButton.Ok)
save_dialog.exec()
@classmethod
def dict_to_style(cls, dictionary: dict) -> str:
style = ""
for key, value in dictionary.items():
style = f"{style}{key}: {value};"
return style
class FormWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
def closeEvent(self, event):
UI.load_save_settings(save=True)
if UI.minimize_to_tray:
event.ignore()
self.hide()
def icon_activated(self, reason):
if reason == QtWidgets.QSystemTrayIcon.ActivationReason.DoubleClick:
self.show()
def moveEvent(self, a0: QtGui.QMoveEvent) -> None:
try:
UI.load_save_settings(save=True)
except:
pass
def resizeEvent(self, a0: QtGui.QResizeEvent) -> None:
try:
UI.load_save_settings(save=True)
except:
pass
if __name__ == "__main__":
sentry_sdk.init("https://71bf000cb7c5448c8c08660b29a12c09@o407859.ingest.sentry.io/5277612",
release=f"spotifylyrics@{backend.get_version()}", auto_enabling_integrations=False)
with sentry_sdk.configure_scope() as scope:
try:
scope.set_user({"username": getpass.getuser()})
except ModuleNotFoundError:
pass
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
running = "pyinstaller"
else:
running = "source"
scope.set_tag("running_from", running)
scope.set_tag("os", platform.system())
scope.set_tag("os_version", platform.release())
scope.set_tag("architecture", platform.machine())
APP = QtWidgets.QApplication(sys.argv)
APP.setStyle("fusion")
FORM = FormWidget()
UI = UiForm()
FORM.show()
sys.exit(APP.exec())