diff --git a/CLAUDE.md b/CLAUDE.md index 50c9df5..48a664c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -198,6 +198,12 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal (right: previous/next style, wrapping) — hit-tested on release. No double-click. Both big windows (visualizer, album art) close on a click or Esc. + The library search box filters the sidebar too (Round 89): + `LibraryView.search_changed` → `PlaylistTree.set_filter`, same rule as + the songs (every word, case-folded, in the name); a folder shows when its + name matches (with all it holds) or something inside does, opened while + filtering, and clearing restores the folders the user had open — so + `rebuild` reads the pre-filter expansion while a filter is up. `track_table.py` is the shared track grid (drag/drop, copy/paste, drop indicator). `playlist_ops.py::add_tracks_with_dup_check` is the single funnel for every add-to-playlist path. `theme.py` applies the palette (highlight @@ -860,6 +866,15 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal everywhere, "2" = pyatv's AirPlay 2. `airplay_debug` puts pyatv's logger at DEBUG; every stream's start, first audio and outcome are logged at INFO under `lintunes.airplay`, and the chosen protocol in the control log. + **Testing without a speaker** (Round 89): shairport-sync in Docker + (`mikebrady/shairport-sync:5.5.2-classic`, its own dbus + avahi inside, + on the default bridge so nothing is advertised on the LAN, `-o stdout` + to a file) is a real third-party receiver whose decoded PCM can be + compared with what was sent — silent and bit-checkable. LinTunes' stream + decodes there; the WiiM still plays nothing from pyatv, though + Music Assistant's `cliairplay` binary plays on it. pyatv also died on + shairport's `/info` (not a plist), so the shim treats an unreadable + `/info` as none. ## Conventions & gotchas diff --git a/lintunes/__init__.py b/lintunes/__init__.py index 1ba3550..5260d18 100644 --- a/lintunes/__init__.py +++ b/lintunes/__init__.py @@ -1,3 +1,3 @@ """LinTunes — iTunes-style music library manager and player for Linux.""" -__version__ = "0.57.0" +__version__ = "0.58.0" diff --git a/lintunes/airplay/stream.py b/lintunes/airplay/stream.py index a3d1456..981ec1c 100644 --- a/lintunes/airplay/stream.py +++ b/lintunes/airplay/stream.py @@ -224,6 +224,19 @@ def _install_compat(): rtsp.RtspSession.announce = announce + # GET /info is optional, and pyatv treats an unparseable answer as fatal: + # shairport-sync's classic build answers it with a body that isn't a + # plist, so every stream failed before it began. + real_info = rtsp.RtspSession.info + + async def info(self): + try: + return await real_info(self) + except Exception: # noqa: BLE001 — /info is only a hint + return {} + + rtsp.RtspSession.info = info + real_send = airplayv1.AirPlayV1.send_audio_packet async def send_audio_packet(self, transport, rtp_header, audio): diff --git a/lintunes/airplay/support.py b/lintunes/airplay/support.py index 72aa64c..e1b5f60 100644 --- a/lintunes/airplay/support.py +++ b/lintunes/airplay/support.py @@ -161,10 +161,11 @@ def alac_verbatim(pcm: bytes) -> bytes: _SAMPLE_FORMATS = {2: "s16be", 4: "s32be"} +_SAMPLE_FORMATS_LE = {2: "s16le", 4: "s32le"} def ffmpeg_command(path: str, start_ms: int, sample_rate: int, channels: int, - sample_size: int) -> list[str]: + sample_size: int, big_endian: bool = True) -> list[str]: """Decode `path` from `start_ms` to raw PCM on stdout, in the shape the receiver asked for. @@ -172,8 +173,9 @@ def ffmpeg_command(path: str, start_ms: int, sample_rate: int, channels: int, sending (audio_source._to_audio_samples), so asking ffmpeg for BE is the same bytes on the wire. `-ss` before `-i` is an input seek, which is sample-accurate for audio and instant even deep into a long file. + cliairplay (cli.py) reads little-endian, hence `big_endian=False`. """ - fmt = _SAMPLE_FORMATS.get(sample_size) + fmt = (_SAMPLE_FORMATS if big_endian else _SAMPLE_FORMATS_LE).get(sample_size) if fmt is None: raise ValueError(f"unsupported sample size {sample_size}") command = ["ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error"] diff --git a/lintunes/gui/library_view.py b/lintunes/gui/library_view.py index 4f1556a..f88a68c 100644 --- a/lintunes/gui/library_view.py +++ b/lintunes/gui/library_view.py @@ -179,6 +179,9 @@ class LibraryView(TableSettingsMixin, QWidget): play_requested = pyqtSignal(list, int) info_requested = pyqtSignal(list) show_in_playlist_requested = pyqtSignal(int, str) # track_id, playlist pid + # The search box's text, case-folded, after the debounce ("" when cleared): + # MainWindow filters the sidebar's playlists by it too. + search_changed = pyqtSignal(str) def __init__(self, manager, parent=None): super().__init__(parent) @@ -337,6 +340,7 @@ class LibraryView(TableSettingsMixin, QWidget): self._search.blockSignals(False) self._search_text = "" self._search_tracks = self._all_tracks + self.search_changed.emit("") for lst in (self._genre_list, self._artist_list, self._album_list): lst.blockSignals(True) lst.setCurrentRow(0) # "All" @@ -370,6 +374,7 @@ class LibraryView(TableSettingsMixin, QWidget): def _apply_search(self): self._search_text = self._search.text().strip().casefold() self._search_tracks = self._compute_search_tracks() + self.search_changed.emit(self._search_text) # Rebuild the whole cascade so the genre/artist/album columns reflect # only what the search matched. self._populate_genres() diff --git a/lintunes/gui/main_window.py b/lintunes/gui/main_window.py index 8436100..9f04b69 100644 --- a/lintunes/gui/main_window.py +++ b/lintunes/gui/main_window.py @@ -179,6 +179,8 @@ class MainWindow(QMainWindow): self._library_view = LibraryView(manager) self._content.addWidget(self._library_view) + self._library_view.search_changed.connect( + self._sidebar.tree.set_filter) self._playlist_view = PlaylistView(manager) self._content.addWidget(self._playlist_view) self._content.setCurrentWidget(self._library_view) diff --git a/lintunes/gui/sidebar.py b/lintunes/gui/sidebar.py index d68ff29..a46845a 100644 --- a/lintunes/gui/sidebar.py +++ b/lintunes/gui/sidebar.py @@ -404,6 +404,11 @@ class PlaylistTree(QTreeWidget): # so typing replaces "untitled playlist"; see edit(). self._select_all_next_edit = False + # The library search, as words every shown playlist's name contains; + # the folders that were open before it began, to put back after. + self._filter_tokens: list[str] = [] + self._expanded_before_filter: set[str] | None = None + # Edge auto-scroll during a drag (Qt's built-in autoscroll never runs # because our dragMoveEvent accepts the event itself). Mirrors # track_table's Round 13 machinery. @@ -422,7 +427,7 @@ class PlaylistTree(QTreeWidget): selected_pid = self.current_playlist_id() # Preserve which folders the user has open across rebuilds. On the very # first build this set is empty, so the app opens fully collapsed. - expanded = self._expanded_pids() + expanded = self._expanded_now_or_before_filter() self.blockSignals(True) self.clear() @@ -476,12 +481,76 @@ class PlaylistTree(QTreeWidget): else: self.addTopLevelItem(self._friend_folder(value, expanded)) self.blockSignals(False) + if self._filter_tokens: + self._apply_filter() if selected_pid: item = self._find_item(selected_pid) if item: self.setCurrentItem(item) + # ---- filtering by the library search ---- + + def set_filter(self, text: str): + """Show only playlists whose name has every word of `text` (case- + folded substrings, like the song search). A folder shows when its own + name matches — with all it holds — or when something inside matches, + and opens while the search lasts; clearing it reopens exactly the + folders that were open before.""" + tokens = text.casefold().split() + if tokens == self._filter_tokens: + return + if tokens and not self._filter_tokens: + self._expanded_before_filter = self._expanded_pids() + self._filter_tokens = tokens + if tokens: + self._apply_filter() + return + expanded = self._expanded_before_filter or set() + self._expanded_before_filter = None + stack = [self.topLevelItem(i) for i in range(self.topLevelItemCount())] + while stack: + item = stack.pop() + item.setHidden(False) + if item.childCount(): + item.setExpanded(item.data(0, PID_ROLE) in expanded) + stack.extend(item.child(i) for i in range(item.childCount())) + current = self.currentItem() + if current is not None: + self.scrollToItem(current) + + def _apply_filter(self): + def matches(item) -> bool: + name = item.text(0).casefold() + return all(token in name for token in self._filter_tokens) + + def show_all(item): + item.setHidden(False) + for i in range(item.childCount()): + show_all(item.child(i)) + + def visit(item) -> bool: + if matches(item): + show_all(item) + return True + shown = False + for i in range(item.childCount()): + shown = visit(item.child(i)) or shown + item.setHidden(not shown) + if shown: + item.setExpanded(True) + return shown + + for i in range(self.topLevelItemCount()): + visit(self.topLevelItem(i)) + + def _expanded_now_or_before_filter(self) -> set[str]: + """While filtering, the tree's open folders are the filter's doing; + what a rebuild should keep is what the user had open.""" + if self._expanded_before_filter is not None: + return set(self._expanded_before_filter) + return self._expanded_pids() + def _add_mine(self, pid, children, expanded, add_level): """One of my top-level playlists/folders (and a folder's contents), when the top level is being interleaved with followed ones.""" diff --git a/tests/test_round89.py b/tests/test_round89.py new file mode 100644 index 0000000..0844fcb --- /dev/null +++ b/tests/test_round89.py @@ -0,0 +1,112 @@ +"""Round 89: the library search filters the sidebar's playlists too, and +AirPlay survives a receiver whose /info isn't a plist (shairport-sync).""" + +import asyncio +from types import SimpleNamespace + +from lintunes.gui.sidebar import PID_ROLE, PlaylistTree +from lintunes.library_manager import LibraryManager +from lintunes.models import Playlist, PlaylistType +from lintunes.models.library import Library + + +def _tree(qapp, tmp_path): + library = Library() + def add(pid, name, parent="", folder=False): + library.playlists[pid] = Playlist( + persistent_id=pid, name=name, parent_persistent_id=parent, + playlist_type=PlaylistType.FOLDER if folder else PlaylistType.REGULAR) + add("f0000001", "Summer", folder=True) + add("p0000001", "Beach Day", parent="f0000001") + add("p0000002", "Night Drive", parent="f0000001") + add("f0000002", "Jazz", folder=True) + add("p0000003", "Late Jazz Night", parent="f0000002") + add("p0000004", "Road Trip") + add("p0000005", "Gallery Night") + return PlaylistTree(LibraryManager(library, tmp_path)) + + +def _shown(tree) -> set[str]: + out, stack = set(), [tree.topLevelItem(i) for i in range(tree.topLevelItemCount())] + while stack: + item = stack.pop() + if not item.isHidden(): + out.add(item.text(0)) + stack.extend(item.child(i) for i in range(item.childCount())) + return out + + +def _item(tree, pid): + return tree._find_item(pid) + + +class TestPlaylistFilter: + def test_matches_names_and_keeps_their_folders(self, qapp, tmp_path): + tree = _tree(qapp, tmp_path) + tree.set_filter("night") + assert _shown(tree) == {"Summer", "Night Drive", "Jazz", + "Late Jazz Night", "Gallery Night"} + assert _item(tree, "f0000001").isExpanded() + + def test_every_word_case_folded(self, qapp, tmp_path): + tree = _tree(qapp, tmp_path) + tree.set_filter("NIGHT jazz") + assert _shown(tree) == {"Jazz", "Late Jazz Night"} + + def test_a_matching_folder_shows_everything_in_it(self, qapp, tmp_path): + tree = _tree(qapp, tmp_path) + tree.set_filter("summer") + assert _shown(tree) == {"Summer", "Beach Day", "Night Drive"} + + def test_clearing_restores_all_and_the_old_folder_state(self, qapp, tmp_path): + tree = _tree(qapp, tmp_path) + _item(tree, "f0000002").setExpanded(True) # Jazz open, Summer shut + tree.set_filter("beach") + assert _item(tree, "f0000001").isExpanded() + tree.set_filter("") + assert len(_shown(tree)) == 7 + assert not _item(tree, "f0000001").isExpanded() + assert _item(tree, "f0000002").isExpanded() + + def test_a_rebuild_while_filtering_stays_filtered(self, qapp, tmp_path): + tree = _tree(qapp, tmp_path) + tree.set_filter("road") + tree.rebuild() + assert _shown(tree) == {"Road Trip"} + tree.set_filter("") + assert not _item(tree, "f0000001").isExpanded() # never opened by hand + + def test_the_library_search_drives_it(self, qapp, tmp_path): + from lintunes.gui.main_window import MainWindow + from lintunes.preferences import Preferences + library = Library() + library.playlists["p0000001"] = Playlist(persistent_id="p0000001", + name="Road Trip") + library.playlists["p0000002"] = Playlist(persistent_id="p0000002", + name="Gallery") + window = MainWindow(LibraryManager(library, tmp_path), Preferences(tmp_path)) + try: + view = window._library_view + view._search.setText("gall") + view._apply_search() + assert _shown(window._sidebar.tree) == {"Gallery"} + view._search.setText("") + view._apply_search() + assert _shown(window._sidebar.tree) == {"Road Trip", "Gallery"} + finally: + window.close() + + +class TestInfoTolerance: + def test_an_unreadable_info_is_no_info(self): + from pyatv.support import rtsp + from lintunes.airplay.stream import install_shim + install_shim() + + async def exchange(self, *a, **kw): + return SimpleNamespace(code=200, headers={}, body=b"not a plist") + + session = rtsp.RtspSession(SimpleNamespace(remote_ip="1.2.3.4", + local_ip="1.2.3.5")) + session.exchange = exchange.__get__(session) + assert asyncio.run(session.info()) == {}