diff --git a/src/toad/client/name_wave.py b/src/toad/client/name_wave.py index e480d8ae5..9fe1fb9b8 100644 --- a/src/toad/client/name_wave.py +++ b/src/toad/client/name_wave.py @@ -15,6 +15,8 @@ from ui_theme.effects import NAME_WAVE, Band, Effect +from toad.motion import TAB_MARQUEE, MarqueeSweep + class BandCells: """How a `Band` (fractions of a line) covers a line of `width` cells: each edge rounds @@ -94,3 +96,34 @@ def follow_activity(self, busy: bool) -> None: def name_bold(self) -> bool: """The whole name is bold while the wave runs.""" return self.wave_running() + + +class TitleMarquee: + """Shared banner-scroll state for overflowing tab titles. Runs on the frontend's + `AnimationClock` only while at least one title exceeds its visible rect.""" + + marquee_effect: ClassVar[MarqueeSweep] = TAB_MARQUEE + + def marquee_running(self) -> bool: + raise NotImplementedError + + def start_marquee(self) -> None: + raise NotImplementedError + + def stop_marquee(self) -> None: + raise NotImplementedError + + def marquee_elapsed(self) -> float: + raise NotImplementedError + + def follow_overflow(self, overflowing: bool) -> None: + if overflowing: + if not self.marquee_running(): + self.start_marquee() + elif self.marquee_running(): + self.stop_marquee() + + def marquee_offset(self, content_width: float, viewport_width: float) -> float: + if not self.marquee_running(): + return 0.0 + return self.marquee_effect.offset(self.marquee_elapsed(), content_width, viewport_width) diff --git a/src/toad/motion.py b/src/toad/motion.py index e796e5f7a..4f483a333 100644 --- a/src/toad/motion.py +++ b/src/toad/motion.py @@ -99,6 +99,38 @@ def final(self) -> Mix: ARRIVAL = Cascade(NEW_TEXT, span=0.4) +@dataclass(frozen=True) +class MarqueeSweep(Effect[Amount]): + """Continuous banner scroll for an overflowing label: pauses at the start, then scrolls at + `speed` units/s with `gap` units before wrapping back to zero.""" + + speed: float + pause: float + gap: float + frames_per_second: float = 30.0 + duration: float | None = None + + def frame(self, elapsed: float) -> Amount: + return Amount(elapsed) + + @property + def final(self) -> Amount: + return Amount(0.0) + + def offset(self, elapsed: float, content_width: float, viewport_width: float) -> float: + """Horizontal scroll offset for `content_width` inside `viewport_width` at `elapsed` s.""" + if content_width <= viewport_width + 0.5 or viewport_width <= 0 or self.speed <= 0: + return 0.0 + distance = content_width + self.gap + period = self.pause + distance / self.speed + t = elapsed % period + return 0.0 if t <= self.pause else (t - self.pause) * self.speed + + +# Overflowing tab titles banner-scroll on the shared clock after a 1 s readable pause. +TAB_MARQUEE = MarqueeSweep(speed=28.0, pause=1.0, gap=24.0, frames_per_second=30.0) + + def animations_enabled() -> bool: """Whether this process animates: Textual's own animation level, which the TUI's clock already follows, so one environment setting turns motion off in both frontends.""" diff --git a/src/toad/qt/file_pickers.py b/src/toad/qt/file_pickers.py index 99b0c00b7..baf6eeb27 100644 --- a/src/toad/qt/file_pickers.py +++ b/src/toad/qt/file_pickers.py @@ -39,11 +39,11 @@ def read_picked(url: QUrl, composer: MessagePromptComposer) -> None: def open_file_dialog(parent: QWidget, composer: MessagePromptComposer) -> QFileDialog: - """Qt's file dialog over ``parent``, attaching the file it returns.""" + """Qt's file dialog over ``parent``, attaching all files it returns.""" dialog = QFileDialog(parent, AttachFileAction.title) - dialog.setFileMode(QFileDialog.FileMode.ExistingFile) - # An accepted dialog holds its one choice: Qt's own dialog emits no urlSelected, and - # Android's document picker answers with a content:// URL, so both are read from here. + dialog.setFileMode(QFileDialog.FileMode.ExistingFiles) + # An accepted dialog holds its chosen URLs: Qt's own dialog emits no urlSelected, and + # Android's document picker returns one or more content:// URLs via ClipData/getData. dialog.accepted.connect(lambda: [read_picked(url, composer) for url in dialog.selectedUrls()]) dialog.finished.connect(dialog.deleteLater) dialog.open() @@ -51,7 +51,7 @@ def open_file_dialog(parent: QWidget, composer: MessagePromptComposer) -> QFileD class QtPathSearch(PresentedWindow, ProjectPathSearch, QDialog): - """The project's paths, ranked as you type; choosing one attaches that file.""" + """The project's paths, ranked as you type; choosing one or more attaches those files.""" shown_limit = 100 @@ -65,6 +65,7 @@ def __init__(self, parent: QWidget, root: Path, chosen: Callable[[Path], None], self.query = QLineEdit(self) self.query.setPlaceholderText(f"Search {root}") self.results = QListWidget(self) + self.results.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection) layout = QVBoxLayout(self) layout.addWidget(self.query) layout.addWidget(self.results, 1) @@ -91,12 +92,19 @@ def show_paths(self, spellings: list[str]) -> None: self.results.setCurrentRow(0) def choose_current(self) -> None: - if (item := self.results.currentItem()) is not None: + selected = [item.text() for item in self.results.selectedItems()] + if selected: + self.choose_many(selected) + elif (item := self.results.currentItem()) is not None: self.choose(item.text()) - def choose(self, spelling: str) -> None: + def choose_many(self, spellings: list[str]) -> None: self.accept() - self.chosen(self.root / spelling) + for spelling in spellings: + self.chosen(self.root / spelling) + + def choose(self, spelling: str) -> None: + self.choose_many([spelling]) def open_path_search(parent: QWidget, composer: MessagePromptComposer, root: Path, run: Callable) -> QtPathSearch: diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index a5995294c..a39516735 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -181,7 +181,8 @@ def __init__(self, renderer: QtLineRenderer, pictures: RowPictures, processes: R self._colour_cache: tuple[ColourScheme, str, QColor, QColor] | None = None self._font_metrics_cache: tuple[QFont, float, int] | None = None self._font_spec_cache: tuple[QFont, str, float] | None = None - self._frame_paint: tuple[QWidget | None, QFont, QPalette, float, QImage.Format, str, QColor, QColor, str, float, int] | None = None + self._backing_format_cache: tuple[int, int, QImage.Format] | None = None + self._frame_paint: tuple[QWidget | None, QFont, float, QImage.Format, str, QColor, QColor, str, float, int] | None = None self._frame_source_mode = False @staticmethod @@ -233,17 +234,24 @@ def background_qcolor(self) -> QColor: def foreground_qcolor(self) -> QColor: return self._theme_colours()[2] - def link(self, links: LinkContext) -> None: - """Rows draw with these names from now on; rows prepared before are stale.""" + def link(self, links: LinkContext) -> bool: + """Rows draw with these names from now on; rows prepared before are stale. + Returns True when `links` actually changed so a parallel `acquire_links` with + unchanged links never wipes prepared rows and flashes an already-loaded view.""" + if links == self.renderer.links: + return False self.renderer = self.app_renderer.with_links(links) self.links_revision += 1 # Every row's key names the links it was drawn with: none keeps its height. self.forget_row_sizes() + return True def restyle(self) -> None: """The app's renderer took a new scheme or diff marks: rows draw by it from now on, with the names they had; rows prepared before are stale.""" - self.link(self.renderer.links) + self.renderer = self.app_renderer.with_links(self.renderer.links) + self.links_revision += 1 + self.forget_row_sizes() def row_key(self, fragment: HistoryFragment): return fragment.key @@ -532,6 +540,7 @@ def release_documents(self) -> None: suspending the app, a new width).""" super().release_documents() self.pictures.clear() + self._backing_format_cache = None def _paint_tile_document( self, drawing: QPainter, palette: QPalette, document: QTextDocument, @@ -600,17 +609,24 @@ def _paint_plain_row( def _resolve_frame_paint( self, painter: QPainter, viewport_width: int = 0, - ) -> tuple[QWidget | None, QFont, QPalette, float, QImage.Format, str, QColor, QColor, str, float, int]: + ) -> tuple[QWidget | None, QFont, float, QImage.Format, str, QColor, QColor, str, float, int]: device = self.view.backing_device() font = device.font() if device is not None else QFont() - palette = device.palette() if device is not None else QPalette() - ratio = painter.device().devicePixelRatioF() - img_format = self._backing_image_format(device, painter) + paint_device = painter.device() + ratio = paint_device.devicePixelRatioF() + cached_fmt = self._backing_format_cache + dev_id = id(paint_device) + wid_id = id(device) + if cached_fmt is not None and cached_fmt[0] == dev_id and cached_fmt[1] == wid_id: + img_format = cached_fmt[2] + else: + img_format = self._backing_image_format(device, painter) + self._backing_format_cache = (dev_id, wid_id, img_format) bg_hex, bg_color, fg_color = self._theme_colours() font_family, font_size = self._font_spec(font) layout_w = self.layout_width(viewport_width) if viewport_width else 0 return ( - device, font, palette, ratio, img_format, bg_hex, bg_color, fg_color, + device, font, ratio, img_format, bg_hex, bg_color, fg_color, font_family, font_size, layout_w, ) @@ -634,6 +650,13 @@ def paint_row( return arrival = self.view.arrival_state(fragment.key, rect.height()) if self.view.has_active_arrivals else SETTLED_ARRIVAL paint_rect = rect.translated(0, round(arrival.offset_y)) if arrival.offset_y else rect + # Clip an arriving non-final row to its own layout slot so its downward slide offset + # never draws over the sibling row underneath it while the arrival animation is running. + clip_to_slot = bool(arrival.offset_y and row + 1 < self.view.model_rows.rowCount()) + row_clip = ( + (QRegion(rect) if clip_region is None else clip_region.intersected(QRegion(rect))) + if clip_to_slot else clip_region + ) highlight = self.view.tap_highlight if highlight.matches_row(fragment.key): frame = self._frame_paint @@ -642,11 +665,11 @@ def paint_row( ) document = self.final_document_for(fragment, font, self.layout_width(paint_rect.width())) if document is not None: - self._paint_document_direct(painter, document, paint_rect, clip_region, arrival, highlight) + self._paint_document_direct(painter, document, paint_rect, row_clip, arrival, highlight) self.view.row_painted(fragment, paint_rect) return - if not self.paint_pictures(painter, fragment, paint_rect, clip_region, arrival): - self._paint_plain_row(painter, fragment, paint_rect, clip_region, arrival) + if not self.paint_pictures(painter, fragment, paint_rect, row_clip, arrival, clip_to_shown=clip_to_slot): + self._paint_plain_row(painter, fragment, paint_rect, row_clip, arrival) self.view.row_painted(fragment, paint_rect) def paint_pictures( @@ -656,6 +679,8 @@ def paint_pictures( rect: QRect, clip_region: QRegion | None, arrival: ViewportArrivalState = SETTLED_ARRIVAL, + *, + clip_to_shown: bool = False, ) -> bool: """The tiles of the row that this paint shows, each drawn once into a backing-store-matched `QImage` and blitted with `CompositionMode_Source` on subsequent frames.""" @@ -663,9 +688,10 @@ def paint_pictures( if frame is None: frame = self._resolve_frame_paint(painter) ( - _device, font, palette, ratio, img_format, bg_hex, bg_color, _fg_color, + device, font, ratio, img_format, bg_hex, bg_color, _fg_color, font_family, font_size, layout_w, ) = frame + palette: QPalette | None = None width = layout_w or self.layout_width(rect.width()) cache_key = (((fragment.key, fragment.shown, fragment.revision), self.links_revision, font_family, font_size, width), width) document = self._documents.get(cache_key) @@ -693,12 +719,14 @@ def paint_pictures( rect_h = rect.height() look = (rect_w, rect_h, ratio, bg_hex, img_format) row_id = id(document) if document is not None else (id(self), fragment.key) - needs_state = arrival.active or not self._frame_source_mode + needs_state = arrival.active or clip_to_shown or not self._frame_source_mode if needs_state: painter.save() + if clip_to_shown: + painter.setClipRect(shown) if arrival.active: painter.setOpacity(arrival.opacity) - else: + elif not self._frame_source_mode: painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source) plain_doc: QTextDocument | None = None tile_h = self.TILE @@ -723,6 +751,8 @@ def paint_pictures( tile_key = (row_id, tile_y, tile_x) picture = pictures_kept(tile_key, look, document) if picture is None: + if palette is None: + palette = device.palette() if device is not None else QPalette() picture = QImage( max(1, round(width * ratio)), max(1, round(height * ratio)), @@ -1318,7 +1348,7 @@ def draw_pinned(self, headers: tuple[Divider, ...], x: int, width: int) -> None: in `laid_out` and `_pixmap_cache` so scrolling back and forth across message boundaries avoids re-running `setHtml` / layout / rasterization or no-op geometry calls.""" window = self.history_window - context = (width, window.font().key(), window.rows.links_revision, id(window.rows.renderer)) + context = (width, window.rows._font_spec(window.font()), window.rows.links_revision, id(window.rows.renderer)) drawn = (headers, x, context) if drawn == self.drawn: return @@ -1637,9 +1667,12 @@ def _on_widget_destroyed(self, *_args) -> None: self.stop_arrival_motion() async def acquire_links(self, app) -> None: - """The names this conversation's bodies link through; the rows draw again with them.""" - self.rows.link(await LinkContext.observed(app.renderer.links.root, app.coordination_access)) - self.show_pages() + """The names this conversation's bodies link through; redraw rows only if links changed.""" + links = await LinkContext.observed(app.renderer.links.root, app.coordination_access) + changed = self.rows.link(links) + app.renderer.links = links + if changed: + self.show_pages() def action_page_down(self) -> None: """Move the reader one page toward the latest message (Textual's `ReaderAction` @@ -2183,6 +2216,16 @@ def keep_tail_after_resize(self, was: int, now: int) -> None: if was != now and self.follows_tail and not self.widget_gone: self.follow_latest() + def apply_measured_rows(self, updates: list[tuple[int, int, int]]) -> None: + """Commit background height measurements after flushing pending reader scroll so + `request_reader_layout()` anchors against pre-update geometry.""" + if not updates or self.widget_gone: + return + self._flush_reader_scroll() + for row, height, extent in updates: + self._set_row_geometry(row, height, extent, False) + self.rows_changed() + def rows_changed(self) -> None: """Prepared rows changed height: lay them out again; the layout keeps the reader's message. A destroyed window has no reader to serve.""" diff --git a/src/toad/qt/name_wave.py b/src/toad/qt/name_wave.py index f58c25478..23a817c70 100644 --- a/src/toad/qt/name_wave.py +++ b/src/toad/qt/name_wave.py @@ -8,16 +8,18 @@ from __future__ import annotations +from math import ceil + from PySide6.QtCore import QEvent, QPointF, QRect, QSize, Qt -from PySide6.QtGui import QColor, QFont, QImage, QPainter, QPixmap, QTextCharFormat, QTextLayout -from PySide6.QtWidgets import QHBoxLayout, QLabel, QStyle, QStyleOptionTab, QStyleOptionViewItem, QStylePainter, QTabBar, QToolButton, QWidget +from PySide6.QtGui import QColor, QFont, QFontMetrics, QImage, QPainter, QPixmap, QTextCharFormat, QTextLayout +from PySide6.QtWidgets import QHBoxLayout, QLabel, QScrollArea, QStyle, QStyleOptionTab, QStyleOptionViewItem, QStylePainter, QTabBar, QToolButton, QWidget from pyqt_reactive.widgets.shared.list_item_delegate import MultilinePreviewItemDelegate from pyqt_reactive.widgets.shared.list_item_text_rendering import PreparedTextLayout from pyqt_reactive.widgets.shared.tear_off_tab_widget import TearOffTabBar from ui_theme.effects import Band -from toad.client.name_wave import BandCells, NameWave +from toad.client.name_wave import BandCells, NameWave, TitleMarquee from toad.motion import TAB_CLOSE, TAB_OPEN, TransitionTarget from toad.qt.tap_flash import QtTextButton @@ -380,33 +382,116 @@ def land(self) -> None: self.picture.deleteLater() +class QtTabMarquee(TitleMarquee): + """One shared banner-scroll animation for all overflowing tabs on a `QtSessionTabBar`.""" + + def __init__(self, bar: QtSessionTabBar) -> None: + self.bar = bar + self.animation = None + self._painted_offsets: dict[str, int] = {} + + @property + def animation_visible(self) -> bool: + return self.bar.isVisible() + + def marquee_running(self) -> bool: + return self.animation is not None + + def start_marquee(self) -> None: + self._painted_offsets.clear() + self.animation = self.bar.clock.start(self.marquee_effect, self) + + def stop_marquee(self) -> None: + if self.animation is not None: + self.animation.stop() + self.animation = None + self._painted_offsets.clear() + + def marquee_elapsed(self) -> float: + return 0.0 if self.animation is None else self.animation.frame().value + + def repaint(self) -> None: + """Repaint only overflowing tabs whose integer scroll offset actually moved.""" + self.bar._repaint_marquee_tabs(self._painted_offsets) + + class QtSessionTabBar(QtWaveBandCache, TearOffTabBar): - """The workspace's tab bar: a busy tab's title waves as Textual's `SessionLabel` does. - The title's line is the label with its one cell of padding each side, as the TUI's tab - draws it, so the band covers the same characters. A tab that opens grows in and one that - closes shrinks away, on the same clock.""" + """The workspace's tab bar: compact tabs sized to their title up to a width cap so at least + three tabs fit across Android's tab strip, with overflowing titles scrolling like a banner + on the shared `AnimationClock` and busy tabs waving in the theme accent.""" padding_cells = 1 - TAB_GAP = 6 + TAB_GAP = 4 """Inter-tab right margin (px); read by both the tab stylesheet and `_make_close_button` - so the close button always sits inside the painted tab rather than the gap between tabs.""" - - def __init__(self, clock, accent: QColor, ink: QColor) -> None: + so the close button sits cleanly inside the painted tab without dead padding.""" + TAB_PAD_LEFT = 6 + TAB_PAD_RIGHT = 2 + TAB_TEXT_CLOSE_GAP = 2 + MAX_TITLE_CHARS = 16 + MIN_VISIBLE_TABS = 3 + + def __init__(self, clock, accent: QColor, ink: QColor, inactive_ink: QColor | None = None) -> None: super().__init__() self.clock, self.ink = clock, ink + self.inactive_ink = ink if inactive_ink is None else inactive_ink self._init_wave_ink(accent) - self.lines: dict[tuple[str, int], QTextLayout] = {} + self.lines: dict[tuple[str, bool], QTextLayout] = {} self._shown_titles: dict[tuple[int, str, int], tuple[QRect, str]] = {} self._tab_chrome: dict[tuple, QImage] = {} self.waves: dict[str, QtTabWave] = {} self.growing: dict[str, TabGrowth] = {} + self.marquee = QtTabMarquee(self) + self._strip_width = 0 - def set_colours(self, accent: QColor, ink: QColor) -> None: + def set_colours(self, accent: QColor, ink: QColor, inactive_ink: QColor | None = None) -> None: self.ink = ink + self.inactive_ink = ink if inactive_ink is None else inactive_ink self._set_wave_accent(accent) self._tab_chrome.clear() self.update() + def sync_strip_width(self, width: int) -> None: + """Keep the 3-tab width cap synced with the visible tab strip viewport width.""" + width = max(0, int(width)) + if width == self._strip_width: + return + self._strip_width = width + self._shown_titles.clear() + self._tab_chrome.clear() + self.relayout() + self._sync_marquee() + + def _strip_viewport_width(self) -> int: + if self._strip_width > 0: + return self._strip_width + parent = self.parentWidget() + if parent is not None and isinstance(parent.parentWidget(), QScrollArea) and parent.width() > 0: + return parent.width() + return 0 + + def _close_slot_metrics(self) -> tuple[int, int]: + """(button_px, slot_width_px) for the right-side close button container.""" + size = max(24, self.fontMetrics().height() + 2) + return size, size + self.TAB_GAP + + def _tab_chrome_width(self) -> int: + """Horizontal non-text pixels per tab: left pad + text/close gap + close slot + right pad.""" + _size, slot_w = self._close_slot_metrics() + return self.TAB_PAD_LEFT + self.TAB_TEXT_CLOSE_GAP + slot_w + self.TAB_PAD_RIGHT + + def _max_tab_width(self) -> int: + """Maximum width (px) for one tab: bounded by `MAX_TITLE_CHARS` and by 1/3 of the + visible tab strip so narrow screens (Android) generally show at least three tabs.""" + fm = self.fontMetrics() + avg_char = max(1, fm.averageCharWidth()) + chrome = self._tab_chrome_width() + min_width = chrome + 4 * avg_char + char_cap = chrome + self.MAX_TITLE_CHARS * avg_char + strip_w = self._strip_viewport_width() + if strip_w > 0: + return max(min_width, min(char_cap, strip_w // self.MIN_VISIBLE_TABS)) + return char_cap + def show_tabs(self, entries: list[tuple[str, str]]) -> bool: """Draw ``entries`` (title, mode) as the bar's tabs; whether anything changed. The same tabs in the same order only retitle the ones whose title changed, as Textual's tab @@ -422,6 +507,7 @@ def show_tabs(self, entries: list[tuple[str, str]]) -> bool: for index, (title, _) in enumerate(entries): if current[index][0] != title: self.setTabText(index, title) + self._sync_marquee() return True shown = {self.tabData(index): self.tabRect(index) for index in range(self.count())} modes = {mode for _, mode in entries} @@ -439,17 +525,18 @@ def show_tabs(self, entries: list[tuple[str, str]]) -> bool: self.growing[mode] = TabGrowth(self, mode) for rect, picture in leaving: TabGhost(self, rect, picture) + self._sync_marquee() return True def _make_close_button(self, mode: str) -> QWidget: """A comfortable, theme-tinted close button tucked inside the tab's right edge - instead of Fusion's tiny red cross clipped into the inter-tab gap.""" + without dead horizontal padding next to the title.""" container = QWidget(self) container.setObjectName("tab-close-slot") container.setStyleSheet("QWidget#tab-close-slot { background: transparent; }") layout = QHBoxLayout(container) - right_inset = self.TAB_GAP + 2 - layout.setContentsMargins(2, 0, right_inset, 0) + size, slot_w = self._close_slot_metrics() + layout.setContentsMargins(0, 0, self.TAB_GAP, 0) layout.setSpacing(0) button = QtTextButton(container) button.setObjectName("tab-close-button") @@ -457,11 +544,10 @@ def _make_close_button(self, mode: str) -> QWidget: button.setToolTip("Close tab") button.setAutoRaise(True) button.setFocusPolicy(Qt.FocusPolicy.NoFocus) - size = max(24, self.fontMetrics().height() + 4) button.setFixedSize(size, size) button.clicked.connect(lambda _checked=False, target=mode: self._request_close(target)) layout.addWidget(button) - container.setFixedSize(size + 2 + right_inset, size) + container.setFixedSize(slot_w, size) return container def _request_close(self, mode: str) -> None: @@ -479,11 +565,21 @@ def _grown(self, index: int, hint: QSize) -> QSize: hint.setWidth(round(hint.width() * growth.share)) return hint + def _compact_tab_size(self, index: int, base: QSize) -> QSize: + text = self.tabText(index) + bold_font = QFont(self.font()) + bold_font.setBold(True) + text_w = ceil(QFontMetrics(bold_font).horizontalAdvance(text)) + btn_size, _slot_w = self._close_slot_metrics() + width = min(self._max_tab_width(), self._tab_chrome_width() + max(8, text_w)) + height = max(btn_size + 6, base.height()) + return QSize(width, height) + def tabSizeHint(self, index: int) -> QSize: # type: ignore[override] - return self._grown(index, super().tabSizeHint(index)) + return self._grown(index, self._compact_tab_size(index, super().tabSizeHint(index))) def minimumTabSizeHint(self, index: int) -> QSize: # type: ignore[override] - return self._grown(index, super().minimumTabSizeHint(index)) + return self._grown(index, self._compact_tab_size(index, super().minimumTabSizeHint(index))) def follow_tabs(self, tabs) -> None: """Each open tab's wave follows its busy state; a closed tab's stops.""" @@ -503,28 +599,65 @@ def repaint_tab(self, mode: str) -> None: self.update(self.tabRect(index)) def _cached_title(self, index: int) -> tuple[QRect, str]: - """Cached text rectangle and elided title for ``index``; invalidated on tab/font/style/resize - changes so 60-120 Hz wave ticks do not rebuild QStyleOptionTab + elidedText every tick.""" + """Cached text rectangle and full title for ``index``; derived directly from `tabRect` + and the close-button slot so Fusion's extra `SE_TabBarTabText` gap never clips early.""" text = self.tabText(index) tab_rect = self.tabRect(index) key = (index, text, tab_rect.width()) cached = self._shown_titles.get(key) if cached is not None: return cached - option = QStyleOptionTab() - self.initStyleOption(option, index) - rect = self.style().subElementRect(QStyle.SubElement.SE_TabBarTabText, option, self) - shown = self.fontMetrics().elidedText(option.text, Qt.TextElideMode.ElideRight, rect.width()) - self._shown_titles[key] = (rect, shown) - return rect, shown + _size, slot_w = self._close_slot_metrics() + close_slot = self.tabButton(index, QTabBar.ButtonPosition.RightSide) + if close_slot is not None and close_slot.width() > 0: + slot_w = close_slot.width() + left = tab_rect.left() + self.TAB_PAD_LEFT + right = max(left, tab_rect.right() - slot_w - self.TAB_PAD_RIGHT - self.TAB_TEXT_CLOSE_GAP) + rect = QRect(left, tab_rect.top(), max(0, right - left + 1), tab_rect.height()) + self._shown_titles[key] = (rect, text) + return rect, text def shown_title(self, index: int) -> tuple[QStyleOptionTab, QRect, str]: - """A tab's style option, the rectangle its title draws in, and the title as it fits - there: what the paint draws, and what a wave's band is measured over.""" + """A tab's style option, the rectangle its title draws in, and its title.""" option = QStyleOptionTab() self.initStyleOption(option, index) - rect, shown = self._cached_title(index) - return option, rect, shown + rect, text = self._cached_title(index) + return option, rect, text + + def _tab_overflows(self, index: int) -> bool: + rect, text = self._cached_title(index) + if rect.width() <= 0 or not text: + return False + wave = self.waves.get(self.tabData(index)) + bold = (index == self.currentIndex()) or (wave is not None and wave.wave_running()) + return self.title_line(text, bold=bold).lineAt(0).naturalTextWidth() > rect.width() + 0.5 + + def _sync_marquee(self) -> None: + if not self.isVisible(): + return + overflowing = any(self._tab_overflows(index) for index in range(self.count())) + self.marquee.follow_overflow(overflowing) + + def _repaint_marquee_tabs(self, painted: dict[str, int]) -> None: + any_overflow = False + for index in range(self.count()): + rect, text = self._cached_title(index) + if rect.width() <= 0 or not text: + continue + mode = self.tabData(index) + wave = self.waves.get(mode) + bold = (index == self.currentIndex()) or (wave is not None and wave.wave_running()) + full_w = self.title_line(text, bold=bold).lineAt(0).naturalTextWidth() + if full_w <= rect.width() + 0.5: + continue + any_overflow = True + px = round(self.marquee.marquee_offset(full_w, rect.width())) + key = str(mode) if mode is not None else str(index) + if painted.get(key) != px: + painted[key] = px + self.update(self.tabRect(index)) + if not any_overflow: + self.marquee.follow_overflow(False) def wave_span(self, wave: QtTabWave) -> tuple[int, int] | None: """The band's cells over the title of the tab ``wave`` runs in, padding included.""" @@ -535,8 +668,8 @@ def wave_span(self, wave: QtTabWave) -> tuple[int, int] | None: return self.band_cells(wave.wave_frame(), len(shown) + 2 * self.padding_cells) def _tab_chrome_image(self, index: int, tab_rect: QRect, option: QStyleOptionTab, dpr: float) -> QImage: - """Cache each busy tab's empty-text QSS background chrome so 60-120 Hz wave ticks - blit one image instead of running Fusion's QSS `drawControl(CE_TabBarTab)` every tick.""" + """Cache each tab's empty-text QSS background chrome so wave and marquee ticks blit one + image instead of running Fusion's QSS `drawControl(CE_TabBarTab)` every tick.""" key = ( tab_rect.width(), tab_rect.height(), @@ -569,52 +702,79 @@ def _tab_chrome_image(self, index: int, tab_rect: QRect, option: QStyleOptionTab def paintEvent(self, event) -> None: # type: ignore[override] painter = QStylePainter(self) dpr = self.devicePixelRatioF() + any_overflow = False for index in range(self.count()): tab_rect = self.tabRect(index) if not tab_rect.intersects(event.rect()): - # A wave repaints its own tab: the other tabs' titles were being measured - # and elided again for each of its frames (the paint's largest Python cost - # on a phone, 8% of the GUI thread's samples with a few tabs open). + # A wave or marquee repaints its own tab: untouched tabs skip all layout work. continue option, rect, shown = self.shown_title(index) - wave = self.waves.get(self.tabData(index)) - if wave is None or not wave.wave_running(): - painter.drawControl(QStyle.ControlElement.CE_TabBarTab, option) - continue chrome = self._tab_chrome_image(index, tab_rect, option, dpr) painter.drawImage(tab_rect.topLeft(), chrome) - span = wave.band_drawn() or self.band_cells(wave.wave_frame(), len(shown) + 2 * self.padding_cells) - start, end = span - layout = self.bold_line(shown, rect.width()) - line = layout.lineAt(0) + if rect.width() <= 0 or not shown: + continue + wave = self.waves.get(self.tabData(index)) + waving = wave is not None and wave.wave_running() + selected = bool(option.state & QStyle.StateFlag.State_Selected) + hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) + layout = self.title_line(shown, bold=waving or selected) + if waving: + span = wave.band_drawn() or self.band_cells(wave.wave_frame(), len(shown) + 2 * self.padding_cells) + start, end = span + drawn = self.baked_band_layout( + layout, + (max(0, start - self.padding_cells), max(0, end - self.padding_cells)), + ) + else: + drawn = layout + line = drawn.lineAt(0) + full_w = line.naturalTextWidth() top = rect.top() + (rect.height() - line.height()) / 2 - painter.setPen(self.ink) - baked = self.baked_band_layout( - layout, - (max(0, start - self.padding_cells), max(0, end - self.padding_cells)), - ) - baked.draw(painter, QPointF(rect.left() + (rect.width() - line.naturalTextWidth()) / 2, top)) - - def bold_line(self, shown: str, width: int) -> QTextLayout: - """A working tab's title, bold, on one line ``width`` wide: laid out once for the - title and width, since a frame of its wave moves the band's ink and not the text.""" - kept = self.lines.get((shown, width)) + painter.setPen(self.ink if (waving or selected or hovered) else self.inactive_ink) + painter.save() + painter.setClipRect(rect) + if full_w > rect.width() + 0.5: + any_overflow = True + offset = self.marquee.marquee_offset(full_w, rect.width()) + x = rect.left() - offset + drawn.draw(painter, QPointF(x, top)) + second_x = x + full_w + self.marquee.marquee_effect.gap + if second_x < rect.right(): + drawn.draw(painter, QPointF(second_x, top)) + else: + drawn.draw(painter, QPointF(rect.left() + max(0.0, (rect.width() - full_w) / 2), top)) + painter.restore() + if any_overflow and not self.marquee.marquee_running(): + self.marquee.follow_overflow(True) + + def title_line(self, shown: str, *, bold: bool) -> QTextLayout: + """One tab title laid out on a single unwrapped line so naturalTextWidth is exact.""" + kept = self.lines.get((shown, bold)) if kept is None: if len(self.lines) >= self.KEPT: self.lines.clear() font = QFont(self.font()) - font.setBold(True) - kept = self.lines[(shown, width)] = QTextLayout(shown, font) + font.setBold(bold) + kept = self.lines[(shown, bold)] = QTextLayout(shown, font) kept.setCacheEnabled(True) kept.beginLayout() - kept.createLine().setLineWidth(width) + kept.createLine().setLineWidth(1_000_000) kept.endLayout() return kept + def bold_line(self, shown: str, _width: int = 0) -> QTextLayout: + """A working tab's title, bold, on one line.""" + return self.title_line(shown, bold=True) + + def showEvent(self, event) -> None: # type: ignore[override] + super().showEvent(event) + self._sync_marquee() + def resizeEvent(self, event) -> None: # type: ignore[override] self._shown_titles.clear() self._tab_chrome.clear() super().resizeEvent(event) + self._sync_marquee() def changeEvent(self, event) -> None: # type: ignore[override] if event.type() in (QEvent.Type.FontChange, QEvent.Type.StyleChange, QEvent.Type.PaletteChange): @@ -623,3 +783,5 @@ def changeEvent(self, event) -> None: # type: ignore[override] self._shown_titles.clear() self._tab_chrome.clear() super().changeEvent(event) + if event.type() in (QEvent.Type.FontChange, QEvent.Type.StyleChange): + self._sync_marquee() diff --git a/src/toad/qt/virtual_scroll.py b/src/toad/qt/virtual_scroll.py index f705d8c0c..446f5f0f6 100644 --- a/src/toad/qt/virtual_scroll.py +++ b/src/toad/qt/virtual_scroll.py @@ -397,6 +397,9 @@ def estimating(self) -> bool: def invalidate_row_height(self, row: int) -> None: pass + def apply_measured_rows(self, updates: list[tuple[int, int, int]]) -> None: + pass + def measure_slice_rows(self) -> tuple[tuple, int, QFont, int] | None: return None @@ -812,18 +815,18 @@ def _measure_slice(self) -> None: key=lambda row: abs(row - reader)) self._unmeasured.clear() self.ensure_row_sizes(font, width, count) - started, measured = time.monotonic(), False + started = time.monotonic() + updates: list[tuple[int, int, int]] = [] while waiting and time.monotonic() - started < self.MEASURE_SLICE_SECONDS: row = waiting.pop(0) if self.kept_size(row, measured=True) is None: h, ext, est = self.measure_row(row, fragments[row], font, width, allow_estimate=False) if not est: - self.view._set_row_geometry(row, h, ext, False) - measured = True + updates.append((row, h, ext)) for row in waiting: self._unmeasured.add(row) - if measured: - self.view.rows_changed() + if updates: + self.view.apply_measured_rows(updates) if self._unmeasured and not self._scroll_paused: self._measure_timer.start() @@ -914,6 +917,7 @@ def __init__(self, rows: RowDocumentStore, parent: QWidget | None = None) -> Non self._estimated: list[bool] = [] self._offsets: list[int] = [0] self._dirty_offset_from = 0 + self._dirty_heights: set[int] = set() self._max_extent = 0 self._layout_width_measured = 0 self._layout_font_key = "" @@ -935,11 +939,20 @@ def estimating(self) -> bool: return self._estimating def invalidate_row_height(self, row: int) -> None: + """Mark `row` for re-measurement on the next `do_layout()` without overwriting its + current positive height mid-frame; setting `_heights[row] = -1` before layout runs + would collapse the row to 0 px in any `paintEvent` firing before the update timer.""" if 0 <= row < len(self._heights): - self._heights[row] = -1 - self._estimated[row] = False - if row < self._dirty_offset_from: - self._dirty_offset_from = row + self._dirty_heights.add(row) + + def apply_measured_rows(self, updates: list[tuple[int, int, int]]) -> None: + if not updates: + return + with self.keeping_end() if self.at_end else self.holding_position(): + for row, height, extent in updates: + self._set_row_geometry(row, height, extent, False) + self.schedule_layout() + self.viewport().update() def measure_slice_rows(self) -> tuple[tuple, int, QFont, int] | None: fragments = self.model_rows.fragments @@ -1002,6 +1015,13 @@ def _rows_spliced(self, head: int, removed: int, added: int, changed: int) -> No self._heights[row] = -1 self._extents[row] = 0 self._estimated[row] = False + if self._dirty_heights: + delta = added - removed + self._dirty_heights = { + r if r < head else r + delta + for r in self._dirty_heights + if r < head or r >= head + removed + } if head < self._dirty_offset_from: self._dirty_offset_from = head self._geometry_revision += 1 @@ -1011,6 +1031,7 @@ def _rows_data_changed(self, indices: list[int]) -> None: self.rows.mark_rows_changed(iter(indices)) for row in indices: if 0 <= row < len(self._heights): + self._dirty_heights.discard(row) self._heights[row] = -1 self._extents[row] = 0 self._estimated[row] = False @@ -1083,7 +1104,7 @@ def schedule_layout(self) -> None: self._layout_pending = True def execute_layout(self) -> None: - if self._layout_pending or self._dirty_offset_from <= len(self._heights): + if self._layout_pending or self._dirty_heights or self._dirty_offset_from <= len(self._heights): self.do_layout() @property @@ -1143,6 +1164,7 @@ def do_layout(self) -> None: self._heights.clear() self._extents.clear() self._estimated.clear() + self._dirty_heights.clear() self._offsets = [0] self._dirty_offset_from = 1 self._max_extent = 0 @@ -1156,10 +1178,20 @@ def do_layout(self) -> None: self._heights = [-1] * count self._extents = [0] * count self._estimated = [False] * count + self._dirty_heights.clear() self._dirty_offset_from = 0 self._max_extent = width self._layout_width_measured = width self._layout_font_key = font_key + elif self._dirty_heights: + dirty = self._dirty_heights + self._dirty_heights = set() + for row in dirty: + if 0 <= row < count: + self._heights[row] = -1 + self._estimated[row] = False + if row < self._dirty_offset_from: + self._dirty_offset_from = row self.rows.ensure_row_sizes(font, width, count) reader = min(count - 1, max(0, self.reader_row())) reach = self.MEASURED_VIEWPORTS * max(1, self.viewport().height()) diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index 38295f5ef..71e603681 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -1828,6 +1828,7 @@ def __init__(self, connection: CoreConnection, project: Checkout, self.animation_clock, QColor(self.renderer.theme(WorkspaceTabTones.underline_colour)), QColor(self.renderer.theme(WorkspaceTabTones.active_text_colour)), + QColor(self.renderer.theme(WorkspaceTabTones.inactive_text_colour)), ) self.tabs.setTabsClosable(True) self.tabs.setExpanding(False) @@ -2128,6 +2129,7 @@ def mark_current(self) -> None: QTimer.singleShot(0, partial(self.show_current_tab, scroll_to_current=selection_changed)) def show_current_tab(self, *, scroll_to_current: bool = True) -> None: + self.tabs.sync_strip_width(self.tab_strip.viewport().width()) self.tab_strip.setFixedHeight(self.tabs.sizeHint().height()) scroller = QScroller.scroller(self.tab_strip.viewport()) if scroll_to_current and scroller.state() == QScroller.State.Inactive and (index := self.tabs.currentIndex()) >= 0: @@ -2163,7 +2165,7 @@ def paint_chrome_colours(self) -> None: self.tabs.setStyleSheet( f"QTabBar {{ background-color: {bar_bg}; color: {active_ink}; }}" f"QTabBar::tab {{ background-color: {inactive_bg}; color: {inactive_ink}; border: none;" - f" padding: 6px 10px 6px 12px; margin-right: {self.tabs.TAB_GAP}px;" + f" padding: 4px 2px 4px 6px; margin-right: {self.tabs.TAB_GAP}px;" " border-top-left-radius: 4px; border-top-right-radius: 4px; }" f"QTabBar::tab:hover {{ background-color: {hover_bg}; color: {active_ink}; }}" f"QTabBar::tab:selected {{ background-color: {selected_bg}; color: {active_ink};" @@ -2174,7 +2176,7 @@ def paint_chrome_colours(self) -> None: f"QToolButton#tab-close-button:hover, QToolButton#tab-close-button:pressed {{" f" background: {hover_bg}; color: {close_hover}; }}" ) - self.tabs.set_colours(QColor(underline_hex), QColor(active_ink)) + self.tabs.set_colours(QColor(underline_hex), QColor(active_ink), QColor(inactive_ink)) sep_hex = self.palette().color(QPalette.ColorRole.Mid).name() self.navigation.setStyleSheet( scheme.styles.generate_frame_style() @@ -2299,6 +2301,7 @@ def present_alone(self) -> None: def present_panes(self) -> None: """Draw both sidebars from the one layout and place them; the thread's sidebar is presented only while a conversation is open.""" + self.tabs.sync_strip_width(self.tab_strip.viewport().width()) self._bind_thread_pane() self.present_alone() for side in self.chrome.sidebars: diff --git a/tests/model/test_android_perf_ux_arrivals.py b/tests/model/test_android_perf_ux_arrivals.py index f1eb6448d..0aa9b97ce 100644 --- a/tests/model/test_android_perf_ux_arrivals.py +++ b/tests/model/test_android_perf_ux_arrivals.py @@ -2919,3 +2919,225 @@ def create_row(self, key: str): assert [group.child(i).key for i in range(10)] == [f"c-{i}" for i in range(9, -1, -1)] assert inserts == 1 and removes == 1, f"expected 1 bulk remove+insert, got {removes}/{inserts}" tree2.close() + + +def test_invalidate_row_height_and_arrival_clip_and_link_noop_and_apply_measured_rows(monkeypatch): + """Regression suite for Android glitchy rendering and parallel-path overdraw: + 1. `VirtualRowCanvas.invalidate_row_height` keeps valid `_heights[row]` until `do_layout()`, + so a `paintEvent` firing before `_viewport_update_timer` never collapses a row to 0 px. + 2. `HistoryRowDelegate.paint_row` clips a non-final arriving row (`offset_y > 0`) to its + own layout slot so it never draws pixels over the sibling row underneath it. + 3. `HistoryRowDelegate.link` is a no-op when `LinkContext` is unchanged (preventing parallel + `acquire_links` from flashing an already-loaded conversation), while `restyle()` still updates. + 4. `VirtualRowCanvas.apply_measured_rows` updates heights inside `holding_position()` so a + growing row above the viewport compensates scroll_y with zero visual jump. + """ + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + QApplication.instance() or QApplication([]) + from dataclasses import dataclass + from PySide6.QtCore import QRect, QSize + from PySide6.QtGui import QColor, QFont, QImage, QPainter, QRegion + from toad.arrivals import ViewportArrivalState + from toad.client.line_blocks import Body + from toad.markdown_links import LinkContext + from toad.qt.history import HistoryRowDelegate, RenderedRow, RowPictures + from toad.qt.lines import DiffSettings, QtLineRenderer + from toad.qt.virtual_scroll import VirtualRowCanvas + from agent_comms.messaging.display_references import ProjectReferences + + @dataclass(frozen=True) + class _Frag: + key: tuple + shown: int = 0 + revision: int = 0 + has_blocks: bool = True + clipboard_text: str = "hello world" + line_blocks: tuple = (Body("hello world"),) + header_blocks: int = 0 + pinned_dividers: tuple = () + + renderer = QtLineRenderer( + current_scheme(os.environ), + LinkContext(Path("."), ProjectReferences()), + DiffSettings(), + ) + delegate = HistoryRowDelegate(renderer, RowPictures(1024 * 1024), object()) + delegate.preparing = False + canvas = VirtualRowCanvas(delegate) + canvas.resize(412, 600) + frags = (_Frag(("m", 0)), _Frag(("m", 1)), _Frag(("m", 2))) + canvas.model_rows.show(frags) + canvas.execute_layout() + before_heights = list(canvas._heights) + before_offsets = list(canvas._offsets) + assert all(h > 0 for h in before_heights) + + # 1. Invalidating row 0 defers re-measurement until do_layout(); mid-frame offsets stay intact. + canvas.invalidate_row_height(0) + assert canvas._heights == before_heights + canvas._ensure_offsets() + assert canvas._offsets == before_offsets + assert 0 in canvas._dirty_heights + canvas.execute_layout() + assert not canvas._dirty_heights + assert canvas._heights[0] > 0 + + # 2. Arriving non-final row with offset_y=+20 is clipped strictly inside its own rect. + font = canvas.font() + width = canvas.viewport_width() or 412 + key0 = delegate.fragment_key(frags[0], font, width) + delegate._prepared[key0] = RenderedRow( + "