diff --git a/src/toad/client/platform.py b/src/toad/client/platform.py index e3bc20b4f..fcbb826e9 100644 --- a/src/toad/client/platform.py +++ b/src/toad/client/platform.py @@ -80,6 +80,7 @@ class Platform(DeclaredFamily, affix="Platform"): system: ClassVar[str] key: ClassVar[OS] application_name: ClassVar[str] = "Toad" + auto_focus_composer: ClassVar[bool] = True @classmethod def select[V](cls, matrix: Mapping[OS, V]) -> V | None: @@ -114,6 +115,7 @@ def desktop(cls) -> DesktopService: class AndroidPlatform(Platform): system = "Android" key = "android" + auto_focus_composer = False @classmethod def open_window(cls, window) -> None: diff --git a/src/toad/qt/composer.py b/src/toad/qt/composer.py index 0241efd66..7659eb25b 100644 --- a/src/toad/qt/composer.py +++ b/src/toad/qt/composer.py @@ -45,6 +45,7 @@ PromptSettingEffects, SlashCommandOffer, ) +from toad.client import platform as toad_platform from toad.client.condensed_path import home_relative from toad.key_modes import Standard, VimInsert from pyqt_reactive.protocols.widget_adapters import PyQtWidgetMeta @@ -209,11 +210,15 @@ def __init__(self, composer: Composer) -> None: # Android soft-keyboard wiring: without these the tap registers but the IME # never raises, so the user sees a composer they can't type into. Desktop Qt # raises the OS keyboard implicitly on focus; Android Qt doesn't — the editor - # has to opt in explicitly. Three pieces: (1) StrongFocus so a tap can take - # keyboard focus, (2) WA_InputMethodEnabled so the IME considers the widget, - # (3) mousePressEvent explicitly requests the IME show on tap (focusInEvent - # alone fires too early on Android, before the window is composited). - self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) + # has to opt in explicitly. Three pieces: (1) ClickFocus on Android (StrongFocus + # on desktop) so a tap takes keyboard focus without QStackedWidget tab switches + # auto-selecting the input box, (2) WA_InputMethodEnabled so the IME considers + # the widget, (3) mousePressEvent/MouseFocusReason explicitly requests IME show. + self.setFocusPolicy( + Qt.FocusPolicy.StrongFocus + if toad_platform.host.auto_focus_composer + else Qt.FocusPolicy.ClickFocus + ) self.setAttribute(Qt.WidgetAttribute.WA_InputMethodEnabled, True) self.follow_key_mode() @@ -260,9 +265,10 @@ def mousePressEvent(self, event) -> None: def focusInEvent(self, event) -> None: super().focusInEvent(event) self.composer.focus_changed(True) - # Same defer as mousePressEvent — focusInEvent also runs inside Qt's - # event-dispatch path on Android. - QTimer.singleShot(0, self._show_ime_if_hidden) + # Only raise Android's soft keyboard on an explicit tap/click (MouseFocusReason), + # never on implicit focus transfers when switching tabs or reactivating the window. + if event.reason() == Qt.FocusReason.MouseFocusReason: + QTimer.singleShot(0, self._show_ime_if_hidden) def event(self, event) -> bool: """A key a priority action answers is the action's, not the text control's: Enter diff --git a/src/toad/qt/conversation.py b/src/toad/qt/conversation.py index 60bcbf647..707ea16f9 100644 --- a/src/toad/qt/conversation.py +++ b/src/toad/qt/conversation.py @@ -67,26 +67,33 @@ from toad.turn_presentation import TurnPresentation from toad.live_output import LiveOutput from toad.view_actions import ViewAction +from toad.client import platform as toad_platform from toad.transcript_scope import TranscriptScope, TranscriptView from toad.qt.workspace_frame import QtWorkspaceHosted class ComposerPlaceholder(QWidget): """A view's composer until it is built (`QtConversation.reserve_composer`): as tall as - that kind's composer last was, so nothing moves when it arrives. A tap or the focus on - it builds the composer at once and hands it the focus.""" + that kind's composer last was, so nothing moves when it arrives. A tap on it builds the + composer at once and hands it focus; on Android (`auto_focus_composer = False`), implicit + focus transfers during tab switches never mount or raise the keyboard.""" def __init__(self, view: QtConversation, height: int) -> None: super().__init__() self.view = view self.setFixedHeight(height) - self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) + self.setFocusPolicy( + Qt.FocusPolicy.StrongFocus + if toad_platform.host.auto_focus_composer + else Qt.FocusPolicy.ClickFocus + ) def mousePressEvent(self, event) -> None: # type: ignore[override] self.view.mount_composer(focus=True) def focusInEvent(self, event) -> None: # type: ignore[override] - self.view.mount_composer(focus=True) + if toad_platform.host.auto_focus_composer or event.reason() == Qt.FocusReason.MouseFocusReason: + self.view.mount_composer(focus=True) class QtConversation( @@ -251,13 +258,14 @@ def mount_composer(self, focus: bool = False) -> None: mounted(composer) self.flush_composer_applies(composer) if focus: - composer.editor.setFocus() + composer.editor.setFocus(Qt.FocusReason.MouseFocusReason) QTimer.singleShot(0, partial(self.remember_composer_height, composer)) def release_pooled_composer(self, composer: Composer) -> ComposerDraft: """Freeze this tab's draft and return `composer` to the workspace pool without destroying its widget tree. Parks it hidden under `self.app` so Android never sees a parentless top-level window.""" + composer.editor.clearFocus() draft = composer.capture_composer_draft() spec = self._composer_slot_spec if spec is not None and shiboken6.isValid(self) and shiboken6.isValid(composer): diff --git a/src/toad/qt/name_wave.py b/src/toad/qt/name_wave.py index 23a817c70..57b755b58 100644 --- a/src/toad/qt/name_wave.py +++ b/src/toad/qt/name_wave.py @@ -11,7 +11,7 @@ from math import ceil from PySide6.QtCore import QEvent, QPointF, QRect, QSize, Qt -from PySide6.QtGui import QColor, QFont, QFontMetrics, QImage, QPainter, QPixmap, QTextCharFormat, QTextLayout +from PySide6.QtGui import QColor, QCursor, 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 @@ -388,7 +388,8 @@ class QtTabMarquee(TitleMarquee): def __init__(self, bar: QtSessionTabBar) -> None: self.bar = bar self.animation = None - self._painted_offsets: dict[str, int] = {} + self.painted_offsets: dict[object, float] = {} + self._painted_px: dict[object, int] = {} @property def animation_visible(self) -> bool: @@ -398,21 +399,23 @@ def marquee_running(self) -> bool: return self.animation is not None def start_marquee(self) -> None: - self._painted_offsets.clear() + self.painted_offsets.clear() + self._painted_px.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() + self.painted_offsets.clear() + self._painted_px.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) + """Compute marquee offsets once per tick and repaint only overflowing tabs that moved.""" + self.bar._repaint_marquee_tabs(self.painted_offsets, self._painted_px) class QtSessionTabBar(QtWaveBandCache, TearOffTabBar): @@ -638,23 +641,27 @@ def _sync_marquee(self) -> None: 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: + def _repaint_marquee_tabs(self, offsets: dict[object, float], painted_px: dict[object, int]) -> None: any_overflow = False + elapsed = self.marquee.marquee_elapsed() + effect = self.marquee.marquee_effect 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()) + bold = (index == self.currentIndex()) or (wave is not None and wave.animation is not None) 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 + offset = effect.offset(elapsed, full_w, rect.width()) + px = round(offset) + key = index if mode is None else mode + offsets[key] = offset + if painted_px.get(key) != px: + painted_px[key] = px self.update(self.tabRect(index)) if not any_overflow: self.marquee.follow_overflow(False) @@ -667,22 +674,17 @@ def wave_span(self, wave: QtTabWave) -> tuple[int, int] | None: _rect, shown = self._cached_title(index) 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: + def _tab_chrome_image(self, index: int, tab_rect: QRect, chrome_key: tuple, dpr: float) -> QImage: """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(), - option.state.value, - option.position.value, - option.selectedPosition.value, - dpr, - ) - cached = self._tab_chrome.get(key) + image instead of running Fusion's QSS `drawControl(CE_TabBarTab)` or touching Python + `QStyle.StateFlag` enums on every frame.""" + cached = self._tab_chrome.get(chrome_key) if cached is not None: return cached if len(self._tab_chrome) >= 32: self._tab_chrome.clear() + option = QStyleOptionTab() + self.initStyleOption(option, index) image = QImage( max(1, round(tab_rect.width() * dpr)), max(1, round(tab_rect.height() * dpr)), @@ -690,41 +692,71 @@ def _tab_chrome_image(self, index: int, tab_rect: QRect, option: QStyleOptionTab ) image.setDevicePixelRatio(dpr) image.fill(Qt.GlobalColor.transparent) - opt = QStyleOptionTab(option) - opt.text = "" - opt.rect = QRect(0, 0, tab_rect.width(), tab_rect.height()) + option.text = "" + option.rect = QRect(0, 0, tab_rect.width(), tab_rect.height()) drawing = QPainter(image) - self.style().drawControl(QStyle.ControlElement.CE_TabBarTab, opt, drawing, self) + self.style().drawControl(QStyle.ControlElement.CE_TabBarTab, option, drawing, self) drawing.end() - self._tab_chrome[key] = image + self._tab_chrome[chrome_key] = image return image def paintEvent(self, event) -> None: # type: ignore[override] painter = QStylePainter(self) dpr = self.devicePixelRatioF() + event_rect = event.rect() + count = self.count() + current_index = self.currentIndex() + hover_index = self.tabAt(self.mapFromGlobal(QCursor.pos())) if self.underMouse() else -1 + shown_titles = self._shown_titles + tab_chrome = self._tab_chrome + lines = self.lines + banded = self._banded + waves = self.waves + painted_offsets = self.marquee.painted_offsets + gap = self.marquee.marquee_effect.gap + pad_cells = self.padding_cells any_overflow = False - for index in range(self.count()): + for index in range(count): tab_rect = self.tabRect(index) - if not tab_rect.intersects(event.rect()): + if not tab_rect.intersects(event_rect): # A wave or marquee repaints its own tab: untouched tabs skip all layout work. continue - option, rect, shown = self.shown_title(index) - chrome = self._tab_chrome_image(index, tab_rect, option, dpr) + text = self.tabText(index) + tab_w = tab_rect.width() + title_hit = shown_titles.get((index, text, tab_w)) + if title_hit is None: + title_hit = self._cached_title(index) + rect, shown = title_hit + selected = index == current_index + hovered = index == hover_index + pos_tag = 0 if count == 1 else (1 if index == 0 else (2 if index == count - 1 else 3)) + adj_selected = 1 if index + 1 == current_index else (2 if index - 1 == current_index else 0) + chrome_key = (tab_w, tab_rect.height(), selected, hovered, pos_tag, adj_selected, dpr) + chrome = tab_chrome.get(chrome_key) + if chrome is None: + chrome = self._tab_chrome_image(index, tab_rect, chrome_key, dpr) painter.drawImage(tab_rect.topLeft(), chrome) 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) + mode = self.tabData(index) + wave = waves.get(mode) + waving = wave is not None and wave.animation is not None + bold = waving or selected + layout = lines.get((shown, bold)) + if layout is None: + layout = self.title_line(shown, bold=bold) 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)), - ) + span = wave.painted_span + if span is None: + span = self.band_cells(wave.wave_frame(), len(shown) + 2 * pad_cells) + length = len(shown) + s = min(length, max(0, span[0] - pad_cells)) + e = min(length, max(0, span[1] - pad_cells)) + if s < e: + hit = banded.get((id(layout), s, e)) + drawn = hit[1] if hit is not None and hit[0] is layout else self.baked_band_layout(layout, (s, e)) + else: + drawn = layout else: drawn = layout line = drawn.lineAt(0) @@ -735,16 +767,16 @@ def paintEvent(self, event) -> None: # type: ignore[override] painter.setClipRect(rect) if full_w > rect.width() + 0.5: any_overflow = True - offset = self.marquee.marquee_offset(full_w, rect.width()) + offset = painted_offsets.get(index if mode is None else mode, 0.0) x = rect.left() - offset drawn.draw(painter, QPointF(x, top)) - second_x = x + full_w + self.marquee.marquee_effect.gap + second_x = x + full_w + 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(): + if any_overflow and self.marquee.animation is None: self.marquee.follow_overflow(True) def title_line(self, shown: str, *, bold: bool) -> QTextLayout: diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index 71e603681..e3e2d2c19 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -99,6 +99,7 @@ from toad.client.history import WireSource, WireView from toad.client.history_entry import HistorySessionEntry from toad.application_lifetime import ApplicationStart +from toad.client import platform as toad_platform from toad.client.platform import host from toad.client.line_blocks import MutedRole from toad.qt.banner import Banner @@ -1655,9 +1656,14 @@ def prepare(self, mode: str) -> Page: def select(self, mode: str, visited: Callable[[CommsTab], object]) -> None: if (menu := QtMenu.of(self.app)) is not None and menu.isVisible(): menu.hide() + if not toad_platform.host.auto_focus_composer: + self.app.clear_focus() + QGuiApplication.inputMethod().hide() page = self.prepare(mode) self.pages.setCurrentWidget(page) page.shown(self.app, visited) + if not toad_platform.host.auto_focus_composer: + self.app.clear_focus() def external_transcript_changed(self) -> None: """Every open view reads its CLI items, shown or parked, as Textual's screens do: a @@ -1701,6 +1707,8 @@ def swap_page(self, old: SessionScope, new: SessionScope) -> None: self.views[mode] = new if was_current: self.pages.setCurrentWidget(new) + if not toad_platform.host.auto_focus_composer: + self.app.clear_focus() old.deleteLater() diff --git a/tests/model/test_android_perf_ux_arrivals.py b/tests/model/test_android_perf_ux_arrivals.py index 0aa9b97ce..a6f430a04 100644 --- a/tests/model/test_android_perf_ux_arrivals.py +++ b/tests/model/test_android_perf_ux_arrivals.py @@ -3141,3 +3141,54 @@ def show_failure(self, msg: str) -> None: finally: search.close() host.close() + + +def test_android_tab_switch_does_not_autofocus_composer_or_raise_ime(monkeypatch) -> None: + """On AndroidPlatform (`auto_focus_composer = False`), ComposerPlaceholder and ComposerEditor + use ClickFocus and only mount/raise the IME on an explicit tap (MouseFocusReason), never on + implicit QStackedWidget focus transfers during tab switches.""" + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + app = QApplication.instance() or QApplication([]) + from types import SimpleNamespace + from PySide6.QtCore import Qt + from PySide6.QtGui import QFocusEvent + from toad.client import platform as toad_platform + from toad.client.platform import AndroidPlatform, LinuxPlatform + from toad.qt.composer import ComposerEditor + from toad.qt.conversation import ComposerPlaceholder + + assert LinuxPlatform.auto_focus_composer is True + assert AndroidPlatform.auto_focus_composer is False + monkeypatch.setattr(toad_platform, "host", AndroidPlatform) + + mounted: list[bool] = [] + view = SimpleNamespace(mount_composer=lambda *, focus=False: mounted.append(focus)) + placeholder = ComposerPlaceholder(view, 48) + try: + assert placeholder.focusPolicy() == Qt.FocusPolicy.ClickFocus + # Implicit focus transfer (OtherFocusReason) must NOT mount with focus. + placeholder.focusInEvent(QFocusEvent(QFocusEvent.Type.FocusIn, Qt.FocusReason.OtherFocusReason)) + assert mounted == [] + # Explicit tap (MouseFocusReason) DOES mount with focus. + placeholder.focusInEvent(QFocusEvent(QFocusEvent.Type.FocusIn, Qt.FocusReason.MouseFocusReason)) + assert mounted == [True] + finally: + placeholder.close() + + ime_shown: list[bool] = [] + monkeypatch.setattr(ComposerEditor, "_show_ime_if_hidden", staticmethod(lambda: ime_shown.append(True))) + fake_composer = SimpleNamespace( + settings=SimpleNamespace(ui=SimpleNamespace(key_mode=SimpleNamespace(modal=False))), + focus_changed=lambda _focused: None, + ) + editor = ComposerEditor(fake_composer) + try: + assert editor.focusPolicy() == Qt.FocusPolicy.ClickFocus + editor.focusInEvent(QFocusEvent(QFocusEvent.Type.FocusIn, Qt.FocusReason.OtherFocusReason)) + app.processEvents() + assert ime_shown == [] + editor.focusInEvent(QFocusEvent(QFocusEvent.Type.FocusIn, Qt.FocusReason.MouseFocusReason)) + app.processEvents() + assert ime_shown == [True] + finally: + editor.close() diff --git a/tools/frame_work_baseline.json b/tools/frame_work_baseline.json index c0e5273e6..b6ff370d6 100644 --- a/tools/frame_work_baseline.json +++ b/tools/frame_work_baseline.json @@ -1,3 +1,3 @@ { - "name_wave.QtNameWaveDelegate.paint": 37.7 + "name_wave.QtNameWaveDelegate.paint": 26.9 }