Files
zyt/app/src/doctor_workstation/ui/theme.py
T

1679 lines
59 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Shared typography and neutral reading surfaces for the clinical workspace."""
from __future__ import annotations
import os
import sys
from pathlib import Path
from string import Template
from typing import Any
from PySide6.QtCore import QEvent, QObject, QPointF, QRect, Qt
from PySide6.QtGui import (
QColor,
QFont,
QFontDatabase,
QPainter,
QPainterPath,
QPalette,
QPen,
QPixmap,
QTextBlockFormat,
QTextCharFormat,
QTextCursor,
)
from PySide6.QtWidgets import (
QApplication,
QDialog,
QDialogButtonBox,
QFileDialog,
QInputDialog,
QMessageBox,
QPlainTextEdit,
QScrollArea,
QTextBrowser,
QTextEdit,
QWidget,
)
from doctor_workstation.resources import resource_path
# ``motion`` deliberately imports nothing from this module, so this stays a
# one-way dependency: tokens here, animation there.
from . import motion
from .design_system import PALETTE, RADII, SPACING, clinical_stylesheet
# Shared reading colors keep native pages and dialog chrome consistent.
# Brand accents are independent of reading ink; use opaque text for stable contrast.
# The legacy teal/ink aliases remain for existing callers.
COLORS = {
"canvas": PALETTE["canvas"],
"canvas_mid": PALETTE["surface"],
"canvas_glow": PALETTE["accent_soft"],
"surface": PALETTE["surface"],
"surface_alt": PALETTE["surface_alt"],
"raised": PALETTE["surface_alt"],
"glass": PALETTE["surface"],
"glass_alt": PALETTE["surface_alt"],
"line": PALETTE["line"],
"line_soft": PALETTE["line_strong"],
"text": PALETTE["heading"],
"text_soft": PALETTE["text"],
"muted": PALETTE["muted"],
"disabled_surface": PALETTE["disabled_surface"],
"disabled_text": PALETTE["disabled"],
"indigo": PALETTE["accent"],
"indigo_hover": PALETTE["accent_hover"],
"indigo_pressed": PALETTE["accent_pressed"],
"indigo_pale": PALETTE["accent_soft"],
"focus": PALETTE["focus"],
"selection": PALETTE["accent_soft"],
"success": PALETTE["success"],
"success_pale": PALETTE["success_soft"],
"warning": PALETTE["warning"],
"warning_pale": PALETTE["warning_soft"],
"danger": PALETTE["danger"],
"danger_pale": PALETTE["danger_soft"],
"info": PALETTE["accent"],
"info_pale": PALETTE["accent_soft"],
"ink": PALETTE["heading"],
"ink_soft": PALETTE["text"],
"teal": PALETTE["accent"],
"teal_dark": PALETTE["accent_pressed"],
"teal_pale": PALETTE["accent_soft"],
}
# --- Type scale -----------------------------------------------------------
# Seven steps, tuned for 简体中文 at Windows 100%–150% scaling. CJK glyphs carry
# more ink than Latin at the same pixel size, so the steps are spaced widely
# enough that two adjacent levels are always distinguishable.
TYPE = {
"fs_small": "12px", # secondary shell copy, status, keyboard hints
"fs_caption": "13px", # table headers, hints, badges, timestamps
"fs_body": "14px", # default UI text
"fs_strong": "15px", # emphasised body, dialog prompts
"fs_section": "16px", # card and section titles
"fs_title": "20px", # page titles, dialog titles
"fs_display": "26px", # metric values, empty-state glyphs
}
# The bundled variable font supplies real Regular, Medium and Semibold faces.
# Keep ordinary controls at Medium and reserve Semibold for headings.
WEIGHTS = {
"fw_body": "400",
"fw_control": "500",
"fw_heading": "600",
}
# --- Control metrics ------------------------------------------------------
# Controls leave room for the 14px reading size without increasing table density.
METRICS = {
"h_compact": "28px", # inline row actions, chips, links
"h_default": "34px", # buttons, inputs, combos, tabs
"h_cta": "38px", # primary dialog actions, sidebar navigation
"h_bar": "52px", # dialog header / footer bars
# Corner radii. These existed before but the pages invented their own, so
# the same role - a card - shipped at 10, 11, 12, 13, 14 and 16 px across
# six pages. Nothing in a product is a "10px card"; it is either a card or
# it is not, and it should round like every other card next to it.
#
# Nesting rule: an element sitting flush inside a rounded container takes
# ``outer - gap``. Where the gap is bigger than the outer radius the inner
# element is far enough from the corner that its own radius is free.
"r_xs": "4px", # chips, badges, tiny status pills
"r_sm": f"{RADII['small']}px", # inline row actions, tags
"r_md": f"{RADII['control']}px", # buttons, inputs, combo boxes
"r_lg": f"{RADII['panel']}px", # cards, filter bars, panels
"r_xl": f"{RADII['window']}px", # the shell surfaces the cards sit on
"pad_control": f"{SPACING['control']}px", # horizontal padding inside default controls
"pad_compact": "9px",
}
_QSS_TOKENS = {**COLORS, **TYPE, **WEIGHTS, **METRICS}
def crisp_pixmap(width: int, height: int | None = None) -> QPixmap:
"""Return a transparent pixmap that stays sharp on scaled displays.
Every shell/page icon is painted by hand rather than shipped as an asset.
Allocating those pixmaps at their logical size makes Qt upscale them on the
125%/150% Windows scale factors most clinic workstations run at, which is
what made the icon set look soft next to crisply hinted text. Backing the
pixmap with the screen's device pixel ratio keeps the painter in logical
coordinates while giving it real device pixels to draw into.
"""
height = width if height is None else height
ratio = 1.0
app = QApplication.instance()
if app is not None:
screen = app.primaryScreen()
if screen is not None:
ratio = max(1.0, float(screen.devicePixelRatio()))
pixmap = QPixmap(round(width * ratio), round(height * ratio))
pixmap.setDevicePixelRatio(ratio)
pixmap.fill(Qt.GlobalColor.transparent)
return pixmap
GLOBAL_QSS = Template(
r"""
QWidget {
color: $text;
background-color: transparent;
font-size: $fs_body;
font-weight: $fw_body;
}
QMainWindow, QDialog, QWidget#LoginCanvas {
background-color: $canvas;
}
QDialog[businessDialog="true"] {
background-color: $canvas_mid;
}
QDialog[businessDialog="true"] QFrame#DialogSurface,
QDialog[businessDialog="true"] QFrame[dialogSurface="true"] {
background-color: $surface;
border: 1px solid $line;
border-radius: $r_lg;
}
QDialog[businessDialog="true"] QFrame#DialogHeader,
QDialog[businessDialog="true"] QFrame[dialogRole="header"] {
min-height: $h_bar;
background-color: $surface;
border: 0;
border-bottom: 1px solid $line;
}
QDialog[businessDialog="true"] QLabel[dialogRole="title"] {
color: $text;
font-size: $fs_section;
font-weight: $fw_control;
}
QDialog[businessDialog="true"] QLabel[dialogRole="subtitle"] {
color: $muted;
font-size: $fs_caption;
}
QDialog[businessDialog="true"] QDialogButtonBox,
QMessageBox QDialogButtonBox,
QInputDialog QDialogButtonBox {
min-height: $h_bar;
background-color: $surface;
border: 0;
border-top: 1px solid $line;
}
QDialog[businessDialog="true"] QDialogButtonBox QPushButton,
QMessageBox QDialogButtonBox QPushButton,
QInputDialog QDialogButtonBox QPushButton {
min-width: 88px;
min-height: $h_cta;
}
QMessageBox[businessDialog="true"],
QInputDialog[businessDialog="true"] {
background-color: $canvas_mid;
}
QMessageBox QLabel#qt_msgbox_label {
min-width: 300px;
padding: 8px 2px;
color: $text_soft;
font-size: $fs_strong;
}
QMessageBox QLabel#qt_msgboxex_icon_label {
min-width: 44px;
min-height: 44px;
margin: 4px 10px 4px 0;
}
QMessageBox[messageKind="warning"] QLabel#qt_msgbox_label,
QMessageBox[messageKind="critical"] QLabel#qt_msgbox_label {
color: $text;
}
QInputDialog QLabel {
color: $text_soft;
font-size: $fs_strong;
}
QWidget#AppCanvas {
background-color: $canvas;
border-radius: 18px;
}
QWidget#ShellWorkspace, QStackedWidget#ShellPageStack {
background-color: $canvas_mid;
}
QLabel[role="muted"] { color: $muted; }
QLabel[role="danger"] { color: $danger; }
QLabel[role="breadcrumb"] { color: $muted; font-size: $fs_caption; }
QLabel[role="breadcrumbSeparator"] { color: #8E8F90; font-size: $fs_strong; }
QLabel[role="breadcrumbCurrent"] { color: $text_soft; font-size: $fs_caption; font-weight: $fw_control; }
QLabel[role="eyebrow"] {
color: $indigo_hover;
font-size: $fs_caption;
font-weight: $fw_control;
letter-spacing: 0.04em;
}
QLabel[role="pageTitle"] {
color: $text;
font-size: $fs_title;
font-weight: $fw_heading;
}
QLabel[role="sectionTitle"] {
color: $text;
font-size: $fs_section;
font-weight: $fw_control;
}
QLabel[role="display"] {
color: $text;
font-size: $fs_display;
font-weight: $fw_heading;
}
QLabel[role="metric"] {
color: $text;
font-size: $fs_title;
font-weight: $fw_heading;
}
QFrame#Card, QFrame#Panel, QFrame#FilterBar, QFrame#DetailPanel,
QFrame[glass="true"] {
background-color: $glass;
border: 1px solid $line;
border-radius: $r_lg;
}
QFrame#FilterBar { background-color: $surface; }
QFrame#SubtleCard {
background-color: $glass_alt;
border: 1px solid $line;
border-radius: $r_lg;
}
QFrame#MetricCard {
background-color: $surface;
border: 1px solid $line;
border-radius: $r_md;
}
QFrame#MetricCard:hover { border-color: $line_soft; background-color: $surface_alt; }
QFrame#MetricCard QLabel[role="metricTitle"] { color: $muted; font-size: $fs_caption; }
QFrame#MetricCard QLabel[role="metricValue"] { color: $text; font-size: $fs_title; font-weight: $fw_heading; }
QFrame#MetricCard QLabel[role="metricHint"] { color: $muted; font-size: $fs_caption; }
QFrame#ReceptionDetailPanel { background-color: transparent; border: 0; }
QFrame#ReceptionAiCard {
min-height: 132px;
background-color: #FFFFFF;
border: 1px solid $line_soft;
border-radius: $r_lg;
}
QLabel#ReceptionAiTitle {
color: $indigo_pressed;
font-size: $fs_strong;
font-weight: $fw_control;
}
QFrame#ReceptionAiCard QPushButton[variant="secondary"] {
min-height: $h_compact;
padding: 0 9px;
font-size: $fs_caption;
}
QLabel#MetricGlyph {
color: $indigo;
background-color: $indigo_pale;
border: 1px solid $line_soft;
border-radius: $r_md;
font-size: $fs_section;
font-weight: $fw_heading;
}
QLabel#MetricGlyph[kind="success"] { color: $success; background-color: $success_pale; }
QLabel#MetricGlyph[kind="warning"] { color: $warning; background-color: $warning_pale; }
QLabel#MetricGlyph[kind="info"] { color: $info; background-color: $info_pale; }
QFrame#Divider {
background-color: $line;
min-height: 1px;
max-height: 1px;
}
QGroupBox {
margin-top: 12px;
padding-top: 12px;
border: 1px solid $line;
border-radius: $r_lg;
background-color: $glass;
font-weight: $fw_control;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 12px;
padding: 0 6px;
color: $text_soft;
}
QPushButton {
min-height: $h_default;
padding: 0 $pad_control;
border: 1px solid $line;
border-radius: $r_md;
background-color: $surface;
color: $text;
font-weight: $fw_control;
}
QPushButton:hover {
background-color: $raised;
border-color: $line_soft;
}
QPushButton:pressed {
background-color: $indigo_pale;
border-color: $indigo_pressed;
}
QPushButton:focus {
border: 1px solid $indigo;
background-color: $indigo_pale;
}
QPushButton:checked {
color: #FFFFFF;
background-color: $indigo_pressed;
border-color: $indigo_hover;
}
QPushButton:checked:hover { background-color: $indigo; }
QPushButton:disabled {
color: $disabled_text;
background-color: $disabled_surface;
border-color: $line;
}
QPushButton[variant="primary"] {
color: #FFFFFF;
background-color: $indigo;
border-color: $indigo;
}
QPushButton[variant="primary"]:hover,
QPushButton[variant="primary"]:checked:hover {
background-color: $indigo_hover;
border-color: $indigo_hover;
}
QPushButton[variant="primary"]:pressed,
QPushButton[variant="primary"]:checked {
background-color: $indigo_pressed;
border-color: $indigo_pressed;
}
QPushButton[variant="primary"]:focus {
border: 1px solid $indigo_pressed;
background-color: $indigo_hover;
}
QPushButton[variant="primary"]:disabled {
color: $disabled_text;
background-color: $surface_alt;
border-color: $line;
}
QPushButton[variant="secondary"] {
color: $indigo_hover;
background-color: $indigo_pale;
border-color: $indigo_pale;
}
QPushButton[variant="secondary"]:hover {
color: $indigo_pressed;
background-color: $raised;
border-color: $indigo_hover;
}
QPushButton[variant="secondary"]:pressed,
QPushButton[variant="secondary"]:checked {
color: #FFFFFF;
background-color: $indigo_pressed;
border-color: $indigo_pressed;
}
/* Inline table row actions: quiet links that only gain a surface on hover, so
a column of them reads as text rather than as a wall of buttons. */
QWidget#RowActions QPushButton[rowAction="true"] {
min-height: $h_compact;
padding: 0 $pad_compact;
color: $info;
background-color: transparent;
border: 1px solid transparent;
border-radius: $r_sm;
font-weight: $fw_control;
}
QWidget#RowActions QPushButton[rowAction="true"]:hover {
color: $indigo_pressed;
background-color: $indigo_pale;
border-color: $line_soft;
}
QWidget#RowActions QPushButton[rowAction="true"]:pressed {
color: #FFFFFF;
background-color: $indigo_pressed;
border-color: $indigo_pressed;
}
QWidget#RowActions QPushButton[rowAction="true"][variant="dangerGhost"] { color: $danger; }
QWidget#RowActions QPushButton[rowAction="true"][variant="dangerGhost"]:hover {
color: $danger;
background-color: $danger_pale;
border-color: rgba(240, 120, 134, 96);
}
QToolButton#RowActionsMore {
min-width: 0;
min-height: $h_compact;
padding: 0 $pad_compact;
color: $muted;
background-color: transparent;
border: 1px solid transparent;
border-radius: $r_sm;
font-weight: $fw_control;
}
QToolButton#RowActionsMore:hover {
color: $text;
background-color: $surface_alt;
border-color: $line;
}
QToolButton#RowActionsMore::menu-indicator { width: 0; height: 0; image: none; }
QFrame#NoteAttachmentTile {
background-color: $surface;
border: 1px solid $line;
border-radius: $r_md;
}
QPushButton#NoteAttachmentPreview {
min-height: 132px;
padding: 6px;
color: $muted;
background-color: $surface_alt;
border: 1px solid $line;
border-radius: $r_md;
font-weight: $fw_control;
}
QPushButton#NoteAttachmentPreview:hover {
background-color: $indigo_pale;
border-color: $indigo_hover;
}
QPushButton#NoteAttachmentPreview[loadState="failed"] {
color: $danger;
background-color: $danger_pale;
}
QLabel#NoteAttachmentName {
color: $text_soft;
font-size: $fs_caption;
}
QPushButton[variant="danger"] {
color: $danger;
background-color: $danger_pale;
border-color: rgba(240, 120, 134, 112);
}
QPushButton[variant="danger"]:hover {
color: $canvas;
background-color: $danger;
border-color: $danger;
}
QPushButton[variant="danger"]:pressed,
QPushButton[variant="danger"]:checked {
color: #FFFFFF;
background-color: #C85E6C;
border-color: #C85E6C;
}
QPushButton[variant="dangerGhost"] {
color: $danger;
background-color: transparent;
border-color: transparent;
}
QPushButton[variant="dangerGhost"]:hover {
background-color: $danger_pale;
border-color: rgba(240, 120, 134, 96);
}
QPushButton[variant="success"] {
color: #FFFFFF;
background-color: $success;
border-color: $success;
}
QPushButton[variant="success"]:hover { background-color: #216A56; border-color: #216A56; }
QPushButton[variant="success"]:pressed { background-color: #1B5746; border-color: #1B5746; }
QPushButton[variant="warning"] {
color: #FFFFFF;
background-color: $warning;
border-color: $warning;
}
QPushButton[variant="warning"]:hover { background-color: #925B19; border-color: #925B19; }
QPushButton[variant="warning"]:pressed { background-color: #794B14; border-color: #794B14; }
QPushButton[variant="ghost"] {
color: $text_soft;
border-color: transparent;
background-color: transparent;
}
QPushButton[variant="ghost"]:hover {
color: $text;
background-color: $surface_alt;
border-color: $line;
}
QPushButton[variant="ghost"]:pressed,
QPushButton[variant="ghost"]:checked {
color: $indigo_pressed;
background-color: $indigo_pale;
border-color: $indigo_pressed;
}
QPushButton[variant="link"] {
min-height: $h_compact;
padding: 0 $pad_compact;
color: $info;
background-color: transparent;
border-color: transparent;
}
QPushButton[variant="link"]:hover { color: $indigo_hover; background-color: $indigo_pale; }
QPushButton[variant="link"]:pressed { color: $indigo_hover; background-color: $surface_alt; }
QPushButton[variant="chip"] {
min-height: $h_compact;
padding: 0 $pad_compact;
color: $text_soft;
background-color: $surface_alt;
border-color: $line;
border-radius: $r_md;
}
QPushButton[variant="chip"]:hover {
color: $text;
background-color: $raised;
border-color: $indigo_hover;
}
QPushButton[variant="chip"]:checked {
color: #FFFFFF;
background-color: $indigo_pressed;
border-color: $indigo_hover;
}
QPushButton[variant="nav"] {
min-height: $h_cta;
padding: 0 12px;
border: 0;
border-radius: $r_md;
background-color: transparent;
color: $muted;
text-align: left;
font-weight: $fw_control;
}
QPushButton[variant="nav"]:hover { background-color: $surface_alt; color: $text; }
QPushButton[variant="nav"]:pressed { background-color: $indigo_pale; }
QPushButton[variant="nav"]:checked { background-color: $indigo_pressed; color: #FFFFFF; }
QToolButton {
min-width: $h_default;
min-height: $h_default;
border: 1px solid transparent;
border-radius: $r_md;
color: $text_soft;
background-color: transparent;
}
QToolButton:hover { color: $text; background-color: $surface_alt; border-color: $line; }
QToolButton:pressed { background-color: $indigo_pale; border-color: $indigo_pressed; }
QToolButton:focus { border: 1px solid $indigo; background-color: $indigo_pale; }
QToolButton:checked { color: #FFFFFF; background-color: $indigo_pressed; border-color: $indigo_hover; }
QToolButton:disabled { color: $disabled_text; background-color: transparent; border-color: transparent; }
QToolButton[diagnosisChip="true"] {
color: $text_soft;
background-color: $surface_alt;
border: 1px solid $line;
}
QToolButton[diagnosisChip="true"]:hover { color: $text; border-color: $indigo_hover; }
QToolButton[diagnosisChip="true"]:checked {
color: #FFFFFF;
background-color: $indigo_pressed;
border-color: $indigo_hover;
}
QToolButton[diagnosisChip="true"][semantic="info"] { color: $info; background-color: $info_pale; }
QToolButton[diagnosisChip="true"][semantic="success"] { color: $success; background-color: $success_pale; }
QToolButton[diagnosisChip="true"][semantic="warning"] { color: $warning; background-color: $warning_pale; }
QLineEdit, QTextEdit, QPlainTextEdit, QComboBox, QDateEdit, QDateTimeEdit,
QTimeEdit, QSpinBox, QDoubleSpinBox, QKeySequenceEdit {
min-height: $h_default;
padding: 0 $pad_control;
border: 1px solid $line;
border-radius: $r_md;
background-color: $surface;
color: $text;
selection-background-color: $indigo;
selection-color: #FFFFFF;
}
QTextEdit, QPlainTextEdit { padding: 7px $pad_control; }
QLineEdit:hover, QTextEdit:hover, QPlainTextEdit:hover, QComboBox:hover,
QDateEdit:hover, QDateTimeEdit:hover, QTimeEdit:hover, QSpinBox:hover,
QDoubleSpinBox:hover, QKeySequenceEdit:hover { border-color: $indigo_hover; }
QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus, QComboBox:focus,
QDateEdit:focus, QDateTimeEdit:focus, QTimeEdit:focus, QSpinBox:focus,
QDoubleSpinBox:focus, QKeySequenceEdit:focus {
border: 1px solid $indigo;
background-color: $surface;
}
QLineEdit:read-only, QTextEdit:read-only, QPlainTextEdit:read-only {
color: $muted;
background-color: $disabled_surface;
}
QLineEdit:disabled, QTextEdit:disabled, QPlainTextEdit:disabled, QComboBox:disabled,
QDateEdit:disabled, QDateTimeEdit:disabled, QTimeEdit:disabled, QSpinBox:disabled,
QDoubleSpinBox:disabled, QKeySequenceEdit:disabled {
color: $disabled_text;
background-color: $disabled_surface;
border-color: $line;
}
QComboBox::drop-down, QDateEdit::drop-down, QDateTimeEdit::drop-down {
border: 0;
width: 28px;
}
QComboBox QAbstractItemView {
color: $text;
background-color: $raised;
alternate-background-color: $surface_alt;
border: 1px solid $line;
border-radius: $r_md;
padding: 5px;
outline: 0;
selection-background-color: $indigo_pressed;
selection-color: #FFFFFF;
}
QAbstractSpinBox::up-button, QAbstractSpinBox::down-button {
width: 20px;
border: 0;
background-color: transparent;
}
QCheckBox, QRadioButton { spacing: 8px; color: $text_soft; }
QCheckBox:hover, QRadioButton:hover { color: $text; }
QCheckBox:disabled, QRadioButton:disabled { color: $disabled_text; }
QCheckBox::indicator, QRadioButton::indicator { width: 17px; height: 17px; }
QCheckBox::indicator:unchecked, QRadioButton::indicator:unchecked {
background-color: $surface;
border: 1px solid $line;
}
QCheckBox::indicator:unchecked { border-radius: 4px; }
QRadioButton::indicator:unchecked { border-radius: 9px; }
QCheckBox::indicator:hover, QRadioButton::indicator:hover { border-color: $indigo_hover; }
QCheckBox::indicator:checked, QRadioButton::indicator:checked {
background-color: $indigo;
border: 1px solid $focus;
}
QCheckBox::indicator:checked { border-radius: 4px; }
QRadioButton::indicator:checked { border-radius: 9px; }
QCheckBox::indicator:disabled, QRadioButton::indicator:disabled {
background-color: $disabled_surface;
border-color: $line;
}
QAbstractItemView, QTableWidget, QTableView, QListWidget, QListView, QTreeWidget, QTreeView {
color: $text;
background-color: $surface;
alternate-background-color: $surface_alt;
border: 0;
border-radius: $r_lg;
gridline-color: $line;
selection-background-color: $selection;
selection-color: $text;
outline: 0;
}
QAbstractItemView:focus { border: 0; }
QTableWidget::item, QTableView::item {
padding: 6px 8px;
border-bottom: 1px solid $line;
}
QTableWidget::item:hover, QTableView::item:hover { background-color: $surface_alt; }
QTableWidget::item:selected, QTableView::item:selected {
color: $text;
background-color: $selection;
}
QHeaderView::section {
background-color: $raised;
color: $muted;
border: 0;
border-right: 0;
border-bottom: 1px solid $line;
padding: 7px 8px;
font-size: $fs_caption;
font-weight: $fw_control;
}
QHeaderView::section:hover { color: $text; background-color: $raised; }
QTableCornerButton::section { background-color: $surface_alt; border: 0; }
QListWidget::item, QListView::item, QTreeWidget::item, QTreeView::item {
border: 0;
padding: 6px $pad_compact;
margin: 1px 0;
}
QListWidget::item:selected, QListView::item:selected,
QTreeWidget::item:selected, QTreeView::item:selected {
background-color: $indigo_pale;
color: $indigo_pressed;
border-radius: $r_md;
}
QListWidget::item:hover, QListView::item:hover,
QTreeWidget::item:hover, QTreeView::item:hover {
background-color: $surface_alt;
border-radius: $r_md;
}
QTabWidget::pane {
border: 1px solid $line;
border-radius: $r_lg;
background-color: $glass;
}
QTabBar::tab {
min-height: $h_default;
padding: 0 14px;
margin-right: 2px;
color: $muted;
background-color: transparent;
border: 1px solid transparent;
border-radius: $r_md;
font-weight: $fw_control;
}
QTabBar::tab:hover { color: $text; background-color: $surface_alt; }
QTabBar::tab:focus { border-color: $focus; }
QTabBar::tab:selected {
color: $indigo_pressed;
background-color: $indigo_pale;
border-color: $line_soft;
}
QTabBar::tab:disabled { color: $disabled_text; }
QTabBar#ReceptionDetailTabs {
background-color: $surface;
border-bottom: 1px solid $line;
}
QTabBar#ReceptionDetailTabs::tab {
min-height: $h_cta;
padding: 0 14px;
margin: 0 4px 0 0;
color: $muted;
background-color: transparent;
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
}
QTabBar#ReceptionDetailTabs::tab:hover { color: $text; background-color: $surface_alt; }
QTabBar#ReceptionDetailTabs::tab:selected {
color: $indigo_pressed;
background-color: transparent;
border-bottom: 2px solid $indigo;
}
QMenuBar {
color: $text_soft;
background-color: $surface;
border-bottom: 1px solid $line;
}
QMenuBar::item { padding: 7px 10px; background-color: transparent; border-radius: 6px; }
QMenuBar::item:selected { color: $text; background-color: $raised; }
QMenu {
color: $text;
background-color: $raised;
border: 1px solid $line_soft;
border-radius: $r_md;
padding: 6px;
}
QMenu::item {
min-width: 128px;
min-height: $h_default;
padding: 0 14px 0 30px;
border-radius: $r_sm;
background-color: transparent;
}
QMenu::item:selected { color: $indigo_pressed; background-color: $indigo_pale; }
QMenu::item:pressed { color: #FFFFFF; background-color: $indigo; }
QMenu::item:disabled { color: $disabled_text; background-color: transparent; }
QMenu::item[danger="true"] { color: $danger; }
QMenu::item[danger="true"]:selected { color: $danger; background-color: $danger_pale; }
QMenu::separator { height: 1px; background-color: $line; margin: 6px 8px; }
QMenu::icon { left: 8px; }
QMenu::indicator { width: 16px; height: 16px; }
QCalendarWidget {
color: $text;
background-color: $surface;
border: 1px solid $line;
border-radius: $r_lg;
}
QCalendarWidget QWidget#qt_calendar_navigationbar {
background-color: $raised;
border-bottom: 1px solid $line;
}
QCalendarWidget QToolButton {
color: $text;
background-color: transparent;
border: 0;
border-radius: 7px;
}
QCalendarWidget QToolButton:hover { background-color: $indigo_pale; }
QCalendarWidget QSpinBox {
color: $text;
background-color: $surface_alt;
border: 1px solid $line;
}
QCalendarWidget QAbstractItemView:enabled {
color: $text_soft;
background-color: $surface;
selection-background-color: $indigo;
selection-color: #FFFFFF;
}
QCalendarWidget QAbstractItemView:disabled { color: $disabled_text; }
QScrollArea, QAbstractScrollArea {
border: 0;
background-color: transparent;
}
QScrollBar:vertical {
background: transparent;
width: 10px;
margin: 2px;
}
QScrollBar::handle:vertical {
background: $line;
min-height: $h_compact;
border-radius: 4px;
}
QScrollBar::handle:vertical:hover { background: #A7B1C9; }
QScrollBar::handle:vertical:pressed { background: #8894B2; }
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: transparent; }
QScrollBar:horizontal {
background: transparent;
height: 10px;
margin: 2px;
}
QScrollBar::handle:horizontal {
background: $line;
min-width: 30px;
border-radius: 4px;
}
QScrollBar::handle:horizontal:hover { background: #A7B1C9; }
QScrollBar::handle:horizontal:pressed { background: #8894B2; }
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { width: 0; }
QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { background: transparent; }
QProgressBar {
min-height: 6px;
max-height: 6px;
border: 0;
border-radius: 3px;
background: $line;
color: transparent;
}
QProgressBar::chunk { border-radius: 3px; background-color: $indigo; }
QSlider::groove:horizontal { height: 4px; background-color: $line; border-radius: 2px; }
QSlider::sub-page:horizontal { background-color: $indigo; border-radius: 2px; }
QSlider::handle:horizontal {
width: 14px;
margin: -5px 0;
background-color: $text;
border: 2px solid $indigo;
border-radius: 7px;
}
QSlider::handle:horizontal:hover { border-color: $focus; }
QLabel#StatusBadge {
padding: 2px 8px;
border: 1px solid transparent;
border-radius: $r_sm;
font-size: $fs_caption;
font-weight: $fw_control;
}
QLabel#StatusBadge[kind="neutral"] { color: $muted; background-color: $surface_alt; border-color: $line; }
QLabel#StatusBadge[kind="success"] { color: $success; background-color: $success_pale; border-color: rgba(73, 198, 165, 72); }
QLabel#StatusBadge[kind="warning"] { color: $warning; background-color: $warning_pale; border-color: rgba(228, 185, 103, 72); }
QLabel#StatusBadge[kind="danger"] { color: $danger; background-color: $danger_pale; border-color: rgba(240, 120, 134, 72); }
QLabel#StatusBadge[kind="info"] { color: $info; background-color: $info_pale; border-color: rgba(120, 167, 255, 72); }
QLabel#StatusBadge[kind="accent"] { color: $indigo_hover; background-color: $indigo_pale; border-color: $line_soft; }
QWidget#Pager QLabel#PagerActive {
min-width: 32px;
min-height: $h_compact;
color: #FFFFFF;
background-color: $indigo;
border: 1px solid $indigo;
border-radius: $r_md;
font-size: $fs_caption;
font-weight: $fw_control;
}
QWidget#Pager QPushButton {
min-height: $h_compact;
padding: 0 $pad_compact;
border: 1px solid $line;
background-color: $surface;
}
QWidget#EmptyState { background-color: transparent; }
QLabel#EmptyStateGlyph {
color: $indigo_hover;
background-color: $indigo_pale;
border: 1px solid $line_soft;
border-radius: 22px;
font-size: $fs_display;
font-weight: $fw_control;
}
QFrame#MessageBanner {
border: 1px solid $line;
border-radius: $r_md;
color: $text_soft;
}
QFrame#MessageBanner QLabel { background-color: transparent; }
QFrame#MessageBanner QLabel#MessageBannerIcon { font-weight: $fw_heading; }
QFrame#MessageBanner[kind="info"] { color: $info; background-color: $info_pale; border-color: rgba(120, 167, 255, 82); }
QFrame#MessageBanner[kind="success"] { color: $success; background-color: $success_pale; border-color: rgba(73, 198, 165, 82); }
QFrame#MessageBanner[kind="warning"] { color: $warning; background-color: $warning_pale; border-color: rgba(228, 185, 103, 82); }
QFrame#MessageBanner[kind="danger"] { color: $danger; background-color: $danger_pale; border-color: rgba(240, 120, 134, 82); }
QFrame#MessageBanner[kind="info"] QLabel { color: $info; }
QFrame#MessageBanner[kind="success"] QLabel { color: $success; }
QFrame#MessageBanner[kind="warning"] QLabel { color: $warning; }
QFrame#MessageBanner[kind="danger"] QLabel { color: $danger; }
QLabel#Toast {
color: $text;
background-color: $raised;
border: 1px solid $line_soft;
border-radius: $r_md;
padding: 11px 16px;
font-weight: $fw_control;
}
QLabel#Toast[kind="info"] { color: $info; background-color: $info_pale; border-color: rgba(120, 167, 255, 96); }
QLabel#Toast[kind="success"] { color: $success; background-color: $success_pale; border-color: rgba(73, 198, 165, 96); }
QLabel#Toast[kind="warning"] { color: $warning; background-color: $warning_pale; border-color: rgba(228, 185, 103, 96); }
QLabel#Toast[kind="danger"] { color: $danger; background-color: $danger_pale; border-color: rgba(240, 120, 134, 96); }
QFrame#BusyOverlay {
color: $text_soft;
background-color: rgba(245, 247, 251, 232);
border: 1px solid $line_soft;
border-radius: 16px;
}
QFrame#BusyOverlay QLabel { color: $muted; background-color: transparent; }
QFrame#BusyOverlay QProgressBar { background-color: $line; }
QWidget#Sidebar {
background-color: rgba(255, 255, 255, 250);
border: 1px solid $line;
border-radius: 17px;
}
QFrame#TopBar, QFrame#MultipleTabs {
background-color: rgba(255, 255, 255, 248);
border-bottom: 1px solid $line;
}
QLabel#UserAvatar {
min-width: 36px;
max-width: 36px;
min-height: $h_default;
max-height: $h_default;
color: #FFFFFF;
background-color: $indigo_pressed;
border: 1px solid $line_soft;
border-radius: 18px;
font-size: $fs_strong;
font-weight: $fw_heading;
}
QWidget#LoginBrandPanel {
background-color: $surface_alt;
border: 1px solid $line_soft;
border-radius: $r_lg;
}
QFrame#LoginCard {
background-color: $glass;
border: 1px solid $line_soft;
border-radius: 20px;
}
QSplitter::handle { background-color: transparent; width: 8px; height: 8px; }
QSplitter::handle:hover { background-color: $indigo_pressed; }
QPushButton[variant="secondary"]:disabled,
QPushButton[variant="secondary"]:checked:disabled,
QPushButton[variant="success"]:disabled,
QPushButton[variant="success"]:checked:disabled,
QPushButton[variant="warning"]:disabled,
QPushButton[variant="warning"]:checked:disabled,
QPushButton[variant="danger"]:disabled,
QPushButton[variant="danger"]:checked:disabled,
QPushButton[variant="dangerGhost"]:disabled,
QPushButton[variant="dangerGhost"]:checked:disabled,
QPushButton[variant="ghost"]:disabled,
QPushButton[variant="ghost"]:checked:disabled,
QPushButton[variant="link"]:disabled,
QPushButton[variant="link"]:checked:disabled,
QPushButton[variant="chip"]:disabled,
QPushButton[variant="chip"]:checked:disabled,
QPushButton[variant="nav"]:disabled,
QPushButton[variant="nav"]:checked:disabled {
color: $disabled_text;
background-color: $disabled_surface;
border-color: $line;
}
QToolTip {
color: $text;
background-color: $raised;
border: 1px solid $line_soft;
border-radius: 6px;
padding: 6px 8px;
}
"""
).substitute(_QSS_TOKENS)
GLOBAL_QSS = clinical_stylesheet(GLOBAL_QSS)
#: Per-block reading rhythm, in device pixels. ``(top, bottom, line%)``.
#: QTextDocument's markdown importer builds block formats directly and ignores
#: ``setDefaultStyleSheet``, so spacing has to be applied to the parsed
#: document instead of being declared in CSS.
# 行内收紧、行间放开:一条要点自己的折行必须比两条要点之间更紧,否则整段会散成
# 一行一行的碎片,反而更难读。
_BLOCK_RHYTHM = {
"heading": (22, 10, 148),
"subheading": (18, 8, 148),
# 顶层列表项通常就是小节标题,之间留出整行空白让各小节一眼可数。
"section": (20, 8, 150),
"item": (13, 5, 158), # nested bullet under a section
"paragraph": (10, 10, 168),
}
# --- Surfaces -------------------------------------------------------------
# There is deliberately no drop-shadow system here. One was tried: a painted
# layer behind each page's cards, on the theory that flat outlines were what
# made the workspace look unfinished. It does not work in this palette. The
# cards are #FFFFFF sitting on a #FFFFFF workspace - barely one percent apart -
# so a shadow has no tonal room to read as depth and instead composites into a
# neutral grey rim around every card, which against the blue-tinted ground looks
# like a dirty second border rather than elevation.
#
# Depth in this product comes from the border and the fill, not from shadow.
# --- Control indicator glyphs --------------------------------------------
# Styling ``QCheckBox::indicator`` with a background and border but no image
# tells Qt to stop drawing its own tick, so every checked box in the product
# rendered as a plain indigo square and the partially-checked state was an
# unlabelled grey one. Selection columns on the prescription, patient and
# diagnosis tables all depend on that tick, so the marks are painted here and
# handed back to the stylesheet as cached PNGs.
_INDICATOR_BOX = 15
_INDICATOR_REVISION = "1"
#: The dropdown caret is the one glyph Fusion still drew itself - a solid
#: triangle sitting beside an otherwise entirely stroked icon set. Rendering it
#: here brings every QComboBox, date field and tool-button menu onto the same
#: 24-unit grid as the rest of the product.
_CARET_BOX = 12
def _indicator_pixmap(kind: str, color: str, ratio: int, box_size: int | None = None) -> QPixmap:
box = (box_size or _INDICATOR_BOX) * ratio
pixmap = QPixmap(box, box)
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
try:
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
scale = box / 24.0
painter.scale(scale, scale)
pen = QPen(QColor(color), 3.4)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
painter.setBrush(Qt.BrushStyle.NoBrush)
if kind == "check":
path = QPainterPath(QPointF(5.0, 12.5))
path.lineTo(QPointF(10.0, 17.5))
path.lineTo(QPointF(19.0, 6.5))
painter.drawPath(path)
elif kind == "dash":
painter.drawLine(QPointF(6.0, 12.0), QPointF(18.0, 12.0))
elif kind == "dot":
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(color))
painter.drawEllipse(QPointF(12.0, 12.0), 4.6, 4.6)
elif kind == "caret":
pen.setWidthF(2.6)
painter.setPen(pen)
path = QPainterPath(QPointF(6.0, 9.5))
path.lineTo(QPointF(12.0, 15.5))
path.lineTo(QPointF(18.0, 9.5))
painter.drawPath(path)
finally:
painter.end()
return pixmap
def _indicator_asset_dir() -> Path | None:
try:
from platformdirs import user_cache_dir
from ..config import APP_AUTHOR, APP_NAME
directory = Path(user_cache_dir(APP_NAME, APP_AUTHOR)) / "indicators"
except Exception: # pragma: no cover - falls back to the user home
directory = Path.home() / ".zhenyangdoctor" / "indicators"
try:
directory.mkdir(parents=True, exist_ok=True)
except OSError: # pragma: no cover - read-only deployment
return None
return directory
def _indicator_url(kind: str, color: str, box_size: int | None = None) -> str | None:
"""Return a stylesheet ``url()`` body for one indicator mark, or None."""
directory = _indicator_asset_dir()
if directory is None:
return None
stem = f"{kind}-{color.lstrip('#').lower()}-{box_size or _INDICATOR_BOX}-{_INDICATOR_REVISION}"
base = directory / f"{stem}.png"
# Qt resolves the ``@2x`` companion itself on scaled displays, which keeps
# the mark crisp at the 125%/150% factors clinic workstations run at.
retina = directory / f"{stem}@2x.png"
try:
if not base.exists() and not _indicator_pixmap(kind, color, 1, box_size).save(
str(base), "PNG"
):
return None
if not retina.exists():
_indicator_pixmap(kind, color, 2, box_size).save(str(retina), "PNG")
except OSError: # pragma: no cover - read-only deployment
return None
return base.as_posix()
def _indicator_qss() -> str:
"""Stylesheet fragment that restores the tick, dash and radio dot."""
marks = {
"check": _indicator_url("check", "#FFFFFF"),
"check_disabled": _indicator_url("check", COLORS["disabled_text"]),
"dash": _indicator_url("dash", "#FFFFFF"),
"dot": _indicator_url("dot", "#FFFFFF"),
"dot_disabled": _indicator_url("dot", COLORS["disabled_text"]),
"caret": _indicator_url("caret", COLORS["muted"], _CARET_BOX),
"caret_disabled": _indicator_url("caret", COLORS["disabled_text"], _CARET_BOX),
}
if any(value is None for value in marks.values()):
return ""
return f"""
QCheckBox::indicator:checked {{ image: url({marks["check"]}); }}
QCheckBox::indicator:indeterminate {{
background-color: {COLORS["indigo"]};
border: 1px solid {COLORS["indigo"]};
border-radius: 4px;
image: url({marks["dash"]});
}}
QCheckBox::indicator:checked:disabled {{ image: url({marks["check_disabled"]}); }}
QRadioButton::indicator:checked {{ image: url({marks["dot"]}); }}
QRadioButton::indicator:checked:disabled {{ image: url({marks["dot_disabled"]}); }}
QComboBox::down-arrow, QDateEdit::down-arrow, QDateTimeEdit::down-arrow,
QTimeEdit::down-arrow {{
width: {_CARET_BOX}px;
height: {_CARET_BOX}px;
image: url({marks["caret"]});
}}
/* A tool button's menu indicator defaults to the bottom-right corner, which was
invisible while it was Fusion's 6 px triangle and became obvious once it was a
12 px chevron - the caret dropped below the label instead of sitting beside
it. Anchor it to the right edge; the buttons that show one already reserve
right padding for it, so nothing here changes their metrics. */
QToolButton::menu-indicator {{
width: {_CARET_BOX}px;
height: {_CARET_BOX}px;
image: url({marks["caret"]});
subcontrol-origin: padding;
subcontrol-position: right center;
right: 6px;
}}
/* Re-assert the suppressions that the block above would otherwise override.
These live here rather than in the main sheet because this fragment is
appended after it, and a later rule wins in Qt when specificity ties. */
QToolButton#RowActionsMore::menu-indicator {{ width: 0; height: 0; image: none; }}
QComboBox::down-arrow:disabled, QDateEdit::down-arrow:disabled,
QDateTimeEdit::down-arrow:disabled, QTimeEdit::down-arrow:disabled,
QToolButton::menu-indicator:disabled {{ image: url({marks["caret_disabled"]}); }}
"""
def _block_is_all_bold(block: Any) -> bool:
"""True when every visible run in the block is bold.
Models title their sections as ``1. **症状演变与疗效评估**`` rather than as
real markdown headings, so a fully bold top-level list item is the only
reliable signal that a block is a section title and not a content bullet.
"""
iterator = block.begin()
seen = False
while not iterator.atEnd():
fragment = iterator.fragment()
iterator += 1
if not fragment.isValid() or not fragment.text().strip():
continue
seen = True
if fragment.charFormat().fontWeight() < QFont.Weight.DemiBold.value:
return False
return seen
def apply_reading_rhythm(browser: QTextBrowser, *, role: str, start_position: int = 0) -> None:
"""Give a parsed reply real hierarchy and breathing room.
Model answers are long "section heading + two levels of bullets" documents.
Qt renders every one of those blocks at the same size with 6px margins, so
the reply arrives as a wall of text. This walks the parsed document once
and applies a heading scale plus per-level spacing.
"""
document = browser.document()
base_font = browser.font()
base_px = base_font.pixelSize()
if base_px <= 0:
base_px = max(12, round(base_font.pointSizeF() * 96 / 72))
cursor = QTextCursor(document)
cursor.beginEditBlock()
try:
block = document.findBlock(start_position)
while block.isValid():
heading = block.blockFormat().headingLevel()
text_list = block.textList()
indent = text_list.format().indent() if text_list is not None else 0
if heading:
kind = "heading" if heading <= 2 else "subheading"
size = base_px + (3 if heading <= 2 else 1)
elif indent >= 2:
kind, size = "item", None
elif indent == 1:
kind = "section"
# 只有整行加粗的顶层条目才是小节标题,普通要点保持正文字号。
size = base_px + 2 if _block_is_all_bold(block) else None
else:
kind, size = "paragraph", None
top, bottom, line = _BLOCK_RHYTHM[kind]
# 首块的上边距会在气泡顶部留出一段空白,视觉上像是排版错位。
if block.position() == 0:
top = 0
block_format = QTextBlockFormat(block.blockFormat())
block_format.setTopMargin(top)
block_format.setBottomMargin(bottom)
block_format.setLineHeight(
line, QTextBlockFormat.LineHeightTypes.ProportionalHeight.value
)
cursor.setPosition(block.position())
cursor.setBlockFormat(block_format)
if size is not None and block.length() > 1:
heading_font = QFont(base_font)
heading_font.setPixelSize(size)
heading_font.setBold(True)
char_format = QTextCharFormat()
char_format.setFont(heading_font)
if role != "doctor":
char_format.setForeground(QColor("#1A1C1F"))
cursor.setPosition(block.position())
cursor.setPosition(
block.position() + block.length() - 1,
QTextCursor.MoveMode.KeepAnchor,
)
cursor.mergeCharFormat(char_format)
block = block.next()
finally:
cursor.endEditBlock()
def _apply_group(
palette: QPalette,
group: QPalette.ColorGroup,
colors: dict[QPalette.ColorRole, str],
) -> None:
for role, value in colors.items():
palette.setColor(group, role, QColor(value))
def _register_preferred_cjk_fonts() -> str:
"""Prefer the shipped outline font, with native CJK faces as a fallback."""
app = QApplication.instance()
registered = getattr(app, "_doctor_bundled_font_family", None)
if registered:
return registered
bundled_font = resource_path("fonts", "NotoSansSC-VF.ttf")
if bundled_font.is_file():
font_id = QFontDatabase.addApplicationFont(str(bundled_font))
families = QFontDatabase.applicationFontFamilies(font_id) if font_id >= 0 else []
if families:
family = families[0]
if app is not None:
app._doctor_bundled_font_family = family
return family
platform_families = {
"win32": ("Microsoft YaHei UI", "Microsoft YaHei"),
"darwin": ("PingFang SC", "Hiragino Sans GB"),
}
preferred = platform_families.get(sys.platform, ("Noto Sans CJK SC", "Source Han Sans SC"))
available = set(QFontDatabase.families())
if not any(family in available for family in preferred) and sys.platform == "win32":
windows_root = Path(
os.environ.get("SYSTEMROOT") or os.environ.get("WINDIR") or r"C:\Windows"
)
font_dir = windows_root / "Fonts"
for filename in ("msyh.ttc", "msyhbd.ttc", "msyhl.ttc"):
font_path = font_dir / filename
if not font_path.is_file():
continue
font_id = QFontDatabase.addApplicationFont(str(font_path))
if font_id >= 0 and QFontDatabase.applicationFontFamilies(font_id):
available.update(QFontDatabase.applicationFontFamilies(font_id))
for family in (*preferred, "Arial Unicode MS"):
if family in available:
return family
return QApplication.font().family()
_PRIMARY_STANDARD_BUTTONS = frozenset(
{
QDialogButtonBox.StandardButton.Ok,
QDialogButtonBox.StandardButton.Save,
QDialogButtonBox.StandardButton.SaveAll,
QDialogButtonBox.StandardButton.Open,
QDialogButtonBox.StandardButton.Apply,
QDialogButtonBox.StandardButton.Yes,
QDialogButtonBox.StandardButton.YesToAll,
QDialogButtonBox.StandardButton.Retry,
}
)
_DANGER_STANDARD_BUTTONS = frozenset(
{
QDialogButtonBox.StandardButton.Abort,
QDialogButtonBox.StandardButton.Discard,
}
)
def _refresh_widget_style(widget: object) -> None:
style = getattr(widget, "style", lambda: None)()
if style is None:
return
style.unpolish(widget)
style.polish(widget)
def _polish_dialog_buttons(button_box: QDialogButtonBox) -> None:
"""Assign semantic variants to Qt standard buttons without changing behavior."""
for button in button_box.buttons():
if button.property("variant"):
continue
standard = button_box.standardButton(button)
if standard in _PRIMARY_STANDARD_BUTTONS:
variant = "primary"
elif standard in _DANGER_STANDARD_BUTTONS:
variant = "danger"
else:
variant = "secondary"
button.setProperty("variant", variant)
_refresh_widget_style(button)
def allow_dialog_resize(dialog: QDialog) -> None:
"""Give a business subwindow the usual minimise/maximise affordances.
``QDialog`` ships with a close button only, so every AI panel, report and
editor was stuck at whatever size it was constructed with — unusable for the
long, dense clinical replies these windows carry. Transient prompts
(message and input boxes) are deliberately left alone, and a dialog that has
pinned itself to a fixed size keeps that decision.
"""
if isinstance(dialog, (QMessageBox, QInputDialog, QFileDialog)):
return
if dialog.minimumSize() == dialog.maximumSize():
return
# Qt hides a window whose flags change while it is visible, so a dialog that
# is already on screen keeps the flags it was shown with.
if dialog.isVisible():
dialog.setSizeGripEnabled(True)
return
flags = dialog.windowFlags()
if flags & Qt.WindowType.WindowMaximizeButtonHint:
return
dialog.setWindowFlags(
flags
| Qt.WindowType.WindowMinimizeButtonHint
| Qt.WindowType.WindowMaximizeButtonHint
)
dialog.setSizeGripEnabled(True)
def mark_business_dialog(dialog: QDialog, object_name: str | None = None) -> None:
"""Opt a business subwindow into the shared visual contract.
The helper intentionally does not change modality, ownership or result
handling. It only supplies stable styling metadata, semantic button roles
and window affordances, so existing workflows keep their original behavior.
"""
if object_name and not dialog.objectName():
dialog.setObjectName(object_name)
dialog.setProperty("businessDialog", True)
allow_dialog_resize(dialog)
for button_box in dialog.findChildren(QDialogButtonBox):
_polish_dialog_buttons(button_box)
_refresh_widget_style(dialog)
def main_window_target_rect(window: QWidget) -> QRect | None:
"""Return a centered rectangle covering 85% of the visible workstation."""
app = QApplication.instance()
if app is None:
return None
main = next(
(
candidate
for candidate in app.topLevelWidgets()
if candidate is not window
and candidate.property("doctorMainWindow")
and candidate.isVisible()
),
None,
)
if main is None:
return None
main_frame = main.frameGeometry()
target_width = max(1, round(main_frame.width() * 0.85))
target_height = max(1, round(main_frame.height() * 0.85))
return QRect(
main_frame.center().x() - target_width // 2,
main_frame.center().y() - target_height // 2,
target_width,
target_height,
)
def _size_new_window_to_main(window: QWidget) -> None:
"""Open a business window at 85% of the visible workstation, centered."""
if not window.isWindow() or window.property("doctorMainWindow"):
return
if window.property("doctorSkipOpenGeometry"):
return
if (
isinstance(window, (QMessageBox, QInputDialog, QFileDialog))
or window.metaObject().className() == "QPrintDialog"
):
return
if window.windowFlags() & Qt.WindowType.FramelessWindowHint:
# Drawers have their own owner-sync routines and use the same target rect.
return
target = main_window_target_rect(window)
if target is None:
return
target_width = target.width()
target_height = target.height()
if window.minimumWidth() > target_width:
window.setMinimumWidth(target_width)
if window.minimumHeight() > target_height:
window.setMinimumHeight(target_height)
if window.maximumWidth() < target_width:
window.setMaximumWidth(target_width)
if window.maximumHeight() < target_height:
window.setMaximumHeight(target_height)
window.resize(target_width, target_height)
frame = window.frameGeometry()
window.move(
target.center().x() - frame.width() // 2,
target.center().y() - frame.height() // 2,
)
class _BusinessDialogStyleFilter(QObject):
"""Style dynamically-created Qt dialogs just before they become visible."""
@staticmethod
def _is_native_or_overlay(dialog: QDialog) -> bool:
return (
isinstance(dialog, QFileDialog)
or dialog.metaObject().className() == "QPrintDialog"
or dialog.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
)
#: The filter is installed on the QApplication, so it is handed every event
#: in the process - roughly 5,000 per list refresh. Only two event types
#: matter, and bailing on the type before touching ``isinstance`` keeps the
#: hot path to a single comparison.
_WATCHED = frozenset({QEvent.Type.Polish, QEvent.Type.Show})
#: Reading surfaces that get eased wheel scrolling when they are polished.
#: Deliberately not every ``QAbstractScrollArea``: animating the scrollbar of
#: an item view that hosts a widget per row means repainting those widgets
#: for the length of the animation, which would trade a jerky scroll for a
#: slow one. The list pages opt their own tables in individually.
_SMOOTH_SCROLL = (QScrollArea, QTextEdit, QTextBrowser, QPlainTextEdit)
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802
event_type = event.type()
if event_type not in self._WATCHED:
return False
if event_type is QEvent.Type.Polish and isinstance(watched, self._SMOOTH_SCROLL):
motion.install_smooth_scroll(watched)
return False
if isinstance(watched, QDialogButtonBox):
_polish_dialog_buttons(watched)
elif isinstance(watched, QDialog) and event_type == QEvent.Type.Polish:
# Window flags can only be changed before the dialog is on screen,
# so dynamically-created dialogs get their affordances at polish
# time rather than when they are already visible.
if not self._is_native_or_overlay(watched):
allow_dialog_resize(watched)
elif isinstance(watched, QDialog) and event_type == QEvent.Type.Show:
_size_new_window_to_main(watched)
for button_box in watched.findChildren(QDialogButtonBox):
_polish_dialog_buttons(button_box)
if not self._is_native_or_overlay(watched):
mark_business_dialog(watched)
if isinstance(watched, QMessageBox):
icon_kinds = {
QMessageBox.Icon.Information: "info",
QMessageBox.Icon.Warning: "warning",
QMessageBox.Icon.Critical: "critical",
QMessageBox.Icon.Question: "question",
}
watched.setProperty("messageKind", icon_kinds.get(watched.icon(), "plain"))
watched.setMinimumWidth(max(watched.minimumWidth(), 460))
elif isinstance(watched, QInputDialog):
watched.setMinimumWidth(max(watched.minimumWidth(), 480))
elif (
isinstance(watched, QWidget)
and event_type == QEvent.Type.Show
and watched.isWindow()
and watched.windowType() == Qt.WindowType.Window
):
_size_new_window_to_main(watched)
return False
def _install_business_dialog_styling(app: QApplication) -> None:
existing = getattr(app, "_doctor_business_dialog_style_filter", None)
if existing is not None:
return
style_filter = _BusinessDialogStyleFilter(app)
app.installEventFilter(style_filter)
app._doctor_business_dialog_style_filter = style_filter
def apply_theme(app: QApplication) -> None:
"""Apply the global Fusion palette and stylesheet to ``app``."""
app.setStyle("Fusion")
cjk_family = _register_preferred_cjk_fonts()
# Resolve once for both styled widgets and custom-painted table cells.
application_font = QFont(cjk_family)
application_font.setPixelSize(int(TYPE["fs_body"].removesuffix("px")))
application_font.setWeight(QFont.Weight.Normal)
application_font.setStyleStrategy(
QFont.StyleStrategy.PreferAntialias
| QFont.StyleStrategy.PreferOutline
)
# Keep the platform's pixel fitting and subpixel rendering available.
# Forcing grayscale plus vertical-only hinting softens small Windows text.
application_font.setHintingPreference(QFont.HintingPreference.PreferDefaultHinting)
app.setFont(application_font)
palette = QPalette()
active = {
QPalette.ColorRole.WindowText: COLORS["text"],
QPalette.ColorRole.Button: COLORS["surface_alt"],
QPalette.ColorRole.Light: "#FFFFFF",
QPalette.ColorRole.Midlight: COLORS["line"],
QPalette.ColorRole.Dark: COLORS["canvas"],
QPalette.ColorRole.Mid: COLORS["line"],
QPalette.ColorRole.Text: COLORS["text"],
QPalette.ColorRole.BrightText: "#FFFFFF",
QPalette.ColorRole.ButtonText: COLORS["text"],
QPalette.ColorRole.Base: COLORS["surface"],
QPalette.ColorRole.Window: COLORS["canvas"],
QPalette.ColorRole.Shadow: "#C2C2C2",
QPalette.ColorRole.Highlight: COLORS["indigo"],
QPalette.ColorRole.HighlightedText: "#FFFFFF",
QPalette.ColorRole.Link: COLORS["info"],
QPalette.ColorRole.LinkVisited: COLORS["indigo_hover"],
QPalette.ColorRole.AlternateBase: COLORS["surface_alt"],
QPalette.ColorRole.ToolTipBase: COLORS["raised"],
QPalette.ColorRole.ToolTipText: COLORS["text"],
QPalette.ColorRole.PlaceholderText: COLORS["muted"],
QPalette.ColorRole.Accent: COLORS["indigo"],
}
disabled = {
QPalette.ColorRole.WindowText: COLORS["disabled_text"],
QPalette.ColorRole.Button: COLORS["disabled_surface"],
QPalette.ColorRole.Light: COLORS["line"],
QPalette.ColorRole.Midlight: COLORS["line"],
QPalette.ColorRole.Dark: COLORS["canvas"],
QPalette.ColorRole.Mid: COLORS["line"],
QPalette.ColorRole.Text: COLORS["disabled_text"],
QPalette.ColorRole.BrightText: COLORS["muted"],
QPalette.ColorRole.ButtonText: COLORS["disabled_text"],
QPalette.ColorRole.Base: COLORS["disabled_surface"],
QPalette.ColorRole.Window: COLORS["canvas"],
QPalette.ColorRole.Shadow: "#D2D2D2",
QPalette.ColorRole.Highlight: COLORS["line"],
QPalette.ColorRole.HighlightedText: COLORS["disabled_text"],
QPalette.ColorRole.Link: COLORS["disabled_text"],
QPalette.ColorRole.LinkVisited: COLORS["disabled_text"],
QPalette.ColorRole.AlternateBase: COLORS["disabled_surface"],
QPalette.ColorRole.ToolTipBase: COLORS["raised"],
QPalette.ColorRole.ToolTipText: COLORS["disabled_text"],
QPalette.ColorRole.PlaceholderText: COLORS["disabled_text"],
QPalette.ColorRole.Accent: COLORS["line"],
}
_apply_group(palette, QPalette.ColorGroup.Active, active)
_apply_group(palette, QPalette.ColorGroup.Inactive, active)
_apply_group(palette, QPalette.ColorGroup.Disabled, disabled)
app.setPalette(palette)
app.setStyleSheet(GLOBAL_QSS + _indicator_qss())
_install_business_dialog_styling(app)
__all__ = [
"COLORS",
"allow_dialog_resize",
"apply_reading_rhythm",
"GLOBAL_QSS",
"METRICS",
"TYPE",
"WEIGHTS",
"apply_theme",
"crisp_pixmap",
"mark_business_dialog",
"main_window_target_rect",
]