noneto-cli 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. noneto/__init__.py +1 -0
  2. noneto/__main__.py +3 -0
  3. noneto/app.py +113 -0
  4. noneto/assets/noneto.ico +0 -0
  5. noneto/audio/__init__.py +1 -0
  6. noneto/audio/controller.py +427 -0
  7. noneto/audio/inspector.py +21 -0
  8. noneto/audio/ipc_unix.py +29 -0
  9. noneto/audio/ipc_windows.py +94 -0
  10. noneto/audio/lifetime.py +68 -0
  11. noneto/audio/media_controls.py +107 -0
  12. noneto/audio/mpv_install.py +71 -0
  13. noneto/audio/player.py +222 -0
  14. noneto/audio/pulse_tap.py +120 -0
  15. noneto/audio/spectrum.py +44 -0
  16. noneto/audio/streams.py +101 -0
  17. noneto/audio/tap.py +208 -0
  18. noneto/audio/windows_identity.py +79 -0
  19. noneto/audio/windows_media.py +157 -0
  20. noneto/auth/__init__.py +1 -0
  21. noneto/auth/dpapi.py +28 -0
  22. noneto/auth/service.py +53 -0
  23. noneto/auth/storage.py +120 -0
  24. noneto/diagnostics.py +115 -0
  25. noneto/errors.py +12 -0
  26. noneto/i18n.py +199 -0
  27. noneto/platform/__init__.py +1 -0
  28. noneto/platform/paths.py +27 -0
  29. noneto/security.py +59 -0
  30. noneto/services/__init__.py +1 -0
  31. noneto/services/covers.py +88 -0
  32. noneto/services/executor.py +83 -0
  33. noneto/services/library.py +110 -0
  34. noneto/services/tidal.py +188 -0
  35. noneto/settings.py +48 -0
  36. noneto/state/__init__.py +1 -0
  37. noneto/state/queue.py +130 -0
  38. noneto/state/writer.py +38 -0
  39. noneto/ui/__init__.py +1 -0
  40. noneto/ui/common.py +36 -0
  41. noneto/ui/cover.py +88 -0
  42. noneto/ui/dialogs.py +107 -0
  43. noneto/ui/linux_login.py +57 -0
  44. noneto/ui/login_window.py +201 -0
  45. noneto/ui/lyrics.py +142 -0
  46. noneto/ui/player.py +172 -0
  47. noneto/ui/quality.py +75 -0
  48. noneto/ui/queue.py +34 -0
  49. noneto/ui/terminal.py +65 -0
  50. noneto/ui/themes.py +352 -0
  51. noneto/ui/top.py +39 -0
  52. noneto/ui/tracks.py +139 -0
  53. noneto/ui/tui.py +601 -0
  54. noneto/ui/visualizer.py +343 -0
  55. noneto_cli-1.1.1.dist-info/METADATA +222 -0
  56. noneto_cli-1.1.1.dist-info/RECORD +59 -0
  57. noneto_cli-1.1.1.dist-info/WHEEL +4 -0
  58. noneto_cli-1.1.1.dist-info/entry_points.txt +2 -0
  59. noneto_cli-1.1.1.dist-info/licenses/LICENSE +21 -0
