diff --git a/comic_translate_desktop/ui/api_config_page.py b/comic_translate_desktop/ui/api_config_page.py index 7bbca74..b3dca06 100644 --- a/comic_translate_desktop/ui/api_config_page.py +++ b/comic_translate_desktop/ui/api_config_page.py @@ -27,7 +27,7 @@ from comic_translate_core.languages import SOURCE_LANGUAGES from .advanced_config import AdvancedConfigSection from .manga_components import PanelHeading -from .motion import set_reduced_motion +from .motion import install_tab_motion, set_reduced_motion from .theme import apply_theme @@ -49,6 +49,7 @@ def __init__(self, config: dict, parent=None): self._sections = QTabWidget() self._sections.setDocumentMode(True) self._sections.setAccessibleName(tr('设置分类')) + install_tab_motion(self._sections) body_layout.addWidget(self._sections) outer.addWidget(body, 1) root = self._add_section(tr('01 翻译服务'), tr('连接你的翻译服务'), tr('配置接口、翻译方式和输出水印,保存后将在下一次任务生效。')) diff --git a/comic_translate_desktop/ui/editor_page.py b/comic_translate_desktop/ui/editor_page.py index 3f3e3f0..c5a19d8 100644 --- a/comic_translate_desktop/ui/editor_page.py +++ b/comic_translate_desktop/ui/editor_page.py @@ -5,7 +5,7 @@ from collections import OrderedDict from copy import deepcopy from pathlib import Path -from PySide6.QtCore import Qt, QRect, QSize, QSettings, QTimer, QEvent, QPoint +from PySide6.QtCore import Qt, QRect, QSize, QSettings, QTimer, QEvent, QPoint, QVariantAnimation from PySide6.QtGui import QColor, QFont, QPainter, QPixmap, QIcon, QImageReader, QShortcut, QKeySequence from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QFrame, QLabel, QListWidget, QListWidgetItem, QPushButton, QScrollArea, QSplitter, QComboBox, QSpinBox, QDoubleSpinBox, QPlainTextEdit, QFileDialog, QMessageBox, QSizePolicy, QTabWidget, QCheckBox, QToolButton, QApplication, QLineEdit, QTextEdit, QAbstractSpinBox, QAbstractButton, QAbstractItemView, QStyledItemDelegate, QStyle) from ..config import load_ai_config, MAIN_DIR @@ -26,6 +26,16 @@ from .thumbnail_loader import ThumbnailLoader from .theme import color, set_themed_icon, ui_font from .manga_components import PanelHeading +from .motion import ( + STANDARD, + fade_in, + fade_out, + install_list_motion, + install_tab_motion, + play_reveal_overlay, + play_slide_overlay, + reduced_motion, +) from .searchable_combo import SearchableFontCombo from .favorite_fonts import FavoriteFontBar from .tool_flow import ToolFlowLayout @@ -335,7 +345,7 @@ def _build_ui(self): self._zoom.setInsertPolicy(QComboBox.NoInsert) self._zoom.lineEdit().setReadOnly(True) self._zoom.lineEdit().setAlignment(Qt.AlignCenter) - self._zoom.setMinimumWidth(88) + self._zoom.setMinimumWidth(116) self._zoom.setToolTip(tr('缩放:Alt+滚轮以光标为中心,空格+拖动平移;Ctrl+0/1/2 适应页面/100%/适应宽度')) toolbar.addWidget(self._zoom) self._zoom_in_btn = QPushButton() @@ -421,6 +431,7 @@ def _build_ui(self): self.page_list.setTextElideMode(Qt.ElideMiddle) self.page_list.currentItemChanged.connect(self._select_page) self.page_list.itemSelectionChanged.connect(self._update_repair_controls) + install_list_motion(self.page_list) left.addWidget(self.page_list, 1) sidebar_footer = QFrame() sidebar_footer.setObjectName('sidebarFooter') @@ -470,7 +481,7 @@ def _build_ui(self): self._zoom_hud_timer = QTimer(self) self._zoom_hud_timer.setSingleShot(True) self._zoom_hud_timer.setInterval(900) - self._zoom_hud_timer.timeout.connect(self._zoom_hud.hide) + self._zoom_hud_timer.timeout.connect(lambda: fade_out(self._zoom_hud, 160)) canvas_tools_frame = QFrame() canvas_tools_frame.setObjectName('canvasToolBar') @@ -600,8 +611,10 @@ def _build_ui(self): self.block_list.setMouseTracking(True) self.block_list.setItemDelegate(_BlockItemDelegate(self.block_list)) self.block_list.currentRowChanged.connect(self._load_properties) + install_list_motion(self.block_list) self._inspector_tabs = QTabWidget() self._inspector_tabs.setDocumentMode(True) + install_tab_motion(self._inspector_tabs) self._inspector_splitter = QSplitter(Qt.Vertical) self._inspector_splitter.setObjectName('inspectorSplitter') self._inspector_splitter.setChildrenCollapsible(False) @@ -634,6 +647,8 @@ def _build_ui(self): self._source_text.setReadOnly(True) self._source_text.setFixedHeight(92) self._source_text.setFont(ui_font(japanese=True)) + self._source_anim = None + self._source_anim_gen = 0 text_props.addWidget(self._source_text) self._source_toggle.toggled.connect(self._toggle_source_text) target_label = QLabel(tr('译文')) @@ -963,7 +978,10 @@ def _sync_zoom_display(self, value): self._zoom_hud.setText(text) self._zoom_hud.adjustSize() self._place_zoom_hud() + was_visible = self._zoom_hud.isVisible() self._zoom_hud.show() + if not was_visible: + fade_in(self._zoom_hud, 110) self._zoom_hud.raise_() self._zoom_hud_timer.start() @@ -1013,7 +1031,18 @@ def _apply_panel_layout(self): button.blockSignals(True) button.setChecked(effective[index]) button.blockSignals(False) - panel.setVisible(effective[index]) + was_visible = panel.isVisible() + want_visible = effective[index] + if self.isVisible() and was_visible != want_visible: + edge = 'left' if index == 0 else 'right' + if want_visible: + panel.setVisible(True) + play_reveal_overlay(panel, edge=edge, duration=190) + else: + play_slide_overlay(panel, edge=edge, duration=160) + panel.setVisible(False) + else: + panel.setVisible(want_visible) button.setToolTip(tr('窗口较窄时暂时收起;展开此栏会让出另一个侧栏的位置。') if self._desired_panels[index] and not effective[index] and not focused else '') if not compact and self._was_compact and not focused and self._wide_splitter_state is not None: @@ -1024,12 +1053,28 @@ def _apply_panel_layout(self): def _toggle_canvas_focus(self, focused): if focused: self._focus_splitter_state = self.splitter.saveState() - self._apply_panel_layout() - if not focused: + self._apply_panel_layout() + else: self.splitter.restoreState(self._focus_splitter_state) self._apply_panel_layout() - for widget in (self._canvas_heading, self._status, self._pages_toggle, self._properties_toggle): - widget.setVisible(not focused) + for widget, edge, slide_hide in ( + (self._canvas_heading, 'top', True), + (self._status, 'bottom', True), + (self._pages_toggle, 'top', False), + (self._properties_toggle, 'top', False), + ): + want_visible = not focused + was_visible = widget.isVisible() + if self.isVisible() and was_visible != want_visible: + if want_visible: + widget.setVisible(True) + play_reveal_overlay(widget, edge=edge, duration=155) + else: + if slide_hide: + play_slide_overlay(widget, edge=edge, duration=135) + widget.setVisible(False) + else: + widget.setVisible(want_visible) self._update_toolbar_labels() def _update_toolbar_labels(self): @@ -1126,7 +1171,56 @@ def _apply_source_layout(self): self._source_toggle.setChecked(expanded) self._source_toggle.blockSignals(False) self._source_toggle.setArrowType(Qt.DownArrow if expanded else Qt.RightArrow) - self._source_text.setVisible(expanded) + if getattr(self, '_source_anim', None) is not None: + self._source_anim.stop() + self._source_anim.deleteLater() + self._source_anim = None + self._source_anim_gen += 1 + gen = self._source_anim_gen + + if not self.isVisible() or reduced_motion(): + self._source_text.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) + self._source_text.setFixedHeight(92 if expanded else 0) + self._source_text.setVisible(expanded) + return + + was_visible = self._source_text.isVisible() + if was_visible == expanded and self._source_text.height() == (92 if expanded else 0): + return + + start_h = self._source_text.height() if was_visible else 0 + end_h = 92 if expanded else 0 + self._source_text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self._source_text.setVisible(True) + self._source_text.setFixedHeight(start_h) + + anim = QVariantAnimation(self) + anim.setDuration(195 if expanded else 160) + anim.setStartValue(float(start_h)) + anim.setEndValue(float(end_h)) + anim.setEasingCurve(STANDARD) + + def _on_val(val): + if gen != self._source_anim_gen: + return + self._source_text.setFixedHeight(max(0, int(round(float(val))))) + + def _on_done(): + if gen != self._source_anim_gen: + return + self._source_anim = None + self._source_text.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) + if expanded: + self._source_text.setFixedHeight(92) + self._source_text.setVisible(True) + else: + self._source_text.setFixedHeight(0) + self._source_text.setVisible(False) + + anim.valueChanged.connect(_on_val) + anim.finished.connect(_on_done) + self._source_anim = anim + anim.start() def _set_editable(self, enabled): restored = 0 <= self._loaded_row < len(self.items) and self.items[self._loaded_row].get('restore_original', False) diff --git a/comic_translate_desktop/ui/error_log_page.py b/comic_translate_desktop/ui/error_log_page.py index cb1d7f2..a335e95 100644 --- a/comic_translate_desktop/ui/error_log_page.py +++ b/comic_translate_desktop/ui/error_log_page.py @@ -18,6 +18,7 @@ from ..ai_diagnosis import AiDiagnosis from .theme import ui_font from .manga_components import PanelHeading +from .motion import install_tab_motion class DiagnosisWorker(QThread): @@ -64,6 +65,7 @@ def __init__(self, diagnostics, parent=None): self._sections.setAccessibleName(tr('诊断工作区')) self._sections.addTab(self._build_prompt_panel(), tr('01 诊断资料')) self._sections.addTab(self._build_ai_panel(), tr('02 AI 对话')) + install_tab_motion(self._sections) content.addWidget(self._sections, 1) content.addWidget(self._file_label) root.addWidget(body, 1) diff --git a/comic_translate_desktop/ui/halftone.py b/comic_translate_desktop/ui/halftone.py index 0bbd855..b74d564 100644 --- a/comic_translate_desktop/ui/halftone.py +++ b/comic_translate_desktop/ui/halftone.py @@ -5,7 +5,7 @@ from math import ceil, hypot, sqrt from PySide6.QtCore import QByteArray, QRectF, Qt -from PySide6.QtGui import QPainter, QPainterPath +from PySide6.QtGui import QPainter, QPainterPath, QPixmap from PySide6.QtSvg import QSvgRenderer from .theme import theme @@ -78,19 +78,37 @@ def _renderer(width, height, compact, mask, profile, direction, dot_color): return QSvgRenderer(QByteArray(halftone_svg(width, height, compact, mask, profile, direction, dot_color))) +@lru_cache(maxsize=96) +def _tone_pixmap(width, height, dpr_tenth, compact, mask, profile, direction, dot_color): + dpr = max(1.0, dpr_tenth / 10.0) + pix = QPixmap(max(1, round(width * dpr)), max(1, round(height * dpr))) + pix.fill(Qt.transparent) + pix.setDevicePixelRatio(dpr) + p = QPainter(pix) + _renderer(width, height, compact, mask, profile, direction, dot_color).render( + p, QRectF(0, 0, width, height) + ) + p.end() + return pix + + def draw_tone(painter, bounds, *, compact=False, mask='linear', profile='section', direction='left'): if bounds.width() <= 0 or bounds.height() <= 0: return palette = theme() - renderer = _renderer(max(1, round(bounds.width())), max(1, round(bounds.height())), - compact, mask, profile, direction, palette['tone']) + w = max(1, round(bounds.width())) + h = max(1, round(bounds.height())) + dev = painter.device() + dpr = dev.devicePixelRatioF() if dev is not None and hasattr(dev, 'devicePixelRatioF') else 1.0 + dpr_tenth = max(10, round(dpr * 10)) + pix = _tone_pixmap(w, h, dpr_tenth, compact, mask, profile, direction, palette['tone']) painter.save() if palette['toneBlend'] == 'multiply': # QWidget 中用 Qt 的对应混合模式实现 SVG 的 mix-blend-mode: multiply。 painter.setCompositionMode(QPainter.CompositionMode_Multiply) else: painter.setOpacity(palette['toneAlpha']) - renderer.render(painter, bounds) + painter.drawPixmap(bounds, pix, QRectF(0, 0, pix.width(), pix.height())) painter.restore() @@ -98,8 +116,8 @@ def draw_corner_tones(painter, bounds, *, compact=False): """Small page-edge accents; keep the central reading area open.""" if bounds.width() < 320 or bounds.height() < 150: return - width = min(192, bounds.width() * .24) - height = min(112, bounds.height() * .28) + width = max(16, round(min(192, bounds.width() * .24) / 8) * 8) + height = max(16, round(min(112, bounds.height() * .28) / 8) * 8) painter.save() painter.setRenderHint(QPainter.Antialiasing) painter.setOpacity(.3 if theme()['toneBlend'] == 'multiply' else 1.0) diff --git a/comic_translate_desktop/ui/main_window.py b/comic_translate_desktop/ui/main_window.py index 0c09e64..cd3fde9 100644 --- a/comic_translate_desktop/ui/main_window.py +++ b/comic_translate_desktop/ui/main_window.py @@ -17,6 +17,7 @@ QTimer, QThread, QUrl, + QVariantAnimation, ) from PySide6.QtGui import ( QDesktopServices, @@ -70,7 +71,20 @@ from .error_log_page import ErrorLogPage from .step_panel import StepPanel from .theme import apply_theme, brand_font, refresh_style, set_themed_icon -from .motion import reduced_motion, set_pulse, set_reduced_motion +from .motion import ( + STANDARD, + SlidingNavUnderline, + StatusShimmerOverlay, + fade_in, + install_list_motion, + install_stack_motion, + install_tab_motion, + play_reveal_overlay, + play_slide_overlay, + reduced_motion, + set_pulse, + set_reduced_motion, +) from .window_chrome import apply_window_chrome, watch_window_chrome from .preview import ImagePreview from .log_panel import LogPanel @@ -170,6 +184,7 @@ def _build_ui(self) -> None: self.status_pill.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) self.status_pill.setMinimumWidth(96) self.status_pill.setMaximumWidth(190) + self._status_shimmer = StatusShimmerOverlay(self.status_pill) pill_layout = QHBoxLayout(self.status_pill) pill_layout.setContentsMargins(8, 4, 10, 4) pill_layout.setSpacing(6) @@ -234,10 +249,12 @@ def _build_ui(self) -> None: self.editor_page = EditorPage() self.tabs.addWidget(self.editor_page) root.addWidget(self.tabs, 1) + install_stack_motion(self.tabs) self._apply_compact_layout() self._nav_auto.clicked.connect(lambda: self.tabs.setCurrentWidget(self.translate_tab)) self._nav_editor.clicked.connect(lambda: self.tabs.setCurrentWidget(self.editor_page)) self._nav_auto.setChecked(True) + self._nav_underline = SlidingNavUnderline(top_bar, [self._nav_auto, self._nav_editor]) self.tabs.currentChanged.connect(self._on_tab_changed) self._add_btn.clicked.connect(self._choose_files) self._folder_btn.clicked.connect(self._choose_folder) @@ -307,6 +324,7 @@ def _build_file_panel(self) -> QWidget: self.file_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.file_list.setAccessibleName(tr('漫画文件队列')) self.file_list.itemSelectionChanged.connect(self._on_file_selection) + install_list_motion(self.file_list) layout.addWidget(self.file_list, 1) buttons = QHBoxLayout() self._remove_btn = QPushButton(tr('移除选中')) @@ -607,6 +625,7 @@ def _build_work_panel(self) -> QWidget: self.result_view = ImagePreview(illustration='studio-editor-v1.png') self.preview_tabs.addTab(self.original_view, tr('原图')) self.preview_tabs.addTab(self.result_view, tr('译图')) + install_tab_motion(self.preview_tabs) self._log_panel = LogPanel(self.diagnostics.log_path) self.log_view = self._log_panel.view self.work_splitter = QSplitter(Qt.Vertical) @@ -894,6 +913,13 @@ def _set_status(self, text: str, state: str = "idle") -> None: self._status_dot.setProperty("state", state) refresh_style(self.status_label) refresh_style(self._status_dot) + active_work = state in ('running', 'warming', 'stopping') + active_prop = 'true' if active_work else 'false' + if self.status_pill.property('active') != active_prop: + self.status_pill.setProperty('active', active_prop) + refresh_style(self.status_pill) + if hasattr(self, '_status_shimmer'): + self._status_shimmer.set_active(active_work) set_pulse(self._status_dot, state in ('running', 'warming')) self.status_label.setAccessibleName(tr(text)) self.status_pill.setToolTip(tr(text)) @@ -1372,32 +1398,39 @@ def _animate_preferences(self, expand: bool) -> None: previous.deleteLater() self._pref_animation = None target = self._pref_target_height() if expand else 0 - duration = 220 if expand else 180 - if reduced_motion() or self.height() < 760: + duration = 230 if expand else 195 + if reduced_motion() or self.height() < 680: # Short windows hide the log and stage focus while the foldout is open; # apply compact visibility first so _pref_target_height sees freed space. self._pref_animating = False self._apply_compact_layout() target = self._pref_target_height() if expand else 0 + container.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) container.setVisible(expand) container.setMinimumHeight(target) container.setMaximumHeight(target) if expand: self._restore_preferences_scroll() return - start = container.maximumHeight() if container.isVisible() else 0 + start = container.height() if container.isVisible() else 0 if start > 10000: start = 0 + container.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) container.setVisible(True) - container.setMinimumHeight(start) - container.setMaximumHeight(start) - animation = QPropertyAnimation(container, b"minimumHeight", self) + if expand: + container.verticalScrollBar().setValue(self._pref_scroll_value) + container.setFixedHeight(start) + + animation = QVariantAnimation(self) animation.setDuration(duration) - animation.setStartValue(start) - animation.setEndValue(target) - animation.setEasingCurve(QEasingCurve.OutCubic) - animation.valueChanged.connect( - lambda value: container.setMaximumHeight(int(value))) + animation.setStartValue(float(start)) + animation.setEndValue(float(target)) + animation.setEasingCurve(STANDARD) + + def _on_val(value) -> None: + container.setFixedHeight(max(0, int(round(float(value))))) + + animation.valueChanged.connect(_on_val) animation.finished.connect( lambda: self._finish_preferences_animation(expand, target)) self._pref_animation = animation @@ -1411,10 +1444,13 @@ def _finish_preferences_animation(self, expand: bool, target: int) -> None: else: target = 0 container = self._pref_container + container.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) container.setMinimumHeight(target) container.setMaximumHeight(target) if expand: - self._restore_preferences_scroll() + bar = container.verticalScrollBar() + if bar.value() != self._pref_scroll_value: + bar.setValue(self._pref_scroll_value) else: container.setVisible(False) self._apply_compact_layout() @@ -1424,7 +1460,16 @@ def _restore_preferences_scroll(self) -> None: 0, lambda: self._pref_container.verticalScrollBar().setValue(self._pref_scroll_value)) def _toggle_log_panel(self, visible: bool) -> None: - self._log_panel.setVisible(visible) + was_visible = self._log_panel.isVisible() + if self.isVisible() and was_visible != visible: + if visible: + self._log_panel.setVisible(True) + play_reveal_overlay(self._log_panel, edge='bottom', duration=185) + else: + play_slide_overlay(self._log_panel, edge='bottom', duration=160) + self._log_panel.setVisible(False) + else: + self._log_panel.setVisible(visible) self._log_toggle.setText(tr('详细日志') if visible else tr('展开日志')) self._log_toggle.setArrowType(Qt.DownArrow if visible else Qt.RightArrow) self._apply_compact_layout() diff --git a/comic_translate_desktop/ui/manga_components.py b/comic_translate_desktop/ui/manga_components.py index 13a6ba6..af84ac2 100644 --- a/comic_translate_desktop/ui/manga_components.py +++ b/comic_translate_desktop/ui/manga_components.py @@ -2,12 +2,13 @@ from __future__ import annotations from ..i18n import tr -from PySide6.QtCore import QRectF, Qt -from PySide6.QtGui import QColor, QFont, QPainter +from PySide6.QtCore import QElapsedTimer, QPointF, QRectF, QTimer, Qt +from PySide6.QtGui import QColor, QFont, QPainter, QPen from PySide6.QtWidgets import QLabel, QSizePolicy, QWidget from .theme import color, ui_font from .halftone import COMPACT_BREAKPOINT, draw_tone +from .motion import reduced_motion def label(parent, text, size, *, weight=QFont.Bold): result = QLabel(tr(text), parent) @@ -67,14 +68,34 @@ def __init__(self, parent=None): self._detail = label(self, tr('添加漫画后,开始自动处理'), 12, weight=QFont.Normal) self._detail.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred) self._detail.setProperty('muted', True) + self._last_key = ('—', tr('等待任务')) + self._pulse_until = 0 + self._clock = QElapsedTimer() + self._clock.start() + self._pulse_timer = QTimer(self) + self._pulse_timer.setInterval(16) + self._pulse_timer.timeout.connect(self._step_pulse) + + def _step_pulse(self): + if int(self._clock.elapsed()) >= self._pulse_until: + self._pulse_until = 0 + self._pulse_timer.stop() + self.update() def set_stage(self, number, title, detail): + key = (str(number), str(title)) + changed = key != self._last_key + self._last_key = key self._number.setText(tr(number)) self._title.setText(tr(title)) self._detail.setText(tr(detail)) self.setToolTip(tr(detail)) self.setAccessibleName(f'{title},{detail}') self._place() + if changed and self.isVisible() and not reduced_motion(): + self._pulse_until = int(self._clock.elapsed()) + 340 + if not self._pulse_timer.isActive(): + self._pulse_timer.start() self.update() def _place(self): @@ -89,6 +110,11 @@ def resizeEvent(self, event): super().resizeEvent(event) self._place() + def hideEvent(self, event): + self._pulse_timer.stop() + self._pulse_until = 0 + super().hideEvent(event) + def paintEvent(self, event): p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) @@ -96,4 +122,14 @@ def paintEvent(self, event): p.setPen(Qt.NoPen) p.setBrush(QColor(color('muted'))) p.drawEllipse(QRectF(1, 4, 26, 26)) + if self._pulse_until > 0 and not reduced_motion(): + rem = self._pulse_until - int(self._clock.elapsed()) + if rem > 0: + t = 1.0 - max(0.0, min(1.0, rem / 340.0)) + ring = QColor(color('ink')) + ring.setAlpha(int(round(145 * ((1.0 - t) ** 2)))) + p.setPen(QPen(ring, 1.3)) + p.setBrush(Qt.NoBrush) + r = 12.0 + 2.5 * t + p.drawEllipse(QPointF(14.0, 17.0), r, r) p.end() diff --git a/comic_translate_desktop/ui/motion.py b/comic_translate_desktop/ui/motion.py index 38b398f..f25596c 100644 --- a/comic_translate_desktop/ui/motion.py +++ b/comic_translate_desktop/ui/motion.py @@ -1,57 +1,1751 @@ -"""Small UI motion helpers that honour the reduced-motion preference.""" +"""60fps monochrome motion primitives inspired by Google AI Studio & Gemini. + +Strictly preserves ComiTrans's Paper White / Night Ink manga palette while +adding responsive Material-style tactile ripples, center-out focus underlines, +gliding navigation/tab indicators, list selection rails, non-blocking overlay +transitions, and monochrome shimmer bars. +""" + from __future__ import annotations -from PySide6.QtCore import QEasingCurve, QPropertyAnimation -from PySide6.QtWidgets import QGraphicsOpacityEffect +import math -_reduced = False -_pulses = {} +from PySide6.QtCore import ( + QAbstractAnimation, + QElapsedTimer, + QEasingCurve, + QEvent, + QObject, + QPoint, + QPointF, + QPropertyAnimation, + QRect, + QRectF, + QSize, + QTimer, + QVariantAnimation, + Qt, +) +from PySide6.QtGui import ( + QColor, + QFont, + QFontMetrics, + QLinearGradient, + QPainter, + QPainterPath, + QPalette, + QPixmap, + QRadialGradient, +) +from PySide6.QtWidgets import ( + QAbstractButton, + QAbstractItemView, + QApplication, + QComboBox, + QDoubleSpinBox, + QFrame, + QGraphicsOpacityEffect, + QLineEdit, + QListWidget, + QPlainTextEdit, + QProgressBar, + QSpinBox, + QSplitter, + QStackedWidget, + QStyle, + QStyledItemDelegate, + QTabBar, + QTabWidget, + QTextEdit, + QWidget, +) +from shiboken6 import isValid +DURATION_FAST = 140 +DURATION_MEDIUM = 210 +DURATION_SLOW = 280 -def set_reduced_motion(value): - global _reduced - _reduced = bool(value) +EMPHASIZED_DECELERATE = QEasingCurve(QEasingCurve.OutCubic) +STANDARD = QEasingCurve(QEasingCurve.InOutCubic) -def reduced_motion(): - return _reduced +_REDUCED_MOTION = False +_MOTION_CONTROLLER = None -def fade_in(widget, duration=180): - if widget is None or _reduced: - return - effect = widget.graphicsEffect() - if not isinstance(effect, QGraphicsOpacityEffect): - effect = QGraphicsOpacityEffect(widget) - widget.setGraphicsEffect(effect) +def set_reduced_motion(enabled: bool) -> None: + global _REDUCED_MOTION + _REDUCED_MOTION = bool(enabled) + + +def reduced_motion() -> bool: + return _REDUCED_MOTION + + +def _theme_color(name: str) -> QColor: + from .theme import color + + return QColor(color(name)) + + +def _with_alpha(c: QColor, alpha: int) -> QColor: + out = QColor(c) + out.setAlpha(max(0, min(255, int(alpha)))) + return out + + +def _button_is_dark_filled(btn: QAbstractButton) -> bool: + role = str(btn.property('role') or '') + if role == 'primary': + return True + if btn.isCheckable() and btn.isChecked() and role in ('toggle', 'pill', 'mode', 'segment'): + return True + pal_l = btn.palette().color(QPalette.Button).lightness() + ink_l = _theme_color('ink').lightness() + paper_l = _theme_color('paper').lightness() + # Dark button in light mode or bright button in dark mode + return abs(pal_l - ink_l) < abs(pal_l - paper_l) and abs(ink_l - paper_l) > 60 + + +def _stop_existing_fade(widget: QWidget) -> None: + anim = getattr(widget, '_motion_fade_anim', None) + if anim is not None and isValid(anim): + anim.stop() + widget._motion_fade_anim = None + + +def fade_in(widget: QWidget | None, duration: int = 180) -> QPropertyAnimation | None: + """Fade widget cleanly to full opacity and strip the temporary effect afterward.""" + if widget is None or not isValid(widget): + return None + gen = getattr(widget, '_motion_fade_gen', 0) + 1 + widget._motion_fade_gen = gen + _stop_existing_fade(widget) + + if _REDUCED_MOTION or duration <= 0: + if widget.graphicsEffect() is not None: + widget.setGraphicsEffect(None) + return None + + effect = QGraphicsOpacityEffect(widget) + effect.setOpacity(0.0) + widget.setGraphicsEffect(effect) + + anim = QPropertyAnimation(effect, b'opacity', widget) + anim.setDuration(max(50, int(duration))) + anim.setStartValue(0.0) + anim.setEndValue(1.0) + anim.setEasingCurve(EMPHASIZED_DECELERATE) + + def _finish() -> None: + if not isValid(widget): + return + if getattr(widget, '_motion_fade_gen', 0) != gen: + return + if isValid(effect) and widget.graphicsEffect() is effect: + widget.setGraphicsEffect(None) + widget._motion_fade_anim = None + + anim.finished.connect(_finish) + widget._motion_fade_anim = anim + anim.start(QAbstractAnimation.DeleteWhenStopped) + return anim + + +def fade_out( + widget: QWidget | None, + duration: int = 130, + *, + hide_on_finish: bool = True, + on_finished=None, +) -> QPropertyAnimation | None: + """Fade a widget out smoothly without blocking subsequent immediate shows.""" + if widget is None or not isValid(widget): + return None + gen = getattr(widget, '_motion_fade_gen', 0) + 1 + widget._motion_fade_gen = gen + _stop_existing_fade(widget) + + if _REDUCED_MOTION or duration <= 0 or not widget.isVisible(): + if widget.graphicsEffect() is not None: + widget.setGraphicsEffect(None) + if hide_on_finish: + widget.hide() + if callable(on_finished): + on_finished() + return None + + effect = QGraphicsOpacityEffect(widget) effect.setOpacity(1.0) - animation = QPropertyAnimation(effect, b'opacity', widget) - animation.setDuration(duration) - animation.setStartValue(0.2) - animation.setEndValue(1.0) - animation.setEasingCurve(QEasingCurve.OutCubic) - animation.finished.connect(lambda: widget.setGraphicsEffect(None)) - widget._fade_animation = animation - animation.start() + widget.setGraphicsEffect(effect) + anim = QPropertyAnimation(effect, b'opacity', widget) + anim.setDuration(max(50, int(duration))) + anim.setStartValue(1.0) + anim.setEndValue(0.0) + anim.setEasingCurve(STANDARD) -def set_pulse(widget, active, duration=1200): - if widget is None: + def _finish() -> None: + if not isValid(widget): + return + if getattr(widget, '_motion_fade_gen', 0) != gen: + return + if isValid(effect) and widget.graphicsEffect() is effect: + widget.setGraphicsEffect(None) + if hide_on_finish: + widget.hide() + widget._motion_fade_anim = None + if callable(on_finished): + on_finished() + + anim.finished.connect(_finish) + widget._motion_fade_anim = anim + anim.start(QAbstractAnimation.DeleteWhenStopped) + return anim + + +def set_pulse(widget: QWidget | None, active: bool, duration: int = 1200) -> None: + """Gentle monochrome breathing pulse on a small indicator widget.""" + if widget is None or not isValid(widget): return - existing = _pulses.pop(widget, None) - if existing is not None: + existing = getattr(widget, '_motion_pulse_anim', None) + if existing is not None and isValid(existing): existing.stop() - widget.setGraphicsEffect(None) - if not active or _reduced: + widget._motion_pulse_anim = None + + if not active or _REDUCED_MOTION: + if widget.graphicsEffect() is not None: + widget.setGraphicsEffect(None) return + effect = QGraphicsOpacityEffect(widget) + effect.setOpacity(1.0) widget.setGraphicsEffect(effect) - animation = QPropertyAnimation(effect, b'opacity', widget) - animation.setDuration(duration) - animation.setStartValue(1.0) - animation.setKeyValueAt(0.5, 0.35) - animation.setEndValue(1.0) - animation.setLoopCount(-1) - animation.setEasingCurve(QEasingCurve.InOutSine) - _pulses[widget] = animation - animation.start() + + anim = QPropertyAnimation(effect, b'opacity', widget) + anim.setDuration(max(400, int(duration))) + anim.setStartValue(1.0) + anim.setKeyValueAt(0.5, 0.42) + anim.setEndValue(1.0) + anim.setEasingCurve(STANDARD) + anim.setLoopCount(-1) + widget._motion_pulse_anim = anim + anim.start(QAbstractAnimation.DeleteWhenStopped) + + +# --------------------------------------------------------------------------- +# 1. Button Hover State Layer + Ink-Wash Radial Ripple +# --------------------------------------------------------------------------- + +class _RippleOverlay(QWidget): + """Translucent 60fps monochrome hover veil & cursor-centered ink ripple.""" + + _MAX_RIPPLES = 4 + _EXPAND_MS = 280.0 + _FADE_MS = 240.0 + + def __init__(self, target: QAbstractButton) -> None: + super().__init__(target) + self._target = target + self.setAttribute(Qt.WA_TransparentForMouseEvents, True) + self.setGeometry(target.rect()) + + self._hover_alpha = 0.0 + self._hover_target = 0.0 + self._last_ms = 0.0 + self._ripples: list[dict] = [] + + self._clock = QElapsedTimer() + self._clock.start() + + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._step) + self.show() + + def set_hovered(self, hovered: bool) -> None: + if _REDUCED_MOTION: + self._hover_target = 1.0 if hovered else 0.0 + self._hover_alpha = self._hover_target + self.update() + return + self._hover_target = 1.0 if hovered else 0.0 + self._ensure_running() + + def trigger_ripple(self, pos: QPointF) -> None: + if _REDUCED_MOTION or not isValid(self._target): + return + w = max(1, self._target.width()) + h = max(1, self._target.height()) + max_r = max( + math.hypot(pos.x(), pos.y()), + math.hypot(w - pos.x(), pos.y()), + math.hypot(pos.x(), h - pos.y()), + math.hypot(w - pos.x(), h - pos.y()), + ) + now = float(self._clock.elapsed()) + self._ripples.append( + { + 'pos': QPointF(pos), + 'max_r': max_r * 1.08, + 'start_ms': now, + 'release_ms': None, + } + ) + if len(self._ripples) > self._MAX_RIPPLES: + self._ripples = self._ripples[-self._MAX_RIPPLES :] + self._ensure_running() + + def release_ripples(self) -> None: + if not self._ripples: + return + now = float(self._clock.elapsed()) + for rp in self._ripples: + if rp['release_ms'] is None: + rp['release_ms'] = now + self._ensure_running() + + def _ensure_running(self) -> None: + self._last_ms = float(self._clock.elapsed()) + if not self._timer.isActive(): + self._timer.start() + + def _step(self) -> None: + if not isValid(self) or not isValid(self._target): + self._timer.stop() + return + now = float(self._clock.elapsed()) + dt = max(1.0, min(48.0, now - self._last_ms)) + self._last_ms = now + + # Hover spring settle (~110ms) + if abs(self._hover_alpha - self._hover_target) > 0.005: + rate = 1.0 - math.exp(-dt / 42.0) + self._hover_alpha += (self._hover_target - self._hover_alpha) * rate + else: + self._hover_alpha = self._hover_target + + alive: list[dict] = [] + for rp in self._ripples: + age = now - rp['start_ms'] + rel = rp['release_ms'] + if rel is not None and (now - rel) >= self._FADE_MS and age >= self._EXPAND_MS * 0.65: + continue + if age > 2400.0: + continue + alive.append(rp) + self._ripples = alive + + if not self._ripples and abs(self._hover_alpha - self._hover_target) <= 0.005: + self._timer.stop() + self.update() + + def paintEvent(self, event) -> None: + if not isValid(self._target) or (self._hover_alpha <= 0.004 and not self._ripples): + return + r = QRectF(self.rect()) + if r.width() <= 2 or r.height() <= 2: + return + + dark_fill = _button_is_dark_filled(self._target) + base = _theme_color('paper' if dark_fill else 'ink') + role = str(self._target.property('role') or '') + + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + + radius = 8.0 + if role in ('pill', 'toggle'): + radius = min(r.height() / 2.0, 14.0) + elif role == 'nav': + radius = 4.0 + + clip = QPainterPath() + clip.addRoundedRect(r, radius, radius) + p.setClipPath(clip) + + # Hover state veil (Material 3 surface tint, strictly monochrome) + if self._hover_alpha > 0.004: + max_veil = 24 if dark_fill else (10 if role == 'nav' else 14) + p.fillRect(r, _with_alpha(base, int(round(max_veil * self._hover_alpha)))) + + # Ink-wash ripples + now = float(self._clock.elapsed()) + for rp in self._ripples: + age = max(0.0, now - rp['start_ms']) + t = min(1.0, age / self._EXPAND_MS) + eased_r = 1.0 - (1.0 - t) ** 3 + rad = max(2.0, rp['max_r'] * eased_r) + + fade = 1.0 + if rp['release_ms'] is not None: + fade_t = min(1.0, max(0.0, (now - rp['release_ms']) / self._FADE_MS)) + fade = 1.0 - fade_t * fade_t + peak_alpha = 46 if dark_fill else 28 + alpha = int(round(peak_alpha * fade * (0.65 + 0.35 * (1.0 - t)))) + if alpha <= 0: + continue + + pt = rp['pos'] + grad = QRadialGradient(pt, rad) + grad.setColorAt(0.0, _with_alpha(base, alpha)) + grad.setColorAt(0.72, _with_alpha(base, int(alpha * 0.55))) + grad.setColorAt(1.0, _with_alpha(base, 0)) + p.setPen(Qt.NoPen) + p.setBrush(grad) + p.drawEllipse(pt, rad, rad) + p.end() + + +# --------------------------------------------------------------------------- +# 2. Text / Combo / Spin Center-Out Focus Underline +# --------------------------------------------------------------------------- + +class _FocusLineOverlay(QWidget): + """Draws Google AI Studio center-out expanding monochrome focus underline.""" + + def __init__(self, target: QWidget) -> None: + super().__init__(target) + self._target = target + self.setAttribute(Qt.WA_TransparentForMouseEvents, True) + self.setGeometry(target.rect()) + + self._progress = 0.0 + self._target_progress = 0.0 + self._last_ms = 0.0 + + self._clock = QElapsedTimer() + self._clock.start() + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._step) + self.show() + + def set_focused(self, focused: bool) -> None: + self._target_progress = 1.0 if focused else 0.0 + if _REDUCED_MOTION: + self._progress = self._target_progress + self._timer.stop() + self.update() + return + self._last_ms = float(self._clock.elapsed()) + if not self._timer.isActive(): + self._timer.start() + + def _step(self) -> None: + if not isValid(self) or not isValid(self._target): + self._timer.stop() + return + now = float(self._clock.elapsed()) + dt = max(1.0, min(48.0, now - self._last_ms)) + self._last_ms = now + + duration = 175.0 if self._target_progress > self._progress else 130.0 + step = dt / duration + if self._target_progress > self._progress: + self._progress = min(1.0, self._progress + step) + else: + self._progress = max(0.0, self._progress - step) + + if abs(self._progress - self._target_progress) <= 0.004: + self._progress = self._target_progress + self._timer.stop() + self.update() + + def paintEvent(self, event) -> None: + if self._progress <= 0.004 or not isValid(self._target): + return + r = QRectF(self.rect()) + if r.width() <= 6 or r.height() <= 6: + return + # OutCubic curve for snappy AI Studio expand + t = self._progress + eased = 1.0 - (1.0 - t) ** 3 + + usable_w = max(0.0, r.width() - 6.0) + span = usable_w * eased + if span <= 1.0: + return + cx = r.center().x() + x0 = cx - span * 0.5 + y = r.bottom() - 2.0 + + ink = _theme_color('ink') + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + p.setPen(Qt.NoPen) + p.setBrush(_with_alpha(ink, int(round(235 * min(1.0, eased * 1.15))))) + p.drawRoundedRect(QRectF(x0, y, span, 2.0), 1.0, 1.0) + p.end() + + +# --------------------------------------------------------------------------- +# 3. Application-Wide Material Motion Event Filter +# --------------------------------------------------------------------------- + +class _MangaComboItemDelegate(QStyledItemDelegate): + """Monochrome Paper White / Night Ink pill item renderer for combo popups.""" + + def sizeHint(self, option, index) -> QSize: + base = super().sizeHint(option, index) + return QSize(max(base.width() + 24, 72), max(30, base.height() + 10)) + + def paint(self, painter: QPainter, option, index) -> None: + rect = QRectF(option.rect) + if rect.width() <= 4 or rect.height() <= 4: + return + pill = rect.adjusted(2.0, 1.0, -2.0, -1.0) + selected = bool(option.state & QStyle.State_Selected) + hovered = bool(option.state & QStyle.State_MouseOver) + enabled = bool(option.state & QStyle.State_Enabled) + + ink = _theme_color('ink') + paper = _theme_color('paper') + muted = _theme_color('muted') + disabled = _theme_color('disabled') + + painter.save() + painter.setRenderHint(QPainter.Antialiasing, True) + if selected: + painter.setPen(Qt.NoPen) + painter.setBrush(ink) + painter.drawRoundedRect(pill, 6.0, 6.0) + bar_h = min(12.0, max(6.0, pill.height() * 0.44)) + painter.setBrush(paper) + painter.drawRoundedRect( + QRectF(pill.left() + 5.0, pill.center().y() - bar_h * 0.5, 2.5, bar_h), + 1.25, + 1.25, + ) + fg = paper + elif hovered and enabled: + painter.setPen(Qt.NoPen) + painter.setBrush(muted) + painter.drawRoundedRect(pill, 6.0, 6.0) + fg = ink + else: + fg = ink if enabled else disabled + + text = str(index.data(Qt.DisplayRole) or '') + font = QFont(option.font) + if selected: + font.setWeight(QFont.DemiBold) + painter.setFont(font) + painter.setPen(fg) + text_rect = pill.adjusted(12.0, 0.0, -10.0, 0.0) + view = getattr(option, 'widget', None) + wrap = bool(hasattr(view, 'wordWrap') and view.wordWrap()) + if wrap: + painter.drawText(text_rect, Qt.AlignVCenter | Qt.AlignLeft | Qt.TextWordWrap, text) + else: + elided = QFontMetrics(font).elidedText(text, Qt.ElideRight, int(max(12.0, text_rect.width()))) + painter.drawText(text_rect, Qt.AlignVCenter | Qt.AlignLeft | Qt.TextSingleLine, elided) + painter.restore() + + +class _MaterialMotionController(QObject): + """Hooks buttons, inputs & combo popups lazily with zero form boilerplate.""" + + _INPUT_TYPES = (QLineEdit, QSpinBox, QDoubleSpinBox, QPlainTextEdit, QTextEdit) + + def _polish_combo(self, combo: QComboBox) -> None: + if not isValid(combo) or getattr(combo, '_motion_combo_polished', False): + return + combo._motion_combo_polished = True + views: list[QAbstractItemView] = [] + view = combo.view() + if view is not None and isValid(view): + views.append(view) + if combo.isEditable() and combo.completer() is not None: + comp_popup = combo.completer().popup() + if isinstance(comp_popup, QAbstractItemView) and isValid(comp_popup) and comp_popup not in views: + views.append(comp_popup) + + for v in views: + if not isinstance(v.itemDelegate(), _MangaComboItemDelegate): + v.setItemDelegate(_MangaComboItemDelegate(v)) + v.setMouseTracking(True) + popup = v.window() + if popup is not None and isValid(popup) and popup is not combo.window(): + if not popup.isVisible(): + popup.setWindowFlags(popup.windowFlags() | Qt.FramelessWindowHint | Qt.NoDropShadowWindowHint) + popup.setAttribute(Qt.WA_TranslucentBackground, True) + if isinstance(popup, QFrame): + popup.setFrameShape(QFrame.NoFrame) + popup.setStyleSheet('QComboBoxPrivateContainer { background: transparent; border: none; }') + popup._motion_combo_popup = True + popup._motion_combo_owner = combo + + def _stop_popup_anims(self, popup: QWidget) -> None: + for attr in ('_motion_popup_op_anim', '_motion_popup_pos_anim'): + anim = getattr(popup, attr, None) + if anim is not None and isValid(anim): + anim.stop() + setattr(popup, attr, None) + + def _animate_combo_popup(self, popup: QWidget) -> None: + if not isValid(popup): + return + self._stop_popup_anims(popup) + target_pos = popup.pos() + owner = getattr(popup, '_motion_combo_owner', None) + opening_above = bool( + owner is not None and isValid(owner) and target_pos.y() < owner.mapToGlobal(QPoint(0, 0)).y() + ) + gap = -4 if opening_above else 4 + final_pos = QPoint(target_pos.x(), max(0, target_pos.y() + gap)) + if _REDUCED_MOTION: + popup.move(final_pos) + popup.setWindowOpacity(1.0) + return + dy = 6 if opening_above else -6 + start_pos = QPoint(final_pos.x(), max(0, final_pos.y() + dy)) + popup.move(start_pos) + popup.setWindowOpacity(0.0) + + op_anim = QPropertyAnimation(popup, b'windowOpacity', popup) + op_anim.setDuration(130) + op_anim.setStartValue(0.0) + op_anim.setEndValue(1.0) + op_anim.setEasingCurve(QEasingCurve.OutCubic) + + pos_anim = QPropertyAnimation(popup, b'pos', popup) + pos_anim.setDuration(145) + pos_anim.setStartValue(start_pos) + pos_anim.setEndValue(final_pos) + pos_anim.setEasingCurve(EMPHASIZED_DECELERATE) + + popup._motion_popup_op_anim = op_anim + popup._motion_popup_pos_anim = pos_anim + op_anim.start(QAbstractAnimation.DeleteWhenStopped) + pos_anim.start(QAbstractAnimation.DeleteWhenStopped) + + def _overlay_for_button(self, btn: QAbstractButton, create: bool = True) -> _RippleOverlay | None: + if not isValid(btn) or btn.property('noRipple') is True: + return None + # Skip internal QScrollBar/QTabBar tiny sub-buttons + if btn.objectName().startswith('qt_') or btn.width() < 12 or btn.height() < 12: + return None + ov = getattr(btn, '_motion_ripple_overlay', None) + if ov is not None and isValid(ov): + if ov.geometry() != btn.rect(): + ov.setGeometry(btn.rect()) + return ov + if not create: + return None + ov = _RippleOverlay(btn) + btn._motion_ripple_overlay = ov + return ov + + def _overlay_for_input(self, inp: QWidget, create: bool = True) -> _FocusLineOverlay | None: + if not isValid(inp) or inp.property('noFocusLine') is True: + return None + if isinstance(inp, (QPlainTextEdit, QTextEdit)) and inp.isReadOnly(): + return None + # Avoid duplicate underline on embedded QComboBox/SpinBox inner QLineEdit + if isinstance(inp, QLineEdit) and isinstance(inp.parentWidget(), (QComboBox, QSpinBox, QDoubleSpinBox)): + return None + ov = getattr(inp, '_motion_focus_overlay', None) + if ov is not None and isValid(ov): + if ov.geometry() != inp.rect(): + ov.setGeometry(inp.rect()) + return ov + if not create: + return None + ov = _FocusLineOverlay(inp) + inp._motion_focus_overlay = ov + return ov + + def eventFilter(self, watched: QObject | None, event: QEvent) -> bool: + if watched is None or not isValid(watched): + return False + etype = event.type() + + if isinstance(watched, QComboBox): + if not getattr(watched, '_motion_combo_polished', False) and etype in ( + QEvent.Show, + QEvent.Enter, + QEvent.MouseButtonPress, + QEvent.FocusIn, + QEvent.Paint, + ): + self._polish_combo(watched) + elif isinstance(watched, QWidget) and ( + getattr(watched, '_motion_combo_popup', False) + or watched.metaObject().className() == 'QComboBoxPrivateContainer' + ): + if etype == QEvent.Show: + self._animate_combo_popup(watched) + elif etype == QEvent.Hide: + self._stop_popup_anims(watched) + watched.setWindowOpacity(1.0) + elif isinstance(watched, QAbstractButton): + if etype == QEvent.Enter: + if watched.isEnabled(): + ov = self._overlay_for_button(watched, create=True) + if ov is not None: + ov.set_hovered(True) + elif etype == QEvent.Leave: + ov = self._overlay_for_button(watched, create=False) + if ov is not None: + ov.set_hovered(False) + ov.release_ripples() + elif etype == QEvent.MouseButtonPress: + if watched.isEnabled(): + ov = self._overlay_for_button(watched, create=True) + if ov is not None: + ov.trigger_ripple(QPointF(event.position())) + elif etype == QEvent.MouseButtonRelease: + ov = self._overlay_for_button(watched, create=False) + if ov is not None: + ov.release_ripples() + elif etype == QEvent.Resize: + ov = self._overlay_for_button(watched, create=False) + if ov is not None: + ov.setGeometry(watched.rect()) + + elif isinstance(watched, self._INPUT_TYPES): + if etype == QEvent.FocusIn: + if watched.isEnabled(): + ov = self._overlay_for_input(watched, create=True) + if ov is not None: + ov.set_focused(True) + elif etype == QEvent.FocusOut: + ov = self._overlay_for_input(watched, create=False) + if ov is not None: + ov.set_focused(False) + elif etype == QEvent.Resize: + ov = self._overlay_for_input(watched, create=False) + if ov is not None: + ov.setGeometry(watched.rect()) + + return False + + +def install_material_motion(app: QApplication | None) -> _MaterialMotionController | None: + """Install application-wide monochrome ripple & focus-line controller once.""" + global _MOTION_CONTROLLER + if app is None or not isValid(app): + return None + if _MOTION_CONTROLLER is not None and isValid(_MOTION_CONTROLLER) and _MOTION_CONTROLLER.parent() is app: + return _MOTION_CONTROLLER + _MOTION_CONTROLLER = _MaterialMotionController(app) + app.installEventFilter(_MOTION_CONTROLLER) + return _MOTION_CONTROLLER + + +# --------------------------------------------------------------------------- +# 4. Gliding Ink Underlines for Top Nav & Tab Bars +# --------------------------------------------------------------------------- + +class SlidingNavUnderline(QWidget): + """Gliding 2px monochrome ink underline beneath checkable navigation buttons.""" + + def __init__(self, parent: QWidget, buttons: list[QAbstractButton]) -> None: + super().__init__(parent) + self._buttons = [b for b in buttons if b is not None] + self.setAttribute(Qt.WA_TransparentForMouseEvents, True) + self.setGeometry(parent.rect()) + + self._cur_x = 0.0 + self._cur_w = 0.0 + self._start_x = 0.0 + self._start_w = 0.0 + self._target_x = 0.0 + self._target_w = 0.0 + self._t = 1.0 + self._initialized = False + self._active_btn: QAbstractButton | None = next((b for b in self._buttons if b.isChecked()), None) + + self._clock = QElapsedTimer() + self._clock.start() + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._step) + + parent.installEventFilter(self) + for btn in self._buttons: + btn.setProperty('animatedIndicator', 'true') + btn.style().unpolish(btn) + btn.style().polish(btn) + btn.toggled.connect(lambda checked, b=btn: self._on_button_toggled(b, checked)) + btn.installEventFilter(self) + + self.show() + self.raise_() + self.sync_immediately() + + def _active_rect(self) -> QRect | None: + parent = self.parentWidget() + if parent is None or not isValid(parent): + return None + btn = self._active_btn + if btn is not None and isValid(btn) and btn.isChecked(): + tl = btn.mapTo(parent, btn.rect().topLeft()) + return QRect(tl, btn.size()) + for b in self._buttons: + if isValid(b) and b.isChecked(): + self._active_btn = b + tl = b.mapTo(parent, b.rect().topLeft()) + return QRect(tl, b.size()) + self._active_btn = None + return None + + def sync_immediately(self) -> None: + parent = self.parentWidget() + if parent is not None and isValid(parent): + self.setGeometry(parent.rect()) + r = self._active_rect() + if r is None or r.width() <= 0: + self.update() + return + self._cur_x = float(r.x()) + self._cur_w = float(r.width()) + self._start_x = self._cur_x + self._start_w = self._cur_w + self._target_x = self._cur_x + self._target_w = self._cur_w + self._t = 1.0 + self._initialized = True + self._timer.stop() + self.update() + + def _on_button_toggled(self, btn: QAbstractButton, checked: bool) -> None: + if checked: + self._active_btn = btn + self._animate_to_active() + return + if self._active_btn is btn: + self._active_btn = next((b for b in self._buttons if isValid(b) and b.isChecked()), None) + if self._active_btn is None: + self._timer.stop() + self.update() + else: + self._animate_to_active() + + def _animate_to_active(self) -> None: + r = self._active_rect() + if r is None or r.width() <= 0: + return + if _REDUCED_MOTION or not self._initialized or not self.isVisible(): + self.sync_immediately() + return + self._start_x = self._cur_x + self._start_w = self._cur_w + self._target_x = float(r.x()) + self._target_w = float(r.width()) + if abs(self._target_x - self._cur_x) < 0.5 and abs(self._target_w - self._cur_w) < 0.5: + return + self._t = 0.0 + self._clock.restart() + if not self._timer.isActive(): + self._timer.start() + + def eventFilter(self, watched: QObject | None, event: QEvent) -> bool: + if watched is None or not isValid(watched): + return False + etype = event.type() + if etype in (QEvent.Resize, QEvent.Move, QEvent.LayoutRequest): + parent = self.parentWidget() + if parent is not None and isValid(parent) and self.geometry() != parent.rect(): + self.setGeometry(parent.rect()) + if not self._timer.isActive(): + self.sync_immediately() + elif etype == QEvent.Show and watched is self.parentWidget(): + self.sync_immediately() + return False + + def _step(self) -> None: + if not isValid(self): + self._timer.stop() + return + elapsed = float(self._clock.elapsed()) + raw = min(1.0, elapsed / 165.0) + # Smooth cubic decelerate + eased = 1.0 - (1.0 - raw) ** 3 + self._t = raw + self._cur_x = self._start_x + (self._target_x - self._start_x) * eased + self._cur_w = self._start_w + (self._target_w - self._start_w) * eased + if raw >= 1.0: + self._cur_x = self._target_x + self._cur_w = self._target_w + self._timer.stop() + self.update() + + def paintEvent(self, event) -> None: + r = self._active_rect() + if r is None or self._cur_w <= 1.0: + return + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + p.setPen(Qt.NoPen) + p.setBrush(_theme_color('ink')) + y = float(r.bottom()) - 1.5 + p.drawRoundedRect(QRectF(self._cur_x + 2.0, y, max(4.0, self._cur_w - 4.0), 2.0), 1.0, 1.0) + p.end() + + +class _SlidingTabIndicator(QWidget): + """Gliding 2px monochrome ink underline inside a QTabBar.""" + + def __init__(self, tab_bar: QTabBar) -> None: + super().__init__(tab_bar) + self._bar = tab_bar + self.setAttribute(Qt.WA_TransparentForMouseEvents, True) + self.setGeometry(tab_bar.rect()) + + self._cur_x = 0.0 + self._cur_w = 0.0 + self._start_x = 0.0 + self._start_w = 0.0 + self._target_x = 0.0 + self._target_w = 0.0 + self._initialized = False + + self._clock = QElapsedTimer() + self._clock.start() + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._step) + + tab_bar.setProperty('animatedIndicator', 'true') + tab_bar.style().unpolish(tab_bar) + tab_bar.style().polish(tab_bar) + tab_bar.currentChanged.connect(self._on_current_changed) + tab_bar.tabMoved.connect(lambda *_: self.sync_immediately()) + tab_bar.installEventFilter(self) + + self.show() + self.raise_() + self.sync_immediately() + + def sync_immediately(self) -> None: + if not isValid(self._bar): + return + self.setGeometry(self._bar.rect()) + idx = self._bar.currentIndex() + if idx < 0: + return + rect = self._bar.tabRect(idx) + if rect.width() <= 0: + return + self._cur_x = float(rect.x()) + self._cur_w = float(rect.width()) + self._start_x = self._cur_x + self._start_w = self._cur_w + self._target_x = self._cur_x + self._target_w = self._cur_w + self._initialized = True + self._timer.stop() + self.update() + + def _on_current_changed(self, idx: int) -> None: + if not isValid(self._bar) or idx < 0: + return + rect = self._bar.tabRect(idx) + if rect.width() <= 0: + return + if _REDUCED_MOTION or not self._initialized or not self._bar.isVisible(): + self.sync_immediately() + return + self._start_x = self._cur_x + self._start_w = self._cur_w + self._target_x = float(rect.x()) + self._target_w = float(rect.width()) + if abs(self._target_x - self._cur_x) < 0.5 and abs(self._target_w - self._cur_w) < 0.5: + return + self._clock.restart() + if not self._timer.isActive(): + self._timer.start() + + def eventFilter(self, watched: QObject | None, event: QEvent) -> bool: + if watched is None or not isValid(watched) or not isValid(self._bar): + return False + etype = event.type() + if etype in (QEvent.Resize, QEvent.LayoutRequest, QEvent.Show): + self.setGeometry(self._bar.rect()) + if not self._timer.isActive(): + self.sync_immediately() + return False + + def _step(self) -> None: + if not isValid(self) or not isValid(self._bar): + self._timer.stop() + return + raw = min(1.0, float(self._clock.elapsed()) / 165.0) + eased = 1.0 - (1.0 - raw) ** 3 + self._cur_x = self._start_x + (self._target_x - self._start_x) * eased + self._cur_w = self._start_w + (self._target_w - self._start_w) * eased + if raw >= 1.0: + self._cur_x = self._target_x + self._cur_w = self._target_w + self._timer.stop() + self.update() + + def paintEvent(self, event) -> None: + if not isValid(self._bar) or self._bar.currentIndex() < 0 or self._cur_w <= 1.0: + return + rect = self._bar.tabRect(self._bar.currentIndex()) + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + p.setPen(Qt.NoPen) + p.setBrush(_theme_color('ink')) + y = float(rect.bottom()) - 1.5 + p.drawRoundedRect(QRectF(self._cur_x + 2.0, y, max(4.0, self._cur_w - 4.0), 2.0), 1.0, 1.0) + p.end() + + +def install_tab_motion( + tab_target: QTabWidget | QTabBar | None, + *, + animate_pages: bool = True, +) -> _SlidingTabIndicator | None: + """Attach a smooth 60fps gliding ink indicator to a QTabWidget or QTabBar.""" + if tab_target is None or not isValid(tab_target): + return None + if animate_pages and isinstance(tab_target, QTabWidget): + stack = tab_target.findChild(QStackedWidget) + if stack is not None: + install_stack_motion(stack) + bar = tab_target.tabBar() if isinstance(tab_target, QTabWidget) else tab_target + if bar is None or not isValid(bar): + return None + existing = getattr(bar, '_motion_tab_indicator', None) + if existing is not None and isValid(existing): + return existing + indicator = _SlidingTabIndicator(bar) + bar._motion_tab_indicator = indicator + return indicator + + +# --------------------------------------------------------------------------- +# 5. Non-Blocking Drawer & Page Transition Overlays +# --------------------------------------------------------------------------- + +def _cancel_widget_transition_overlay(widget: QWidget) -> None: + ov = getattr(widget, '_motion_transition_overlay', None) + if ov is not None and isValid(ov): + timer = getattr(ov, '_timer', None) + if timer is not None and isValid(timer): + timer.stop() + ov.hide() + ov.deleteLater() + widget._motion_transition_overlay = None + + +def _overlay_host(widget: QWidget) -> QWidget | None: + """Return nearest ancestor that is safe to parent overlays onto (never QSplitter).""" + host = widget.parentWidget() + while host is not None and isValid(host) and isinstance(host, (QSplitter, QStackedWidget)): + host = host.parentWidget() + if host is None or not isValid(host): + return None + return host + + +def _sync_splitter_layout(widget: QWidget) -> None: + """Force QSplitter/layout settlement so a newly-shown drawer has final size immediately.""" + parent = widget.parentWidget() + if parent is not None and isValid(parent): + QApplication.sendPostedEvents(parent, QEvent.LayoutRequest) + if parent.layout() is not None: + parent.layout().activate() + if widget.layout() is not None: + widget.layout().activate() + + +def _infer_edge(edge: str | None, dx: float, dy: float) -> str: + if edge in ('left', 'right', 'top', 'bottom'): + return edge + if abs(dx) >= abs(dy): + return 'right' if dx > 0 else 'left' + return 'bottom' if dy > 0 else 'top' + + +class _DrawerSlideOverlay(QWidget): + """Clipped physical edge-slide transition rendered safely above QSplitter/layouts.""" + + def __init__( + self, + host: QWidget, + rect: QRect, + pixmap: QPixmap, + *, + edge: str, + reveal: bool, + duration: int, + target_widget: QWidget | None = None, + ) -> None: + super().__init__(host) + self._host = host + self._widget = target_widget + self._pixmap = pixmap + self._edge = edge + self._reveal = reveal + self._duration = float(max(60, duration)) + self._progress = 0.0 + + self.setAttribute(Qt.WA_TransparentForMouseEvents, True) + self.setGeometry(rect) + + self._clock = QElapsedTimer() + self._clock.start() + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._step) + + host.installEventFilter(self) + if target_widget is not None and isValid(target_widget): + target_widget.installEventFilter(self) + + self.show() + self.raise_() + self._timer.start() + + def _finish(self) -> None: + self._timer.stop() + if self._widget is not None and isValid(self._widget): + if getattr(self._widget, '_motion_transition_overlay', None) is self: + self._widget._motion_transition_overlay = None + if isValid(self): + self.hide() + self.deleteLater() + + def eventFilter(self, watched: QObject | None, event: QEvent) -> bool: + if watched is None or not isValid(watched) or not isValid(self): + return False + etype = event.type() + if watched is self._host and etype in (QEvent.Resize, QEvent.Hide): + self._finish() + elif self._widget is not None and watched is self._widget: + if etype in (QEvent.Hide, QEvent.Destroy): + self._finish() + elif etype in (QEvent.Resize, QEvent.Move) and isValid(self._host): + self.setGeometry(QRect(self._widget.mapTo(self._host, QPoint(0, 0)), self._widget.size())) + return False + + def _step(self) -> None: + if not isValid(self) or not isValid(self._host) or not self._host.isVisible(): + self._finish() + return + if self._reveal and (self._widget is None or not isValid(self._widget) or not self._widget.isVisible()): + self._finish() + return + raw = min(1.0, float(self._clock.elapsed()) / self._duration) + self._progress = raw + if raw >= 1.0: + self._finish() + return + self.update() + + def paintEvent(self, event) -> None: + if self._pixmap.isNull(): + return + eased = 1.0 - (1.0 - self._progress) ** 3 + factor = (1.0 - eased) if self._reveal else eased + w = float(self.width()) + h = float(self.height()) + if self._edge == 'left': + ox, oy = -w * factor, 0.0 + elif self._edge == 'right': + ox, oy = w * factor, 0.0 + elif self._edge == 'top': + ox, oy = 0.0, -h * factor + else: + ox, oy = 0.0, h * factor + + p = QPainter(self) + p.setClipRect(self.rect()) + if self._reveal: + # Cover static widget beneath cleanly while sliding new panel into its clipped slot + p.fillRect(self.rect(), _theme_color('paper')) + p.setOpacity(1.0) + else: + alpha = 1.0 if eased <= 0.65 else max(0.0, (1.0 - eased) / 0.35) + p.setOpacity(alpha) + p.drawPixmap(QPointF(ox, oy), self._pixmap) + p.end() + + +def play_slide_overlay( + widget: QWidget | None, + dx: float = 0.0, + dy: float = 0.0, + duration: int = 165, + *, + edge: str | None = None, +) -> None: + """Capture widget BEFORE synchronously hiding it, then slide cleanly into its bezel.""" + if widget is None or not isValid(widget): + return + _cancel_widget_transition_overlay(widget) + if _REDUCED_MOTION: + return + host = _overlay_host(widget) + if host is None or not isValid(host) or not widget.isVisible(): + return + if widget.width() <= 2 or widget.height() <= 2: + return + rect = QRect(widget.mapTo(host, QPoint(0, 0)), widget.size()) + pix = widget.grab() + if pix.isNull(): + return + ov = _DrawerSlideOverlay( + host, + rect, + pix, + edge=_infer_edge(edge, dx, dy), + reveal=False, + duration=duration, + target_widget=None, + ) + widget._motion_transition_overlay = ov + + +def play_reveal_overlay( + widget: QWidget | None, + dx: float = 0.0, + dy: float = 0.0, + duration: int = 190, + *, + edge: str | None = None, +) -> None: + """Slide a newly-shown widget cleanly out from its clipped edge without delaying visibility.""" + if widget is None or not isValid(widget): + return + _cancel_widget_transition_overlay(widget) + if _REDUCED_MOTION: + return + host = _overlay_host(widget) + if host is None or not isValid(host) or not widget.isVisible(): + return + _sync_splitter_layout(widget) + if widget.width() <= 2 or widget.height() <= 2: + return + rect = QRect(widget.mapTo(host, QPoint(0, 0)), widget.size()) + pix = widget.grab() + if pix.isNull(): + return + ov = _DrawerSlideOverlay( + host, + rect, + pix, + edge=_infer_edge(edge, dx, dy), + reveal=True, + duration=duration, + target_widget=widget, + ) + widget._motion_transition_overlay = ov + + +class _StackSlideOverlay(QWidget): + """Cross-slide transition overlay for QStackedWidget with opaque paper backing.""" + + def __init__(self, stack: QStackedWidget) -> None: + super().__init__(stack) + self._stack = stack + self.setAttribute(Qt.WA_TransparentForMouseEvents, True) + self.setGeometry(stack.rect()) + self._progress = 1.0 + self._direction = 1 + self._pixmap = QPixmap() + + self._clock = QElapsedTimer() + self._clock.start() + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._step) + stack.installEventFilter(self) + self.hide() + + def trigger(self, direction: int, idx: int) -> None: + if _REDUCED_MOTION or not isValid(self._stack) or not self._stack.isVisible(): + return + if self._stack.width() <= 20 or self._stack.height() <= 20: + return + self._timer.stop() + self.hide() + new_widget = self._stack.widget(idx) + if new_widget is None or not isValid(new_widget): + return + if new_widget.size() != self._stack.size(): + new_widget.resize(self._stack.size()) + if new_widget.layout() is not None: + new_widget.layout().activate() + self._pixmap = new_widget.grab() + if self._pixmap.isNull(): + return + self._direction = 1 if direction >= 0 else -1 + self._progress = 0.0 + self.setGeometry(self._stack.rect()) + self.show() + self.raise_() + self._clock.restart() + self._timer.start() + self.update() + + def eventFilter(self, watched: QObject | None, event: QEvent) -> bool: + if watched is self._stack and isValid(self) and event.type() in (QEvent.Resize, QEvent.Hide): + self._timer.stop() + self._progress = 1.0 + self.hide() + return False + + def _step(self) -> None: + if not isValid(self) or not isValid(self._stack): + self._timer.stop() + return + raw = min(1.0, float(self._clock.elapsed()) / 150.0) + self._progress = raw + if raw >= 1.0: + self._timer.stop() + self._pixmap = QPixmap() + self.hide() + return + self.update() + + def paintEvent(self, event) -> None: + if self._progress >= 1.0 or self._pixmap.isNull(): + return + eased = 1.0 - (1.0 - self._progress) ** 3 + inv = 1.0 - eased + p = QPainter(self) + p.fillRect(self.rect(), _theme_color('paper')) + p.setOpacity(0.35 + 0.65 * eased) + p.drawPixmap(QPointF(float(self._direction) * 14.0 * inv, 0.0), self._pixmap) + p.end() + + +def install_stack_motion(stack: QStackedWidget | None) -> None: + """Attach a non-blocking fast page cross-slide transition to a QStackedWidget.""" + if stack is None or not isValid(stack): + return + if getattr(stack, '_motion_stack_installed', False): + return + stack._motion_stack_installed = True + stack._motion_prev_index = stack.currentIndex() + overlay = _StackSlideOverlay(stack) + stack._motion_stack_overlay = overlay + + def _on_changed(idx: int) -> None: + if not isValid(stack) or not isValid(overlay): + return + prev = getattr(stack, '_motion_prev_index', idx) + stack._motion_prev_index = idx + if idx != prev: + overlay.trigger(1 if idx > prev else -1, idx) + + stack.currentChanged.connect(_on_changed) + + +# --------------------------------------------------------------------------- +# 6. List Gliding Selection Rail & Hover Wash +# --------------------------------------------------------------------------- + +class _ListSelectionRail(QWidget): + """Gliding 3px monochrome ink pill rail + hover wash on QListWidget viewport.""" + + def __init__(self, lst: QListWidget) -> None: + vp = lst.viewport() + super().__init__(vp) + self._list = lst + self._vp = vp + self.setAttribute(Qt.WA_TransparentForMouseEvents, True) + self.setGeometry(vp.rect()) + + self._cur_top = 0.0 + self._cur_h = 0.0 + self._start_top = 0.0 + self._start_h = 0.0 + self._target_top = 0.0 + self._target_h = 0.0 + self._has_rail = False + + self._hover_row = -1 + self._hover_alpha = 0.0 + + self._clock = QElapsedTimer() + self._clock.start() + self._last_ms = 0.0 + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._step) + + lst.setMouseTracking(True) + vp.setMouseTracking(True) + vp.installEventFilter(self) + lst.currentRowChanged.connect(self._on_row_changed) + lst.itemSelectionChanged.connect(lambda: self._on_row_changed(lst.currentRow())) + if lst.verticalScrollBar() is not None: + lst.verticalScrollBar().valueChanged.connect(lambda *_: self._sync_instant()) + model = lst.model() + if model is not None: + model.modelReset.connect(self._sync_instant) + model.rowsRemoved.connect(lambda *_: self._sync_instant()) + + self.show() + self.raise_() + self._sync_instant() + + def _selected_rect(self) -> QRect | None: + if not isValid(self._list): + return None + item = self._list.currentItem() + if item is None: + return None + r = self._list.visualItemRect(item) + if not r.isValid() or r.height() <= 0: + return None + return r + + def _sync_instant(self) -> None: + if not isValid(self._vp): + return + self.setGeometry(self._vp.rect()) + r = self._selected_rect() + if r is None: + self._has_rail = False + self.update() + return + self._cur_top = float(r.top()) + self._cur_h = float(r.height()) + self._start_top = self._cur_top + self._start_h = self._cur_h + self._target_top = self._cur_top + self._target_h = self._cur_h + self._has_rail = True + self.update() + + def _on_row_changed(self, row: int) -> None: + if not isValid(self._list): + return + r = self._selected_rect() + if r is None: + self._has_rail = False + self.update() + return + if _REDUCED_MOTION or not self._has_rail or not self._list.isVisible(): + self._sync_instant() + return + self._start_top = self._cur_top + self._start_h = self._cur_h + self._target_top = float(r.top()) + self._target_h = float(r.height()) + self._has_rail = True + self._last_ms = float(self._clock.elapsed()) + self._clock.restart() + self._last_ms = 0.0 + if not self._timer.isActive(): + self._timer.start() + + def eventFilter(self, watched: QObject | None, event: QEvent) -> bool: + if watched is None or not isValid(watched) or not isValid(self._list) or not isValid(self._vp): + return False + etype = event.type() + if etype == QEvent.Resize: + self.setGeometry(self._vp.rect()) + self._sync_instant() + elif etype == QEvent.MouseMove: + item = self._list.itemAt(event.position().toPoint()) + new_row = self._list.row(item) if item is not None else -1 + if new_row != self._hover_row: + self._hover_row = new_row + if _REDUCED_MOTION: + self._hover_alpha = 1.0 if new_row >= 0 else 0.0 + self.update() + else: + self._last_ms = float(self._clock.elapsed()) + if not self._timer.isActive(): + self._timer.start() + elif etype == QEvent.Leave: + if self._hover_row != -1: + self._hover_row = -1 + if _REDUCED_MOTION: + self._hover_alpha = 0.0 + self.update() + elif not self._timer.isActive(): + self._last_ms = float(self._clock.elapsed()) + self._timer.start() + return False + + def _step(self) -> None: + if not isValid(self) or not isValid(self._list): + self._timer.stop() + return + now = float(self._clock.elapsed()) + dt = max(1.0, min(48.0, now - self._last_ms)) + self._last_ms = now + + rail_done = True + if self._has_rail: + raw = min(1.0, now / 170.0) + eased = 1.0 - (1.0 - raw) ** 3 + self._cur_top = self._start_top + (self._target_top - self._start_top) * eased + self._cur_h = self._start_h + (self._target_h - self._start_h) * eased + rail_done = raw >= 1.0 + + hover_target = 1.0 if self._hover_row >= 0 else 0.0 + rate = 1.0 - math.exp(-dt / 45.0) + self._hover_alpha += (hover_target - self._hover_alpha) * rate + hover_done = abs(self._hover_alpha - hover_target) <= 0.01 + if hover_done: + self._hover_alpha = hover_target + + if rail_done and hover_done: + self._timer.stop() + self.update() + + def paintEvent(self, event) -> None: + if not isValid(self._list): + return + ink = _theme_color('ink') + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + p.setPen(Qt.NoPen) + + # Hover wash + if self._hover_row >= 0 and self._hover_alpha > 0.01: + item = self._list.item(self._hover_row) + if item is not None: + hr = QRectF(self._list.visualItemRect(item)) + if hr.isValid() and not hr.isEmpty() and self._hover_row != self._list.currentRow(): + p.setBrush(_with_alpha(ink, int(round(12 * self._hover_alpha)))) + p.drawRoundedRect(hr.adjusted(2, 1, -2, -1), 6.0, 6.0) + + # Gliding left selection rail + if self._has_rail and self._cur_h > 6.0: + inset = min(7.0, self._cur_h * 0.24) + rail = QRectF(3.0, self._cur_top + inset, 3.0, max(6.0, self._cur_h - 2.0 * inset)) + p.setBrush(ink) + p.drawRoundedRect(rail, 1.5, 1.5) + p.end() + + +def install_list_motion(list_widget: QListWidget | None) -> _ListSelectionRail | None: + """Attach gliding selection rail and subtle monochrome hover wash to QListWidget.""" + if list_widget is None or not isValid(list_widget): + return None + existing = getattr(list_widget, '_motion_list_rail', None) + if existing is not None and isValid(existing): + return existing + rail = _ListSelectionRail(list_widget) + list_widget._motion_list_rail = rail + return rail + + +# --------------------------------------------------------------------------- +# 7. Gemini Status Pill Shimmer & Monochrome Dual-Segment Progress Bar +# --------------------------------------------------------------------------- + +class StatusShimmerOverlay(QWidget): + """Subtle 60fps monochrome sheen sweeping across statusPill when active.""" + + def __init__(self, pill: QWidget) -> None: + super().__init__(pill) + self._pill = pill + self.setAttribute(Qt.WA_TransparentForMouseEvents, True) + self.setGeometry(pill.rect()) + self._active = False + + self._clock = QElapsedTimer() + self._clock.start() + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._tick) + pill.installEventFilter(self) + self.hide() + + def set_active(self, active: bool) -> None: + self._active = bool(active) + if not self._active or _REDUCED_MOTION: + self._timer.stop() + self.hide() + return + self.setGeometry(self._pill.rect()) + self.show() + self.raise_() + if self._pill.isVisible() and not self._timer.isActive(): + self._clock.restart() + self._timer.start() + + def eventFilter(self, watched: QObject | None, event: QEvent) -> bool: + if watched is None or not isValid(watched) or not isValid(self._pill): + return False + etype = event.type() + if etype == QEvent.Resize: + self.setGeometry(self._pill.rect()) + elif etype == QEvent.Show and self._active and not _REDUCED_MOTION: + if not self._timer.isActive(): + self._clock.restart() + self._timer.start() + elif etype == QEvent.Hide: + self._timer.stop() + return False + + def _tick(self) -> None: + if not isValid(self) or not isValid(self._pill) or not self._active or not self._pill.isVisible(): + self._timer.stop() + return + self.update() + + def paintEvent(self, event) -> None: + if not self._active or _REDUCED_MOTION: + return + r = QRectF(self.rect()) + if r.width() <= 8 or r.height() <= 4: + return + phase = (self._clock.elapsed() % 1500) / 1500.0 + # Sweep smoothly left -> right during first 72% of cycle, rest slightly between sweeps + sweep_t = min(1.0, phase / 0.72) + alpha_fade = 1.0 if phase <= 0.72 else max(0.0, 1.0 - (phase - 0.72) / 0.14) + band_w = max(24.0, r.width() * 0.42) + cx = -band_w * 0.6 + (r.width() + band_w * 1.2) * sweep_t + + ink = _theme_color('ink') + peak = 24 if ink.lightness() < 128 else 32 + peak = int(round(peak * alpha_fade)) + if peak <= 1: + return + + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + clip = QPainterPath() + clip.addRoundedRect(r, min(r.height() * 0.5, 10.0), min(r.height() * 0.5, 10.0)) + p.setClipPath(clip) + + grad = QLinearGradient(cx - band_w * 0.5, 0.0, cx + band_w * 0.5, r.height()) + grad.setColorAt(0.0, _with_alpha(ink, 0)) + grad.setColorAt(0.5, _with_alpha(ink, peak)) + grad.setColorAt(1.0, _with_alpha(ink, 0)) + p.fillRect(r, grad) + p.end() + + +class MonochromeShimmerBar(QProgressBar): + """Gemini-style dual-segment 60fps monochrome indeterminate progress bar.""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setTextVisible(False) + self._display_frac = 0.0 + self._clock = QElapsedTimer() + self._clock.start() + self._timer = QTimer(self) + self._timer.setInterval(16) + self._timer.timeout.connect(self._tick) + + def _is_indeterminate(self) -> bool: + return self.minimum() == 0 and self.maximum() == 0 + + def _sync_timer(self) -> None: + if _REDUCED_MOTION or not self.isVisible(): + self._timer.stop() + return + if self._is_indeterminate(): + if not self._timer.isActive(): + self._clock.restart() + self._timer.start() + else: + span = max(1, self.maximum() - self.minimum()) + target = (self.value() - self.minimum()) / float(span) + if abs(target - self._display_frac) > 0.005: + if not self._timer.isActive(): + self._timer.start() + else: + self._display_frac = target + self._timer.stop() + + def setRange(self, minimum: int, maximum: int) -> None: + super().setRange(minimum, maximum) + self._sync_timer() + self.update() + + def setValue(self, value: int) -> None: + super().setValue(value) + if _REDUCED_MOTION: + span = max(1, self.maximum() - self.minimum()) + self._display_frac = max(0.0, min(1.0, (value - self.minimum()) / float(span))) + self._sync_timer() + self.update() + + def showEvent(self, event) -> None: + super().showEvent(event) + self._sync_timer() + + def hideEvent(self, event) -> None: + self._timer.stop() + super().hideEvent(event) + + def _tick(self) -> None: + if not isValid(self) or not self.isVisible(): + self._timer.stop() + return + if not self._is_indeterminate(): + span = max(1, self.maximum() - self.minimum()) + target = max(0.0, min(1.0, (self.value() - self.minimum()) / float(span))) + self._display_frac += (target - self._display_frac) * 0.25 + if abs(target - self._display_frac) <= 0.004: + self._display_frac = target + self._timer.stop() + self.update() + + def paintEvent(self, event) -> None: + r = QRectF(self.rect()) + if r.width() <= 2 or r.height() <= 1: + return + h = min(r.height(), 4.0) + y = r.center().y() - h * 0.5 + track = QRectF(r.left(), y, r.width(), h) + rad = h * 0.5 + + ink = _theme_color('ink') + rule = _theme_color('rule') + + p = QPainter(self) + p.setRenderHint(QPainter.Antialiasing, True) + p.setPen(Qt.NoPen) + p.setBrush(_with_alpha(rule, 160)) + p.drawRoundedRect(track, rad, rad) + + if not self._is_indeterminate(): + fill_w = track.width() * max(0.0, min(1.0, self._display_frac)) + if fill_w > 1.0: + p.setBrush(ink) + p.drawRoundedRect(QRectF(track.left(), y, fill_w, h), rad, rad) + p.end() + return + + if _REDUCED_MOTION: + p.setBrush(_with_alpha(ink, 190)) + seg_w = track.width() * 0.35 + p.drawRoundedRect(QRectF(track.left() + (track.width() - seg_w) * 0.5, y, seg_w, h), rad, rad) + p.end() + return + + # Dual-segment Material 3 indeterminate wave, strictly monochrome + cycle = (self._clock.elapsed() % 1400) / 1400.0 + clip = QPainterPath() + clip.addRoundedRect(track, rad, rad) + p.setClipPath(clip) + + # Primary bar: sweeps from -0.25 -> 1.15 + p1_head = -0.05 + 1.35 * (cycle ** 0.85) + p1_tail = -0.35 + 1.45 * (cycle ** 1.35) + # Secondary bar: delayed chase + c2 = max(0.0, (cycle - 0.35) / 0.65) if cycle >= 0.35 else 0.0 + p2_head = -0.02 + 1.18 * (c2 ** 0.78) if c2 > 0 else -1.0 + p2_tail = -0.22 + 1.25 * (c2 ** 1.25) if c2 > 0 else -1.0 + + for tail, head, alpha in ((p1_tail, p1_head, 235), (p2_tail, p2_head, 165)): + if head <= tail: + continue + x0 = track.left() + tail * track.width() + x1 = track.left() + head * track.width() + seg = QRectF(x0, y, max(4.0, x1 - x0), h) + grad = QLinearGradient(seg.left(), 0.0, seg.right(), 0.0) + grad.setColorAt(0.0, _with_alpha(ink, int(alpha * 0.35))) + grad.setColorAt(0.45, _with_alpha(ink, alpha)) + grad.setColorAt(1.0, _with_alpha(ink, alpha)) + p.setBrush(grad) + p.drawRoundedRect(seg, rad, rad) + p.end() diff --git a/comic_translate_desktop/ui/preview.py b/comic_translate_desktop/ui/preview.py index e38e139..ab4620e 100644 --- a/comic_translate_desktop/ui/preview.py +++ b/comic_translate_desktop/ui/preview.py @@ -3,14 +3,14 @@ from pathlib import Path from functools import lru_cache -from PySide6.QtCore import Qt, QRectF, QPointF, QSize, Signal, QEvent +from PySide6.QtCore import Qt, QElapsedTimer, QRectF, QPointF, QSize, QTimer, Signal, QEvent from PySide6.QtGui import QColor, QPainter, QPen, QPixmap, QImageReader, QRegion from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QScrollArea, QStackedLayout, QPushButton, QSizePolicy, QProgressBar from ..pdf_utils import render_pdf_preview from ..config import ICON_PATH from .halftone import COMPACT_BREAKPOINT, draw_corner_tones, draw_tone from .theme import color, display_font, theme_name, ui_font -from .motion import fade_in +from .motion import MonochromeShimmerBar, fade_in, reduced_motion @lru_cache(maxsize=4) @@ -91,16 +91,67 @@ def __init__(self, parent=None): self.regions = [] self.regions_visible = True self._hover_index = -1 + self._hover_strength = 0.0 + self._select_pulse_until = 0 + self._fx_clock = QElapsedTimer() + self._fx_clock.start() + self._fx_last_ms = 0.0 + self._fx_timer = QTimer(self) + self._fx_timer.setInterval(16) + self._fx_timer.timeout.connect(self._step_fx) self._region_drag = None self._view_pixmap = None self._view_scale = 1.0 self.setMouseTracking(True) self.setAccessibleName(tr('漫画画布')) + def _ensure_fx_timer(self): + hovering = self._hover_index is not None and self._hover_index >= 0 + if reduced_motion() or not self.isVisible(): + self._hover_strength = 1.0 if hovering else 0.0 + self._select_pulse_until = 0 + self._fx_timer.stop() + return + self._fx_last_ms = float(self._fx_clock.elapsed()) + if not self._fx_timer.isActive(): + self._fx_timer.start() + + def trigger_select_pulse(self): + if reduced_motion(): + self._select_pulse_until = 0 + self._fx_timer.stop() + return + if self.region is None or self._region_drag is not None or not self.isVisible(): + return + self._select_pulse_until = int(self._fx_clock.elapsed()) + 240 + self._ensure_fx_timer() + + def _step_fx(self): + now = float(self._fx_clock.elapsed()) + dt = max(1.0, min(48.0, now - self._fx_last_ms)) + self._fx_last_ms = now + + hovering = self._hover_index is not None and self._hover_index >= 0 + hover_target = 1.0 if hovering else 0.0 + rate = 1.0 - (2.718281828 ** (-dt / 36.0)) + self._hover_strength += (hover_target - self._hover_strength) * rate + hover_done = abs(self._hover_strength - hover_target) <= 0.01 + if hover_done: + self._hover_strength = hover_target + + pulse_done = now >= float(self._select_pulse_until) + if pulse_done: + self._select_pulse_until = 0 + + if hover_done and pulse_done: + self._fx_timer.stop() + self.update() + def set_regions(self, regions, visible=True): self.regions = list(regions or ()) self.regions_visible = bool(visible) self._hover_index = -1 + self._hover_strength = 0.0 self.update() def set_view(self, pixmap, scale, viewport): @@ -299,6 +350,12 @@ def mouseMoveEvent(self, event): hover = self._region_at(event.position()) if hover != self._hover_index: self._hover_index = hover + hovering = hover is not None and hover >= 0 + if hovering and not reduced_motion() and self.isVisible(): + self._hover_strength = 0.15 + self._ensure_fx_timer() + else: + self._hover_strength = 1.0 if hovering else 0.0 self.update() hit = self._region_hit(event.position()) self._region_cursor(hit) @@ -346,12 +403,15 @@ def keyPressEvent(self, event): def leaveEvent(self, event): if self._hover_index != -1: self._hover_index = -1 + self._hover_strength = 0.0 self.update() if self._region_drag is None: self.unsetCursor() super().leaveEvent(event) def hideEvent(self, event): + self._fx_timer.stop() + self._select_pulse_until = 0 self.cancel_region_drag() super().hideEvent(event) @@ -431,18 +491,19 @@ def _paint_canvas_overlay(self): continue guide = QColor(color('guide')) if index == self._hover_index: + hs = max(0.25, min(1.0, self._hover_strength if self._hover_strength > 0 else 1.0)) halo = QColor(color('guideHalo')) - halo.setAlpha(180) + halo.setAlpha(int(round(180 * hs))) halo_pen = QPen(halo, 2.5, Qt.SolidLine) halo_pen.setCosmetic(True) painter.setPen(halo_pen) painter.setBrush(Qt.NoBrush) painter.drawRect(rect) - guide.setAlpha(235) + guide.setAlpha(int(round(235 * hs))) pen = QPen(guide, 1.5, Qt.SolidLine) pen.setCosmetic(True) painter.setPen(pen) - painter.setBrush(QColor(guide.red(), guide.green(), guide.blue(), 24)) + painter.setBrush(QColor(guide.red(), guide.green(), guide.blue(), int(round(24 * hs)))) else: guide.setAlpha(85) pen = QPen(guide, 1, Qt.DashLine) @@ -467,6 +528,18 @@ def _paint_canvas_overlay(self): pen.setCosmetic(True) painter.setPen(pen) painter.drawRect(rect) + if self._select_pulse_until > 0 and not reduced_motion(): + rem = self._select_pulse_until - int(self._fx_clock.elapsed()) + if rem > 0: + pt = 1.0 - max(0.0, min(1.0, rem / 240.0)) + spread = 2.0 + 7.0 * pt + pulse_c = QColor(color('guide')) + pulse_c.setAlpha(int(round(165 * (1.0 - pt) ** 2))) + pulse_pen = QPen(pulse_c, 1.4, Qt.SolidLine) + pulse_pen.setCosmetic(True) + painter.setPen(pulse_pen) + painter.setBrush(Qt.NoBrush) + painter.drawRect(rect.adjusted(-spread, -spread, spread, spread)) if selected_index is not None and rect.width() >= 24 and rect.height() >= 20: badge_text = f'{selected_index + 1:02d}' badge_font = ui_font(11, mono=True) @@ -563,9 +636,10 @@ def __init__(self, parent=None, *, import_action=False, illustration='studio-imp self._state_title.setAlignment(Qt.AlignCenter) self._state_title.setWordWrap(True) state_layout.addWidget(self._state_title) - self._state_bar = QProgressBar() + self._state_bar = MonochromeShimmerBar() self._state_bar.setRange(0, 0) self._state_bar.setFixedWidth(180) + self._state_bar.setFixedHeight(5) self._state_bar.setTextVisible(False) self._state_bar.setObjectName('canvasStateBar') state_layout.addWidget(self._state_bar, 0, Qt.AlignHCenter) @@ -863,7 +937,9 @@ def set_regions(self, regions, visible=True): def set_region(self, box=None, *, editable=False): """Canvas-only selection guide; never alter the rendered/exported pixels.""" - self._label.region = tuple(box) if box is not None else None + prev_box = self._label.region + new_box = tuple(box) if box is not None else None + self._label.region = new_box self._label.region_editable = editable and box is not None self._label.setFocusPolicy(Qt.StrongFocus if (self._label.region_editable or self._label.region_creation or self._label.bubble_creation @@ -874,6 +950,8 @@ def set_region(self, box=None, *, editable=False): if (not self._label.region_editable and not self._label.region_creation and not self._label.bubble_creation): self.cancel_region_drag() + if new_box is not None and new_box != prev_box and self._label._region_drag is None: + self._label.trigger_select_pulse() self._label.update() def cancel_region_drag(self): diff --git a/comic_translate_desktop/ui/star_prompt.py b/comic_translate_desktop/ui/star_prompt.py index 5b74356..72e7b67 100644 --- a/comic_translate_desktop/ui/star_prompt.py +++ b/comic_translate_desktop/ui/star_prompt.py @@ -6,6 +6,8 @@ from PySide6.QtGui import QDesktopServices from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton, QToolButton, QVBoxLayout, QWidget +from .motion import fade_in + REPOSITORY_URL = 'https://github.com/Aaaaamadeus/ComiTrans' STAR_PROMPT_PROBABILITY = 0.15 @@ -60,6 +62,7 @@ def __init__(self, parent, *, idle_timeout_ms=STAR_PROMPT_IDLE_MS): def show_prompt(self): self.reposition() self.show() + fade_in(self, 180) self.raise_() self._idle_timer.start() @@ -73,6 +76,8 @@ def reposition(self): def dismiss(self): self._idle_timer.stop() + if self.graphicsEffect() is not None: + self.setGraphicsEffect(None) self.hide() def _open_repository(self): diff --git a/comic_translate_desktop/ui/step_panel.py b/comic_translate_desktop/ui/step_panel.py index 985b8e0..0c1cede 100644 --- a/comic_translate_desktop/ui/step_panel.py +++ b/comic_translate_desktop/ui/step_panel.py @@ -4,8 +4,8 @@ from dataclasses import dataclass from math import pi, sin -from PySide6.QtCore import QPointF, QRectF, Qt, QTimer -from PySide6.QtGui import QColor, QFont, QFontMetrics, QPainter, QPainterPath, QPen +from PySide6.QtCore import QElapsedTimer, QPointF, QRectF, Qt, QTimer +from PySide6.QtGui import QColor, QFont, QFontMetrics, QLinearGradient, QPainter, QPainterPath, QPen from PySide6.QtWidgets import QLabel, QSizePolicy, QWidget from ..i18n import tr, ui_language @@ -54,8 +54,8 @@ _NORMAL_HEIGHT = 112 _COMPACT_HEIGHT = 66 -_PULSE_INTERVAL_MS = 60 -_PULSE_PERIOD_TICKS = 24 +_PULSE_INTERVAL_MS = 16 +_PULSE_PERIOD_TICKS = 75 @dataclass(frozen=True) @@ -117,6 +117,10 @@ def __init__(self, parent=None): self._tile_rects: list[tuple[QRectF, str, str]] = [] self._hover_target: tuple[str, str] | None = None self._pulse_tick = 0 + self._pulse_clock = QElapsedTimer() + self._pulse_clock.start() + self._prev_stage_states: dict[str, int] = {} + self._done_flash_until: dict[str, int] = {} self.setFixedHeight(_NORMAL_HEIGHT) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) @@ -535,8 +539,11 @@ def _compute_stage_views(self) -> dict[str, _StageView]: return views def _sync_pulse_timer(self, views: dict[str, _StageView]) -> None: + now = int(self._pulse_clock.elapsed()) + self._done_flash_until = {k: v for k, v in self._done_flash_until.items() if v > now} any_running = any(view.state == RUNNING for view in views.values()) - should_pulse = any_running and not reduced_motion() and self.isVisible() + any_flashing = bool(self._done_flash_until) + should_pulse = (any_running or any_flashing) and not reduced_motion() and self.isVisible() if should_pulse: if not self._pulse_timer.isActive(): self._pulse_timer.start() @@ -545,6 +552,8 @@ def _sync_pulse_timer(self, views: dict[str, _StageView]) -> None: def _advance_pulse(self) -> None: self._pulse_tick = (self._pulse_tick + 1) % _PULSE_PERIOD_TICKS + if self._done_flash_until: + self._sync_pulse_timer(self._compute_stage_views()) self.update() def showEvent(self, event) -> None: @@ -558,9 +567,15 @@ def hideEvent(self, event) -> None: def _refresh(self) -> None: views = self._compute_stage_views() + now = int(self._pulse_clock.elapsed()) + can_flash = self.isVisible() and not reduced_motion() summary = [] for index, stage in enumerate(STAGE_ORDER, start=1): view = views[stage] + old_state = self._prev_stage_states.get(stage) + if can_flash and old_state == RUNNING and view.state == DONE: + self._done_flash_until[stage] = now + 440 + self._prev_stage_states[stage] = view.state name, status = self._labels[stage] name.setText(f'{index:02d} {tr(STAGE_LABELS[stage])}') status.setText(tr(STATUS_TEXT[view.state])) @@ -582,6 +597,9 @@ def mouseMoveEvent(self, event) -> None: if rect.contains(pos): views = self._compute_stage_views() tip = views[stage].tooltip + if self._hover_target != ('node', stage): + self._hover_target = ('node', stage) + self.update() if self.toolTip() != tip: self.setToolTip(tip) return @@ -783,11 +801,17 @@ def _draw_wire_path( painter.drawPath(chevron) if travel and energized and not reduced_motion() and self._pulse_timer.isActive(): - t = (self._pulse_tick % _PULSE_PERIOD_TICKS) / float(_PULSE_PERIOD_TICKS) - pt = path.pointAtPercent(t) + base_t = ((self._pulse_clock.elapsed() % 1350) / 1350.0) * 1.12 - 0.02 painter.setPen(Qt.NoPen) - painter.setBrush(QColor(color('ink'))) - painter.drawEllipse(pt, 2.6, 2.6) + ink = QColor(color('ink')) + for offset, rad, alpha in ((0.0, 2.8, 255), (-0.055, 2.1, 150), (-0.11, 1.4, 70)): + t = base_t + offset + if 0.0 <= t <= 1.0: + pt = path.pointAtPercent(t) + c = QColor(ink) + c.setAlpha(alpha) + painter.setBrush(c) + painter.drawEllipse(pt, rad, rad) def _draw_wires( self, @@ -985,6 +1009,49 @@ def _draw_node(self, painter: QPainter, rect: QRectF, view: _StageView) -> None: painter.setBrush(fill) painter.drawRoundedRect(rect, radius, radius) + if self._hover_target == ('node', view.stage) and not is_running: + hover_c = QColor(color('ink')) + hover_c.setAlpha(18) + painter.setPen(QPen(QColor(color('ink')), 1.1)) + painter.setBrush(hover_c) + painter.drawRoundedRect(rect, radius, radius) + + if is_running and not reduced_motion() and self._pulse_timer.isActive(): + inner = rect.adjusted(2.0, 4.0, -2.0, -4.0) + if inner.width() > 6.0 and inner.height() > 4.0: + painter.save() + clip = QPainterPath() + clip.addRoundedRect(inner, max(2.0, radius - 2.0), max(2.0, radius - 2.0)) + painter.setClipPath(clip) + phase = (self._pulse_clock.elapsed() % 1350) / 1350.0 + sweep = min(1.0, phase / 0.78) + band_w = max(20.0, inner.width() * 0.44) + cx = inner.left() - band_w * 0.6 + (inner.width() + band_w * 1.2) * sweep + sheen = QColor(color('paper')) + fade = 1.0 if phase <= 0.78 else max(0.0, 1.0 - (phase - 0.78) / 0.14) + sheen_c = QColor(sheen) + sheen_c.setAlpha(0) + sheen_peak = QColor(sheen) + sheen_peak.setAlpha(int(round(34 * fade))) + grad = QLinearGradient(cx - band_w * 0.5, inner.top(), cx + band_w * 0.5, inner.bottom()) + grad.setColorAt(0.0, sheen_c) + grad.setColorAt(0.5, sheen_peak) + grad.setColorAt(1.0, sheen_c) + painter.fillRect(inner, grad) + painter.restore() + + flash_until = self._done_flash_until.get(view.stage) + if flash_until is not None and not reduced_motion(): + rem = flash_until - int(self._pulse_clock.elapsed()) + if rem > 0: + ft = 1.0 - max(0.0, min(1.0, rem / 440.0)) + spread = 1.5 + 5.5 * ft + ring_c = QColor(color('ink')) + ring_c.setAlpha(int(round(135 * (1.0 - ft) ** 2))) + painter.setPen(QPen(ring_c, 1.3)) + painter.setBrush(Qt.NoBrush) + painter.drawRoundedRect(rect.adjusted(-spread, -spread, spread, spread), radius + spread * 0.4, radius + spread * 0.4) + # Status glyph on the left inside the node pad_x = 6.0 if self._compact else 9.0 glyph_r = 4.0 if self._compact else 5.2 @@ -1056,12 +1123,18 @@ def _draw_status_glyph( if state == RUNNING: fg = QColor(color('paper') if inverted else color('ink')) if not reduced_motion() and self._pulse_timer.isActive(): - phase = 0.5 + 0.5 * sin(2 * pi * self._pulse_tick / _PULSE_PERIOD_TICKS) + ms = float(self._pulse_clock.elapsed()) + phase = 0.5 + 0.5 * sin(2 * pi * ms / 1100.0) ring = QColor(fg) - ring.setAlphaF(0.25 + 0.45 * phase) + ring.setAlphaF(0.28 + 0.48 * phase) painter.setPen(QPen(ring, 1.3)) painter.setBrush(Qt.NoBrush) - painter.drawEllipse(center, r * (0.85 + 0.25 * phase), r * (0.85 + 0.25 * phase)) + painter.drawEllipse(center, r * (0.86 + 0.24 * phase), r * (0.86 + 0.24 * phase)) + echo_t = (ms % 1100.0) / 1100.0 + echo_c = QColor(fg) + echo_c.setAlphaF(0.45 * ((1.0 - echo_t) ** 2)) + painter.setPen(QPen(echo_c, 1.0)) + painter.drawEllipse(center, r * (0.95 + 0.85 * echo_t), r * (0.95 + 0.85 * echo_t)) painter.setPen(Qt.NoPen) painter.setBrush(fg) painter.drawEllipse(center, r * 0.52, r * 0.52) diff --git a/comic_translate_desktop/ui/theme.py b/comic_translate_desktop/ui/theme.py index a866353..c4cd151 100644 --- a/comic_translate_desktop/ui/theme.py +++ b/comic_translate_desktop/ui/theme.py @@ -184,6 +184,8 @@ def apply_theme(app, mode='light'): _theme_mode = resolved apply_palette(app) app.setStyleSheet(build_stylesheet()) + from .motion import install_material_motion + install_material_motion(app) if not _theme_watched: _theme_watched = True try: @@ -203,6 +205,8 @@ def install_ui_font(app): app.setFont(font) apply_palette(app) app.setStyleSheet(build_stylesheet()) + from .motion import install_material_motion + install_material_motion(app) return font.family() @@ -258,6 +262,7 @@ def refresh_themed_icons(): QLabel#cardTitle { font-size: 13px; font-weight: 700; color: @ink; } QLabel#fontChoiceName { color: @secondary; font-size: 12px; padding: 2px 0 2px 0; } QFrame#statusPill { background: transparent; border: none; } +QFrame#statusPill[active="true"] { background: @muted; border-radius: 10px; } QLabel#statusText { font-size: 12px; color: @secondary; background: transparent; } QLabel#statusText[state="running"], QLabel#statusText[state="warming"], QLabel#statusText[state="error"], QLabel#statusText[state="warning"] { color: @ink; font-weight: 700; } @@ -279,6 +284,8 @@ def refresh_themed_icons(): QPushButton[role="nav"]:checked { border-bottom: 2px solid @ink; color: @ink; background: transparent; font-weight: 700; } QPushButton[role="nav"]:hover { background: transparent; color: @ink; border-bottom-color: @rule; } QPushButton[role="nav"]:checked:hover { border-bottom-color: @ink; } +QPushButton[role="nav"][animatedIndicator="true"]:checked, +QPushButton[role="nav"][animatedIndicator="true"]:checked:hover { border-bottom-color: transparent; } QPushButton[role="utility"], QToolButton[role="utility"] { border: 1px solid @rule; background: @paper; color: @ink; padding: 5px 10px; border-radius: 8px; } QPushButton[role="utility"]:checked, QToolButton[role="utility"]:checked { background: @muted; color: @ink; border: 1.5px solid @ink; } QPushButton[role="utility"]:hover:!checked, QToolButton[role="utility"]:hover:!checked { background: @muted; border-color: @ruleStrong; } @@ -326,13 +333,29 @@ def refresh_themed_icons(): QTabWidget::pane { border: none; background: transparent; } QTabBar::tab { padding: 7px 14px; min-height: 24px; border: none; border-bottom: 2px solid transparent; background: transparent; color: @secondary; font-weight: 500; } QTabBar::tab:selected { background: transparent; color: @ink; border-bottom: 2px solid @ink; font-weight: 700; } +QTabBar[animatedIndicator="true"]::tab:selected { border-bottom-color: transparent; } QTabBar::tab:hover:!selected { background: transparent; color: @ink; border-bottom: 2px solid @rule; } QFrame#editorInspector QTabBar::tab { padding: 5px 12px; min-height: 20px; } -QLineEdit, QPlainTextEdit, QTextEdit, QComboBox, QSpinBox, QDoubleSpinBox { padding: 6px 9px; border: 1px solid transparent; border-bottom: 1px solid @ruleStrong; border-radius: 8px; background: @workspace; selection-background-color: @ink; selection-color: @paper; } -QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox { min-height: 26px; } -QLineEdit:focus, QPlainTextEdit:focus, QTextEdit:focus, QComboBox:focus, QSpinBox:focus, QDoubleSpinBox:focus { border-color: transparent; border-bottom: 1px solid @focusRing; background: @paper; } -QFrame#inspectorCard QComboBox, QFrame#inspectorCard QSpinBox, QFrame#inspectorCard QDoubleSpinBox { min-height: 18px; padding: 2px 7px; border: 1px solid @rule; border-bottom: 1px solid @ruleStrong; background: @workspace; } -QFrame#inspectorCard QComboBox:focus, QFrame#inspectorCard QSpinBox:focus, QFrame#inspectorCard QDoubleSpinBox:focus { border: 1px solid @focusRing; background: @paper; } +QLineEdit, QPlainTextEdit, QTextEdit, QSpinBox, QDoubleSpinBox { padding: 6px 9px; border: 1px solid transparent; border-bottom: 1px solid @ruleStrong; border-radius: 8px; background: @workspace; selection-background-color: @ink; selection-color: @paper; } +QLineEdit, QSpinBox, QDoubleSpinBox { min-height: 26px; } +QLineEdit:focus, QPlainTextEdit:focus, QTextEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus { border-color: transparent; border-bottom: 1px solid @focusRing; background: @paper; } +QComboBox { combobox-popup: 0; min-height: 26px; padding: 5px 6px 5px 10px; border: 1px solid @rule; border-radius: 8px; background: @workspace; color: @ink; selection-background-color: @ink; selection-color: @paper; } +QComboBox:hover { border-color: @ruleStrong; background: @paper; } +QComboBox:focus, QComboBox:on { border: 1.5px solid @ink; background: @paper; } +QComboBox:disabled { background: @workspace; color: @disabled; border-color: @rule; } +QComboBox::drop-down { subcontrol-origin: padding; subcontrol-position: top right; width: 26px; border: none; background: transparent; border-top-right-radius: 8px; border-bottom-right-radius: 8px; } +QComboBox::down-arrow { image: url("@icons/chevron-down.svg"); width: 14px; height: 14px; } +QComboBox::down-arrow:on { image: url("@icons/chevron-up.svg"); width: 14px; height: 14px; } +QComboBox QLineEdit, QComboBox QLineEdit:focus { padding: 0; min-height: 0; border: none; border-radius: 0; background: transparent; } +QComboBox QAbstractItemView, QCompleter QAbstractItemView { background: @elevated; color: @ink; border: 1px solid @ruleStrong; border-radius: 10px; padding: 4px; outline: none; selection-background-color: @ink; selection-color: @paper; } +QComboBox QAbstractItemView::item, QCompleter QAbstractItemView::item { min-height: 28px; padding: 4px 10px; border-radius: 6px; color: @ink; background: transparent; } +QComboBox QAbstractItemView::item:hover, QCompleter QAbstractItemView::item:hover { background: @muted; color: @ink; } +QComboBox QAbstractItemView::item:selected, QCompleter QAbstractItemView::item:selected { background: @ink; color: @paper; } +QFrame#inspectorCard QSpinBox, QFrame#inspectorCard QDoubleSpinBox { min-height: 18px; padding: 2px 7px; border: 1px solid @rule; border-bottom: 1px solid @ruleStrong; background: @workspace; } +QFrame#inspectorCard QSpinBox:focus, QFrame#inspectorCard QDoubleSpinBox:focus { border: 1px solid @focusRing; background: @paper; } +QFrame#inspectorCard QComboBox { min-height: 22px; padding: 3px 4px 3px 8px; border: 1px solid @rule; border-radius: 7px; background: @workspace; } +QFrame#inspectorCard QComboBox:hover { border-color: @ruleStrong; background: @paper; } +QFrame#inspectorCard QComboBox:focus, QFrame#inspectorCard QComboBox:on { border: 1.5px solid @ink; background: @paper; } QPlainTextEdit[readOnly="true"] { border: none; background: transparent; } QPlainTextEdit[readOnly="true"]:focus { border: none; background: transparent; } QPlainTextEdit#logContent, QPlainTextEdit#logContent:focus { border: none; background: @paper; padding: 8px 10px; } @@ -341,12 +364,13 @@ def refresh_themed_icons(): QPlainTextEdit#textInput { background: @paper; border: 1px solid @rule; border-radius: 8px; padding: 8px 10px; font-size: 15px; } QPlainTextEdit#textInput:focus { border: 1.5px solid @focusRing; background: @paper; } QPlainTextEdit#textSource { background: @paper; border: 1px solid @rule; border-radius: 8px; padding: 7px 10px; font-size: 14px; } -QLineEdit:disabled, QComboBox:disabled, QSpinBox:disabled, QDoubleSpinBox:disabled, QPlainTextEdit:disabled { background: @workspace; color: @disabled; border-color: transparent; } +QLineEdit:disabled, QSpinBox:disabled, QDoubleSpinBox:disabled, QPlainTextEdit:disabled { background: @workspace; color: @disabled; border-color: transparent; } QFrame#inspectorCard QComboBox:disabled, QFrame#inspectorCard QSpinBox:disabled, QFrame#inspectorCard QDoubleSpinBox:disabled { background: @workspace; color: @disabled; border-color: @rule; } -QComboBox::drop-down { width: 24px; border: none; } -QComboBox::down-arrow { image: url("@icons/chevron-down.svg"); width: 16px; height: 16px; } -QFrame#controlCard QLineEdit, QFrame#controlCard QComboBox { min-height: 28px; padding: 4px 10px; border-color: transparent; font-size: 13px; } -QFrame#controlCard QLineEdit:focus, QFrame#controlCard QComboBox:focus { border-color: @ruleStrong; } +QFrame#controlCard QLineEdit { min-height: 28px; padding: 4px 10px; border-color: transparent; font-size: 13px; } +QFrame#controlCard QLineEdit:focus { border-color: @ruleStrong; } +QFrame#controlCard QComboBox { min-height: 28px; padding: 4px 6px 4px 10px; border: 1px solid @rule; border-radius: 8px; background: @workspace; font-size: 13px; } +QFrame#controlCard QComboBox:hover { border-color: @ruleStrong; background: @paper; } +QFrame#controlCard QComboBox:focus, QFrame#controlCard QComboBox:on { border: 1.5px solid @ink; background: @paper; } QFrame#controlCard QPushButton, QFrame#controlCard QToolButton { min-height: 28px; padding: 4px 12px; border-color: transparent; font-size: 13px; } QFrame#controlCard QPushButton[role="primary"] { border-radius: 10px; min-height: 32px; } QFrame#optionDivider { background: @rule; border: none; margin: 6px 0; } diff --git a/tests/test_theme.py b/tests/test_theme.py index 25c4261..96b2bc7 100644 --- a/tests/test_theme.py +++ b/tests/test_theme.py @@ -4,9 +4,45 @@ import unittest os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen') -from PySide6.QtWidgets import QApplication, QPushButton +from PySide6.QtCore import QEvent, QPointF, Qt +from PySide6.QtGui import QFocusEvent, QPixmap +from PySide6.QtTest import QTest +from PySide6.QtWidgets import ( + QApplication, + QButtonGroup, + QComboBox, + QFrame, + QHBoxLayout, + QLineEdit, + QListWidget, + QPushButton, + QSplitter, + QStackedWidget, + QTabWidget, + QWidget, +) from shiboken6 import delete +from comic_translate_desktop.ui.motion import ( + EMPHASIZED_DECELERATE, + MonochromeShimmerBar, + STANDARD, + SlidingNavUnderline, + StatusShimmerOverlay, + _DrawerSlideOverlay, + _MangaComboItemDelegate, + _StackSlideOverlay, + install_list_motion, + install_material_motion, + install_stack_motion, + install_tab_motion, + play_reveal_overlay, + play_slide_overlay, + reduced_motion, + set_reduced_motion, +) +from comic_translate_desktop.ui.preview import ImagePreview +from comic_translate_desktop.ui.searchable_combo import SearchableFontCombo from comic_translate_desktop.ui.theme import ( PALETTES, apply_theme, build_stylesheet, set_themed_icon, theme, theme_name, ) @@ -66,6 +102,241 @@ def test_theme_change_skips_destroyed_buttons_and_updates_live_icons(self): finally: apply_theme(self.app, 'light') + def test_material_motion_hooks_ripple_and_focus_underline(self): + host = QWidget() + layout = QHBoxLayout(host) + btn = QPushButton('Action', host) + edit = QLineEdit(host) + layout.addWidget(btn) + layout.addWidget(edit) + host.resize(320, 60) + host.show() + QApplication.processEvents() + try: + set_reduced_motion(False) + install_material_motion(self.app) + QTest.mousePress(btn, Qt.LeftButton, pos=btn.rect().center()) + QTest.mouseRelease(btn, Qt.LeftButton, pos=btn.rect().center()) + overlay = getattr(btn, '_motion_ripple_overlay', None) + self.assertIsNotNone(overlay) + self.assertEqual(len(overlay._ripples), 1) + + QApplication.sendEvent(edit, QFocusEvent(QEvent.FocusIn, Qt.MouseFocusReason)) + focus_ov = getattr(edit, '_motion_focus_overlay', None) + self.assertIsNotNone(focus_ov) + self.assertEqual(focus_ov._target_progress, 1.0) + QTest.qWait(50) + self.assertGreater(focus_ov._progress, 0.0) + + set_reduced_motion(True) + QApplication.sendEvent(edit, QFocusEvent(QEvent.FocusOut, Qt.MouseFocusReason)) + self.assertEqual(focus_ov._progress, 0.0) + finally: + set_reduced_motion(False) + host.close() + delete(host) + + def test_sliding_nav_and_tabs_and_list_rail_track_selection(self): + host = QWidget() + layout = QHBoxLayout(host) + b1 = QPushButton('01 Auto', host) + b2 = QPushButton('02 Editor', host) + grp = QButtonGroup(host) + for b in (b1, b2): + b.setCheckable(True) + b.setProperty('role', 'nav') + grp.addButton(b) + layout.addWidget(b) + b1.setChecked(True) + nav = SlidingNavUnderline(host, [b1, b2]) + + tabs = QTabWidget(host) + tabs.addTab(QWidget(), 'A') + tabs.addTab(QWidget(), 'B') + layout.addWidget(tabs) + tab_ind = install_tab_motion(tabs) + + lst = QListWidget(host) + lst.addItems(['page1', 'page2', 'page3']) + layout.addWidget(lst) + rail = install_list_motion(lst) + + host.resize(640, 180) + host.show() + QApplication.processEvents() + try: + set_reduced_motion(False) + b2.setChecked(True) + QTest.qWait(30) + self.assertEqual(nav._target_x, float(b2.x())) + + tabs.setCurrentIndex(1) + QTest.qWait(30) + self.assertEqual(tabs.tabBar().property('animatedIndicator'), 'true') + self.assertEqual(tab_ind._target_x, float(tabs.tabBar().tabRect(1).x())) + + lst.setCurrentRow(2) + QTest.qWait(30) + self.assertTrue(rail._has_rail) + self.assertEqual(rail._target_top, float(lst.visualItemRect(lst.item(2)).top())) + + set_reduced_motion(True) + b1.setChecked(True) + self.assertEqual(nav._cur_x, float(b1.x())) + finally: + set_reduced_motion(False) + host.close() + delete(host) + + def test_status_shimmer_progress_bar_and_canvas_pulse(self): + host = QWidget() + layout = QHBoxLayout(host) + pill = QFrame(host) + pill.setFixedSize(120, 28) + shimmer = StatusShimmerOverlay(pill) + bar = MonochromeShimmerBar(host) + bar.setRange(0, 0) + bar.setFixedSize(180, 5) + preview = ImagePreview() + pix = QPixmap(200, 200) + pix.fill(Qt.white) + preview.set_pixmap(pix) + layout.addWidget(pill) + layout.addWidget(bar) + layout.addWidget(preview) + host.resize(520, 280) + host.show() + QApplication.processEvents() + try: + set_reduced_motion(False) + shimmer.set_active(True) + self.assertTrue(shimmer._timer.isActive()) + self.assertTrue(shimmer.isVisible()) + self.assertTrue(bar._timer.isActive()) + + preview.set_region((10, 10, 80, 40), editable=True) + self.assertGreater(preview._label._select_pulse_until, 0) + self.assertIsNone(preview._label._region_drag) + QTest.qWait(30) + + set_reduced_motion(True) + shimmer.set_active(False) + self.assertFalse(shimmer._timer.isActive()) + self.assertFalse(shimmer.isVisible()) + preview.set_region((20, 20, 70, 50), editable=True) + self.assertEqual(preview._label._select_pulse_until, 0) + self.assertTrue(reduced_motion()) + finally: + set_reduced_motion(False) + host.close() + delete(host) + + def test_combo_polish_and_popup_animation_lifecycle(self): + set_reduced_motion(False) + install_material_motion(self.app) + host = QWidget() + layout = QHBoxLayout(host) + plain = QComboBox(host) + plain.addItems(['日本語', 'English', '한국어']) + searchable = SearchableFontCombo(host) + searchable.addItems(['自动匹配漫画风格', '思源黑体', '手写杂书体']) + layout.addWidget(plain) + layout.addWidget(searchable) + host.resize(420, 80) + host.show() + QApplication.processEvents() + try: + for combo in (plain, searchable): + self.assertTrue(getattr(combo, '_motion_combo_polished', False)) + self.assertIsNone(getattr(combo, '_motion_focus_overlay', None)) + view = combo.view() + self.assertIsInstance(view.itemDelegate(), _MangaComboItemDelegate) + popup = view.window() + self.assertTrue(popup.testAttribute(Qt.WA_TranslucentBackground)) + combo.showPopup() + QTest.qWait(40) + combo.hidePopup() + QApplication.processEvents() + self.assertEqual(popup.windowOpacity(), 1.0) + finally: + set_reduced_motion(False) + host.close() + delete(host) + + def test_stack_slide_and_splitter_drawer_overlays_and_curves(self): + self.assertLess(EMPHASIZED_DECELERATE.valueForProgress(0.1), 0.35) + self.assertLess(STANDARD.valueForProgress(0.2), 0.15) + + host = QWidget() + layout = QHBoxLayout(host) + layout.setContentsMargins(0, 0, 0, 0) + stack = QStackedWidget(host) + p1, p2 = QFrame(), QFrame() + p1.setStyleSheet('background: #FFFFFF;') + p2.setStyleSheet('background: #FFFFFF;') + stack.addWidget(p1) + stack.addWidget(p2) + stack.setFixedSize(100, 120) + + splitter = QSplitter(Qt.Horizontal, host) + left, center, right = QFrame(), QFrame(), QFrame() + left.setStyleSheet('background: #F8F8F8;') + center.setStyleSheet('background: #FFFFFF;') + right.setStyleSheet('background: #F8F8F8;') + for pane in (left, center, right): + splitter.addWidget(pane) + splitter.setSizes([110, 180, 110]) + + layout.addWidget(stack) + layout.addWidget(splitter, 1) + host.resize(540, 200) + host.show() + QApplication.processEvents() + try: + set_reduced_motion(False) + install_stack_motion(stack) + overlay = stack._motion_stack_overlay + self.assertIsInstance(overlay, _StackSlideOverlay) + + stack.setCurrentIndex(1) + self.assertTrue(overlay.isVisible()) + QTest.qWait(200) + self.assertFalse(overlay.isVisible()) + + play_slide_overlay(left, edge='left', duration=90) + left.hide() + self.assertEqual(splitter.count(), 3) + QTest.qWait(140) + self.assertEqual(splitter.count(), 3) + + left.show() + play_reveal_overlay(left, edge='left', duration=90) + right.hide() + right.show() + play_reveal_overlay(right, edge='right', duration=90) + self.assertEqual(splitter.count(), 3) + + left_ov = getattr(left, '_motion_transition_overlay', None) + right_ov = getattr(right, '_motion_transition_overlay', None) + self.assertIsInstance(left_ov, _DrawerSlideOverlay) + self.assertIsInstance(right_ov, _DrawerSlideOverlay) + self.assertIs(left_ov.parentWidget(), host) + self.assertIs(right_ov.parentWidget(), host) + self.assertLess(left_ov.x(), right_ov.x()) + + QTest.qWait(150) + self.assertIsNone(getattr(left, '_motion_transition_overlay', None)) + self.assertIsNone(getattr(right, '_motion_transition_overlay', None)) + self.assertEqual(splitter.count(), 3) + + set_reduced_motion(True) + stack.setCurrentIndex(0) + self.assertFalse(overlay.isVisible()) + finally: + set_reduced_motion(False) + host.close() + delete(host) + if __name__ == '__main__': unittest.main()