From b36157d8c1775fb441afc92b91de5cd0475acc2c Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 28 Nov 2026 01:43:58 -0500 Subject: [PATCH] Add mobile chrome hairlines, flush input box, suspend animation pause, and virtual_scroll cleanup --- src/toad/client/application.py | 5 + src/toad/qt/side_bar.py | 37 +++-- src/toad/qt/virtual_scroll.py | 17 ++- src/toad/qt/window.py | 16 +- src/toad/setting_choices.py | 8 +- src/toad/sidebar_layout.py | 14 ++ src/toad/sidebar_placement.py | 15 ++ .../test_mobile_chrome_polish_and_suspend.py | 142 ++++++++++++++++++ 8 files changed, 232 insertions(+), 22 deletions(-) create mode 100644 tests/model/test_mobile_chrome_polish_and_suspend.py diff --git a/src/toad/client/application.py b/src/toad/client/application.py index 1b2e0c125..14170a0bd 100644 --- a/src/toad/client/application.py +++ b/src/toad/client/application.py @@ -100,6 +100,7 @@ def deactivate(self, app: ClientApplication) -> ApplicationPresence: def suspend(self, app: ClientApplication) -> ApplicationPresence: app.application.backgrounded() + app.set_animations_paused(True) return SUSPENDED_PRESENCE @@ -116,6 +117,7 @@ def activate(self, app: ClientApplication) -> ApplicationPresence: class SuspendedPresence(ApplicationPresence): def activate(self, app: ClientApplication) -> ApplicationPresence: + app.set_animations_paused(False) # `resume()` publishes `CoordinationObserved` once the fresh observation attaches, # which triggers `stores_changed` -> `selected.reload()` on the new observer instead # of racing a synchronous reload against the retiring one (`ObserverRetired`). @@ -144,6 +146,9 @@ def history_displayed(self) -> None: after its startup.""" HEAP.history_displayed() + def set_animations_paused(self, paused: bool) -> None: + """Pause or resume the frontend's animation timer while the app is suspended.""" + def open_settings(self) -> SavedSettings: """The settings file every frontend reads at launch and writes on a change; each change applies its `Effect` through `apply_setting_effect`, so a setting changed in diff --git a/src/toad/qt/side_bar.py b/src/toad/qt/side_bar.py index 6dedaad43..0728d0971 100644 --- a/src/toad/qt/side_bar.py +++ b/src/toad/qt/side_bar.py @@ -202,11 +202,13 @@ def __init__(self, surface: QtSideBar) -> None: self.setAlignment(Qt.AlignmentFlag.AlignCenter) self.setCursor(Qt.CursorShape.PointingHandCursor) self._symbol = self._heading = "" + self._leading_splitter = False self._trailing_splitter = False - def set_trailing_splitter(self, shown: bool) -> None: - if self._trailing_splitter != shown: - self._trailing_splitter = shown + def set_band_splitters(self, leading: bool, trailing: bool) -> None: + if self._leading_splitter != leading or self._trailing_splitter != trailing: + self._leading_splitter = leading + self._trailing_splitter = trailing self.update() def show_toggle(self, text: str, tooltip: str) -> None: @@ -219,21 +221,23 @@ def show_turned(self, symbol: str, heading: str) -> None: self._symbol, self._heading = symbol, heading self.update() - def _draw_trailing_splitter(self, painter: QPainter) -> None: - if not self._trailing_splitter: - return + def _draw_hairlines(self, painter: QPainter, *, vertical: bool) -> None: painter.save() painter.setPen(self.palette().color(QPalette.ColorRole.Mid)) - x = self.width() - 1 - painter.drawLine(x, 0, x, self.height()) + w, h = self.width(), self.height() + x1, y1, x2, y2 = self._surface.placement.side.inner_hairline(w, h) + painter.drawLine(x1, y1, x2, y2) + if vertical and self._leading_splitter: + painter.drawLine(0, 0, 0, h) + if self._trailing_splitter: + painter.drawLine(w - 1, 0, w - 1, h) painter.restore() def paintEvent(self, event) -> None: # type: ignore[override] if self.height() <= self.width(): super().paintEvent(event) - if self._trailing_splitter: - painter = QPainter(self) - self._draw_trailing_splitter(painter) + painter = QPainter(self) + self._draw_hairlines(painter, vertical=False) return painter = QPainter(self) option = QStyleOption() @@ -253,7 +257,7 @@ def paintEvent(self, event) -> None: # type: ignore[override] span = QRect(-reach, -self.width() // 2, 2 * reach, self.width()) painter.drawText(span, Qt.AlignmentFlag.AlignCenter, shown) painter.restore() - self._draw_trailing_splitter(painter) + self._draw_hairlines(painter, vertical=True) class QtSidebarResizeHandle(QtGripPointer, SidebarResizeGrip, QWidget, metaclass=PyQtWidgetMeta): @@ -482,10 +486,15 @@ def arrange(self, *, animate: bool = True) -> None: if region is None: self._land(bar) self.placed.pop(bar, None) - bar.toggle.set_trailing_splitter(False) + bar.toggle.set_band_splitters(False, False) bar.hide() continue - bar.toggle.set_trailing_splitter(self._layout.splits_after(bar.placement_identity, collapsed)) + leading = self._layout.splits_before(bar.placement_identity, collapsed) + trailing = ( + self._layout.splits_after(bar.placement_identity, collapsed) + and (bar.collapsed or not self._layout.next_in_band_folded(bar.placement_identity, collapsed)) + ) + bar.toggle.set_band_splitters(leading, trailing) now = PlacedSidebar(region, bar.collapsed) slide = self.slides.get(bar) if slide is not None and slide.target == now: diff --git a/src/toad/qt/virtual_scroll.py b/src/toad/qt/virtual_scroll.py index 446f5f0f6..9296b624c 100644 --- a/src/toad/qt/virtual_scroll.py +++ b/src/toad/qt/virtual_scroll.py @@ -24,6 +24,7 @@ import math import time +import shiboken6 from PySide6.QtCore import QPoint, QRect, QRectF, QSize, Qt, QTimer from PySide6.QtGui import ( QAbstractTextDocumentLayout, @@ -661,8 +662,10 @@ def _application_state_changed(self, state: Qt.ApplicationState) -> None: """Defer dropping laid-out documents and tiles across brief Android app switches so reopening within `SUSPEND_RELEASE_MS` paints from warm caches without a 100+ ms re-layout/re-rasterize stall, while prolonged backgrounding still returns memory.""" + if self._stopped or not shiboken6.isValid(self._suspend_release_timer): + return if state is Qt.ApplicationState.ApplicationSuspended: - if not self._stopped and not self._suspend_release_timer.isActive(): + if not self._suspend_release_timer.isActive(): self._suspend_release_timer.start() elif state is Qt.ApplicationState.ApplicationActive: self._suspend_release_timer.stop() @@ -840,9 +843,15 @@ def cleanup(self) -> None: return self._stopped = True self.preparing = False - self._viewport_update_timer.stop() - self._measure_timer.stop() - self._suspend_release_timer.stop() + app = QGuiApplication.instance() + if app is not None: + try: + app.applicationStateChanged.disconnect(self._application_state_changed) + except (RuntimeError, TypeError): + pass + for timer in (self._viewport_update_timer, self._measure_timer, self._suspend_release_timer): + if shiboken6.isValid(timer): + timer.stop() self.preparer.clear() self.stop_preparation() self.preparer.stop() diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index 3f7906252..28a6fe9b0 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -1756,6 +1756,8 @@ def __init__(self, connection: CoreConnection, project: Checkout, # would land some ticks between two frames and show one frame twice. self._animation_timer.setTimerType(Qt.TimerType.PreciseTimer) self._animation_timer.timeout.connect(self._tick_animation) + self._animation_interval: float | None = None + self._animations_paused = False self._layout_pending = False self._presence: ApplicationPresence = ACTIVE_PRESENCE self.animation_clock = AnimationClock(self._schedule_animation, enabled=animations_enabled()) @@ -1882,6 +1884,7 @@ def __init__(self, connection: CoreConnection, project: Checkout, # The bar row is Toad's header band: a frame in the theme's header tone. Notices # float over the pages in `float_layer`; they are no part of this band. self.navigation = chrome = QFrame(self) + chrome.setObjectName("toad-navigation") chrome_layout = QVBoxLayout(chrome) chrome_layout.setContentsMargins(0, 0, 0, 0) chrome_layout.setSpacing(0) @@ -2111,13 +2114,20 @@ def source(self) -> ObservedSource: def _schedule_animation(self, interval: float | None) -> None: """The clock's one timer: tick every ``interval`` seconds, or stop.""" + self._animation_interval = interval if not shiboken6.isValid(self._animation_timer): return - if interval is None: + if interval is None or self._animations_paused: self._animation_timer.stop() else: self._animation_timer.start(max(1, round(interval * 1000))) + def set_animations_paused(self, paused: bool) -> None: + if self._animations_paused == paused: + return + self._animations_paused = paused + self._schedule_animation(self._animation_interval) + def _tick_animation(self) -> None: self.animation_clock.tick() @@ -2203,9 +2213,10 @@ def paint_chrome_colours(self) -> None: ) self.tabs.set_colours(QColor(underline_hex), QColor(active_ink), QColor(inactive_ink)) sep_hex = self.palette().color(QPalette.ColorRole.Mid).name() + nav_edge = self.settings.ui.navigation_bar.qt_separator_edge self.navigation.setStyleSheet( scheme.styles.generate_frame_style() - + f"QFrame {{ background-color: {bar_bg}; padding: 2px 2px; }}" + + f"QFrame#toad-navigation {{ background-color: {bar_bg}; padding: 2px 2px; border: none; {nav_edge}: 1px solid {sep_hex}; }}" + f"QFrame#toad-nav-separator {{ border: none; padding: 0px; margin: 4px 0px; background: {sep_hex}; }}" ) self.float_layer.follow_scheme(scheme) @@ -2239,6 +2250,7 @@ def apply_layout_preferences(self) -> None: layout.removeWidget(widget) layout.insertWidget(index, widget, 1 if widget is self.chrome else 0) self.apply_text_scale(self.settings.ui.message_font_scale) + self.paint_chrome_colours() self._sync_keyboard_chrome() def follow_theme(self) -> None: diff --git a/src/toad/setting_choices.py b/src/toad/setting_choices.py index 20bed3c67..d4a4138a4 100644 --- a/src/toad/setting_choices.py +++ b/src/toad/setting_choices.py @@ -253,7 +253,6 @@ class NormalInputBox(TitledChoice, InputBox): """The classic prompt: a bordered, padded box above the info bar.""" title = "Normal (bordered and padded)" - frame_margin = Spacing(0, 1, 0, 1) frame_padding = Spacing(0, 1, 0, 0) qt_border_pixels = 2 @@ -267,7 +266,7 @@ def qt_frame_sheet(cls, field: str, colour: str) -> str: @classmethod def info_bar_margin(cls, footer: bool) -> Spacing: - return Spacing(0, 2, 0, 2) + return Spacing(0, 1, 0, 1) class CompactInputBox(TitledChoice, InputBox): @@ -316,6 +315,8 @@ class NavigationBarPosition(DeclaredChoice, affix="NavigationBar"): yields_to_keyboard: ClassVar[bool] = False """Bottom-docked bars hide while a touch soft keyboard is open so the composer sits flush above the keyboard instead of floating over dead chrome.""" + qt_separator_edge: ClassVar[str] + """Qt CSS border property separating the navigation bar from the adjacent workspace chrome.""" @classmethod @abstractmethod @@ -330,6 +331,8 @@ def place(cls, navigation, body) -> None: class TopNavigationBar(NavigationBarPosition): + qt_separator_edge = "border-bottom" + @classmethod def around[W](cls, navigation: W, body: W) -> tuple[W, W]: return navigation, body @@ -337,6 +340,7 @@ def around[W](cls, navigation: W, body: W) -> tuple[W, W]: class BottomNavigationBar(NavigationBarPosition): yields_to_keyboard = True + qt_separator_edge = "border-top" @classmethod def around[W](cls, navigation: W, body: W) -> tuple[W, W]: diff --git a/src/toad/sidebar_layout.py b/src/toad/sidebar_layout.py index 6e050667b..b31152b5d 100644 --- a/src/toad/sidebar_layout.py +++ b/src/toad/sidebar_layout.py @@ -685,6 +685,12 @@ def set_split(self, side: type[SidebarEdge], percent: int) -> bool: self._save(replace(self.terminal, splits=(*others, BandSplit(side, percent)))) return True + def splits_before(self, identity: type[SidebarPlacement], + collapsed: Mapping[type[SidebarPlacement], bool]) -> bool: + """Whether an earlier shown bar in this one's band sits beside it on the left.""" + shown = tuple(key for key in self._slot(self.placements, identity) if key in collapsed) + return shown.index(identity) > 0 + def splits_after(self, identity: type[SidebarPlacement], collapsed: Mapping[type[SidebarPlacement], bool]) -> bool: """Whether the next shown bar in this one's band sits beside it, so its splitter shows: @@ -694,6 +700,14 @@ def splits_after(self, identity: type[SidebarPlacement], index = shown.index(identity) return index + 1 < len(shown) + def next_in_band_folded(self, identity: type[SidebarPlacement], + collapsed: Mapping[type[SidebarPlacement], bool]) -> bool: + """Whether the next shown bar in this band is folded (and therefore draws its own + full-height leading hairline beside this open pane).""" + shown = tuple(key for key in self._slot(self.placements, identity) if key in collapsed) + index = shown.index(identity) + return index + 1 < len(shown) and collapsed[shown[index + 1]] + def _store(self, placements: dict[type[SidebarPlacement], SidebarPlacement]) -> None: self._save(replace(self.terminal, placements=tuple(placements.values()))) diff --git a/src/toad/sidebar_placement.py b/src/toad/sidebar_placement.py index ea5ae98ba..3e3d90e96 100644 --- a/src/toad/sidebar_placement.py +++ b/src/toad/sidebar_placement.py @@ -111,6 +111,11 @@ def _toggle_text_step(cls, collapsed: bool, heading: str, symbol) -> str: @abstractmethod def control_offset(cls, distance: int) -> Offset: ... + @classmethod + @abstractmethod + def inner_hairline(cls, width: int, height: int) -> tuple[int, int, int, int]: + """Line endpoints (x1, y1, x2, y2) for the 1 px hairline on the conversation-facing edge.""" + @classmethod def opposite(cls) -> type[SidebarEdge]: """The other concrete edge on the same axis (left<->right, top<->bottom). @@ -219,6 +224,11 @@ def _toggle_text_step(cls, collapsed: bool, heading: str, symbol) -> str: def control_offset(cls, distance: int) -> Offset: return Offset(-cls.sign * distance, 0) + @classmethod + def inner_hairline(cls, width: int, height: int) -> tuple[int, int, int, int]: + x = width - 1 if cls.sign > 0 else 0 + return (x, 0, x, height) + class HeightSidebarEdge(SidebarEdge): minimum = 9 @@ -301,6 +311,11 @@ def _toggle_text_step(cls, collapsed: bool, heading: str, symbol) -> str: def control_offset(cls, distance: int) -> Offset: return Offset(0, -cls.sign * distance) + @classmethod + def inner_hairline(cls, width: int, height: int) -> tuple[int, int, int, int]: + y = height - 1 if cls.sign > 0 else 0 + return (0, y, width, y) + class LeftSidebarEdge(LeadingSidebarEdge, WidthSidebarEdge): dock = "left" diff --git a/tests/model/test_mobile_chrome_polish_and_suspend.py b/tests/model/test_mobile_chrome_polish_and_suspend.py new file mode 100644 index 000000000..34d8bab96 --- /dev/null +++ b/tests/model/test_mobile_chrome_polish_and_suspend.py @@ -0,0 +1,142 @@ +"""Mobile chrome hairlines, flush NormalInputBox outer margin, suspend animation pause, +and virtual-scroll applicationStateChanged cleanup.""" +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock + +from PySide6.QtCore import Qt, QTimer +from PySide6.QtGui import QImage, QPainter, QPalette +from PySide6.QtWidgets import QApplication, QWidget +from textual.geometry import Spacing + +from toad.client.application import ACTIVE_PRESENCE, SUSPENDED_PRESENCE +from toad.preferences import SavedSettings +from toad.qt.side_bar import QtSideBarToggle +from toad.qt.virtual_scroll import RowDocumentStore +from toad.qt.window import QtToadApp +from toad.setting_choices import BottomNavigationBar, NormalInputBox, TopNavigationBar +from toad.sidebar_layout import SidebarLayout +from toad.sidebar_placement import ( + BottomSidebarEdge, + ChannelsSidebarPlacement, + LeftSidebarEdge, + RightSidebarEdge, + ThreadSidebarPlacement, + TopSidebarEdge, +) +from toad.terminal_origin import LocalTerminal + + +def test_normal_input_box_has_no_horizontal_outer_margin(): + assert NormalInputBox.frame_margin == Spacing(0, 0, 0, 0) + assert NormalInputBox.info_bar_margin(False) == Spacing(0, 1, 0, 1) + + +def test_navigation_bar_position_declares_content_facing_qt_separator_edge(): + assert TopNavigationBar.qt_separator_edge == "border-bottom" + assert BottomNavigationBar.qt_separator_edge == "border-top" + + +def test_sidebar_edge_inner_hairline_and_band_splitters(): + assert BottomSidebarEdge.inner_hairline(100, 30) == (0, 0, 100, 0) + assert TopSidebarEdge.inner_hairline(100, 30) == (0, 29, 100, 29) + assert LeftSidebarEdge.inner_hairline(30, 100) == (29, 0, 29, 100) + assert RightSidebarEdge.inner_hairline(30, 100) == (0, 0, 0, 100) + + layout = SidebarLayout(SavedSettings({}), LocalTerminal) + layout.move(ChannelsSidebarPlacement, BottomSidebarEdge) + layout.move(ThreadSidebarPlacement, BottomSidebarEdge) + first, second = ChannelsSidebarPlacement, ThreadSidebarPlacement + + both_folded = {first: True, second: True} + assert not layout.splits_before(first, both_folded) + assert layout.splits_after(first, both_folded) + assert layout.splits_before(second, both_folded) + assert not layout.splits_after(second, both_folded) + + first_open = {first: False, second: True} + assert layout.next_in_band_folded(first, first_open) + assert not layout.next_in_band_folded(second, first_open) + both_open = {first: False, second: False} + assert not layout.next_in_band_folded(first, both_open) + + +def test_rotated_side_bar_toggle_paints_leading_and_top_hairlines(monkeypatch): + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + app = QApplication.instance() or QApplication([]) + host = QWidget() + host.placement = SimpleNamespace(side=BottomSidebarEdge) + toggle = QtSideBarToggle(host) + try: + toggle.resize(24, 120) + toggle.show_turned("↑", "#comms") + toggle.set_band_splitters(leading=True, trailing=False) + pal = toggle.palette() + mid = pal.color(QPalette.ColorRole.Mid).rgb() + img = QImage(24, 120, QImage.Format.Format_ARGB32) + img.fill(Qt.GlobalColor.transparent) + painter = QPainter(img) + toggle._draw_hairlines(painter, vertical=True) + painter.end() + assert img.pixelColor(12, 0).rgb() == mid, "Top hairline spans the rotated bottom-band toggle" + assert img.pixelColor(0, 60).rgb() == mid, "Leading vertical hairline separates rotated toggle from open sibling" + assert img.pixelColor(23, 60).alpha() == 0, "No trailing hairline when trailing=False" + finally: + toggle.deleteLater() + host.deleteLater() + app.processEvents() + + +def test_suspend_pauses_and_resume_restores_animation_timer(monkeypatch): + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + app = QApplication.instance() or QApplication([]) + timer = QTimer() + fake = MagicMock() + fake._animation_timer = timer + fake._animation_interval = None + fake._animations_paused = False + fake._schedule_animation = lambda iv: QtToadApp._schedule_animation(fake, iv) + fake.set_animations_paused = lambda p: QtToadApp.set_animations_paused(fake, p) + try: + QtToadApp._schedule_animation(fake, 0.05) + assert timer.isActive() + presence = ACTIVE_PRESENCE.suspend(fake) + assert presence is SUSPENDED_PRESENCE + assert not timer.isActive() + presence = presence.activate(fake) + assert presence is ACTIVE_PRESENCE + assert timer.isActive() + finally: + timer.stop() + timer.deleteLater() + app.processEvents() + + +def test_row_document_store_cleanup_disconnects_app_state(monkeypatch): + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + app = QApplication.instance() or QApplication([]) + + class DummyStore(RowDocumentStore): + def row_key(self, fragment): return fragment + def row_text(self, fragment): return "" + def preparation_key_for(self, fragment, font, width): return fragment + def submit_preparation(self, key, fragment, font, width): pass + def stop_preparation(self): pass + def background_qcolor(self): return None + def final_document_for(self, *args, **kwargs): return None + def paint_row(self, *args, **kwargs): pass + def preparation_for(self, *args, **kwargs): return None + + store = DummyStore() + store.preparer = MagicMock() + parent = QWidget() + store._viewport_update_timer.setParent(parent) + store._measure_timer.setParent(parent) + store._suspend_release_timer.setParent(parent) + store.cleanup() + parent.deleteLater() + app.processEvents() + # Must not raise RuntimeError on deleted QTimer after tab cleanup. + store._application_state_changed(Qt.ApplicationState.ApplicationSuspended) + store._application_state_changed(Qt.ApplicationState.ApplicationActive)