noneto/ui/cover.py ADDED
@@ -0,0 +1,88 @@
1
+ """Album covers in the Lyrics tab and the player: a real image when the terminal can draw one."""
2
+ import logging
3
+
4
+ from PIL import Image
5
+ from rich.style import Style
6
+ from rich.text import Text
7
+ from textual.widgets import Static
8
+
9
+ from ..diagnostics import emit, failure
10
+
11
+ CSS = """
12
+ #cover { width: 14; height: 6; margin: 1 1 0 1; }
13
+ #cover.picture { width: 12; margin: 1 3 0 1; }
14
+ #mini-cover { width: 6; height: 3; margin-right: 2; }
15
+ """
16
+
17
+
18
+ def cover_text(image, cols=12, rows=6):
19
+ """Draw the artwork with half blocks: each cell shows two pixels, one above the other."""
20
+ if image is None:
21
+ return Text("\n".join([" " * cols] * rows))
22
+ pixels = image.resize((cols, rows * 2), Image.Resampling.LANCZOS).load()
23
+ output = Text()
24
+ for row in range(rows):
25
+ if row:
26
+ output.append("\n")
27
+ for x in range(cols):
28
+ top, bottom = pixels[x, row * 2], pixels[x, row * 2 + 1]
29
+ output.append("▀", style=Style(color=f"rgb({top[0]},{top[1]},{top[2]})",
30
+ bgcolor=f"rgb({bottom[0]},{bottom[1]},{bottom[2]})"))
31
+ return output
32
+
33
+
34
+ def terminal_artwork():
35
+ """Image widget for terminals with sixel or kitty graphics; None keeps half blocks.
36
+
37
+ Importing textual_image probes the terminal, so this must run before Textual owns stdin.
38
+ """
39
+ logging.getLogger("textual_image").addHandler(logging.NullHandler())
40
+ logging.getLogger("textual_image").propagate = False
41
+ try:
42
+ from textual_image.renderable import HalfcellImage, Image as Renderable, UnicodeImage
43
+ from textual_image.widget import Image as ImageWidget
44
+ except Exception as error:
45
+ failure("cover.graphics_unavailable", error)
46
+ return None
47
+ emit("cover.graphics", method=Renderable.__module__.rsplit(".", 1)[-1])
48
+ return None if Renderable in (HalfcellImage, UnicodeImage) else ImageWidget
49
+
50
+
51
+ class CoverArt:
52
+ """Builds every cover widget and draws the current artwork (a PIL image) on all of them.
53
+
54
+ `artwork` comes from terminal_artwork(): an image widget scales the picture to whatever size
55
+ its styles give it; None draws half blocks, redrawn by `resize()` for each size.
56
+ """
57
+
58
+ def __init__(self, artwork=None):
59
+ self.artwork = artwork
60
+ self.image = None
61
+ self._sizes = {} # widget id -> (widget, cols, rows)
62
+
63
+ def widget(self, identifier, cols, rows):
64
+ if self.artwork is not None:
65
+ widget = self.artwork(id=identifier, classes="picture")
66
+ else:
67
+ widget = Static(cover_text(None, cols, rows), id=identifier)
68
+ self._sizes[identifier] = (widget, cols, rows)
69
+ return widget
70
+
71
+ def show(self, image=None):
72
+ self.image = image
73
+ for identifier in self._sizes:
74
+ self._draw(identifier)
75
+
76
+ def resize(self, widget, cols, rows):
77
+ widget, old_cols, old_rows = self._sizes[widget.id]
78
+ if (cols, rows) != (old_cols, old_rows):
79
+ self._sizes[widget.id] = (widget, cols, rows)
80
+ if self.artwork is None:
81
+ self._draw(widget.id)
82
+
83
+ def _draw(self, identifier):
84
+ widget, cols, rows = self._sizes[identifier]
85
+ if self.artwork is not None:
86
+ widget.image = self.image
87
+ else:
88
+ widget.update(cover_text(self.image, cols, rows))
noneto/ui/dialogs.py ADDED
@@ -0,0 +1,107 @@
1
+ """Modal dialogs: the library picker, creating a playlist and choosing where to add a song."""
2
+ from rich.text import Text
3
+ from textual import on
4
+ from textual.app import ComposeResult
5
+ from textual.containers import Horizontal, Vertical
6
+ from textual.screen import ModalScreen
7
+ from textual.widgets import Button, Input, Label, ListItem, ListView, Static
8
+
9
+ from ..i18n import _
10
+ from .common import clean
11
+
12
+ CSS = """
13
+ ModalScreen { align: center middle; background: $background 65%; }
14
+ #dialog { width: 60; max-width: 90%; height: auto; max-height: 85%; padding: 1 2; background: $panel; border: solid $border; }
15
+ .dialog-title { height: 2; text-style: bold; }
16
+ .dialog-actions { height: 1; margin-top: 1; }
17
+ #playlists, #destinations { height: auto; max-height: 18; margin-bottom: 1; }
18
+ #dialog ListItem { padding: 0 1; }
19
+ """
20
+
21
+
22
+ class LibraryScreen(ModalScreen):
23
+ """Playlist picker that replaces the old sidebar; creating and refreshing live here too."""
24
+ BINDINGS = [("escape", "dismiss(None)", _("Cancel"))]
25
+
26
+ def __init__(self, playlists, writing=False):
27
+ super().__init__()
28
+ self.playlists = playlists
29
+ self.writing = writing
30
+
31
+ def compose(self):
32
+ with Vertical(id="dialog"):
33
+ yield Label(_("Your library"), classes="dialog-title")
34
+ if self.playlists:
35
+ yield ListView(*(ListItem(Label(Text(clean(p.name)))) for p in self.playlists), id="playlists")
36
+ else:
37
+ yield Static(_("No playlists. Create one or refresh."), id="empty-library", markup=False)
38
+ with Horizontal(classes="dialog-actions"):
39
+ yield Button(_("+ New playlist"), id="new-playlist", variant="primary", disabled=self.writing)
40
+ yield Button(_("Refresh"), id="refresh")
41
+ yield Button(_("Close"), id="cancel")
42
+
43
+ def on_mount(self):
44
+ if self.playlists:
45
+ self.query_one(ListView).focus()
46
+
47
+ @on(ListView.Selected)
48
+ def choose(self, event):
49
+ if event.list_view.index is not None:
50
+ self.dismiss(("open", self.playlists[event.list_view.index]))
51
+
52
+ @on(Button.Pressed)
53
+ def pressed(self, event):
54
+ event.stop()
55
+ self.dismiss({"new-playlist": ("new", None), "refresh": ("refresh", None)}.get(event.button.id))
56
+
57
+
58
+ class CreatePlaylist(ModalScreen):
59
+ BINDINGS = [("escape", "dismiss(None)", _("Cancel"))]
60
+
61
+ def compose(self) -> ComposeResult:
62
+ with Vertical(id="dialog"):
63
+ yield Label(_("New playlist"), classes="dialog-title")
64
+ yield Input(placeholder=_("Your playlist's name"), max_length=100, id="playlist-name")
65
+ with Horizontal(classes="dialog-actions"):
66
+ yield Button(_("Cancel"), id="cancel")
67
+ yield Button(_("Create"), id="confirm", variant="primary")
68
+
69
+ def on_mount(self):
70
+ self.query_one(Input).focus()
71
+
72
+ @on(Input.Submitted)
73
+ @on(Button.Pressed, "#confirm")
74
+ def confirm(self):
75
+ title = self.query_one(Input).value.strip()
76
+ if title:
77
+ self.dismiss(title)
78
+
79
+ @on(Button.Pressed, "#cancel")
80
+ def cancel(self):
81
+ self.dismiss(None)
82
+
83
+
84
+ class ChoosePlaylist(ModalScreen):
85
+ BINDINGS = [("escape", "dismiss(None)", _("Cancel"))]
86
+
87
+ def __init__(self, playlists):
88
+ super().__init__()
89
+ self.playlists = playlists
90
+
91
+ def compose(self):
92
+ with Vertical(id="dialog"):
93
+ yield Label(_("Add to one of your playlists"), classes="dialog-title")
94
+ yield ListView(*(ListItem(Label(Text(clean(p.name)))) for p in self.playlists), id="destinations")
95
+ yield Button(_("Cancel"), id="cancel")
96
+
97
+ def on_mount(self):
98
+ self.query_one(ListView).focus()
99
+
100
+ @on(ListView.Selected)
101
+ def choose(self, event):
102
+ if event.list_view.index is not None:
103
+ self.dismiss(self.playlists[event.list_view.index])
104
+
105
+ @on(Button.Pressed, "#cancel")
106
+ def cancel(self):
107
+ self.dismiss(None)
@@ -0,0 +1,57 @@
1
+ """Private Qt WebEngine login window, used only inside the isolated Linux worker."""
2
+
3
+
4
+ def render_login(url, redirect):
5
+ from PyQt6.QtCore import QTimer, QUrl, pyqtSignal
6
+ from PyQt6.QtWidgets import QApplication
7
+ from PyQt6.QtWebEngineCore import (QWebEnginePage, QWebEngineProfile,
8
+ QWebEngineUrlRequestInfo, QWebEngineUrlRequestInterceptor)
9
+ from PyQt6.QtWebEngineWidgets import QWebEngineView
10
+
11
+ from ..i18n import _
12
+
13
+ app = QApplication(["noneto-login"])
14
+ app.setApplicationName("Noneto CLI")
15
+ view = QWebEngineView()
16
+ view.setWindowTitle(_("Sign in to TIDAL - Noneto CLI"))
17
+ view.resize(500, 780)
18
+ # A profile without a storage name is off-the-record: cookies/cache stay in memory.
19
+ profile = QWebEngineProfile(view)
20
+ profile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.NoPersistentCookies)
21
+ page = QWebEnginePage(profile, view)
22
+ view.setPage(page)
23
+ captured = []
24
+
25
+ class Interceptor(QWebEngineUrlRequestInterceptor):
26
+ authorized = pyqtSignal(str)
27
+
28
+ def interceptRequest(self, info):
29
+ target = info.requestUrl().toString()
30
+ if (info.resourceType() == QWebEngineUrlRequestInfo.ResourceType.ResourceTypeMainFrame
31
+ and len(target) <= 16384 and target.startswith(redirect + "?")):
32
+ info.block(True)
33
+ self.authorized.emit(target)
34
+
35
+ def finish(target):
36
+ if not captured:
37
+ captured.append(target)
38
+ view.close()
39
+ app.quit()
40
+
41
+ interceptor = Interceptor(profile)
42
+ interceptor.authorized.connect(finish)
43
+ profile.setUrlRequestInterceptor(interceptor)
44
+ # Bound the window lifetime even if the owner disappears. No event loop survives the worker.
45
+ import os
46
+ owner = os.getppid()
47
+ timer = QTimer(view)
48
+ timer.timeout.connect(lambda: view.close() if os.getppid() != owner else None)
49
+ timer.start(500)
50
+ view.load(QUrl(url))
51
+ view.show()
52
+ app.exec()
53
+ # Delete the page before its profile, so teardown cannot keep renderer processes alive.
54
+ view.setPage(None)
55
+ page.deleteLater()
56
+ app.processEvents()
57
+ return captured[0] if captured else ""
@@ -0,0 +1,201 @@
1
+ """Automatic TIDAL login: WebView2 on Windows, isolated Qt WebEngine on Linux.
2
+
3
+ TIDAL redirects to a fixed page (no localhost callback is possible), so the redirect URL that
4
+ carries the code is captured here and handed to auth/service.py, which validates it.
5
+ """
6
+ import ctypes
7
+ from ctypes import wintypes
8
+ import logging
9
+ import json
10
+ import os
11
+ import signal
12
+ import subprocess
13
+ import sys
14
+ import threading
15
+ import time
16
+
17
+ from ..errors import AppError
18
+ from ..i18n import _, language, set_language
19
+
20
+ CLIPBOARD_TIMEOUT = 600
21
+ CF_UNICODETEXT = 13
22
+
23
+
24
+ class WindowUnavailable(Exception):
25
+ """The web renderer is unavailable; use the system browser."""
26
+
27
+
28
+ class ClipboardUnavailable(Exception):
29
+ """No supported clipboard command is available."""
30
+
31
+
32
+ def window_login(url, redirect):
33
+ if sys.platform == "linux":
34
+ return _linux_window_login(url, redirect)
35
+ return _render_login(url, redirect, "edgechromium")
36
+
37
+
38
+ def _linux_window_login(url, redirect):
39
+ # URLs/codes never enter the process command line. Qt diagnostics cannot reach the terminal.
40
+ try:
41
+ process = subprocess.Popen([sys.executable, "-m", "noneto.ui.login_window", "--worker"],
42
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
43
+ start_new_session=True)
44
+ except OSError:
45
+ raise WindowUnavailable from None
46
+ try:
47
+ output, _stderr = process.communicate(json.dumps({"url": url, "redirect": redirect,
48
+ "language": language()}).encode(),
49
+ timeout=CLIPBOARD_TIMEOUT)
50
+ if process.returncode != 0 or len(output) > 32768:
51
+ raise WindowUnavailable
52
+ result = json.loads(output)
53
+ if not isinstance(result, dict) or set(result) != {"redirect"} or not isinstance(result["redirect"], str):
54
+ raise WindowUnavailable
55
+ target = result["redirect"]
56
+ if target and (len(target) > 16384 or not target.startswith(redirect + "?")):
57
+ raise WindowUnavailable
58
+ return target # Empty means the user closed the window: cancel, without opening a browser.
59
+ except (OSError, ValueError, subprocess.TimeoutExpired):
60
+ raise WindowUnavailable from None
61
+ finally:
62
+ if process.poll() is None:
63
+ try:
64
+ os.killpg(process.pid, signal.SIGTERM)
65
+ except ProcessLookupError:
66
+ pass
67
+ try:
68
+ process.wait(timeout=2)
69
+ except subprocess.TimeoutExpired:
70
+ try:
71
+ os.killpg(process.pid, signal.SIGKILL)
72
+ except ProcessLookupError:
73
+ pass
74
+ process.wait(timeout=2)
75
+ for pipe in (process.stdin, process.stdout):
76
+ if pipe is not None and not pipe.closed:
77
+ try:
78
+ pipe.close()
79
+ except OSError:
80
+ pass
81
+
82
+
83
+ def _render_login(url, redirect, renderer):
84
+ """Show the login page; return the redirect URL it reaches, or "" if the user closes the window."""
85
+ try:
86
+ import webview
87
+ except ImportError:
88
+ raise WindowUnavailable from None
89
+ log = logging.getLogger("pywebview")
90
+ log.addHandler(logging.NullHandler())
91
+ log.propagate = False
92
+ log.setLevel(logging.CRITICAL + 1) # its logs would include URLs with the code
93
+ captured = []
94
+ lock = threading.Lock()
95
+ try:
96
+ window = webview.create_window(_("Sign in to TIDAL - Noneto CLI"), url, width=500, height=780)
97
+ except Exception:
98
+ raise WindowUnavailable from None
99
+
100
+ def on_request(request):
101
+ target = str(getattr(request, "url", ""))
102
+ if len(target) > 16384 or not target.startswith(redirect + "?"):
103
+ return
104
+ with lock:
105
+ if captured:
106
+ return
107
+ captured.append(target)
108
+ window.destroy()
109
+
110
+ window.events.request_sent += on_request
111
+ try:
112
+ # Private mode keeps no persistent login cookies. TLS validation stays enabled.
113
+ webview.start(gui=renderer, private_mode=True)
114
+ except Exception:
115
+ if not captured:
116
+ raise WindowUnavailable from None
117
+ return captured[0] if captured else ""
118
+
119
+
120
+ def read_clipboard():
121
+ if sys.platform == "linux":
122
+ return _read_linux_clipboard()
123
+ return _read_windows_clipboard()
124
+
125
+
126
+ def _read_linux_clipboard():
127
+ import shutil
128
+ choices = []
129
+ if os.environ.get("WAYLAND_DISPLAY"):
130
+ choices.append(["wl-paste", "--no-newline", "--type", "text/plain"])
131
+ if os.environ.get("DISPLAY"):
132
+ choices.extend((["xclip", "-selection", "clipboard", "-out"],
133
+ ["xsel", "--clipboard", "--output"]))
134
+ for command in choices:
135
+ executable = shutil.which(command[0])
136
+ if executable is None:
137
+ continue
138
+ try:
139
+ result = subprocess.run([executable, *command[1:]], stdout=subprocess.PIPE,
140
+ stderr=subprocess.DEVNULL, timeout=1)
141
+ if result.returncode == 0:
142
+ return result.stdout[:16384].decode("utf-8", errors="replace")
143
+ except (OSError, subprocess.TimeoutExpired):
144
+ continue
145
+ raise ClipboardUnavailable
146
+
147
+
148
+ def _read_windows_clipboard():
149
+ user32 = ctypes.WinDLL("user32", use_last_error=True)
150
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
151
+ user32.GetClipboardData.restype = wintypes.HANDLE
152
+ kernel.GlobalLock.argtypes = [wintypes.HGLOBAL]
153
+ kernel.GlobalLock.restype = ctypes.c_void_p
154
+ kernel.GlobalUnlock.argtypes = [wintypes.HGLOBAL]
155
+ if not user32.OpenClipboard(None):
156
+ return ""
157
+ try:
158
+ handle = user32.GetClipboardData(CF_UNICODETEXT)
159
+ if not handle:
160
+ return ""
161
+ pointer = kernel.GlobalLock(handle)
162
+ if not pointer:
163
+ return ""
164
+ try:
165
+ return ctypes.wstring_at(pointer)[:16384]
166
+ finally:
167
+ kernel.GlobalUnlock(handle)
168
+ finally:
169
+ user32.CloseClipboard()
170
+
171
+
172
+ def clipboard_login(redirect, read=read_clipboard, interval=0.5, timeout=CLIPBOARD_TIMEOUT):
173
+ """Wait until the user copies the redirect URL; text copied before the login started is ignored."""
174
+ before = read()
175
+ deadline = time.monotonic() + timeout
176
+ while time.monotonic() < deadline:
177
+ time.sleep(interval)
178
+ text = read().strip()
179
+ if text != before.strip() and text.startswith(redirect + "?"):
180
+ return text
181
+ raise AppError(_("The sign-in address did not arrive in time. Run noneto again."))
182
+
183
+
184
+ def _worker():
185
+ try:
186
+ payload = json.loads(sys.stdin.buffer.read(32769))
187
+ if (not isinstance(payload, dict) or set(payload) != {"url", "redirect", "language"}
188
+ or any(not isinstance(value, str) or len(value) > 16384 for value in payload.values())):
189
+ return 2
190
+ set_language(payload["language"])
191
+ # The parent authenticated UI boundary supplies these values; auth validates the returned code.
192
+ from .linux_login import render_login
193
+ target = render_login(payload["url"], payload["redirect"])
194
+ sys.stdout.write(json.dumps({"redirect": target}))
195
+ return 0
196
+ except Exception:
197
+ return 2 # No exception messages: renderer failures can contain an authorization URL.
198
+
199
+
200
+ if __name__ == "__main__":
201
+ raise SystemExit(_worker() if sys.argv[1:] == ["--worker"] else 2)
noneto/ui/lyrics.py ADDED
@@ -0,0 +1,142 @@
1
+ """Lyrics tab: the cover beside the lyrics, or the cover alone and centered.
2
+
3
+ Two layouts the user switches between: "lyrics" (small cover + lyrics highlighted line by line
4
+ when TIDAL times them) and "cover" (large centered cover). A song without lyrics always shows
5
+ the large cover.
6
+ """
7
+ import bisect
8
+ import re
9
+
10
+ from rich.text import Text
11
+ from textual.containers import Horizontal, Vertical, VerticalScroll
12
+ from textual.message import Message
13
+ from textual.widgets import Static
14
+
15
+ from ..i18n import _
16
+ from .common import clean
17
+
18
+ CSS = """
19
+ #lyrics-pane { height: 1fr; }
20
+ #lyrics-body { width: 1fr; padding: 0 1; }
21
+ #lyrics-scroll { height: 1fr; scrollbar-size: 1 1; }
22
+ #lyrics-text { height: auto; }
23
+ #lyrics-pane.centered { align: center middle; }
24
+ #lyrics-pane.centered #lyrics-body { display: none; }
25
+ #lyrics-pane.centered #cover { margin: 0; }
26
+ """
27
+
28
+ LAYOUTS = ("lyrics", "cover")
29
+ SMALL_COVER = (12, 6) # cells: 12 columns × 6 rows is square with 1:2 cells
30
+ # The 640 px download fills 32 rows of 20 px (Windows Terminal's sixel cell); larger only blurs it
31
+ # and makes each redraw slower (~80 ms to encode at 800 px).
32
+ MAX_COVER_ROWS = 32
33
+
34
+
35
+ def lyric_lines(plain, subtitles):
36
+ """Accept bounded LRC lines; use plain text if timing is unavailable."""
37
+ timed = []
38
+ for line in (subtitles or "").splitlines()[:400]:
39
+ match = re.match(r"^\[(\d{1,3}):(\d{2})(?:\.(\d{1,3}))?\](.*)$", line)
40
+ if match:
41
+ fraction = (match[3] or "0").ljust(3, "0")
42
+ second = int(match[1]) * 60 + int(match[2]) + int(fraction) / 1000
43
+ timed.append((second, clean(match[4])[:300]))
44
+ if timed:
45
+ return sorted(timed), True
46
+ return [(None, clean(line)[:300]) for line in (plain or "").splitlines()[:300]], False
47
+
48
+
49
+ class LyricsPanel(Horizontal):
50
+ class CoverClicked(Message):
51
+ """Posted when the cover is clicked, to switch layouts."""
52
+
53
+ def __init__(self, covers, layout="lyrics", **kwargs):
54
+ super().__init__(**kwargs)
55
+ self._covers = covers
56
+ self._cover = covers.widget("cover", *SMALL_COVER)
57
+ self.cover_layout = layout if layout in LAYOUTS else "lyrics"
58
+ self.missing = False # the current song has no lyrics
59
+ self._lines = []
60
+ self._times = ()
61
+ self._timed = False
62
+ self.active_line = None
63
+
64
+ def compose(self):
65
+ yield self._cover
66
+ with Vertical(id="lyrics-body"):
67
+ with VerticalScroll(id="lyrics-scroll"):
68
+ yield Static(_("Play a song to see its lyrics."), id="lyrics-text", markup=False)
69
+
70
+ def on_mount(self):
71
+ self._text = self.query_one("#lyrics-text", Static)
72
+ self._scroll = self.query_one("#lyrics-scroll", VerticalScroll)
73
+ self._arrange()
74
+
75
+ def on_resize(self):
76
+ self._arrange()
77
+
78
+ def on_click(self, event):
79
+ if event.button == 1 and self._cover in (event.widget, *event.widget.ancestors):
80
+ self.post_message(self.CoverClicked())
81
+ event.stop()
82
+
83
+ def set_layout(self, layout):
84
+ self.cover_layout = layout if layout in LAYOUTS else "lyrics"
85
+ self._arrange()
86
+
87
+ @property
88
+ def centered(self):
89
+ return self.cover_layout == "cover" or self.missing
90
+
91
+ def _arrange(self):
92
+ self.set_class(self.centered, "centered")
93
+ if not self.centered:
94
+ self._cover.styles.width = self._cover.styles.height = None # back to the CSS size
95
+ self._covers.resize(self._cover, *SMALL_COVER)
96
+ return
97
+ # As large as the pane allows with one free row above and below, kept square.
98
+ rows = max(1, min(self.size.height - 2, (self.size.width - 2) // 2, MAX_COVER_ROWS))
99
+ self._cover.styles.width, self._cover.styles.height = rows * 2, rows
100
+ self._covers.resize(self._cover, rows * 2, rows)
101
+
102
+ def reset(self, playing):
103
+ self._lines, self.active_line = [], None
104
+ self._times = ()
105
+ self._text.update(_("Loading lyrics…") if playing else _("Play a song to see its lyrics."))
106
+ self._set_missing(False)
107
+
108
+ def load(self, plain, subtitles, position):
109
+ self._lines, self._timed = lyric_lines(plain, subtitles)
110
+ self._times = tuple(when for when, _line in self._lines)
111
+ self.active_line = None
112
+ if not self._lines:
113
+ self.unavailable()
114
+ return
115
+ self._set_missing(False)
116
+ self.follow(position)
117
+
118
+ def unavailable(self):
119
+ self._text.update(_("No lyrics available for this song."))
120
+ self._set_missing(True)
121
+
122
+ def _set_missing(self, missing):
123
+ if missing != self.missing:
124
+ self.missing = missing
125
+ self._arrange()
126
+
127
+ def follow(self, position):
128
+ if not self._lines:
129
+ return
130
+ active = bisect.bisect_right(self._times, position) - 1 if self._timed else -1
131
+ if active == self.active_line:
132
+ return
133
+ initial = self.active_line is None
134
+ self.active_line = active
135
+ output = Text()
136
+ for index, (_when, line) in enumerate(self._lines):
137
+ output.append(line or " ", style="bold" if index == active else "dim")
138
+ if index < len(self._lines) - 1:
139
+ output.append("\n")
140
+ self._text.update(output, layout=initial)
141
+ if active >= 0:
142
+ self._scroll.scroll_to(y=max(0, active - 3), animate=False)