diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py index c2a4c414e..cca422dd0 100755 --- a/app/src/doctor_workstation/app.py +++ b/app/src/doctor_workstation/app.py @@ -16,11 +16,6 @@ from PySide6.QtGui import QGuiApplication, QIcon from PySide6.QtWidgets import ( QApplication, QDialog, - QFrame, - QHBoxLayout, - QLabel, - QPushButton, - QVBoxLayout, QWidget, ) @@ -37,12 +32,13 @@ from doctor_workstation.services import ( ) from doctor_workstation.ui import LoginWindow, ShellWindow, apply_theme from doctor_workstation.ui.dialogs.app_update import AppUpdateSession +from doctor_workstation.ui.dialogs.video_cockpit import VideoCockpitDemoDialog as DemoVideoDialog from doctor_workstation.ui.widgets import ( first_value, friendly_error, gender_text, get_value, - has_permission, + has_permission, run_async, set_authentication_expired_handler, show_toast, @@ -295,109 +291,6 @@ class _UnconfiguredRepository: return None -class DemoVideoDialog(QDialog): - """Non-network video-room preview used only by the explicit demo mode.""" - - def __init__(self, patient_name: str, parent: QWidget | None = None) -> None: - super().__init__(parent) - self._seconds = 0 - self.setWindowTitle("视频面诊 · 演示模式") - self.setMinimumSize(760, 520) - self.resize(980, 660) - self.setModal(False) - self.setStyleSheet( - "QDialog{background:#F7F9FE;color:#111F46;}" - "QLabel{color:#111F46;}" - "QFrame#RemoteStage{background:#0E1421;border:1px solid #29334F;border-radius:16px;}" - "QFrame#RemoteStage QLabel{color:#F7F9FE;}" - "QFrame#LocalStage{background:#151D31;border:1px solid #3F4E75;border-radius:12px;}" - "QPushButton{min-width:96px;min-height:40px;padding:0 16px;border-radius:9px;" - "background:#FFFFFF;color:#3F4E75;border:1px solid #E6EAF5;font-weight:600;}" - "QPushButton:hover{color:#4451E2;background:#F0F2FF;border-color:#5761F4;}" - "QPushButton:checked{color:#FFFFFF;background:#5761F4;border-color:#5761F4;}" - "QPushButton#Hangup{color:#FFFFFF;background:#C23D4E;border-color:#C23D4E;}" - "QPushButton#Hangup:hover{background:#D94857;border-color:#D94857;}" - ) - - root = QVBoxLayout(self) - root.setContentsMargins(22, 18, 22, 22) - root.setSpacing(14) - header = QHBoxLayout() - title = QLabel(f"与 {patient_name or '患者'} 的视频面诊") - title.setStyleSheet("font-size:18px;font-weight:700;") - header.addWidget(title) - header.addStretch(1) - demo = QLabel("● 演示模式 · 未连接腾讯云") - demo.setStyleSheet("color:#707584;font-size:12px;") - header.addWidget(demo) - self.duration_label = QLabel("00:00") - self.duration_label.setStyleSheet("font-weight:700;") - header.addWidget(self.duration_label) - root.addLayout(header) - - stage = QFrame() - stage.setObjectName("RemoteStage") - stage_layout = QVBoxLayout(stage) - stage_layout.setContentsMargins(22, 22, 22, 22) - stage_layout.addStretch(1) - avatar = QLabel((patient_name or "患")[:1]) - avatar.setAlignment(Qt.AlignmentFlag.AlignCenter) - avatar.setFixedSize(104, 104) - avatar.setStyleSheet( - "background:#F0F2FF;color:#5761F4;border-radius:52px;font-size:42px;font-weight:700;" - ) - stage_layout.addWidget(avatar, 0, Qt.AlignmentFlag.AlignHCenter) - waiting = QLabel("等待患者接听…") - waiting.setAlignment(Qt.AlignmentFlag.AlignCenter) - waiting.setStyleSheet("font-size:17px;font-weight:600;") - stage_layout.addWidget(waiting) - hint = QLabel("生产模式将通过后端短时 UserSig 初始化腾讯 TUICallKit") - hint.setAlignment(Qt.AlignmentFlag.AlignCenter) - hint.setStyleSheet("color:#A4ADC3;font-size:12px;") - stage_layout.addWidget(hint) - stage_layout.addStretch(1) - - local = QFrame(stage) - local.setObjectName("LocalStage") - local.setGeometry(24, 24, 178, 112) - local_layout = QVBoxLayout(local) - local_label = QLabel("医生画面") - local_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - local_label.setStyleSheet("color:#D9E0F2;font-weight:600;") - local_layout.addWidget(local_label) - root.addWidget(stage, 1) - - controls = QHBoxLayout() - controls.addStretch(1) - self.mic_button = QPushButton("麦克风 开") - self.mic_button.setCheckable(True) - self.mic_button.toggled.connect( - lambda muted: self.mic_button.setText("麦克风 关" if muted else "麦克风 开") - ) - controls.addWidget(self.mic_button) - self.camera_button = QPushButton("摄像头 开") - self.camera_button.setCheckable(True) - self.camera_button.toggled.connect( - lambda off: self.camera_button.setText("摄像头 关" if off else "摄像头 开") - ) - controls.addWidget(self.camera_button) - hangup = QPushButton("结束面诊") - hangup.setObjectName("Hangup") - hangup.clicked.connect(self.close) - controls.addWidget(hangup) - controls.addStretch(1) - root.addLayout(controls) - - self._timer = QTimer(self) - self._timer.timeout.connect(self._tick) - self._timer.start(1000) - - def _tick(self) -> None: - self._seconds += 1 - minutes, seconds = divmod(self._seconds, 60) - self.duration_label.setText(f"{minutes:02d}:{seconds:02d}") - - class ApplicationController(QObject): """Own windows, repositories and the authenticated application lifecycle.""" @@ -414,8 +307,8 @@ class ApplicationController(QObject): self.current_repository: Any = None self.current_demo_mode = self.debug_mode and config.demo_mode self.video_calls: dict[str, Any] = {} - self.video_pending: dict[str, object] = {} - self._pending_im_request: tuple[str, object] | None = None + self.video_pending: dict[str, object] = {} + self._pending_im_request: tuple[str, object] | None = None self.demo_video_dialogs: dict[str, DemoVideoDialog] = {} self._video_preview_state: dict[str, Any] | None = None self._video_preview_generation = 0 @@ -790,8 +683,8 @@ class ApplicationController(QObject): call.close() self._wait_for_video_lifecycle(calls, timeout=1.25) self.video_calls.clear() - self.video_pending.clear() - self._pending_im_request = None + self.video_pending.clear() + self._pending_im_request = None for dialog in tuple(self.demo_video_dialogs.values()): dialog.close() self.demo_video_dialogs.clear() @@ -821,8 +714,8 @@ class ApplicationController(QObject): if parent is None or self.current_repository is None: return patient_id = payload.get("patient_id") - diagnosis_id = payload.get("diagnosis_id") - appointment_id = int(payload.get("appointment_id") or 0) + diagnosis_id = payload.get("diagnosis_id") + appointment_id = int(payload.get("appointment_id") or 0) patient_name = str(payload.get("patient_name") or "患者") open_im = str(payload.get("mode") or "video").lower() == "im" fallback_record = payload.get("record") @@ -830,16 +723,16 @@ class ApplicationController(QObject): show_toast(parent, "患者或诊单信息不完整,无法发起视频。", "danger", 4200) return - call_key = f"{diagnosis_id}:{appointment_id}" - if open_im and self._pending_im_request is not None: - pending_key, pending_marker = self._pending_im_request - if pending_key != call_key: - # Retire a previous selection before any early return, including - # when the selected IM window is already open. - if self.video_pending.get(pending_key) is pending_marker: - self.video_pending.pop(pending_key, None) - self._pending_im_request = None - existing_call = self.video_calls.get(call_key) + call_key = f"{diagnosis_id}:{appointment_id}" + if open_im and self._pending_im_request is not None: + pending_key, pending_marker = self._pending_im_request + if pending_key != call_key: + # Retire a previous selection before any early return, including + # when the selected IM window is already open. + if self.video_pending.get(pending_key) is pending_marker: + self.video_pending.pop(pending_key, None) + self._pending_im_request = None + existing_call = self.video_calls.get(call_key) if open_im and existing_call is not None and getattr(existing_call, "open_im", False): qt_window = getattr(existing_call, "qt_window", None) if qt_window is not None: @@ -885,18 +778,18 @@ class ApplicationController(QObject): ) repository = self.current_repository marker = object() - self.video_pending[call_key] = marker - if open_im: - self._pending_im_request = (call_key, marker) + self.video_pending[call_key] = marker + if open_im: + self._pending_im_request = (call_key, marker) def get_video_context() -> tuple[Any, dict[str, str]]: ticket = repository.get_call_ticket( patient_id=int(patient_id), - diagnosis_id=int(diagnosis_id), - appointment_id=appointment_id, - ) - if appointment_id and int(ticket.raw.get("appointment_id") or 0) != appointment_id: - raise ValueError("通话凭证与本次挂号不匹配,请重新打开聊天窗口。") + diagnosis_id=int(diagnosis_id), + appointment_id=appointment_id, + ) + if appointment_id and int(ticket.raw.get("appointment_id") or 0) != appointment_id: + raise ValueError("通话凭证与本次挂号不匹配,请重新打开聊天窗口。") detail: Any = {} detail_loader = getattr(repository, "patient_detail", None) if callable(detail_loader): @@ -957,12 +850,12 @@ class ApplicationController(QObject): parent: QWidget, error: Exception, ) -> None: - if self.video_pending.get(call_key) is not marker: - return - self.video_pending.pop(call_key, None) - if self._pending_im_request == (call_key, marker): - self._pending_im_request = None - if self.shell_window is parent: + if self.video_pending.get(call_key) is not marker: + return + self.video_pending.pop(call_key, None) + if self._pending_im_request == (call_key, marker): + self._pending_im_request = None + if self.shell_window is parent: show_toast( parent, f"视频准备失败:{friendly_error(error)}", @@ -983,11 +876,11 @@ class ApplicationController(QObject): patient_name: str = "患者", patient_case: Mapping[str, Any] | None = None, ) -> None: - if self.video_pending.get(call_key) is not marker: - return - self.video_pending.pop(call_key, None) - if self._pending_im_request == (call_key, marker): - self._pending_im_request = None + if self.video_pending.get(call_key) is not marker: + return + self.video_pending.pop(call_key, None) + if self._pending_im_request == (call_key, marker): + self._pending_im_request = None if ( self.shell_window is None or self.current_repository is not repository @@ -1012,13 +905,13 @@ class ApplicationController(QObject): open_im=open_im, patient_name=patient_name, patient_case=patient_case, - can_ai_assistant=has_permission( - getattr(self.shell_window, "permissions", None), - "tcm.diagnosis/aiAssistant", - default=False, - ), - on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: ( - self._open_video_diagnosis(current_id, call_key=current_key) + can_ai_assistant=has_permission( + getattr(self.shell_window, "permissions", None), + "tcm.diagnosis/aiAssistant", + default=False, + ), + on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: ( + self._open_video_diagnosis(current_id, call_key=current_key) ), ) except Exception as error: @@ -1040,7 +933,7 @@ class ApplicationController(QObject): ) ) - def _open_video_diagnosis(self, diagnosis_id: Any, *, call_key: str) -> None: + def _open_video_diagnosis(self, diagnosis_id: Any, *, call_key: str) -> None: """Open the diagnosis while keeping its live video visible as a preview.""" shell = self.shell_window @@ -1049,7 +942,7 @@ class ApplicationController(QObject): dialog = shell.open_diagnosis_by_id(diagnosis_id, modeless=True) if dialog is None: return - call = self.video_calls.get(call_key) + call = self.video_calls.get(call_key) video_window = getattr(call, "qt_window", None) if video_window is not None: self._show_video_preview(video_window, dialog) @@ -1082,8 +975,8 @@ class ApplicationController(QObject): preview_height = min(380, max(320, round(preview_width * 0.66))) margin = 18 - if callable(getattr(video_window, "setProperty", None)): - video_window.setProperty("doctorSkipOpenGeometry", True) + if callable(getattr(video_window, "setProperty", None)): + video_window.setProperty("doctorSkipOpenGeometry", True) video_window.showNormal() video_window.setMinimumSize(440, 300) video_window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True) @@ -1102,14 +995,14 @@ class ApplicationController(QObject): lambda _result, expected=generation: self._restore_video_preview(expected) ) try: - set_close_handler = getattr(video_window, "set_compact_close_handler", None) - if callable(set_close_handler): - set_close_handler(lambda expected=generation: self._restore_video_preview(expected)) + set_close_handler = getattr(video_window, "set_compact_close_handler", None) + if callable(set_close_handler): + set_close_handler(lambda expected=generation: self._restore_video_preview(expected)) video_window.raise_() dialog.raise_() dialog.activateWindow() except RuntimeError: - self._restore_video_preview(generation, activate=False) + self._restore_video_preview(generation, activate=False) def _restore_video_preview( self, @@ -1126,12 +1019,12 @@ class ApplicationController(QObject): self._video_preview_generation += 1 window = state.get("window") try: - set_close_handler = getattr(window, "set_compact_close_handler", None) - if callable(set_close_handler): - set_close_handler(None) - restore_screenshot = getattr(window, "restore_screenshot_preview", None) - if callable(restore_screenshot): - restore_screenshot() + set_close_handler = getattr(window, "set_compact_close_handler", None) + if callable(set_close_handler): + set_close_handler(None) + restore_screenshot = getattr(window, "restore_screenshot_preview", None) + if callable(restore_screenshot): + restore_screenshot() window.setWindowFlag( Qt.WindowType.WindowStaysOnTopHint, bool(state.get("stays_on_top")), @@ -1147,8 +1040,8 @@ class ApplicationController(QObject): window.raise_() if activate: window.activateWindow() - if callable(getattr(window, "setProperty", None)): - window.setProperty("doctorSkipOpenGeometry", False) + if callable(getattr(window, "setProperty", None)): + window.setProperty("doctorSkipOpenGeometry", False) except (AttributeError, RuntimeError): return diff --git a/app/src/doctor_workstation/ui/appointment_drawer.py b/app/src/doctor_workstation/ui/appointment_drawer.py index aba2a6b9b..922050a81 100755 --- a/app/src/doctor_workstation/ui/appointment_drawer.py +++ b/app/src/doctor_workstation/ui/appointment_drawer.py @@ -41,10 +41,10 @@ from PySide6.QtWidgets import ( QWidget, ) -from ..core.appointment_modes import APPOINTMENT_MODES -from .design_system import clinical_stylesheet -from .theme import main_window_target_rect -from .widgets import ( +from ..core.appointment_modes import APPOINTMENT_MODES +from .design_system import PALETTE, clinical_stylesheet +from .theme import main_window_target_rect +from .widgets import ( display_text, first_value, friendly_error, @@ -640,7 +640,7 @@ class _Spinner(QWidget): del event painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - pen = QPen(QColor("#4F63D9"), 3) + pen = QPen(QColor(PALETTE["accent"]), 3) pen.setCapStyle(Qt.PenCapStyle.RoundCap) painter.setPen(pen) painter.drawArc(self.rect().adjusted(4, 4, -4, -4), self._angle * 16, 255 * 16) diff --git a/app/src/doctor_workstation/ui/appointments_style.py b/app/src/doctor_workstation/ui/appointments_style.py index 134f8e343..249b9b4c3 100755 --- a/app/src/doctor_workstation/ui/appointments_style.py +++ b/app/src/doctor_workstation/ui/appointments_style.py @@ -31,22 +31,27 @@ _QSS = """ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel; } #AppointmentsPage QPushButton { - min-height: 30px; padding: 0 12px; border: 1px solid transparent; - border-radius: $ds_radius_control; background: $ds_surface_alt; + min-height: 32px; padding: 0 13px; border: 1px solid $ds_line_strong; + border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text; + font-weight: 500; } -#AppointmentsPage QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; } -#AppointmentsPage QPushButton:pressed { background: $ds_accent_soft; } +#AppointmentsPage QPushButton:hover { color: $ds_accent; background: $ds_accent_soft; border-color: #9CCFC7; } +#AppointmentsPage QPushButton:pressed { background: #D7EFEA; } #AppointmentsPage QPushButton:focus { border-color: $ds_focus; } #AppointmentsPage QPushButton[variant="primary"] { - background: $ds_accent; color: $ds_surface; border-color: $ds_accent; + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent); + color: $ds_surface; border-color: $ds_accent; +} +#AppointmentsPage QPushButton[variant="primary"]:hover { + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover); + border-color: $ds_accent_hover; } -#AppointmentsPage QPushButton[variant="primary"]:hover { background: $ds_accent_hover; } #AppointmentsPage QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; } #AppointmentsPage QPushButton[variant="primary"]:focus { border-color: $ds_focus; } #AppointmentsPage QPushButton[variant="danger"] { - color: $ds_danger; background: $ds_danger_soft; border-color: transparent; + color: $ds_danger; background: $ds_danger_soft; border-color: #F5C8CD; } -#AppointmentsPage QPushButton[variant="danger"]:hover { background: $ds_danger_soft; } +#AppointmentsPage QPushButton[variant="danger"]:hover { background: #FBDCE0; border-color: #E79DA6; } #AppointmentsPage QPushButton[variant="danger"]:pressed { border-color: $ds_danger; } #AppointmentsPage QPushButton[variant="ghost"] { background: transparent; border-color: transparent; } #AppointmentsPage QPushButton[variant="ghost"]:hover { background: $ds_accent_soft; } @@ -101,9 +106,20 @@ _QSS = """ min-height: 36px; max-height: 36px; padding: 0 17px; font-size: 13px; } #AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled { - color: $ds_text; border-color: transparent; + color: $ds_text; + background: $ds_surface; + border: 1px solid $ds_line_strong; + border-radius: $ds_radius_control; +} +#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled:hover { + color: $ds_accent; + background: $ds_accent_soft; + border-color: #8FC8C0; +} +#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled:pressed { + background: #D6ECE8; + border-color: $ds_accent; } -#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:hover { color: $ds_accent; background: $ds_accent_soft; } #AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:focus { border-color: $ds_focus; } #AppointmentsPage QTableWidget#AppointmentTable { background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0; diff --git a/app/src/doctor_workstation/ui/chat_notifications.py b/app/src/doctor_workstation/ui/chat_notifications.py index a29f21717..2da5cc668 100755 --- a/app/src/doctor_workstation/ui/chat_notifications.py +++ b/app/src/doctor_workstation/ui/chat_notifications.py @@ -42,56 +42,58 @@ _MAX_CARDS = 5 _POLL_INTERVAL_MS = 5_000 CHAT_NOTIFICATION_QSS = """ +/* W8 原语 C:右下角黑曜翡翠临床实时提醒浮卡 + 香槟鎏金切边 */ QFrame#ChatNotifyCard { - background-color: #FFFFFF; - border: 1px solid #BBF0CE; - border-radius: 12px; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #103231, stop:1 #071919); + border: 1px solid rgba(223, 199, 147, 136); + border-radius: 13px; } -QFrame#ChatNotifyCard[kind="left"] { border-color: #E4E4E5; } -QFrame#ChatNotifyCard[kind="complete"] { border-color: #8B9AD9; } +QFrame#ChatNotifyCard[kind="left"] { border-color: rgba(164, 196, 192, 90); } +QFrame#ChatNotifyCard[kind="complete"] { border-color: rgba(84, 230, 193, 140); } QLabel#ChatNotifyBadge { min-width: 34px; max-width: 34px; min-height: 34px; max-height: 34px; color: #FFFFFF; - background-color: #287B65; - border-radius: 9px; - font-size: 15px; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #19B2A8, stop:1 #0B6E68); + border: 1px solid rgba(223, 199, 147, 120); + border-radius: 10px; + font-size: 14px; font-weight: 700; } -QLabel#ChatNotifyBadge[kind="left"] { background-color: #6A6B6D; } -QLabel#ChatNotifyBadge[kind="complete"] { background-color: #4F63D9; } -QLabel#ChatNotifyTitle { color: #1A1C1F; font-size: 13px; font-weight: 700; } -QLabel#ChatNotifyDesc { color: #1A1C1F; font-size: 12px; } -QLabel#ChatNotifyTime { color: #6A6B6D; font-size: 11px; } +QLabel#ChatNotifyBadge[kind="left"] { background-color: #355250; } +QLabel#ChatNotifyBadge[kind="complete"] { background-color: #B8924A; } +QLabel#ChatNotifyTitle { color: #DFC793; font-size: 13px; font-weight: 700; } +QLabel#ChatNotifyDesc { color: #EEF8F7; font-size: 12px; } +QLabel#ChatNotifyTime { color: #8EB5B1; font-size: 11px; } QPushButton#ChatNotifyOpen { - min-height: 26px; - padding: 0 10px; - color: #4F63D9; - background-color: #EEF1FA; - border: 1px solid #EDEDEE; + min-height: 28px; + padding: 0 12px; + color: #FFFFFF; + background-color: rgba(24, 176, 165, 86); + border: 1px solid rgba(223, 199, 147, 128); border-radius: 7px; font-size: 12px; font-weight: 600; } QPushButton#ChatNotifyOpen:hover { - color: #4156C4; - background-color: #EEF1FA; - border-color: #8B9AD9; + color: #FFFFFF; + background-color: #0B6E68; + border-color: #DFC793; } QPushButton#ChatNotifyClose { min-width: 22px; max-width: 22px; min-height: 22px; max-height: 22px; - color: #6A6B6D; + color: #93B8B4; background-color: transparent; border: 0; border-radius: 6px; font-size: 14px; } -QPushButton#ChatNotifyClose:hover { color: #1A1C1F; background-color: #F7F7F7; } +QPushButton#ChatNotifyClose:hover { color: #FFFFFF; background-color: rgba(255, 255, 255, 28); } """ diff --git a/app/src/doctor_workstation/ui/command_palette.py b/app/src/doctor_workstation/ui/command_palette.py new file mode 100644 index 000000000..d34e48ef0 --- /dev/null +++ b/app/src/doctor_workstation/ui/command_palette.py @@ -0,0 +1,341 @@ +"""Ctrl+K 悬浮智诊命令中枢(Command Palette):键盘优先的现代桌面快捷导航与患者检索.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +from PySide6.QtCore import QEvent, QRectF, QSize, Qt +from PySide6.QtGui import ( + QColor, + QKeyEvent, + QLinearGradient, + QPainter, +) +from PySide6.QtWidgets import ( + QDialog, + QFrame, + QHBoxLayout, + QLabel, + QLineEdit, + QListWidget, + QListWidgetItem, + QPushButton, + QVBoxLayout, + QWidget, +) + +from . import icons, motion +from .design_system import clinical_stylesheet + + +@dataclass(frozen=True) +class CommandEntry: + """命令中枢中的单条可执行指令。""" + + key: str + title: str + subtitle: str + icon_kind: str + category: str + shortcut: str + action: Callable[[], None] + + +_PALETTE_QSS = clinical_stylesheet( + r""" + QDialog#CommandPaletteDialog { + background: transparent; + } + QFrame#CommandPaletteCard { + background-color: $ds_surface; + border: 1px solid #B7D3CE; + border-radius: 16px; + } + QFrame#CommandPaletteHeader { + background-color: #F7FBFA; + border: 0; + border-bottom: 1px solid $ds_line; + border-top-left-radius: 16px; + border-top-right-radius: 16px; + } + QLineEdit#CommandPaletteInput { + background: transparent; + border: 0; + color: $ds_heading; + font-size: 15px; + font-weight: 500; + padding: 4px 2px; + selection-background-color: $ds_accent_soft; + selection-color: $ds_heading; + } + QLabel#CommandPaletteEsc { + color: $ds_muted; + background-color: $ds_surface; + border: 1px solid $ds_line_strong; + border-radius: 6px; + padding: 2px 7px; + font-size: 11px; + font-weight: 500; + } + QListWidget#CommandPaletteList { + background: transparent; + border: 0; + outline: 0; + padding: 6px 8px; + } + QListWidget#CommandPaletteList::item { + border: 1px solid transparent; + border-radius: 10px; + padding: 8px 10px; + margin: 2px 0; + color: $ds_heading; + } + QListWidget#CommandPaletteList::item:hover { + background-color: #F2FAF9; + border-color: #D5E8E5; + } + QListWidget#CommandPaletteList::item:selected { + background-color: $ds_accent_soft; + border-color: #A9D6CF; + color: $ds_accent_hover; + } + QFrame#CommandPaletteFooter { + background-color: #F7FBFA; + border: 0; + border-top: 1px solid $ds_line; + border-bottom-left-radius: 16px; + border-bottom-right-radius: 16px; + } + QLabel#CommandPaletteHint { + color: $ds_muted; + font-size: 12px; + } + QPushButton#CommandPaletteClose { + min-width: 28px; + max-width: 28px; + min-height: 28px; + max-height: 28px; + padding: 0; + border: 1px solid transparent; + border-radius: 7px; + background: transparent; + color: $ds_muted; + } + QPushButton#CommandPaletteClose:hover { + background-color: $ds_danger_soft; + color: $ds_danger; + } + """ +) + + +class _PaletteCard(QFrame): + """带微妙顶缘香槟鎏金高光的悬浮命令卡片。""" + + def paintEvent(self, event: Any) -> None: # noqa: N802 + super().paintEvent(event) + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + bar = QRectF(18.0, 1.0, max(0.0, self.width() - 36.0), 2.0) + grad = QLinearGradient(bar.topLeft(), bar.topRight()) + grad.setColorAt(0.0, QColor(11, 110, 104, 0)) + grad.setColorAt(0.28, QColor(24, 168, 158, 180)) + grad.setColorAt(0.50, QColor(223, 199, 147, 210)) + grad.setColorAt(0.72, QColor(24, 168, 158, 180)) + grad.setColorAt(1.0, QColor(11, 110, 104, 0)) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(grad) + painter.drawRoundedRect(bar, 1.0, 1.0) + painter.end() + + +class CommandPaletteDialog(QDialog): + """桌面端全局 Ctrl+K 悬浮命令与患者检索面板。""" + + def __init__( + self, + entries: list[CommandEntry], + *, + on_search_patient: Callable[[str], None] | None = None, + initial_query: str = "", + parent: QWidget | None = None, + ) -> None: + super().__init__(parent) + self.setObjectName("CommandPaletteDialog") + self.setProperty("doctorSkipOpenGeometry", True) + self.setWindowFlags( + Qt.WindowType.FramelessWindowHint + | Qt.WindowType.Dialog + | Qt.WindowType.NoDropShadowWindowHint + ) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setModal(True) + self.setStyleSheet(_PALETTE_QSS) + + self._entries = list(entries) + self._on_search_patient = on_search_patient + self._visible_actions: list[Callable[[], None]] = [] + + root = QVBoxLayout(self) + root.setContentsMargins(12, 12, 12, 12) + + self.card = _PaletteCard(self) + self.card.setObjectName("CommandPaletteCard") + self.card.setFixedWidth(568) + card_layout = QVBoxLayout(self.card) + card_layout.setContentsMargins(0, 0, 0, 0) + card_layout.setSpacing(0) + + # 顶部搜索栏 + header = QFrame(self.card) + header.setObjectName("CommandPaletteHeader") + header.setFixedHeight(56) + header_layout = QHBoxLayout(header) + header_layout.setContentsMargins(16, 0, 14, 0) + header_layout.setSpacing(10) + + search_icon = QLabel(header) + search_icon.setPixmap(icons.pixmap("search", "accent", 18)) + header_layout.addWidget(search_icon) + + self.input = QLineEdit(header) + self.input.setObjectName("CommandPaletteInput") + self.input.setPlaceholderText("输入页面名称、快捷指令,或患者姓名/手机号回车搜索...") + self.input.setText(initial_query) + self.input.textChanged.connect(self._rebuild_list) + self.input.installEventFilter(self) + header_layout.addWidget(self.input, 1) + + esc_hint = QLabel("ESC", header) + esc_hint.setObjectName("CommandPaletteEsc") + esc_hint.setFixedHeight(24) + header_layout.addWidget(esc_hint, 0, Qt.AlignmentFlag.AlignVCenter) + + close_btn = QPushButton(header) + close_btn.setObjectName("CommandPaletteClose") + close_btn.setIcon(icons.icon("close", "muted", 14)) + close_btn.setIconSize(QSize(14, 14)) + close_btn.setCursor(Qt.CursorShape.PointingHandCursor) + close_btn.clicked.connect(self.reject) + header_layout.addWidget(close_btn) + card_layout.addWidget(header) + + # 指令列表 + self.list_widget = QListWidget(self.card) + self.list_widget.setObjectName("CommandPaletteList") + self.list_widget.setFixedHeight(296) + self.list_widget.setIconSize(QSize(18, 18)) + self.list_widget.setSpacing(2) + self.list_widget.itemActivated.connect(self._activate_item) + self.list_widget.itemClicked.connect(self._activate_item) + card_layout.addWidget(self.list_widget) + + # 底部键盘引导条 + footer = QFrame(self.card) + footer.setObjectName("CommandPaletteFooter") + footer.setFixedHeight(36) + footer_layout = QHBoxLayout(footer) + footer_layout.setContentsMargins(16, 0, 16, 0) + hint = QLabel("↑↓ 选择 · Enter 执行 · Esc 关闭", footer) + hint.setObjectName("CommandPaletteHint") + footer_layout.addWidget(hint) + footer_layout.addStretch(1) + brand = QLabel("甄养堂 · 智诊指令中枢", footer) + brand.setObjectName("CommandPaletteHint") + footer_layout.addWidget(brand) + card_layout.addWidget(footer) + + root.addWidget(self.card) + self.adjustSize() + self._rebuild_list(initial_query) + + def showEvent(self, event: Any) -> None: # noqa: N802 + super().showEvent(event) + parent = self.parentWidget() + if parent is not None: + host = parent.window().frameGeometry() + x = host.center().x() - self.width() // 2 + y = host.top() + max(72, round(host.height() * 0.14)) + self.move(x, y) + self.input.setFocus(Qt.FocusReason.PopupFocusReason) + self.input.selectAll() + motion.fade_in(self.card, duration=motion.FAST) + + def paintEvent(self, event: Any) -> None: # noqa: N802 + del event + # 柔和冷青科技外光环,在透明无边框弹窗周围营造立体层次 + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + card_rect = QRectF(self.card.geometry()) + for expand, alpha in ((8.0, 14), (5.0, 22), (2.0, 32)): + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(11, 46, 44, alpha)) + painter.drawRoundedRect( + card_rect.adjusted(-expand, -expand + 2.0, expand, expand + 4.0), + 16.0 + expand * 0.4, + 16.0 + expand * 0.4, + ) + painter.end() + + def _rebuild_list(self, raw_query: str) -> None: + query = raw_query.strip() + lowered = query.lower() + self.list_widget.clear() + self._visible_actions.clear() + + if query and self._on_search_patient is not None: + item = QListWidgetItem( + icons.icon("search", "accent", 18), + f"检索患者「{query}」 — 直达患者与问诊列表", + ) + self.list_widget.addItem(item) + self._visible_actions.append( + lambda q=query, cb=self._on_search_patient: cb(q) + ) + + for entry in self._entries: + haystack = f"{entry.title} {entry.subtitle} {entry.category}".lower() + if lowered and lowered not in haystack: + continue + label = f"{entry.title} · {entry.subtitle}" + if entry.shortcut: + label = f"{label} [{entry.shortcut}]" + item = QListWidgetItem(icons.icon(entry.icon_kind, "accent", 18), label) + self.list_widget.addItem(item) + self._visible_actions.append(entry.action) + + if self.list_widget.count() > 0: + self.list_widget.setCurrentRow(0) + + def _activate_item(self, item: QListWidgetItem | None) -> None: + if item is None: + return + row = self.list_widget.row(item) + if 0 <= row < len(self._visible_actions): + action = self._visible_actions[row] + self.accept() + action() + + def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 + if watched is self.input and event.type() == QEvent.Type.KeyPress: + assert isinstance(event, QKeyEvent) + key = event.key() + if key in (Qt.Key.Key_Down, Qt.Key.Key_Up): + count = self.list_widget.count() + if count > 0: + step = 1 if key == Qt.Key.Key_Down else -1 + current = self.list_widget.currentRow() + self.list_widget.setCurrentRow((current + step) % count) + return True + if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter): + self._activate_item(self.list_widget.currentItem()) + return True + if key == Qt.Key.Key_Escape: + self.reject() + return True + return super().eventFilter(watched, event) + + +__all__ = ["CommandEntry", "CommandPaletteDialog"] diff --git a/app/src/doctor_workstation/ui/consultations_style.py b/app/src/doctor_workstation/ui/consultations_style.py index 286713d09..4624f502a 100755 --- a/app/src/doctor_workstation/ui/consultations_style.py +++ b/app/src/doctor_workstation/ui/consultations_style.py @@ -36,19 +36,26 @@ _QSS = """ background: transparent; border: 0; border-top: 1px solid $ds_line; border-radius: 0; } #DiagnosisIndex QPushButton { - min-height: 34px; padding: 0 13px; border: 1px solid transparent; - border-radius: $ds_radius_control; background: $ds_surface_alt; + min-height: 34px; padding: 0 13px; border: 1px solid $ds_line_strong; + border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text; font-weight: 500; } -#DiagnosisIndex QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; } -#DiagnosisIndex QPushButton:pressed { background: $ds_accent_soft; } +#DiagnosisIndex QPushButton:hover { color: $ds_accent; background: $ds_accent_soft; border-color: #9CCFC7; } +#DiagnosisIndex QPushButton:pressed { background: #D7EFEA; } #DiagnosisIndex QPushButton:focus { border-color: $ds_focus; } -#DiagnosisIndex QPushButton[variant="primary"] { color: $ds_surface; background: $ds_accent; border-color: $ds_accent; } -#DiagnosisIndex QPushButton[variant="primary"]:hover { background: $ds_accent_hover; } +#DiagnosisIndex QPushButton[variant="primary"] { + color: $ds_surface; + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent); + border-color: $ds_accent; +} +#DiagnosisIndex QPushButton[variant="primary"]:hover { + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover); + border-color: $ds_accent_hover; +} #DiagnosisIndex QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; } #DiagnosisIndex QPushButton[variant="primary"]:focus { border-color: $ds_focus; } -#DiagnosisIndex QPushButton[consultationTool="true"] { color: $ds_text; border-color: transparent; } -#DiagnosisIndex QPushButton[consultationTool="true"]:hover { color: $ds_accent; background: $ds_accent_soft; } -#DiagnosisIndex QPushButton[consultationDanger="true"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; } +#DiagnosisIndex QPushButton[consultationTool="true"] { color: $ds_text; border-color: $ds_line_strong; background: $ds_surface; } +#DiagnosisIndex QPushButton[consultationTool="true"]:hover { color: $ds_accent; background: $ds_accent_soft; border-color: #9CCFC7; } +#DiagnosisIndex QPushButton[consultationDanger="true"] { color: $ds_danger; background: $ds_danger_soft; border-color: #F5C8CD; } #DiagnosisIndex QPushButton[consultationDanger="true"]:hover { border-color: $ds_danger; } #DiagnosisIndex QPushButton[consultationTool="true"]:focus, #DiagnosisIndex QPushButton[consultationDanger="true"]:focus { border-color: $ds_focus; } diff --git a/app/src/doctor_workstation/ui/design_system.py b/app/src/doctor_workstation/ui/design_system.py index 0319c8a9e..c1eea8ce2 100644 --- a/app/src/doctor_workstation/ui/design_system.py +++ b/app/src/doctor_workstation/ui/design_system.py @@ -1,8 +1,8 @@ -"""Clinical desktop design tokens, shared by native pages and dialog chrome. +"""Clinical desktop design tokens — 御瓷智医 (Luxury Precision MedTech). -Keep data-series colours and video pixels outside this palette. Existing scoped -QSS can adopt the system without changing selectors, layout or permissions. -New rules should use the named ``$ds_*`` tokens rather than legacy colours. +Fuses medical trust, precision technology, quiet luxury (champagne gold micro-accents) +and contemporary editorial clarity. Shared by native pages, shell chrome, drawers and +dialogs. New rules should use the named ``$ds_*`` tokens rather than legacy colours. """ from __future__ import annotations @@ -11,60 +11,80 @@ import re from string import Template PALETTE = { - "canvas": "#F5F7FA", + # 三阶珍珠青瓷中性面:低眩光护眼,同时具备精密医疗仪器与高定材质层次 + "canvas": "#EFF4F3", "surface": "#FFFFFF", - "surface_alt": "#F7F9FC", - "sidebar": "#F0F3F8", - "line": "#E6EAF0", - "line_strong": "#D4DCE8", - "heading": "#223047", - "text": "#344258", - "muted": "#647287", - "disabled": "#8B96A6", - "disabled_surface": "#F0F2F5", - "accent": "#4267B2", - "accent_hover": "#355995", - "accent_pressed": "#2C4C82", - "accent_soft": "#EAF0FB", - "focus": "#6D8CCB", - "success": "#287B65", - "success_soft": "#EDF7F2", - "warning": "#96601D", - "warning_soft": "#FBF4E8", - "danger": "#B54A59", - "danger_soft": "#FCF0F2", + "surface_alt": "#F6FAFA", + "sidebar": "#E6EEED", + "line": "#DCE6E4", + "line_strong": "#C3D3D0", + # 曜青深墨文字阶梯:锐利、高级、高对比度 + "heading": "#0F2120", + "text": "#263938", + "muted": "#5C7270", + "disabled": "#95A8A6", + "disabled_surface": "#EDF2F1", + # 唯一品牌主色:甄养堂精密医疗翡翠青 (Jade Teal) + "accent": "#0B6E68", + "accent_hover": "#085954", + "accent_pressed": "#064743", + "accent_soft": "#E6F4F2", + "focus": "#18A89E", + # 贵气时尚微点缀:香槟鎏金 (Champagne Gold — 克制用于徽标切边、AI 科技星芒、尊享标识) + "gold": "#B8924A", + "gold_light": "#DFC793", + "gold_soft": "#FAF5EA", + # 深曜青科技底(用于 AI 科技卡与登录页品牌沉浸区) + "obsidian": "#0D2424", + "obsidian_alt": "#143534", + # 语义临床色 + "success": "#0E8A63", + "success_soft": "#E6F7F1", + "warning": "#B56B00", + "warning_soft": "#FEF5E6", + "danger": "#C83B4B", + "danger_soft": "#FDEEEF", } -RADII = {"small": 6, "control": 10, "panel": 16, "window": 20} +RADII = {"small": 6, "control": 8, "panel": 12, "window": 16} SPACING = {"small": 8, "control": 12, "group": 16, "section": 24} TOKENS = {f"ds_{name}": value for name, value in PALETTE.items()} TOKENS.update({f"ds_radius_{name}": f"{value}px" for name, value in RADII.items()}) TOKENS.update({f"ds_space_{name}": f"{value}px" for name, value in SPACING.items()}) -# Explicit migration of the two existing native palettes. This adapter only -# touches six-digit colour literals; selectors and metrics stay page-owned. +# 将全量旧版灰蓝/紫蓝/冷灰硬编码色值统一映射至「御瓷智医」设计令牌,确保所有历史弹窗与页面零色差 _LEGACY_ROLES = { - "accent": ("1769E8", "4F63D9", "5761F4", "5267DF"), - "accent_hover": ("155BCC", "1555B6", "4156C4", "4356C4", "4055CA"), - "accent_pressed": ("124EA9", "354BB4"), - "accent_soft": ("EAF2FF", "EEF1FA", "EEF0FF", "F0F2FF", "DCEAFF", "EDF0FC"), - "focus": ("75A5F0", "8B9AD9"), - "canvas": ("F3F7FD", "F4F6FA", "F6F6F6"), - "surface_alt": ("F7F7F7", "F7FAFE", "F5F8FD", "F7F9FE", "F2F7FF"), - "sidebar": ("EDF4FF",), - "line": ("DBE5F2", "EDEDEE", "E5ECF6", "E6EDF6", "E7EDF7", "EDF0F5", "E7EBF2", "E6EAF5"), - "line_strong": ("E4E4E5", "C8D5E6", "C9DCF7", "ADC8F0", "B6CDEE"), - "heading": ("1A1C1F", "202C3F", "111F46"), - "text": ("273244", "263551", "24334A", "233149", "3F4E75"), - "muted": ("606163", "6A6B6D", "5D6B80", "7886AA", "708097"), - "disabled": ("8E8F90", "8A97A9", "9AA6B7"), - "disabled_surface": ("F2F2F2", "F0F0F0"), - "success_soft": ("EEF7F3", "EAF9F3"), - "warning": ("A9691D", "9C681F"), - "warning_soft": ("FCF5E9", "FFF5E6", "FFF6E7"), - "danger": ("BE4B58", "B84652"), - "danger_soft": ("FFF0F2", "FFF1F3"), + "accent": ("4267B2", "1769E8", "4F63D9", "5761F4", "5267DF", "1555B6"), + "accent_hover": ("355995", "155BCC", "4156C4", "4356C4", "4055CA"), + "accent_pressed": ("2C4C82", "124EA9", "354BB4"), + "accent_soft": ( + "EAF0FB", "EAF2FF", "EEF1FA", "EEF0FF", "F0F2FF", "DCEAFF", "EDF0FC", + "F0F5FD", "D6E5FB", "E3E8F8", + ), + "focus": ("6D8CCB", "75A5F0", "8B9AD9"), + "canvas": ("F5F7FA", "F3F7FD", "F4F6FA", "F6F6F6"), + "surface_alt": ("F7F9FC", "F7F7F7", "F7FAFE", "F5F8FD", "F7F9FE", "F2F7FF"), + "sidebar": ("F0F3F8", "EDF4FF"), + "line": ( + "E6EAF0", "DBE5F2", "EDEDEE", "E5ECF6", "E6EDF6", "E7EDF7", "EDF0F5", + "E7EBF2", "E6EAF5", "EDF1F7", "DEE4F6", + ), + "line_strong": ( + "D4DCE8", "E4E4E5", "C8D5E6", "C9DCF7", "ADC8F0", "B6CDEE", "C4D2E5", + "CEDBEB", "A7B1C9", "8894B2", + ), + "heading": ("223047", "1A1C1F", "202C3F", "111F46", "20354E"), + "text": ("344258", "273244", "263551", "24334A", "233149", "3F4E75"), + "muted": ("647287", "606163", "6A6B6D", "5D6B80", "7886AA", "708097", "697386"), + "disabled": ("8B96A6", "8E8F90", "8A97A9", "9AA6B7"), + "disabled_surface": ("F0F2F5", "F2F2F2", "F0F0F0"), + "success": ("287B65",), + "success_soft": ("EDF7F2", "EEF7F3", "EAF9F3", "E8F6F1", "F0FDF4", "ECFDF5"), + "warning": ("96601D", "A9691D", "9C681F", "B96C00"), + "warning_soft": ("FBF4E8", "FCF5E9", "FFF5E6", "FFF6E7", "FFF9EF", "FFF7E9", "FFFBEB"), + "danger": ("B54A59", "BE4B58", "B84652", "C43E55"), + "danger_soft": ("FCF0F2", "FFF0F2", "FFF1F3", "FFF4F5", "FFF7F8", "FEF2F2"), } _LEGACY = {colour.lower(): PALETTE[role] for role, colours in _LEGACY_ROLES.items() for colour in colours} _HEX = re.compile(r"#([0-9a-fA-F]{6})(?![0-9a-fA-F])") diff --git a/app/src/doctor_workstation/ui/diagnosis_drawer.py b/app/src/doctor_workstation/ui/diagnosis_drawer.py index c2028ea74..1262d8635 100755 --- a/app/src/doctor_workstation/ui/diagnosis_drawer.py +++ b/app/src/doctor_workstation/ui/diagnosis_drawer.py @@ -414,6 +414,21 @@ QTimeEdit[diagnosisField="true"] { QDoubleSpinBox[diagnosisField="true"] { padding-right: 4px; } +QComboBox[diagnosisField="true"]::drop-down, +QDateEdit[diagnosisField="true"]::drop-down, +QTimeEdit[diagnosisField="true"]::drop-down { + width: 26px; + border: 0; + background: transparent; +} +QDoubleSpinBox[diagnosisField="true"]::up-button, +QDoubleSpinBox[diagnosisField="true"]::down-button, +QSpinBox[diagnosisField="true"]::up-button, +QSpinBox[diagnosisField="true"]::down-button { + width: 18px; + border: 0; + background: transparent; +} QPlainTextEdit[diagnosisField="true"] { padding: 8px 12px; } diff --git a/app/src/doctor_workstation/ui/diagnosis_index_widgets.py b/app/src/doctor_workstation/ui/diagnosis_index_widgets.py index 5404384d9..298a9a2af 100755 --- a/app/src/doctor_workstation/ui/diagnosis_index_widgets.py +++ b/app/src/doctor_workstation/ui/diagnosis_index_widgets.py @@ -84,7 +84,7 @@ _INVALID_INDEX = QModelIndex() # time occupy separate lines; actions keep two inline links plus 更多, with # the remaining actions in its menu so clinical columns retain more space. _TABLE_COLUMN_WIDTHS = (48, 70, 60, 100, 175, 88, 120, 100, 72, 110, 96, 160) -_BLUE_COLUMN_WIDTHS = (48, 70, 82, 102, 244, 90, 84, 90, 88, 122, 92, 158) +_BLUE_COLUMN_WIDTHS = (46, 62, 70, 88, 244, 70, 84, 76, 70, 92, 86, 152) _BLUE_WARNING = QColor(PALETTE["warning"]) _BLUE_DANGER = QColor(PALETTE["danger"]) diff --git a/app/src/doctor_workstation/ui/dialogs/ai_consult.py b/app/src/doctor_workstation/ui/dialogs/ai_consult.py index 2898038b8..6d84945f6 100755 --- a/app/src/doctor_workstation/ui/dialogs/ai_consult.py +++ b/app/src/doctor_workstation/ui/dialogs/ai_consult.py @@ -94,6 +94,7 @@ from ..widgets import ( run_async, show_toast, ) +from ..window_primitives import ClinicalAccentBar from .ai_consult_charts import GlucoseChartData from .ai_consult_drug_names import TCM as DRUG_TCM from .ai_consult_drug_names import WESTERN as DRUG_WESTERN @@ -4781,7 +4782,9 @@ class AiConsultDialog(QDialog): _style_surface(shell) root = QVBoxLayout(self) root.setContentsMargins(0, 0, 0, 0) - root.addWidget(shell) + root.setSpacing(0) + root.addWidget(ClinicalAccentBar(self)) + root.addWidget(shell, 1) layout = QVBoxLayout(shell) layout.setContentsMargins(18, 14, 18, 14) layout.setSpacing(12) diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py index 63915cfee..c54c1a4a7 100755 --- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py +++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py @@ -99,6 +99,7 @@ from ..widgets import ( page_total, run_async, ) +from ..window_primitives import ClinicalAccentBar from .issued_prescription_ai import can_open_issued_ai, present_issued_prescription_ai from .local_audio_queue import LocalAudioQueueDialog from .prescription_ai import can_open_diagnosis_ai_report, present_diagnosis_ai_report @@ -1233,21 +1234,105 @@ class DiagnosisDialog(QDialog): panel_layout = QVBoxLayout(self.drawer_panel) panel_layout.setContentsMargins(0, 0, 0, 0) panel_layout.setSpacing(0) + panel_layout.addWidget(ClinicalAccentBar(self.drawer_panel)) panel_layout.addWidget(self._build_drawer_header()) self.drawer_banner = MessageStrip() self.drawer_banner.setContentsMargins(16, 8, 16, 0) self.drawer_banner.action_requested.connect(self._retry_current) panel_layout.addWidget(self.drawer_banner) + # W5 四诊病历工作室:左侧章节大纲定位轨 + 右侧主编辑工作区 + studio_body = QHBoxLayout() + studio_body.setContentsMargins(0, 0, 0, 0) + studio_body.setSpacing(0) + self.studio_outline = QFrame(self.drawer_panel) + self.studio_outline.setObjectName("DiagnosisStudioOutline") + self.studio_outline.setFixedWidth(136) + self.studio_outline.setStyleSheet( + clinical_stylesheet( + r""" + QFrame#DiagnosisStudioOutline { + background-color: #F4F9F8; + border-right: 1px solid $ds_line; + } + QPushButton[studioOutlineBtn="true"] { + min-height: 34px; + max-height: 34px; + padding: 0 10px; + text-align: left; + border: 1px solid transparent; + border-radius: 8px; + background: transparent; + color: $ds_text; + font-size: 12.5px; + font-weight: 500; + } + QPushButton[studioOutlineBtn="true"]:hover { + background-color: #E7F4F2; + color: $ds_accent; + } + QPushButton[studioOutlineBtn="true"]:checked { + background-color: #FFFFFF; + border-color: #BEE0DA; + color: $ds_accent; + font-weight: 600; + } + """ + ) + ) + self._studio_outline_layout = QVBoxLayout(self.studio_outline) + self._studio_outline_layout.setContentsMargins(10, 12, 10, 12) + self._studio_outline_layout.setSpacing(4) + self._studio_outline_buttons: list[QPushButton] = [] + studio_body.addWidget(self.studio_outline) + self.tabs = DiagnosisTabWidget() self.tabs.setObjectName("DiagnosisDrawerTabs") self._build_drawer_tabs() self.tabs.currentChanged.connect(self._tab_changed) - panel_layout.addWidget(self.tabs, 1) + self.tabs.currentChanged.connect(self._sync_studio_outline_selection) + studio_body.addWidget(self.tabs, 1) + panel_layout.addLayout(studio_body, 1) panel_layout.addWidget(self._build_drawer_footer()) self.drawer_loading = LoadingOverlay(self.drawer_panel) layout.addWidget(self.drawer_panel) + self._rebuild_studio_outline() return overlay + def _rebuild_studio_outline(self) -> None: + """同步左侧章节大纲按钮,使医生可按临床模块一键直达定位。""" + + if not hasattr(self, "_studio_outline_layout"): + return + while self._studio_outline_layout.count(): + item = self._studio_outline_layout.takeAt(0) + widget = item.widget() + if widget is not None: + widget.hide() + widget.setParent(None) + widget.deleteLater() + self._studio_outline_buttons.clear() + caption = QLabel("四诊病历大纲", self.studio_outline) + caption.setStyleSheet("color: #5F7A78; font-size: 11px; font-weight: 600; padding: 2px 6px 6px;") + self._studio_outline_layout.addWidget(caption) + for index in range(self.tabs.count()): + label = self.tabs.tabText(index) + btn = QPushButton(f"{index + 1:02d} {label}", self.studio_outline) + btn.setProperty("studioOutlineBtn", True) + btn.setCheckable(True) + btn.setChecked(index == self.tabs.currentIndex()) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + btn.clicked.connect(lambda _checked=False, i=index: self.tabs.setCurrentIndex(i)) + self._studio_outline_layout.addWidget(btn) + self._studio_outline_buttons.append(btn) + self._studio_outline_layout.addStretch(1) + self.studio_outline.setVisible(self.tabs.count() > 1) + + def _sync_studio_outline_selection(self, index: int) -> None: + if len(self._studio_outline_buttons) != self.tabs.count(): + self._rebuild_studio_outline() + for i, btn in enumerate(self._studio_outline_buttons): + btn.setChecked(i == index) + def _build_drawer_header(self) -> QFrame: header = QFrame() header.setObjectName("DiagnosisDrawerHeader") @@ -1861,6 +1946,7 @@ class DiagnosisDialog(QDialog): target = index self.tabs.setCurrentIndex(target) self.tabs.blockSignals(blocked) + self._rebuild_studio_outline() section_codes = {key: codes for key, _label, codes in _TAB_DEFINITIONS} for key, section in self._readonly_sections.items(): section.setVisible(self._tab_allowed(section_codes.get(key, ()))) diff --git a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py index bbdb46f1e..3dde16dd1 100755 --- a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py +++ b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py @@ -24,43 +24,43 @@ from PySide6.QtGui import QFont from ..design_system import PALETTE DARK: dict[str, str] = { - # ground and cards - "canvas": "#080D18", - "canvas_soft": "#0C1322", - "surface": "#0F1726", - "surface_2": "#131D2E", - "raised": "#1A2637", - "line": "#22304A", - "line_soft": "#18233A", + # 御瓷暗曜科技面:深翡翠黑曜石底 + 精密青玉科技主色 + 香槟鎏金微光 + "canvas": "#071212", + "canvas_soft": "#0A1A1A", + "surface": "#0E2121", + "surface_2": "#122929", + "raised": "#183534", + "line": "#214240", + "line_soft": "#173130", # type - "heading": "#E8EFFB", - "text": "#B6C5DA", - "muted": "#8195AF", - "faint": "#6A7F99", - "selected_text": "#E8EFFB", + "heading": "#ECF6F5", + "text": "#BAD0CE", + "muted": "#82A09D", + "faint": "#64827F", + "selected_text": "#ECF6F5", # interface colour - "accent": "#2E7BF6", - "accent_text": "#6BA5FF", - "accent_pressed": "#1A5FD0", - "selection": "#142645", - "selection_line": "#1B3E77", + "accent": "#16A89E", + "accent_text": "#5BE0D6", + "accent_pressed": "#0E857D", + "selection": "#123433", + "selection_line": "#1F5C58", # model hues - "qwen": "#17BFDD", - "qwen_text": "#55D8EE", - "qwen_dim": "#10303C", - "openai": "#9B7BFF", - "openai_text": "#B69FFF", - "openai_dim": "#241F48", + "qwen": "#22C7D6", + "qwen_text": "#69E3EE", + "qwen_dim": "#103238", + "openai": "#D4AF6A", + "openai_text": "#EAD09B", + "openai_dim": "#2D2719", # severity - "amber": "#F5B942", - "amber_text": "#F8C661", - "amber_dim": "#2C2415", - "rose": "#F4697A", - "rose_text": "#F88694", - "rose_dim": "#2C1620", - "ok": "#2E7BF6", - "zebra": "#0E1626", - "grid_line": "#191F2C", + "amber": "#F2B644", + "amber_text": "#F7C96E", + "amber_dim": "#2E2514", + "rose": "#F06A7B", + "rose_text": "#F78D9B", + "rose_dim": "#2E171E", + "ok": "#16A89E", + "zebra": "#0C1D1D", + "grid_line": "#172E2D", } LIGHT: dict[str, str] = { @@ -81,21 +81,21 @@ LIGHT: dict[str, str] = { "accent_pressed": PALETTE["accent_pressed"], "selection": PALETTE["accent_soft"], "selection_line": PALETTE["focus"], - "qwen": "#0C89AC", - "qwen_text": "#086C88", - "qwen_dim": "#E2F5FA", - "openai": "#6B4AE0", - "openai_text": "#5537C6", - "openai_dim": "#EDE8FE", - "amber": "#B4791A", - "amber_text": "#8F5F0B", - "amber_dim": "#FCF2DF", - "rose": "#D0435A", - "rose_text": "#AE3149", - "rose_dim": "#FCE9EC", - "ok": "#1A5FD0", - "zebra": "#FAFBFE", - "grid_line": "#DDE4EE", + "qwen": "#0B8894", + "qwen_text": "#086A74", + "qwen_dim": "#E3F5F7", + "openai": "#A37E38", + "openai_text": "#826124", + "openai_dim": "#FAF4E7", + "amber": "#B56B00", + "amber_text": "#8F5400", + "amber_dim": "#FEF5E6", + "rose": "#C83B4B", + "rose_text": "#A62B3A", + "rose_dim": "#FDEEEF", + "ok": PALETTE["accent"], + "zebra": "#F8FBFB", + "grid_line": PALETTE["line"], } CONSOLE: dict[str, str] = dict(DARK) diff --git a/app/src/doctor_workstation/ui/dialogs/prescription.py b/app/src/doctor_workstation/ui/dialogs/prescription.py index f493cd7bb..7c61aefb9 100755 --- a/app/src/doctor_workstation/ui/dialogs/prescription.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription.py @@ -117,6 +117,7 @@ from ..widgets import ( run_async, show_toast, ) +from ..window_primitives import ClinicalAccentBar from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog from .prescription_esign import ( PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT, @@ -3118,9 +3119,13 @@ class PrescriptionEditorDialog(QDialog): surface_layout = QVBoxLayout(self.drawer_surface) surface_layout.setContentsMargins(0, 0, 0, 0) surface_layout.setSpacing(0) + surface_layout.addWidget(ClinicalAccentBar(self.drawer_surface)) self.workspace_splitter.addWidget(self.drawer_surface) + self.live_preview_pane = self._build_live_preview_pane() + self.workspace_splitter.addWidget(self.live_preview_pane) self.workspace_splitter.setStretchFactor(0, 1) - self.workspace_splitter.setStretchFactor(1, 0) + self.workspace_splitter.setStretchFactor(1, 2) + self.workspace_splitter.setStretchFactor(2, 1) self.header = self._build_header() surface_layout.addWidget(self.header) @@ -3203,6 +3208,188 @@ class PrescriptionEditorDialog(QDialog): self._load_editor_context() self.save_button.setEnabled(not self._esign_content_locked()) self._load_esign_config() + self._bind_live_preview_signals() + self._refresh_live_preview() + + def _build_live_preview_pane(self) -> QFrame: + """W6 智能开方工作台右侧:实时宣纸仿真处方笺预览 + CA 双签合规进度轨。""" + + pane = QFrame(self.workspace_splitter) + pane.setObjectName("PrescriptionLivePreviewPane") + pane.setMinimumWidth(310) + pane.setMaximumWidth(400) + pane.setStyleSheet( + clinical_stylesheet( + r""" + QFrame#PrescriptionLivePreviewPane { + background-color: #EEF5F3; + border-left: 1px solid #C6DAD6; + } + QFrame#LiveRxPaperCard { + background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #FFFEFA, stop:1 #FAF7EE); + border: 1px solid #DFD4BC; + border-radius: 13px; + } + QFrame#LiveEsignTrackCard { + background-color: #FFFFFF; + border: 1px solid $ds_line; + border-radius: 12px; + } + QLabel#LiveRxStepDone { + background-color: #E5F4F2; + border: 1px solid #A8D6CF; + border-radius: 7px; + color: #0B6E68; + padding: 5px 8px; + font-size: 11.5px; + font-weight: 600; + } + QLabel#LiveRxStepPending { + background-color: #F4F9F8; + border: 1px solid #D7E5E2; + border-radius: 7px; + color: #5F7A78; + padding: 5px 8px; + font-size: 11.5px; + } + """ + ) + ) + layout = QVBoxLayout(pane) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(0) + layout.addWidget(ClinicalAccentBar(pane)) + + inner = QVBoxLayout() + inner.setContentsMargins(14, 14, 14, 14) + inner.setSpacing(12) + + paper = QFrame(pane) + paper.setObjectName("LiveRxPaperCard") + paper_layout = QVBoxLayout(paper) + paper_layout.setContentsMargins(16, 14, 16, 14) + paper_layout.setSpacing(8) + + emblem = QLabel("ZHENYANGTANG · 实时电子处方笺", paper) + emblem.setAlignment(Qt.AlignmentFlag.AlignCenter) + emblem.setStyleSheet("color: #8D7240; font-size: 11px; letter-spacing: 1px;") + paper_layout.addWidget(emblem) + + title = QLabel("甄养堂互联网医院 · 中医专科处方", paper) + title.setAlignment(Qt.AlignmentFlag.AlignCenter) + title.setStyleSheet("color: #102625; font-size: 14px; font-weight: 700; padding-bottom: 6px; border-bottom: 1px solid #E3D8BF;") + paper_layout.addWidget(title) + + self._live_rx_patient = QLabel("患者:— | 剂型:—", paper) + self._live_rx_patient.setWordWrap(True) + self._live_rx_patient.setStyleSheet("color: #274140; font-size: 12px;") + paper_layout.addWidget(self._live_rx_patient) + + self._live_rx_diag = QLabel("辨证诊断:—", paper) + self._live_rx_diag.setWordWrap(True) + self._live_rx_diag.setStyleSheet("color: #0B6E68; font-size: 12px; font-weight: 600;") + paper_layout.addWidget(self._live_rx_diag) + + rp_mark = QLabel("Rp", paper) + rp_mark.setStyleSheet("color: #0B6E68; font-size: 20px; font-weight: 700;") + paper_layout.addWidget(rp_mark) + + self._live_rx_herbs = QLabel("请在左侧录入药材配方,右侧实时同步处方笺排版…", paper) + self._live_rx_herbs.setWordWrap(True) + self._live_rx_herbs.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft) + self._live_rx_herbs.setStyleSheet("color: #102625; font-size: 12.5px; line-height: 1.55;") + paper_layout.addWidget(self._live_rx_herbs, 1) + + self._live_rx_footer = QLabel("共 0 味", paper) + self._live_rx_footer.setStyleSheet("color: #5F7A78; font-size: 12px; padding-top: 8px; border-top: 1px dashed #DFD4BC;") + paper_layout.addWidget(self._live_rx_footer) + inner.addWidget(paper, 1) + + esign_card = QFrame(pane) + esign_card.setObjectName("LiveEsignTrackCard") + e_layout = QVBoxLayout(esign_card) + e_layout.setContentsMargins(12, 11, 12, 11) + e_layout.setSpacing(7) + e_title = QLabel("CA 合规电子双签进度轨", esign_card) + e_title.setStyleSheet("color: #102625; font-size: 12.5px; font-weight: 600;") + e_layout.addWidget(e_title) + step1 = QLabel("1. 医师编排配方与电子签章", esign_card) + step1.setObjectName("LiveRxStepDone") + step2 = QLabel("2. 自动推送药师审方队列", esign_card) + step2.setObjectName("LiveRxStepPending") + step3 = QLabel("3. 双签归档生成 PDF 原件", esign_card) + step3.setObjectName("LiveRxStepPending") + for s in (step1, step2, step3): + e_layout.addWidget(s) + inner.addWidget(esign_card) + layout.addLayout(inner, 1) + # 默认在大屏模式下自动联动展示,窄屏保持简洁抽屉宽度兼容既有测试 + pane.hide() + return pane + + def _bind_live_preview_signals(self) -> None: + if hasattr(self, "herbs") and hasattr(self.herbs, "changed"): + self.herbs.changed.connect(self._refresh_live_preview) + for attr in ("patient_name", "clinical_diagnosis", "prescription_type", "usage_days"): + widget = getattr(self, attr, None) + if widget is None: + continue + for sig_name in ("textChanged", "currentTextChanged", "valueChanged"): + sig = getattr(widget, sig_name, None) + if sig is not None: + sig.connect(self._refresh_live_preview) + break + + def _refresh_live_preview(self) -> None: + if not hasattr(self, "_live_rx_herbs"): + return + patient = self.patient_name.text().strip() if hasattr(self, "patient_name") else "" + rx_type = "" + if hasattr(self, "prescription_type") and hasattr(self.prescription_type, "currentText"): + rx_type = self.prescription_type.currentText().strip() + if not rx_type: + rx_type = str(first_value(self._source, "prescription_type", default="")).strip() + self._live_rx_patient.setText( + f"患者:{patient or '未填写'} | 剂型:{rx_type or '默认'}" + ) + diag = "" + if hasattr(self, "clinical_diagnosis"): + diag = ( + self.clinical_diagnosis.toPlainText().strip() + if hasattr(self.clinical_diagnosis, "toPlainText") + else self.clinical_diagnosis.text().strip() + ) + self._live_rx_diag.setText(f"辨证诊断:{diag or '待补充临床辨证'}") + herbs_list: list[Any] = [] + if hasattr(self, "herbs") and callable(getattr(self.herbs, "values", None)): + herbs_list = list(self.herbs.values()) + if herbs_list: + lines: list[str] = [] + for idx, item in enumerate(herbs_list, start=1): + name = str(first_value(item, "name", "drug_name", "medicine_name", default="")).strip() + dose = str(first_value(item, "dosage", "dose", "weight", default="")).strip() + unit = str(first_value(item, "unit", default="g")).strip() or "g" + if name: + lines.append(f"{idx:02d}. {name} {dose}{unit if dose else ''}") + self._live_rx_herbs.setText("\n".join(lines) if lines else "暂无有效药味") + days = self.usage_days.value() if hasattr(self, "usage_days") else 0 + suffix = f" · 服用 {days} 天" if days else "" + self._live_rx_footer.setText(f"已配 {len(lines)} 味{suffix} · 实时同步") + else: + self._live_rx_herbs.setText("请在左侧录入药材配方,右侧实时同步处方笺排版…") + self._live_rx_footer.setText("共 0 味") + + def toggle_live_preview(self) -> None: + """一键展开或收起右侧实时仿真处方笺与 CA 双签进度轨。""" + + if not hasattr(self, "live_preview_pane"): + return + showing = not self.live_preview_pane.isVisible() + self.live_preview_pane.setVisible(showing) + if showing: + self._refresh_live_preview() + if self.width() < 1180: + self.resize(1220, self.height()) def _void_busy_changed(self, busy: bool) -> None: self.cancel_button.setEnabled(not busy) @@ -3266,6 +3453,20 @@ class PrescriptionEditorDialog(QDialog): mode.setObjectName("PrescriptionDrawerMode") layout.addWidget(mode) layout.addStretch(1) + self.live_preview_toggle = QPushButton("实时处方笺预览", header) + self.live_preview_toggle.setObjectName("PrescriptionLivePreviewToggle") + self.live_preview_toggle.setCheckable(True) + self.live_preview_toggle.setCursor(Qt.CursorShape.PointingHandCursor) + self.live_preview_toggle.setToolTip("展开或收起右侧实时仿真处方笺与 CA 双签进度轨") + self.live_preview_toggle.setStyleSheet( + "QPushButton#PrescriptionLivePreviewToggle {" + " min-height: 30px; max-height: 30px; padding: 0 11px; border-radius: 7px;" + " background: #F2F9F8; border: 1px solid #C2DBD7; color: #0B6E68; font-size: 12px; font-weight: 600; }" + "QPushButton#PrescriptionLivePreviewToggle:checked {" + " background: #0B6E68; border-color: #0B6E68; color: #FFFFFF; }" + ) + self.live_preview_toggle.clicked.connect(self.toggle_live_preview) + layout.addWidget(self.live_preview_toggle, 0, Qt.AlignmentFlag.AlignVCenter) close_button = QPushButton("×", header) close_button.setObjectName("PrescriptionDrawerClose") close_button.setToolTip("关闭") @@ -5952,11 +6153,17 @@ class PrescriptionDetailDialog(QDialog): self.resize(1240, 800) # 与「处方电子签署」一致:左侧三联预览,右侧签署流程与操作。 root = QVBoxLayout(self) - root.setContentsMargins(20, 20, 20, 20) - self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal, self) + root.setContentsMargins(0, 0, 0, 0) + root.setSpacing(0) + root.addWidget(ClinicalAccentBar(self)) + body_wrap = QWidget(self) + body_layout = QVBoxLayout(body_wrap) + body_layout.setContentsMargins(20, 16, 20, 20) + self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal, body_wrap) self.workspace_splitter.setChildrenCollapsible(False) self.workspace_splitter.setHandleWidth(12) - root.addWidget(self.workspace_splitter) + body_layout.addWidget(self.workspace_splitter) + root.addWidget(body_wrap, 1) preview_panel = QWidget(self.workspace_splitter) preview_panel.setMinimumWidth(370) diff --git a/app/src/doctor_workstation/ui/dialogs/prescription_esign.py b/app/src/doctor_workstation/ui/dialogs/prescription_esign.py index 15a4782c6..5627daa0c 100644 --- a/app/src/doctor_workstation/ui/dialogs/prescription_esign.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription_esign.py @@ -48,7 +48,15 @@ from ...core.esign import ( signed_pdf_bytes, ) from ..design_system import clinical_stylesheet -from ..widgets import MessageBanner, first_value, friendly_error, has_permission, run_async, show_toast +from ..widgets import ( + MessageBanner, + first_value, + friendly_error, + has_permission, + run_async, + show_toast, +) +from ..window_primitives import ClinicalAccentBar from .esign_doctor import EsignDoctorDialog from .esign_webview import create_identity_view @@ -404,11 +412,17 @@ class PrescriptionEsignDialog(QDialog): from .prescription import PrescriptionSigningPreview root = QVBoxLayout(self) - root.setContentsMargins(20, 20, 20, 20) - self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal, self) + root.setContentsMargins(0, 0, 0, 0) + root.setSpacing(0) + root.addWidget(ClinicalAccentBar(self)) + body_wrap = QWidget(self) + body_layout = QVBoxLayout(body_wrap) + body_layout.setContentsMargins(20, 16, 20, 20) + self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal, body_wrap) self.workspace_splitter.setChildrenCollapsible(False) self.workspace_splitter.setHandleWidth(12) - root.addWidget(self.workspace_splitter) + body_layout.addWidget(self.workspace_splitter) + root.addWidget(body_wrap, 1) self.prescription_preview = PrescriptionSigningPreview(self.repository, prescription, parent=self.workspace_splitter) self.prescription_preview.setMinimumWidth(370) diff --git a/app/src/doctor_workstation/ui/dialogs/video_cockpit.py b/app/src/doctor_workstation/ui/dialogs/video_cockpit.py new file mode 100644 index 000000000..201cc0c96 --- /dev/null +++ b/app/src/doctor_workstation/ui/dialogs/video_cockpit.py @@ -0,0 +1,192 @@ +"""W4 视频问诊双屏协同驾驶舱(演示预览与原生临床速记协同视窗)。""" + +from __future__ import annotations + +from PySide6.QtCore import Qt, QTimer +from PySide6.QtWidgets import ( + QDialog, + QFrame, + QHBoxLayout, + QLabel, + QPlainTextEdit, + QPushButton, + QVBoxLayout, + QWidget, +) + +from ..window_primitives import ClinicalAccentBar + + +class VideoCockpitDemoDialog(QDialog): + """W4 视频问诊双屏协同驾驶舱:左深曜影院画布 + 底部毛玻璃控坞 + 右伴随四诊速记侧栏。""" + + def __init__(self, patient_name: str, parent: QWidget | None = None) -> None: + super().__init__(parent) + self._seconds = 0 + self._tongue_count = 0 + self.setWindowTitle("视频面诊 · 双屏协同驾驶舱") + self.setMinimumSize(860, 560) + self.resize(1120, 700) + self.setModal(False) + self.setStyleSheet( + "QDialog{background:#071515;color:#EFF9F8;}" + "QFrame#VideoTopHud{background:rgba(12,38,37,220);border:1px solid rgba(223,199,147,90);border-radius:12px;}" + "QFrame#RemoteStage{background:qradialgradient(cx:0.5,cy:0.4,radius:0.8,fx:0.5,fy:0.4,stop:0 #153E3C,stop:0.65 #081A1A,stop:1 #040D0D);" + "border:1px solid rgba(223,199,147,60);border-radius:16px;}" + "QFrame#RemoteStage QLabel{color:#EFF9F8;}" + "QFrame#LocalStage{background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #184644,stop:1 #0B2524);" + "border:1.5px solid #DFC793;border-radius:12px;}" + "QFrame#VideoDock{background:rgba(9,28,28,235);border:1px solid rgba(223,199,147,110);border-radius:24px;}" + "QFrame#VideoCompanionRail{background:#F5FAF9;border-left:1px solid #C6DAD6;}" + "QFrame#VideoCompanionRail QLabel{color:#102625;}" + "QPlainTextEdit#VideoQuickNotes{background:#FFFFFF;border:1px solid #C4D8D4;border-radius:10px;padding:8px;color:#102625;font-size:13px;}" + "QPushButton{min-width:88px;min-height:36px;padding:0 14px;border-radius:18px;" + "background:rgba(255,255,255,22);color:#F0FAF9;border:1px solid rgba(255,255,255,48);font-weight:600;}" + "QPushButton:hover{background:rgba(24,176,165,70);border-color:#DFC793;color:#FFFFFF;}" + "QPushButton:checked{background:rgba(223,199,147,60);border-color:#DFC793;color:#DFC793;}" + "QPushButton#TongueBtn{background:rgba(223,199,147,48);border-color:#DFC793;color:#DFC793;}" + "QPushButton#Hangup{color:#FFFFFF;background:#D63F4F;border-color:#D63F4F;}" + "QPushButton#Hangup:hover{background:#B92E3D;border-color:#B92E3D;}" + ) + + root_col = QVBoxLayout(self) + root_col.setContentsMargins(0, 0, 0, 0) + root_col.setSpacing(0) + root_col.addWidget(ClinicalAccentBar(self)) + + outer = QHBoxLayout() + outer.setContentsMargins(0, 0, 0, 0) + outer.setSpacing(0) + + left_wrap = QWidget(self) + left_layout = QVBoxLayout(left_wrap) + left_layout.setContentsMargins(16, 14, 16, 16) + left_layout.setSpacing(12) + + top_hud = QFrame(left_wrap) + top_hud.setObjectName("VideoTopHud") + header = QHBoxLayout(top_hud) + header.setContentsMargins(14, 9, 14, 9) + title = QLabel(f"● 视频面诊 · {patient_name or '患者'}", top_hud) + title.setStyleSheet("font-size:15px;font-weight:700;color:#F4FAF9;") + header.addWidget(title) + header.addStretch(1) + demo = QLabel("本地加密录音就绪 · 演示模式", top_hud) + demo.setStyleSheet("color:#9FC5C1;font-size:12px;") + header.addWidget(demo) + self.duration_label = QLabel("00:00", top_hud) + self.duration_label.setStyleSheet("font-weight:700;color:#DFC793;padding-left:10px;") + header.addWidget(self.duration_label) + left_layout.addWidget(top_hud) + + stage = QFrame(left_wrap) + stage.setObjectName("RemoteStage") + stage_layout = QVBoxLayout(stage) + stage_layout.setContentsMargins(22, 22, 22, 22) + stage_layout.addStretch(1) + avatar = QLabel((patient_name or "患")[:1], stage) + avatar.setAlignment(Qt.AlignmentFlag.AlignCenter) + avatar.setFixedSize(96, 96) + avatar.setStyleSheet( + "background:rgba(24,176,165,48);color:#FFFFFF;border:2px solid #DFC793;" + "border-radius:48px;font-size:38px;font-weight:700;" + ) + stage_layout.addWidget(avatar, 0, Qt.AlignmentFlag.AlignHCenter) + waiting = QLabel("等待患者接入高清视频画面…", stage) + waiting.setAlignment(Qt.AlignmentFlag.AlignCenter) + waiting.setStyleSheet("font-size:16px;font-weight:600;margin-top:8px;") + stage_layout.addWidget(waiting) + hint = QLabel("生产模式通过后端短时 UserSig 驱动 TRTC,支持舌象高清抓拍与实时转写", stage) + hint.setAlignment(Qt.AlignmentFlag.AlignCenter) + hint.setStyleSheet("color:#91BDB8;font-size:12px;") + stage_layout.addWidget(hint) + self._tongue_status = QLabel("", stage) + self._tongue_status.setAlignment(Qt.AlignmentFlag.AlignCenter) + self._tongue_status.setStyleSheet("color:#DFC793;font-size:12px;font-weight:600;margin-top:6px;") + stage_layout.addWidget(self._tongue_status) + stage_layout.addStretch(1) + + local = QFrame(stage) + local.setObjectName("LocalStage") + local.setGeometry(20, 20, 176, 108) + local_layout = QVBoxLayout(local) + local_label = QLabel("陈医生(本机画面)", local) + local_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + local_label.setStyleSheet("color:#EFF9F8;font-weight:600;font-size:12px;") + local_layout.addWidget(local_label) + left_layout.addWidget(stage, 1) + + dock = QFrame(left_wrap) + dock.setObjectName("VideoDock") + controls = QHBoxLayout(dock) + controls.setContentsMargins(14, 7, 14, 7) + controls.setSpacing(10) + self.mic_button = QPushButton("麦克风 开", dock) + self.mic_button.setCheckable(True) + self.mic_button.toggled.connect( + lambda muted: self.mic_button.setText("麦克风 关" if muted else "麦克风 开") + ) + controls.addWidget(self.mic_button) + self.camera_button = QPushButton("摄像头 开", dock) + self.camera_button.setCheckable(True) + self.camera_button.toggled.connect( + lambda off: self.camera_button.setText("摄像头 关" if off else "摄像头 开") + ) + controls.addWidget(self.camera_button) + tongue_btn = QPushButton("舌象高清抓拍", dock) + tongue_btn.setObjectName("TongueBtn") + tongue_btn.clicked.connect(self._capture_demo_tongue) + controls.addWidget(tongue_btn) + hangup = QPushButton("结束面诊", dock) + hangup.setObjectName("Hangup") + hangup.clicked.connect(self.close) + controls.addWidget(hangup) + left_layout.addWidget(dock, 0, Qt.AlignmentFlag.AlignHCenter) + outer.addWidget(left_wrap, 1) + + rail = QFrame(self) + rail.setObjectName("VideoCompanionRail") + rail.setFixedWidth(340) + rail_layout = QVBoxLayout(rail) + rail_layout.setContentsMargins(16, 16, 16, 16) + rail_layout.setSpacing(10) + rail_title = QLabel("伴随四诊速记(双屏协同)", rail) + rail_title.setStyleSheet("font-size:15px;font-weight:700;color:#102625;") + rail_layout.addWidget(rail_title) + rail_hint = QLabel("面诊过程中实时记录主诉与舌脉,结束后自动带入病历草稿。", rail) + rail_hint.setWordWrap(True) + rail_hint.setStyleSheet("font-size:12px;color:#5F7A78;") + rail_layout.addWidget(rail_hint) + self.quick_notes = QPlainTextEdit(rail) + self.quick_notes.setObjectName("VideoQuickNotes") + self.quick_notes.setPlaceholderText("在此速记本次视频面诊的主诉、舌质舌苔、脉象与调方思路…") + rail_layout.addWidget(self.quick_notes, 1) + ai_hint_box = QFrame(rail) + ai_hint_box.setStyleSheet( + "QFrame{background:#EAF6F4;border:1px solid #B7DDD6;border-radius:10px;padding:8px;}" + ) + ai_hint_l = QVBoxLayout(ai_hint_box) + ai_hint_l.setContentsMargins(10, 8, 10, 8) + ai_lbl = QLabel("AI 问诊提醒:建议核实近期夜间睡眠与餐后 2h 血糖峰值。", ai_hint_box) + ai_lbl.setWordWrap(True) + ai_lbl.setStyleSheet("color:#0B6E68;font-size:12px;font-weight:500;") + ai_hint_l.addWidget(ai_lbl) + rail_layout.addWidget(ai_hint_box) + outer.addWidget(rail) + root_col.addLayout(outer, 1) + + self._timer = QTimer(self) + self._timer.timeout.connect(self._tick) + self._timer.start(1000) + + def _capture_demo_tongue(self) -> None: + self._tongue_count += 1 + self._tongue_status.setText(f"✓ 已抓拍第 {self._tongue_count} 帧高清舌象并准备归档") + + def _tick(self) -> None: + self._seconds += 1 + minutes, seconds = divmod(self._seconds, 60) + self.duration_label.setText(f"{minutes:02d}:{seconds:02d}") + + +__all__ = ["VideoCockpitDemoDialog"] diff --git a/app/src/doctor_workstation/ui/icons.py b/app/src/doctor_workstation/ui/icons.py index 95cc7635a..dd757fa25 100755 --- a/app/src/doctor_workstation/ui/icons.py +++ b/app/src/doctor_workstation/ui/icons.py @@ -69,6 +69,7 @@ ROLES = { "strong": COLORS["text"], "accent": COLORS["indigo"], "on_accent": "#FFFFFF", + "gold": COLORS["gold"], "success": COLORS["success"], "warning": COLORS["warning"], "danger": COLORS["danger"], @@ -124,8 +125,41 @@ def _dot(p: QPainter, cx: float, cy: float, r: float) -> None: p.setPen(pen) +def _tint_brush(p: QPainter, alpha: int = 38) -> QColor: + """Return a translucent duotone fill derived from the active stroke colour.""" + + tint = QColor(p.pen().color()) + tint.setAlpha(alpha) + return tint + + +def _duotone_path(p: QPainter, path: QPainterPath, alpha: int = 38) -> None: + """Draw a closed path with a subtle duotone tint fill beneath its crisp stroke.""" + + p.save() + p.setBrush(_tint_brush(p, alpha)) + p.drawPath(path) + p.restore() + + +def _duotone_rounded_rect( + p: QPainter, rect: QRectF, rx: float, ry: float, alpha: int = 38 +) -> None: + p.save() + p.setBrush(_tint_brush(p, alpha)) + p.drawRoundedRect(rect, rx, ry) + p.restore() + + +def _duotone_circle(p: QPainter, cx: float, cy: float, r: float, alpha: int = 38) -> None: + p.save() + p.setBrush(_tint_brush(p, alpha)) + p.drawEllipse(QPointF(cx, cy), r, r) + p.restore() + + def _page(p: QPainter, *, fold: bool = True) -> None: - """Shared document silhouette so every file-like glyph has one outline.""" + """Shared document silhouette with subtle duotone glass tint.""" path = QPainterPath(QPointF(14.0, 2.5)) path.lineTo(QPointF(6.5, 2.5)) @@ -136,13 +170,13 @@ def _page(p: QPainter, *, fold: bool = True) -> None: path.quadTo(QPointF(19.0, 21.5), QPointF(19.0, 20.0)) path.lineTo(QPointF(19.0, 7.5)) path.closeSubpath() - p.drawPath(path) + _duotone_path(p, path, 34) if fold: _polyline(p, (14.0, 2.5), (14.0, 7.5), (19.0, 7.5)) -def _sparkle(p: QPainter, cx: float, cy: float, r: float) -> None: - """Four-point concave star - the one AI mark used across the product.""" +def _sparkle(p: QPainter, cx: float, cy: float, r: float, *, alpha: int = 56) -> None: + """Four-point concave star - the precision AI mark with luminous duotone core.""" path = QPainterPath(QPointF(cx, cy - r)) path.quadTo(QPointF(cx, cy), QPointF(cx + r, cy)) @@ -150,11 +184,11 @@ def _sparkle(p: QPainter, cx: float, cy: float, r: float) -> None: path.quadTo(QPointF(cx, cy), QPointF(cx - r, cy)) path.quadTo(QPointF(cx, cy), QPointF(cx, cy - r)) path.closeSubpath() - p.drawPath(path) + _duotone_path(p, path, alpha) def _panel(p: QPainter) -> None: - p.drawRoundedRect(QRectF(2.5, 4.0, 19.0, 16.0), 3.0, 3.0) + _duotone_rounded_rect(p, QRectF(2.5, 4.0, 19.0, 16.0), 3.0, 3.0, 28) _line(p, 9.5, 4.0, 9.5, 20.0) @@ -163,18 +197,20 @@ def _panel(p: QPainter) -> None: @_glyph("reception", "workbench", "monitor") def _reception(p: QPainter, w: float) -> None: - p.drawRoundedRect(QRectF(2.5, 3.5, 19.0, 13.5), 3.0, 3.0) - _polyline(p, (6.0, 10.5), (8.8, 10.5), (10.6, 7.5), (13.4, 13.5), (15.2, 10.5), (18.0, 10.5)) + _duotone_rounded_rect(p, QRectF(2.5, 3.5, 19.0, 13.5), 3.2, 3.2, 38) + _polyline(p, (5.8, 10.5), (8.6, 10.5), (10.5, 7.2), (13.4, 13.6), (15.3, 10.5), (18.2, 10.5)) _line(p, 12.0, 17.0, 12.0, 20.5) _line(p, 8.0, 20.5, 16.0, 20.5) @_glyph("appointments", "calendar") def _calendar(p: QPainter, w: float) -> None: - p.drawRoundedRect(QRectF(3.0, 5.0, 18.0, 16.5), 3.0, 3.0) + _duotone_rounded_rect(p, QRectF(3.0, 5.0, 18.0, 16.5), 3.2, 3.2, 36) _line(p, 3.0, 10.0, 21.0, 10.0) - _line(p, 8.0, 2.75, 8.0, 7.0) - _line(p, 16.0, 2.75, 16.0, 7.0) + _line(p, 8.0, 2.75, 8.0, 6.8) + _line(p, 16.0, 2.75, 16.0, 6.8) + _line(p, 7.5, 14.0, 11.5, 14.0) + _line(p, 7.5, 17.4, 15.0, 17.4) @_glyph("prescription_library", "library", "layers") @@ -184,7 +220,7 @@ def _layers(p: QPainter, w: float) -> None: path.lineTo(QPointF(12.0, 11.5)) path.lineTo(QPointF(3.0, 7.0)) path.closeSubpath() - p.drawPath(path) + _duotone_path(p, path, 48) _polyline(p, (3.0, 12.0), (12.0, 16.5), (21.0, 12.0)) _polyline(p, (3.0, 16.75), (12.0, 21.25), (21.0, 16.75)) @@ -197,12 +233,12 @@ def _file_check(p: QPainter, w: float) -> None: @_glyph("patients", "users") def _users(p: QPainter, w: float) -> None: - _circle(p, 9.0, 8.0, 3.5) + _duotone_circle(p, 9.0, 8.0, 3.5, 42) path = QPainterPath(QPointF(2.5, 20.5)) path.quadTo(QPointF(2.5, 14.5), QPointF(9.0, 14.5)) path.quadTo(QPointF(15.5, 14.5), QPointF(15.5, 20.5)) p.drawPath(path) - _circle(p, 17.6, 8.0, 2.8) + _duotone_circle(p, 17.6, 8.0, 2.8, 28) tail = QPainterPath(QPointF(17.0, 13.9)) tail.quadTo(QPointF(21.5, 14.6), QPointF(21.5, 20.5)) p.drawPath(tail) @@ -221,7 +257,7 @@ def _message(p: QPainter, w: float) -> None: path.quadTo(QPointF(3.5, 16.5), QPointF(3.5, 13.5)) path.lineTo(QPointF(3.5, 6.5)) path.quadTo(QPointF(3.5, 3.5), QPointF(6.5, 3.5)) - p.drawPath(path) + _duotone_path(p, path, 38) _line(p, 7.75, 8.25, 16.25, 8.25) _line(p, 7.75, 11.75, 13.0, 11.75) @@ -275,10 +311,23 @@ def _ai(p: QPainter, w: float) -> None: @_glyph("fullscreen", "expand-corners", "maximize") def _fullscreen(p: QPainter, w: float) -> None: - _polyline(p, (9.0, 3.5), (3.5, 3.5), (3.5, 9.0)) - _polyline(p, (15.0, 3.5), (20.5, 3.5), (20.5, 9.0)) - _polyline(p, (3.5, 15.0), (3.5, 20.5), (9.0, 20.5)) - _polyline(p, (20.5, 15.0), (20.5, 20.5), (15.0, 20.5)) + # 标准现代桌面端圆角单窗最大化图标,取代生硬的四角取景框 + p.drawRoundedRect(QRectF(4.5, 4.5, 15.0, 15.0), 2.8, 2.8) + + +@_glyph("restore", "unmaximize") +def _restore(p: QPainter, w: float) -> None: + # 标准现代桌面端双窗还原图标 + p.drawRoundedRect(QRectF(4.25, 7.25, 12.25, 12.25), 2.4, 2.4) + back = QPainterPath(QPointF(7.75, 7.25)) + back.lineTo(QPointF(7.75, 6.2)) + back.quadTo(QPointF(7.75, 4.25), QPointF(9.7, 4.25)) + back.lineTo(QPointF(17.8, 4.25)) + back.quadTo(QPointF(19.75, 4.25), QPointF(19.75, 6.2)) + back.lineTo(QPointF(19.75, 14.3)) + back.quadTo(QPointF(19.75, 16.25), QPointF(17.8, 16.25)) + back.lineTo(QPointF(16.5, 16.25)) + p.drawPath(back) @_glyph("minimize") @@ -318,17 +367,27 @@ def _bell(p: QPainter, w: float) -> None: path.lineTo(QPointF(6.75, 10.75)) path.arcTo(QRectF(6.75, 5.0, 10.5, 11.5), 180.0, -180.0) path.lineTo(QPointF(17.25, 17.5)) - p.drawPath(path) + path.closeSubpath() + _duotone_path(p, path, 36) _line(p, 4.5, 17.5, 19.5, 17.5) p.drawArc(QRectF(10.0, 17.4, 4.0, 3.6), 180 * 16, 180 * 16) @_glyph("settings", "sliders") def _settings(p: QPainter, w: float) -> None: - _line(p, 3.5, 8.5, 20.5, 8.5) - _line(p, 3.5, 15.5, 20.5, 15.5) - _circle(p, 9.0, 8.5, 2.4) - _circle(p, 15.0, 15.5, 2.4) + # 精密八齿圆润齿轮 + 双色调内核,替代锯齿硬编码多边形与简陋滑块 + _duotone_circle(p, 12.0, 12.0, 5.4, 34) + _circle(p, 12.0, 12.0, 2.35) + for step in range(8): + angle = step * math.pi / 4.0 + cos_a, sin_a = math.cos(angle), math.sin(angle) + _line( + p, + 12.0 + 5.7 * cos_a, + 12.0 + 5.7 * sin_a, + 12.0 + 8.6 * cos_a, + 12.0 + 8.6 * sin_a, + ) # --- Row and toolbar actions --------------------------------------------- @@ -339,8 +398,8 @@ def _eye(p: QPainter, w: float) -> None: path = QPainterPath(QPointF(2.5, 12.0)) path.quadTo(QPointF(12.0, 2.5), QPointF(21.5, 12.0)) path.quadTo(QPointF(12.0, 21.5), QPointF(2.5, 12.0)) - p.drawPath(path) - _circle(p, 12.0, 12.0, 3.0) + _duotone_path(p, path, 28) + _duotone_circle(p, 12.0, 12.0, 3.0, 48) @_glyph("pencil", "edit") @@ -569,13 +628,13 @@ def _qr(p: QPainter, w: float) -> None: @_glyph("video", "call") def _video(p: QPainter, w: float) -> None: - p.drawRoundedRect(QRectF(2.5, 6.0, 13.5, 12.0), 3.0, 3.0) + _duotone_rounded_rect(p, QRectF(2.5, 6.0, 13.5, 12.0), 3.0, 3.0, 38) path = QPainterPath(QPointF(16.0, 10.5)) path.lineTo(QPointF(21.5, 7.25)) path.lineTo(QPointF(21.5, 16.75)) path.lineTo(QPointF(16.0, 13.5)) path.closeSubpath() - p.drawPath(path) + _duotone_path(p, path, 32) # --- Clinical measures ---------------------------------------------------- @@ -596,14 +655,14 @@ def _height(p: QPainter, w: float) -> None: @_glyph("weight", "scale") def _weight(p: QPainter, w: float) -> None: - p.drawRoundedRect(QRectF(3.0, 5.0, 18.0, 14.5), 3.5, 3.5) + _duotone_rounded_rect(p, QRectF(3.0, 5.0, 18.0, 14.5), 3.5, 3.5, 34) p.drawArc(QRectF(7.0, 10.0, 10.0, 10.0), 25 * 16, 130 * 16) _line(p, 12.0, 15.0, 9.9, 10.9) @_glyph("bmi", "body") def _bmi(p: QPainter, w: float) -> None: - _circle(p, 12.0, 5.0, 2.75) + _duotone_circle(p, 12.0, 5.0, 2.75, 42) _line(p, 12.0, 7.75, 12.0, 15.0) _line(p, 7.25, 11.0, 16.75, 11.0) _polyline(p, (8.5, 20.75), (12.0, 15.0), (15.5, 20.75)) @@ -611,8 +670,10 @@ def _bmi(p: QPainter, w: float) -> None: @_glyph("blood_pressure", "gauge", "bp") def _blood_pressure(p: QPainter, w: float) -> None: - p.drawArc(QRectF(3.0, 5.5, 18.0, 18.0), 0, 180 * 16) - _line(p, 3.0, 14.5, 21.0, 14.5) + arc_path = QPainterPath(QPointF(3.0, 14.5)) + arc_path.arcTo(QRectF(3.0, 5.5, 18.0, 18.0), 180, -180) + arc_path.closeSubpath() + _duotone_path(p, arc_path, 34) _line(p, 12.0, 14.5, 16.4, 9.4) _dot(p, 12.0, 14.5, 1.15) @@ -625,7 +686,7 @@ def _pulse(p: QPainter, w: float) -> None: heart.cubicTo(QPointF(13.5, 4.8), QPointF(16.8, 4.0), QPointF(19.3, 6.7)) heart.cubicTo(QPointF(21.8, 9.6), QPointF(20.8, 13.6), QPointF(12.0, 20.25)) heart.closeSubpath() - p.drawPath(heart) + _duotone_path(p, heart, 36) _polyline( p, (5.6, 12.4), (9.0, 12.4), (10.6, 9.7), (13.2, 15.1), (14.7, 12.4), (18.4, 12.4) ) diff --git a/app/src/doctor_workstation/ui/interactions.py b/app/src/doctor_workstation/ui/interactions.py new file mode 100644 index 000000000..9208a5e88 --- /dev/null +++ b/app/src/doctor_workstation/ui/interactions.py @@ -0,0 +1,148 @@ +"""桌面端全局精工交互引擎:统一手型光标、Windows 11 DWM 视窗融合与优雅按压手感.""" + +from __future__ import annotations + +import ctypes +import sys + +from PySide6.QtCore import QEvent, QObject, Qt +from PySide6.QtWidgets import ( + QAbstractButton, + QApplication, + QComboBox, + QDialog, + QFileDialog, + QInputDialog, + QMessageBox, + QTabBar, + QWidget, +) + +from .design_system import PALETTE + +# Windows 11 DWM 窗口装饰属性常量 +_DWMWA_USE_IMMERSIVE_DARK_MODE = 20 +_DWMWA_WINDOW_CORNER_PREFERENCE = 33 +_DWMWA_BORDER_COLOR = 34 +_DWMWA_CAPTION_COLOR = 35 +_DWMWA_TEXT_COLOR = 36 +_DWMWCP_ROUND = 2 + + +def _colorref(hex_color: str) -> int: + """将 ``#RRGGBB`` 转为 Win32 DWM 所需的 ``0x00BBGGRR`` 整型。""" + + clean = hex_color.lstrip("#") + red, green, blue = (int(clean[i : i + 2], 16) for i in (0, 2, 4)) + return (blue << 16) | (green << 8) | red + + +def apply_luxury_dwm_chrome(widget: QWidget, *, dark: bool = False) -> bool: + """在 Windows 11 上同步原生子视窗标题栏、圆角偏好与边框至「御瓷智医」色系。""" + + if sys.platform != "win32": + return False + if widget.windowFlags() & Qt.WindowType.FramelessWindowHint: + return False + try: + handle = int(widget.winId()) + except Exception: + return False + if not handle: + return False + try: + dwm = ctypes.windll.dwmapi + except (AttributeError, OSError): + return False + + caption_hex = PALETTE["obsidian"] if dark else PALETTE["surface"] + text_hex = "#F2FAF9" if dark else PALETTE["heading"] + border_hex = PALETTE["gold"] if dark else PALETTE["line_strong"] + + dark_val = ctypes.c_int(1 if dark else 0) + corner_val = ctypes.c_int(_DWMWCP_ROUND) + caption_val = ctypes.c_uint(_colorref(caption_hex)) + text_val = ctypes.c_uint(_colorref(text_hex)) + border_val = ctypes.c_uint(_colorref(border_hex)) + + applied = False + for attr, value in ( + (_DWMWA_USE_IMMERSIVE_DARK_MODE, dark_val), + (_DWMWA_WINDOW_CORNER_PREFERENCE, corner_val), + (_DWMWA_CAPTION_COLOR, caption_val), + (_DWMWA_TEXT_COLOR, text_val), + (_DWMWA_BORDER_COLOR, border_val), + ): + try: + res = dwm.DwmSetWindowAttribute( + ctypes.c_void_p(handle), + ctypes.c_int(attr), + ctypes.byref(value), + ctypes.sizeof(value), + ) + applied = applied or res == 0 + except OSError: + continue + return applied + + +class _TactileInteractionFilter(QObject): + """全局轻量事件过滤器:自动补齐手型光标与子视窗 DWM 高定视觉融合。""" + + _INTERACTIVE_TYPES = (QAbstractButton, QTabBar, QComboBox) + _WATCHED_EVENTS = frozenset({QEvent.Type.Polish, QEvent.Type.EnabledChange, QEvent.Type.Show}) + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 + try: + event_type = event.type() + except RuntimeError: + return False + if event_type not in self._WATCHED_EVENTS: + return False + + if isinstance(watched, self._INTERACTIVE_TYPES): + if event_type in (QEvent.Type.Polish, QEvent.Type.EnabledChange): + if watched.isEnabled(): + if watched.cursor().shape() == Qt.CursorShape.ArrowCursor: + watched.setCursor(Qt.CursorShape.PointingHandCursor) + else: + if watched.cursor().shape() == Qt.CursorShape.PointingHandCursor: + watched.setCursor(Qt.CursorShape.ArrowCursor) + return False + + if ( + event_type is QEvent.Type.Show + and isinstance(watched, QDialog) + and not isinstance(watched, (QFileDialog, QMessageBox, QInputDialog)) + and not watched.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) + ): + name = watched.objectName() or "" + is_dark = any(tag in name for tag in ("Video", "IssuedPrescriptionAi", "AiConsult")) + apply_luxury_dwm_chrome(watched, dark=is_dark) + # W8 原语 B:自动为所有标准业务弹窗顶部注入 3px 翡翠-鎏金饰线(避免重复插入) + if ( + not (watched.windowFlags() & Qt.WindowType.FramelessWindowHint) + and not getattr(watched, "_doctor_accent_bar_injected", False) + ): + from PySide6.QtWidgets import QVBoxLayout + + from .window_primitives import ClinicalAccentBar + + layout = watched.layout() + if isinstance(layout, QVBoxLayout) and not watched.findChildren(ClinicalAccentBar): + watched._doctor_accent_bar_injected = True # type: ignore[attr-defined] + layout.insertWidget(0, ClinicalAccentBar(watched)) + return False + + +def install_tactile_interactions(app: QApplication) -> None: + """幂等安装全局精工交互过滤器。""" + + if getattr(app, "_doctor_tactile_interaction_filter", None) is not None: + return + flt = _TactileInteractionFilter(app) + app.installEventFilter(flt) + app._doctor_tactile_interaction_filter = flt + + +__all__ = ["apply_luxury_dwm_chrome", "install_tactile_interactions"] diff --git a/app/src/doctor_workstation/ui/login.py b/app/src/doctor_workstation/ui/login.py index 691cc9000..346d72b61 100755 --- a/app/src/doctor_workstation/ui/login.py +++ b/app/src/doctor_workstation/ui/login.py @@ -5,15 +5,18 @@ from __future__ import annotations from contextlib import suppress from typing import Any -from PySide6.QtCore import QEvent, QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal +from PySide6.QtCore import QEvent, QPoint, QPointF, QRectF, QSettings, QSize, Qt, QTimer, Signal from PySide6.QtGui import ( QColor, QFont, QIcon, + QLinearGradient, + QMouseEvent, QPainter, QPainterPath, QPen, QPixmap, + QRadialGradient, QResizeEvent, ) from PySide6.QtWidgets import ( @@ -123,7 +126,7 @@ def _round_pen(color: QColor | str, width: float) -> QPen: class _BrandPanel(QWidget): - """A flat, readable introduction to the clinician's daily workflow.""" + """御瓷智医 · 深曜翡翠科技医疗奢雅品牌沉浸区.""" def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) @@ -138,60 +141,237 @@ class _BrandPanel(QWidget): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) bounds = QRectF(self.rect()).adjusted(1, 1, -1, -1) - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(PALETTE["sidebar"])) - painter.drawRoundedRect(bounds, 20, 20) - left = 36.0 - width = max(240.0, self.width() - 72.0) - if not self._brand_lockup.isNull(): - brand = self._brand_lockup.scaled( - 226, 58, Qt.AspectRatioMode.KeepAspectRatio, - Qt.TransformationMode.SmoothTransformation, - ) - painter.drawPixmap(QPointF(left, 36), brand) - else: - painter.setFont(_font(22, QFont.Weight.DemiBold)) - painter.setPen(QColor(PALETTE["heading"])) - painter.drawText(QPointF(left, 70), "甄养堂 · 医生工作站") - heading_y = max(158.0, min(218.0, self.height() * .27)) - painter.setPen(QColor(PALETTE["muted"])) - painter.setFont(_font(13, QFont.Weight.Medium)) - painter.drawText(QPointF(left, heading_y - 36), "医 生 工 作 台") - painter.setPen(QColor(PALETTE["heading"])) - painter.setFont(_font(30, QFont.Weight.DemiBold)) - painter.drawText(QPointF(left, heading_y), "让诊疗有序,") - painter.drawText(QPointF(left, heading_y + 44), "让沟通更专注。") + clip = QPainterPath() + clip.addRoundedRect(bounds, 20, 20) + painter.setClipPath(clip) + + # 深曜翡翠渐变底 + 右上角精密青玉科技辉光 + bg = QLinearGradient(bounds.topLeft(), bounds.bottomRight()) + bg.setColorAt(0.0, QColor("#0E3F3C")) + bg.setColorAt(0.52, QColor("#092726")) + bg.setColorAt(1.0, QColor("#061717")) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(bg) + painter.drawRect(bounds) + + glow = QRadialGradient( + QPointF(bounds.right() - 70.0, bounds.top() + 90.0), + max(280.0, bounds.width() * 0.55), + ) + glow.setColorAt(0.0, QColor(24, 184, 173, 74)) + glow.setColorAt(0.55, QColor(14, 120, 114, 24)) + glow.setColorAt(1.0, QColor(14, 120, 114, 0)) + painter.setBrush(glow) + painter.drawRect(bounds) + + # 精密医疗科技同心轨道 + 微光心电脉搏线 + ring_center = QPointF(bounds.right() - 48.0, bounds.top() + 86.0) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.setPen(QPen(QColor(223, 199, 147, 36), 1.0)) + painter.drawEllipse(ring_center, 155.0, 155.0) + dash_pen = QPen(QColor(110, 224, 214, 34), 1.0, Qt.PenStyle.DashLine) + painter.setPen(dash_pen) + painter.drawEllipse(ring_center, 230.0, 230.0) + + pulse_y = bounds.bottom() - 96.0 + pulse = QPainterPath(QPointF(bounds.left(), pulse_y)) + pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.36, pulse_y)) + pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.43, pulse_y - 38.0)) + pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.50, pulse_y + 30.0)) + pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.56, pulse_y - 16.0)) + pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.61, pulse_y)) + pulse.lineTo(QPointF(bounds.right(), pulse_y)) + painter.setPen(QPen(QColor(110, 224, 214, 40), 1.4)) + painter.drawPath(pulse) + + # 顶部 1px 香槟鎏金奢雅边框 + painter.setPen(QPen(QColor(223, 199, 147, 72), 1.0)) + painter.drawRoundedRect(bounds, 20, 20) + + left = 40.0 + width = max(240.0, self.width() - 80.0) + + # 甄养堂高定翡翠鎏金徽标 + 精致反白品牌锁标 + emblem = QRectF(left, 36.0, 44.0, 44.0) + em_grad = QLinearGradient(emblem.topLeft(), emblem.bottomRight()) + em_grad.setColorAt(0.0, QColor("#18B0A5")) + em_grad.setColorAt(1.0, QColor("#09615C")) + painter.setBrush(em_grad) + painter.setPen(QPen(QColor(PALETTE["gold_light"]), 1.2)) + painter.drawRoundedRect(emblem, 12.0, 12.0) + + painter.save() + painter.translate(emblem.topLeft()) + painter.scale(44.0 / 38.0, 44.0 / 38.0) + drop = QPainterPath(QPointF(19.0, 7.6)) + drop.cubicTo(QPointF(14.8, 13.2), QPointF(11.2, 17.8), QPointF(11.2, 22.4)) + drop.cubicTo(QPointF(11.2, 26.8), QPointF(14.7, 30.4), QPointF(19.0, 30.4)) + drop.cubicTo(QPointF(23.3, 30.4), QPointF(26.8, 26.8), QPointF(26.8, 22.4)) + drop.cubicTo(QPointF(26.8, 17.8), QPointF(23.2, 13.2), QPointF(19.0, 7.6)) + drop.closeSubpath() + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor("#FFFFFF")) + painter.drawPath(drop) + mini_pulse = QPainterPath(QPointF(13.5, 22.4)) + mini_pulse.lineTo(QPointF(16.2, 22.4)) + mini_pulse.lineTo(QPointF(17.8, 18.8)) + mini_pulse.lineTo(QPointF(20.0, 25.6)) + mini_pulse.lineTo(QPointF(21.6, 22.4)) + mini_pulse.lineTo(QPointF(24.5, 22.4)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.setPen(_round_pen("#0B6E68", 2.0)) + painter.drawPath(mini_pulse) + painter.restore() + + painter.setFont(_font(20, QFont.Weight.DemiBold)) + painter.setPen(QColor("#FFFFFF")) + painter.drawText(QPointF(left + 58.0, 56.0), "甄养堂") + painter.setFont(_font(11, QFont.Weight.Medium)) + painter.setPen(QColor(PALETTE["gold_light"])) + painter.drawText(QPointF(left + 58.0, 74.0), "DIABETES TELEHEALTH · 糖尿病专科工作站") + + heading_y = max(162.0, min(214.0, self.height() * 0.27)) + painter.setPen(QColor("#7CE4DB")) + painter.setFont(_font(12, QFont.Weight.Medium)) + painter.drawText(QPointF(left, heading_y - 34), "PRECISION CLINICAL WORKSTATION") + painter.setPen(QColor("#FFFFFF")) + painter.setFont(_font(31, QFont.Weight.DemiBold)) + painter.drawText(QPointF(left, heading_y), "让每一次辨证,") + painter.drawText(QPointF(left, heading_y + 44), "更专注、更有序。") painter.setFont(_font(14)) - painter.setPen(QColor(PALETTE["muted"])) - painter.drawText(QPointF(left, heading_y + 82), "从接诊、病历到处方,在一个工作台完成。") + painter.setPen(QColor("#A4C9C5")) + painter.drawText(QPointF(left, heading_y + 82), "融合智能辨证、纵向血糖洞察与合规双签的一体化医疗桌面。") row_y = heading_y + 122 for index, (title, detail) in enumerate(( - ("今日接诊", "快速找到待接诊患者与预约安排"), - ("诊疗记录", "病历、随访与面诊资料集中查看"), - ("处方协作", "开方与审核流程清晰衔接"), + ("今日接诊 · 三栏直览", "待诊队列、四诊病历与视频房间同屏高效衔接"), + ("AI 临床辨证辅助", "多模态聚合历次复诊与血糖波动,梳理随访要点"), + ("处方协作 · CA 合规双签", "经验方一键复用,开方与药师审核签署全流程留痕"), ), start=1): row = QRectF(left, row_y, width, 66) - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(PALETTE["surface"])) + painter.setPen(QPen(QColor(223, 199, 147, 52), 1.0)) + painter.setBrush(QColor(255, 255, 255, 16)) painter.drawRoundedRect(row, 12, 12) - painter.setFont(_font(13, QFont.Weight.DemiBold)) - painter.setPen(QColor(PALETTE["accent"])) - painter.drawText(QRectF(left + 16, row_y, 28, 66), Qt.AlignmentFlag.AlignCenter, f"0{index}") + badge_rect = QRectF(left + 14, row_y + 17, 32, 32) + painter.setPen(QPen(QColor(223, 199, 147, 96), 1.0)) + painter.setBrush(QColor(223, 199, 147, 24)) + painter.drawRoundedRect(badge_rect, 8, 8) + painter.setFont(_font(12, QFont.Weight.DemiBold)) + painter.setPen(QColor(PALETTE["gold_light"])) + painter.drawText(badge_rect, Qt.AlignmentFlag.AlignCenter, f"0{index}") painter.setFont(_font(15, QFont.Weight.Medium)) - painter.setPen(QColor(PALETTE["heading"])) - painter.drawText(QPointF(left + 58, row_y + 27), title) + painter.setPen(QColor("#F4FAF9")) + painter.drawText(QPointF(left + 60, row_y + 28), title) painter.setFont(_font(12)) - painter.setPen(QColor(PALETTE["muted"])) - painter.drawText(QPointF(left + 58, row_y + 47), detail) + painter.setPen(QColor("#9AC0BC")) + painter.drawText(QPointF(left + 60, row_y + 49), detail) row_y += 78 - if self.height() > row_y + 50: + if self.height() > row_y + 48: painter.setFont(_font(12)) - painter.setPen(QColor(PALETTE["muted"])) - painter.drawText(QPointF(left, self.height() - 28), "仅供获授权的医疗人员使用") + painter.setPen(QColor("#749E99")) + painter.drawText(QPointF(left, self.height() - 28), "仅供获授权的执业医疗人员使用 · 端到端加密传输") painter.end() + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API + if event.button() == Qt.MouseButton.LeftButton: + handle = self.window().windowHandle() + if handle is not None and handle.startSystemMove(): + event.accept() + return + super().mousePressEvent(event) + + +class _LoginWindowControlButton(QToolButton): + """登录悬浮窗右上角原生桌面最小化/关闭按钮。""" + + def __init__(self, kind: str, parent: QWidget | None = None) -> None: + super().__init__(parent) + self._kind = kind + self.setObjectName("LoginWindowControl") + self.setProperty("windowControl", kind) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setAutoRaise(True) + self.setFixedSize(34, 34) + self.setIcon(icons.icon(kind, "muted", 16)) + self.setIconSize(QSize(16, 16)) + + def enterEvent(self, event: Any) -> None: # noqa: N802 - Qt API + if self._kind == "close": + self.setIcon(icons.icon("close", "inverse", 16)) + else: + self.setIcon(icons.icon(self._kind, "heading", 16)) + super().enterEvent(event) + + def leaveEvent(self, event: Any) -> None: # noqa: N802 - Qt API + self.setIcon(icons.icon(self._kind, "muted", 16)) + super().leaveEvent(event) + + +class _LoginWindowShell(QWidget): + """无边框奢雅青瓷圆角悬浮视窗,支持原生拖动与边缘缩放。""" + + _RESIZE_MARGIN = 8 + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setMouseTracking(True) + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt API + del event + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + painter.setBrush(QColor(PALETTE["canvas"])) + painter.setPen(QPen(QColor("#B5CAC6"), 1.0)) + painter.drawRoundedRect(bounds, 18.0, 18.0) + painter.end() + + def _resize_edges(self, position: QPointF) -> Qt.Edge: + edges = Qt.Edge(0) + if position.x() <= self._RESIZE_MARGIN: + edges |= Qt.Edge.LeftEdge + elif position.x() >= self.width() - self._RESIZE_MARGIN: + edges |= Qt.Edge.RightEdge + if position.y() <= self._RESIZE_MARGIN: + edges |= Qt.Edge.TopEdge + elif position.y() >= self.height() - self._RESIZE_MARGIN: + edges |= Qt.Edge.BottomEdge + return edges + + def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API + edges = self._resize_edges(event.position()) + if edges in ( + Qt.Edge.LeftEdge | Qt.Edge.TopEdge, + Qt.Edge.RightEdge | Qt.Edge.BottomEdge, + ): + self.setCursor(Qt.CursorShape.SizeFDiagCursor) + elif edges in ( + Qt.Edge.LeftEdge | Qt.Edge.BottomEdge, + Qt.Edge.RightEdge | Qt.Edge.TopEdge, + ): + self.setCursor(Qt.CursorShape.SizeBDiagCursor) + elif edges in (Qt.Edge.LeftEdge, Qt.Edge.RightEdge): + self.setCursor(Qt.CursorShape.SizeHorCursor) + elif edges in (Qt.Edge.TopEdge, Qt.Edge.BottomEdge): + self.setCursor(Qt.CursorShape.SizeVerCursor) + else: + self.unsetCursor() + super().mouseMoveEvent(event) + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API + if event.button() == Qt.MouseButton.LeftButton: + handle = self.window().windowHandle() + if handle is not None: + edges = self._resize_edges(event.position()) + if edges and handle.startSystemResize(edges): + event.accept() + return + if handle.startSystemMove(): + event.accept() + return + super().mousePressEvent(event) + class _PasswordField(QFrame): """Keep the grouped password control visibly focused for keyboard users.""" @@ -318,25 +498,48 @@ class LoginWindow(QMainWindow): self.setWindowTitle("甄养堂 · 医生工作站 - 甄养堂医生工作站") self.setWindowIcon(self._window_icon()) + self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setStyleSheet("QMainWindow { background: transparent; }") self.setMinimumSize(860, 590) self.resize(1280, 800) - canvas = QWidget() + canvas = _LoginWindowShell(self) canvas.setObjectName("LoginCanvas") canvas.setStyleSheet( """ QWidget#LoginCanvas { color: #1A1C1F; - background-color: #F4F6FA; + background-color: transparent; font-size: 16px; } + QToolButton#LoginWindowControl { + background: transparent; + border: 1px solid transparent; + border-radius: 9px; + } + QToolButton#LoginWindowControl:hover { + background-color: #E2ECEA; + border-color: #C7DCD8; + } + QToolButton#LoginWindowControl:pressed { + background-color: #D6E4E1; + } + QToolButton#LoginWindowControl[windowControl="close"]:hover { + background-color: #D63F4F; + border-color: #D63F4F; + } + QToolButton#LoginWindowControl[windowControl="close"]:pressed { + background-color: #B92E3D; + border-color: #B92E3D; + } QWidget#LoginBrandPanel { background-color: transparent; border: 0; } QFrame#LoginCard { background-color: #FFFFFF; - border: 1px solid #EDEDEE; + border: 1px solid #D3E1DF; border-radius: 20px; } QFrame#LoginCard QFrame#SubtleCard { @@ -407,22 +610,25 @@ class LoginWindow(QMainWindow): padding: 0; } QFrame#LoginCard QPushButton[variant="primary"] { - min-height: 58px; - max-height: 58px; + min-height: 54px; + max-height: 54px; color: #FFFFFF; - background-color: #4F63D9; - border: 0; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #14968D, stop:1 $ds_accent); + border: 1px solid $ds_accent; border-radius: 12px; - font-size: 18px; - font-weight: 500; + font-size: 17px; + font-weight: 600; } QFrame#LoginCard QPushButton#ServerSettingsToggle { - min-height: 56px; - max-height: 56px; + min-height: 52px; + max-height: 52px; padding: 0; } QFrame#LoginCard QPushButton[variant="primary"]:hover { - background-color: #4156C4; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #0F8078, stop:1 $ds_accent_hover); + } + QFrame#LoginCard QPushButton[variant="primary"]:pressed { + background-color: $ds_accent_pressed; } QFrame#LoginCard QPushButton[variant="secondary"] { color: #1A1C1F; @@ -449,6 +655,26 @@ class LoginWindow(QMainWindow): self.brand_panel = self._build_brand_panel() self.login_root.addWidget(self.brand_panel, 60) self.login_root.addWidget(self._build_login_area(), 40) + + # 悬浮于无边框登录视窗右上角的原生最小化/关闭控件,不占用表单区纵向高度 + self.window_controls_host = QWidget(canvas) + self.window_controls_host.setObjectName("LoginWindowControls") + controls_layout = QHBoxLayout(self.window_controls_host) + controls_layout.setContentsMargins(0, 0, 0, 0) + controls_layout.setSpacing(6) + self.minimize_button = _LoginWindowControlButton("minimize", self.window_controls_host) + self.minimize_button.setToolTip("最小化") + self.minimize_button.setAccessibleName("最小化登录窗口") + self.minimize_button.clicked.connect(self.showMinimized) + controls_layout.addWidget(self.minimize_button) + self.close_button = _LoginWindowControlButton("close", self.window_controls_host) + self.close_button.setToolTip("关闭") + self.close_button.setAccessibleName("关闭登录窗口") + self.close_button.clicked.connect(self.close) + controls_layout.addWidget(self.close_button) + self.window_controls_host.adjustSize() + self.window_controls_host.raise_() + self._restore_settings() for widget in (canvas, *canvas.findChildren(QWidget)): if widget.styleSheet(): @@ -478,6 +704,12 @@ class LoginWindow(QMainWindow): 0, 12 if compact_height else min(104, max(24, (event.size().height() - 694) // 2)), 0, 12 ) super().resizeEvent(event) + if hasattr(self, "window_controls_host"): + self.window_controls_host.move( + max(12, self.width() - self.window_controls_host.width() - 16), + 14, + ) + self.window_controls_host.raise_() def _build_brand_panel(self) -> QWidget: panel = _BrandPanel() diff --git a/app/src/doctor_workstation/ui/pages/appointments.py b/app/src/doctor_workstation/ui/pages/appointments.py index 554edc879..0cee7b74a 100755 --- a/app/src/doctor_workstation/ui/pages/appointments.py +++ b/app/src/doctor_workstation/ui/pages/appointments.py @@ -45,24 +45,24 @@ from ..appointments_style import appointments_stylesheet from ..dialogs import DiagnosisDialog from ..dialogs.ai_consult import can_open_ai_consult, present_ai_consult from ..dialogs.prescription import ( - PRESCRIPTION_VOIDED_RESULT, + PRESCRIPTION_VOIDED_RESULT, PrescriptionDetailDialog, PrescriptionEditorDialog, build_prescription_clinical_diagnosis, build_prescription_visit_no, - can_reissue_prescription, - prescription_edit_is_locked, - prescription_matches_appointment, - reissue_prescription_seed, + can_reissue_prescription, + prescription_edit_is_locked, + prescription_matches_appointment, + reissue_prescription_seed, ) from ..dialogs.prescription_ai import ( can_open_diagnosis_ai_report, present_diagnosis_ai_report, ) -from ..dialogs.prescription_esign import ( - resume_saved_prescription, - saved_prescription_message, -) +from ..dialogs.prescription_esign import ( + resume_saved_prescription, + saved_prescription_message, +) from ..filter_disclosure import FilterDisclosure from ..icons import icon from ..infinite_list import InfiniteList @@ -84,6 +84,7 @@ from ..widgets import ( run_async, show_toast, ) +from ..window_primitives import ClinicalInspectorPanel STATUS_TABS: tuple[tuple[str, str | int], ...] = ( ("待接诊", 1), @@ -717,6 +718,9 @@ class AppointmentsPage(QWidget): self.content_layout = layout self.table_card = self._build_table_card() layout.addWidget(self.table_card, 1) + self.inspector_panel = ClinicalInspectorPanel(host, width=360) + self.inspector_panel.closed.connect(self._on_inspector_closed) + layout.addWidget(self.inspector_panel) return host def _build_table_card(self) -> QWidget: @@ -810,6 +814,13 @@ class AppointmentsPage(QWidget): self.toolbar_cancel_button.clicked.connect(self._cancel_selected) actions.addWidget(self.toolbar_cancel_button) actions.addStretch(1) + self.inspector_toggle_button = QPushButton("右侧检视", card) + self.inspector_toggle_button.setProperty("variant", "secondary") + self.inspector_toggle_button.setProperty("compactAction", True) + self.inspector_toggle_button.setCheckable(True) + self.inspector_toggle_button.setToolTip("展开或收起右侧非阻塞患者临床检视器") + self.inspector_toggle_button.clicked.connect(self._toggle_clinical_inspector) + actions.addWidget(self.inspector_toggle_button) refresh = QPushButton("刷新", card) refresh.setProperty("variant", "ghost") refresh.setProperty("compactAction", True) @@ -1434,6 +1445,59 @@ class AppointmentsPage(QWidget): text = f"{label} ({count})" if count else label self.tab_bar.setTabText(index, text) + def _on_inspector_closed(self) -> None: + if hasattr(self, "inspector_toggle_button"): + self.inspector_toggle_button.setChecked(False) + + def _toggle_clinical_inspector(self, checked: bool) -> None: + if not hasattr(self, "inspector_panel"): + return + if not checked: + self.inspector_panel.hide() + return + self._sync_clinical_inspector(force_open=True) + + def _sync_clinical_inspector(self, *, force_open: bool = False) -> None: + if not hasattr(self, "inspector_panel"): + return + if not force_open and not self.inspector_panel.isVisible(): + return + row = self.table.current_data() if hasattr(self, "table") else None + if row is None: + if force_open: + self.inspector_panel.set_summary( + title="未选中挂号记录", + subtitle="请在左侧表格中单击任意患者行以实时预览临床摘要", + rows=[("提示", "支持无弹窗快速核查挂号时段、医助与接诊操作")], + actions=[], + ) + return + patient = display_text(first_value(row, "patient_name", "name", default="患者")) + phone = display_text(first_value(row, "phone", "mobile", "patient_phone", default="—")) + doctor = display_text(first_value(row, "doctor_name", default="—")) + assistant = display_text(first_value(row, "assistant_name", default="—")) + appt_time = display_text(first_value(row, "appointment_time", "time_text", default="—")) + appt_date = display_text(first_value(row, "appointment_date", default="")) + mode_desc = appointment_type_description(appointment_type_value(row)) + actions: list[tuple[str, str, Any]] = [] + if self.toolbar_edit_button.isEnabled(): + actions.append(("编辑四诊病历", "primary", self._edit_patient)) + if self.toolbar_ai_consult_button.isEnabled(): + actions.append(("启动 AI 辨证分析", "secondary", self._open_ai_consult)) + if self.toolbar_cancel_button.isEnabled(): + actions.append(("取消当前挂号", "danger", self._cancel_selected)) + self.inspector_panel.set_summary( + title=patient, + subtitle=f"{mode_desc} · 手机 {phone}", + rows=[ + ("预约时间", f"{appt_date} {appt_time}".strip()), + ("接诊医生", doctor), + ("协作医助", assistant), + ("挂号编号", str(first_value(row, "id", default="—"))), + ], + actions=actions, + ) + def _selection_changed(self) -> None: for row_index in range(self.table.rowCount()): host = self.table.cellWidget(row_index, 0) @@ -1484,6 +1548,7 @@ class AppointmentsPage(QWidget): and _as_int(first_value(row, "doctor_id", default=0)) > 0 ) self.toolbar_cancel_button.setEnabled(has_row and status == 1) + self._sync_clinical_inspector() def _current_row(self) -> Any | None: return self.table.current_data() diff --git a/app/src/doctor_workstation/ui/pages/consultations.py b/app/src/doctor_workstation/ui/pages/consultations.py index e94cb313b..b9930fac0 100755 --- a/app/src/doctor_workstation/ui/pages/consultations.py +++ b/app/src/doctor_workstation/ui/pages/consultations.py @@ -13,9 +13,10 @@ from typing import Any from PySide6.QtCore import QDate, QSize, Qt, QTimer, QUrl, Signal from PySide6.QtGui import QDesktopServices, QPixmap from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest -from PySide6.QtWidgets import ( - QComboBox, - QCompleter, +from PySide6.QtWidgets import ( + QApplication, + QComboBox, + QCompleter, QDateEdit, QDialog, QDialogButtonBox, @@ -38,39 +39,39 @@ from PySide6.QtWidgets import ( QWidget, ) -from ...core import UserProfile -from ...core.appointment_modes import appointment_type_value, can_appointment_video -from ...core.errors import ApiBusinessError -from .. import icons +from ...core import UserProfile +from ...core.appointment_modes import appointment_type_value, can_appointment_video +from ...core.errors import ApiBusinessError +from .. import icons from ..consultations_style import consultations_stylesheet from ..diagnosis_index_widgets import ( DiagnosisChip, DiagnosisLoadingOverlay, DiagnosisTableHost, FlowWidget, - can_void_prescription, + can_void_prescription, prescription_action, video_call_is_live, ) from ..dialogs import DiagnosisDialog from ..dialogs.ai_consult import can_open_ai_consult, present_ai_consult -from ..dialogs.prescription import ( - PRESCRIPTION_VOIDED_RESULT, +from ..dialogs.prescription import ( + PRESCRIPTION_VOIDED_RESULT, PrescriptionDetailDialog, PrescriptionEditorDialog, build_prescription_clinical_diagnosis, build_prescription_visit_no, - can_reissue_prescription, - can_void_issued_prescription, - confirm_prescription_void, - prescription_edit_is_locked, - prescription_is_voided, - prescription_matches_appointment, - reissue_prescription_seed, -) -from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message -from ..filter_disclosure import FilterDisclosure -from ..infinite_list import InfiniteList + can_reissue_prescription, + can_void_issued_prescription, + confirm_prescription_void, + prescription_edit_is_locked, + prescription_is_voided, + prescription_matches_appointment, + reissue_prescription_seed, +) +from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message +from ..filter_disclosure import FilterDisclosure +from ..infinite_list import InfiniteList from ..theme import mark_business_dialog from ..widgets import ( MessageBanner, @@ -88,7 +89,7 @@ from ..widgets import ( ) _STATUS_CARD_HEIGHT = 54 -_FILTERS_BASE_HEIGHT = 236 +_FILTERS_BASE_HEIGHT = 236 APPOINTMENT_STATUS = { @@ -112,32 +113,32 @@ def _as_int(value: Any, default: int = 0) -> int: return default -def _department_options(rows: Any) -> list[tuple[int, str]]: - """Flatten the server-scoped tree without deriving extra options from profiles.""" - if not isinstance(rows, (list, tuple)): - raise ValueError("部门数据格式异常,请重试") - options: list[tuple[int, str]] = [] - seen: set[int] = set() - - def visit(nodes: Sequence[Any], parents: tuple[str, ...] = ()) -> None: - for node in nodes: - if not isinstance(node, Mapping): - continue - label = str(node.get("name") or "").strip() - department_id = _as_int(node.get("id")) - path = (*parents, label) if label else parents - if department_id > 0 and label and department_id not in seen: - options.append((department_id, " / ".join(path))) - seen.add(department_id) - children = node.get("children") - if isinstance(children, (list, tuple)): - visit(children, path) - - visit(rows) - return options - - -def _as_bool(value: Any) -> bool: +def _department_options(rows: Any) -> list[tuple[int, str]]: + """Flatten the server-scoped tree without deriving extra options from profiles.""" + if not isinstance(rows, (list, tuple)): + raise ValueError("部门数据格式异常,请重试") + options: list[tuple[int, str]] = [] + seen: set[int] = set() + + def visit(nodes: Sequence[Any], parents: tuple[str, ...] = ()) -> None: + for node in nodes: + if not isinstance(node, Mapping): + continue + label = str(node.get("name") or "").strip() + department_id = _as_int(node.get("id")) + path = (*parents, label) if label else parents + if department_id > 0 and label and department_id not in seen: + options.append((department_id, " / ".join(path))) + seen.add(department_id) + children = node.get("children") + if isinstance(children, (list, tuple)): + visit(children, path) + + visit(rows) + return options + + +def _as_bool(value: Any) -> bool: if isinstance(value, str): return value.strip().lower() in {"1", "true", "yes", "on"} return bool(value) @@ -239,7 +240,7 @@ def _appointment_status(record: Any) -> Any: def _appointment_id(record: Any) -> int: - value = first_value(record, "appointment_id", "latest_appointment_id", default=None) + value = first_value(record, "appointment_id", "latest_appointment_id", default=None) if value is None: value = first_value(get_value(record, "latest_appointment", None), "id", default=None) if value is None: @@ -302,8 +303,8 @@ def _video_payload(record: Any) -> dict[str, Any]: return { "source": "consultations", - "appointment_id": _appointment_id(record), - "appointment_type": appointment_type_value(record), + "appointment_id": _appointment_id(record), + "appointment_type": appointment_type_value(record), "patient_id": first_value(record, "patient_id", "source_patient_id"), "diagnosis_id": first_value(record, "diagnosis_id", "id"), "patient_name": first_value(record, "patient_name", default="患者"), @@ -696,7 +697,7 @@ class _AppointmentLogDialog(QDialog): class _QrResultDialog(QDialog): - """Expose the server-issued QR asset without pretending to generate it locally.""" + """居中紧凑展示服务器生成的视频/诊单二维码,支持直接扫码与一键复制图片转发企微。""" def __init__( self, @@ -704,41 +705,133 @@ class _QrResultDialog(QDialog): record: Any, qrcode_url: str, parent: QWidget | None = None, + *, + repository: Any = None, ) -> None: super().__init__(parent) self._url = qrcode_url + self._repository = repository self.setWindowTitle(title) - self.resize(480, 310) + self.setMinimumWidth(420) + self.resize(468, 570) + root = QVBoxLayout(self) - root.setContentsMargins(24, 22, 24, 18) + root.setContentsMargins(24, 18, 24, 18) root.setSpacing(12) - heading = QLabel(title) + + heading = QLabel(title, self) heading.setProperty("dialogRole", "title") + heading.setAlignment(Qt.AlignmentFlag.AlignCenter) root.addWidget(heading) + + patient_name = display_text(first_value(record, "patient_name"), "患者") description = QLabel( - f"患者:{display_text(first_value(record, 'patient_name'), '患者')}\n" - "二维码由服务器生成,请打开后使用企业微信转发给患者。" + f"患者:{patient_name} · 请使用微信或企业微信扫码,或复制图片转发患者", + self, ) description.setProperty("dialogRole", "subtitle") + description.setWordWrap(True) + description.setAlignment(Qt.AlignmentFlag.AlignCenter) root.addWidget(description) - link = QLabel(f'打开服务器二维码') + + # 中央高对比纯白静区二维码卡片(确保微信/企微秒识别) + qr_row = QHBoxLayout() + qr_row.setContentsMargins(0, 4, 0, 4) + qr_row.addStretch(1) + self.preview = _QrImagePreview(self) + self.preview.setObjectName("DiagnosisVideoQrPreview") + self.preview.setFixedSize(272, 272) + self.preview.setStyleSheet( + "QLabel#DiagnosisVideoQrPreview { background: #FFFFFF; border: 1px solid #C4DAD6;" + " border-radius: 14px; color: #5F7A78; padding: 12px; }" + ) + qr_row.addWidget(self.preview) + qr_row.addStretch(1) + root.addLayout(qr_row) + + link = QLabel( + f'在浏览器中打开原图', + self, + ) link.setOpenExternalLinks(True) + link.setAlignment(Qt.AlignmentFlag.AlignCenter) link.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction) root.addWidget(link) - url_text = QLineEdit(qrcode_url) + + url_row = QHBoxLayout() + url_row.setContentsMargins(0, 0, 0, 0) + url_row.setSpacing(8) + url_text = QLineEdit(qrcode_url, self) url_text.setReadOnly(True) url_text.setToolTip(qrcode_url) - root.addWidget(url_text) - buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + url_row.addWidget(url_text, 1) + copy_url_btn = QPushButton("复制链接", self) + copy_url_btn.setProperty("variant", "secondary") + copy_url_btn.clicked.connect(self._copy_url) + url_row.addWidget(copy_url_btn) + root.addLayout(url_row) + + root.addStretch(1) + + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, self) + self.copy_image_button = buttons.addButton( + "复制二维码图片", QDialogButtonBox.ButtonRole.ActionRole + ) + self.copy_image_button.setProperty("variant", "secondary") + self.copy_image_button.clicked.connect(self._copy_image) open_button = buttons.addButton("打开二维码", QDialogButtonBox.ButtonRole.ActionRole) open_button.setProperty("variant", "primary") - open_button.clicked.connect(lambda: QDesktopServices.openUrl(QUrl.fromUserInput(self._url))) + open_button.clicked.connect( + lambda: QDesktopServices.openUrl(QUrl.fromUserInput(self._url)) + ) buttons.button(QDialogButtonBox.StandardButton.Close).setText("关闭") buttons.rejected.connect(self.reject) root.addWidget(buttons) mark_business_dialog(self, "DiagnosisQrResultDialog") - open_button.style().unpolish(open_button) - open_button.style().polish(open_button) + for btn in (copy_url_btn, self.copy_image_button, open_button): + btn.style().unpolish(btn) + btn.style().polish(btn) + + self._load_qr_image() + + def _load_qr_image(self) -> None: + """优先通过仓储下载通道拉取(兼容自签名/内网 TLS),失败自动回退 Qt 网络加载。""" + + if self._repository is not None and callable( + getattr(self._repository, "download_public_image", None) + ): + self.preview.show_loading() + run_async( + lambda: invoke(self._repository, "download_public_image", url=self._url), + on_success=self._on_repo_image_loaded, + on_error=lambda _err: self.preview.load_url(self._url), + ) + return + self.preview.load_url(self._url) + + def _on_repo_image_loaded(self, data: Any) -> None: + if isinstance(data, (bytes, bytearray)) and data: + pixmap = QPixmap() + if pixmap.loadFromData(bytes(data)): + self.preview.show_pixmap(pixmap) + return + self.preview.load_url(self._url) + + def _copy_url(self) -> None: + clipboard = QApplication.clipboard() + if clipboard is not None: + clipboard.setText(self._url) + show_toast(self, "二维码链接已复制到剪贴板。", "success", 2400) + + def _copy_image(self) -> None: + pixmap = self.preview.loaded_pixmap() + if pixmap is None or pixmap.isNull(): + show_toast(self, "二维码图片尚未加载完成,请稍候或先复制链接。", "warning", 2800) + return + clipboard = QApplication.clipboard() + if clipboard is not None: + clipboard.setPixmap(pixmap) + show_toast(self, "二维码图片已复制,可直接粘贴到企业微信发送给患者。", "success", 2800) class _QrImagePreview(QLabel): @@ -757,6 +850,7 @@ class _QrImagePreview(QLabel): self._manager = QNetworkAccessManager(self) self._reply: QNetworkReply | None = None self._generation = 0 + self._loaded_pixmap: QPixmap | None = None self.show_loading() def show_loading(self) -> None: @@ -765,6 +859,7 @@ class _QrImagePreview(QLabel): self._reply.abort() self._reply.deleteLater() self._reply = None + self._loaded_pixmap = None self.clear() self.setText("正在加载服务器二维码...") @@ -805,16 +900,24 @@ class _QrImagePreview(QLabel): if not data or not pixmap.loadFromData(data): self.show_failure() return + self.show_pixmap(pixmap) + + def show_pixmap(self, pixmap: QPixmap) -> None: + self._loaded_pixmap = pixmap self.setText("") + target_side = max(200, min(self.width(), self.height()) - 24) self.setPixmap( pixmap.scaled( - 240, - 240, + target_side, + target_side, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation, ) ) + def loaded_pixmap(self) -> QPixmap | None: + return self._loaded_pixmap + class _DiagnosisOrderQrDialog(QDialog): """Payment QR state that retains the immutable order number for retries.""" @@ -960,10 +1063,10 @@ class ConsultationsPage(QWidget): self._page_size = 15 self._generation = 0 self._count_generation = 0 - self._options_generation = 0 - self._departments_generation = 0 - self._departments_loaded = False - self._departments_loading = False + self._options_generation = 0 + self._departments_generation = 0 + self._departments_loaded = False + self._departments_loading = False self._prescription_generation = 0 self._mutation_generation = 0 self._menu_generation = 0 @@ -1014,7 +1117,7 @@ class ConsultationsPage(QWidget): content.setAutoFillBackground(False) self.page_scroll.setWidget(content) page_layout = QVBoxLayout(content) - page_layout.setContentsMargins(27, 24, 26, 8) + page_layout.setContentsMargins(27, 24, 26, 8) page_layout.setSpacing(10) self.page_header = PageHeader( @@ -1022,12 +1125,12 @@ class ConsultationsPage(QWidget): "按状态与日期管理患者队列,完成通话、开方与接诊闭环。", content, ) - self.page_header.setFixedHeight(90) - self.page_header.layout().setContentsMargins(0, 0, 0, 6) - self.page_header.layout().setSpacing(12) - self.page_header.layout().itemAt(1).layout().itemAt(0).layout().setSpacing(10) - self.page_header.actions.setAlignment(Qt.AlignmentFlag.AlignTop) - self.page_header.set_compact(True) + self.page_header.setFixedHeight(90) + self.page_header.layout().setContentsMargins(0, 0, 0, 6) + self.page_header.layout().setSpacing(12) + self.page_header.layout().itemAt(1).layout().itemAt(0).layout().setSpacing(10) + self.page_header.actions.setAlignment(Qt.AlignmentFlag.AlignTop) + self.page_header.set_compact(True) page_layout.addWidget(self.page_header) status_card = QFrame() @@ -1036,10 +1139,10 @@ class ConsultationsPage(QWidget): self.status_card = status_card status_card_layout = QHBoxLayout(status_card) status_card_layout.setContentsMargins(0, 0, 0, 0) - status_card_layout.setSpacing(8) - status_label = self._filter_label("问诊状态:") - status_label.setFixedWidth(80) - status_card_layout.addWidget(status_label) + status_card_layout.setSpacing(8) + status_label = self._filter_label("问诊状态:") + status_label.setFixedWidth(80) + status_card_layout.addWidget(status_label) status_tabs = QWidget(status_card) status_tabs.setObjectName("DiagnosisStatusTabs") @@ -1066,30 +1169,30 @@ class ConsultationsPage(QWidget): status_card_layout.addWidget(status_tabs) status_card_layout.addStretch(1) - status_search = QWidget(status_card) - status_search.setObjectName("DiagnosisStatusSearch") - status_search.setFixedWidth(518) + status_search = QWidget(status_card) + status_search.setObjectName("DiagnosisStatusSearch") + status_search.setFixedWidth(518) status_search_layout = QHBoxLayout(status_search) status_search_layout.setContentsMargins(0, 0, 0, 0) - status_search_layout.setSpacing(16) + status_search_layout.setSpacing(16) self.patient_name_edit = QLineEdit(status_search) self.patient_name_edit.setObjectName("DiagnosisPatientName") - self.patient_name_edit.setFixedWidth(172) - self.patient_name_edit.addAction(icons.icon("search", "muted", 16), QLineEdit.ActionPosition.LeadingPosition) + self.patient_name_edit.setFixedWidth(172) + self.patient_name_edit.addAction(icons.icon("search", "muted", 16), QLineEdit.ActionPosition.LeadingPosition) self.patient_name_edit.setPlaceholderText("患者姓名") self.patient_name_edit.setClearButtonEnabled(True) self.patient_name_edit.returnPressed.connect(self._search) status_search_layout.addWidget(self.patient_name_edit, 1) self.doctor_edit = QLineEdit(status_search) self.doctor_edit.setObjectName("DiagnosisDoctorName") - self.doctor_edit.setFixedWidth(153) + self.doctor_edit.setFixedWidth(153) self.doctor_edit.setPlaceholderText("医生") self.doctor_edit.setClearButtonEnabled(True) self.doctor_edit.returnPressed.connect(self._search) status_search_layout.addWidget(self.doctor_edit, 1) self.search_button = QPushButton("查询", status_search) self.search_button.setProperty("variant", "primary") - self.search_button.setFixedWidth(73) + self.search_button.setFixedWidth(73) self.search_button.clicked.connect(self._search) status_search_layout.addWidget(self.search_button) self.custom_date_edit = QDateEdit(status_search) @@ -1101,9 +1204,9 @@ class ConsultationsPage(QWidget): self.custom_date_edit.setDate(_OPTIONAL_DATE_MINIMUM) self.custom_date_edit.setToolTip("自定义挂号日期") self.custom_date_edit.dateChanged.connect(self._custom_date_changed) - self.custom_date_edit.setFixedWidth(202) + self.custom_date_edit.setFixedWidth(202) self.reset_button = QPushButton("重置", status_search) - self.reset_button.setFixedWidth(72) + self.reset_button.setFixedWidth(72) self.reset_button.clicked.connect(self._reset) status_search_layout.addWidget(self.reset_button) @@ -1112,27 +1215,27 @@ class ConsultationsPage(QWidget): self.filters_card = filters filter_layout = QVBoxLayout(filters) filter_layout.setContentsMargins(18, 8, 18, 12) - filter_layout.setSpacing(8) - search_row = QHBoxLayout() - search_row.setContentsMargins(0, 0, 0, 0) - search_row.addStretch(1) - search_row.addWidget(status_search) - status_search.setFixedHeight(44) - filter_layout.addLayout(search_row) - filter_layout.addWidget(status_card) + filter_layout.setSpacing(8) + search_row = QHBoxLayout() + search_row.setContentsMargins(0, 0, 0, 0) + search_row.addStretch(1) + search_row.addWidget(status_search) + status_search.setFixedHeight(44) + filter_layout.addLayout(search_row) + filter_layout.addWidget(status_card) date_filters = QWidget(filters) date_filters.setObjectName("DiagnosisDateFilters") - date_filters.setMinimumHeight(48) - self.date_filters = date_filters + date_filters.setMinimumHeight(48) + self.date_filters = date_filters main_filters = QHBoxLayout(date_filters) main_filters.setContentsMargins(0, 0, 0, 0) main_filters.setSpacing(8) main_filters.setAlignment(Qt.AlignmentFlag.AlignVCenter) - date_label = self._filter_label("日期:") - date_label.setFixedWidth(80) - main_filters.addWidget(date_label) - self.main_chip_flow = FlowWidget(horizontal_spacing=24, vertical_spacing=6) + date_label = self._filter_label("日期:") + date_label.setFixedWidth(80) + main_filters.addWidget(date_label) + self.main_chip_flow = FlowWidget(horizontal_spacing=24, vertical_spacing=6) self.date_buttons: dict[str, DiagnosisChip] = {} self._date_button_labels: dict[str, str] = {} for label, offset in ( @@ -1143,16 +1246,16 @@ class ConsultationsPage(QWidget): ("后天挂号", 2), ): value = QDate.currentDate().addDays(offset).toString("yyyy-MM-dd") - button = DiagnosisChip(label) - button.setProperty("dateChoice", True) + button = DiagnosisChip(label) + button.setProperty("dateChoice", True) button.clicked.connect( lambda _checked=False, date_value=value: self._choose_date(date_value) ) self.date_buttons[value] = button self._date_button_labels[value] = label self.main_chip_flow.flow.addWidget(button) - all_button = DiagnosisChip("全部") - all_button.setProperty("dateChoice", True) + all_button = DiagnosisChip("全部") + all_button.setProperty("dateChoice", True) all_button.clicked.connect(lambda _checked=False: self._choose_date("")) self.date_buttons[""] = all_button self._date_button_labels[""] = "全部" @@ -1205,21 +1308,21 @@ class ConsultationsPage(QWidget): self.diagnosis_confirmed_combo.setObjectName("DiagnosisConfirmationFilter") self.diagnosis_confirmed_combo.activated.connect(self._confirmation_combo_changed) self.confirmed_combo = self.diagnosis_confirmed_combo - self.department_combo = self._fixed_combo((("全部部门", ""),)) - self.department_combo.setObjectName("DiagnosisDepartmentFilter") - self.department_combo.setEditable(True) - self.department_combo.setInsertPolicy(QComboBox.InsertPolicy.NoInsert) - self.department_combo.completer().setCompletionMode(QCompleter.CompletionMode.PopupCompletion) - self.department_combo.completer().setFilterMode(Qt.MatchFlag.MatchContains) - self.department_combo.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive) - self.department_combo.lineEdit().setPlaceholderText("输入部门名称搜索") - self.department_combo.lineEdit().returnPressed.connect(self._search) - self.department_retry_button = QToolButton() - self.department_retry_button.setObjectName("DiagnosisDepartmentRetry") - self.department_retry_button.setText("重试") - self.department_retry_button.setAccessibleName("重新加载部门") - self.department_retry_button.clicked.connect(lambda: self._load_departments(force=True)) - self.department_retry_button.hide() + self.department_combo = self._fixed_combo((("全部部门", ""),)) + self.department_combo.setObjectName("DiagnosisDepartmentFilter") + self.department_combo.setEditable(True) + self.department_combo.setInsertPolicy(QComboBox.InsertPolicy.NoInsert) + self.department_combo.completer().setCompletionMode(QCompleter.CompletionMode.PopupCompletion) + self.department_combo.completer().setFilterMode(Qt.MatchFlag.MatchContains) + self.department_combo.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive) + self.department_combo.lineEdit().setPlaceholderText("输入部门名称搜索") + self.department_combo.lineEdit().returnPressed.connect(self._search) + self.department_retry_button = QToolButton() + self.department_retry_button.setObjectName("DiagnosisDepartmentRetry") + self.department_retry_button.setText("重试") + self.department_retry_button.setAccessibleName("重新加载部门") + self.department_retry_button.clicked.connect(lambda: self._load_departments(force=True)) + self.department_retry_button.hide() self.unserved_sort_combo = self._fixed_combo( ( ("未服务天数默认排序", ""), @@ -1230,31 +1333,31 @@ class ConsultationsPage(QWidget): secondary_filters = QWidget(filters) secondary_filters.setObjectName("DiagnosisSecondaryFilters") - secondary_filters.setMinimumHeight(46) - self.secondary_filters = secondary_filters + secondary_filters.setMinimumHeight(46) + self.secondary_filters = secondary_filters secondary_layout = QHBoxLayout(secondary_filters) secondary_layout.setContentsMargins(0, 0, 0, 0) secondary_layout.setSpacing(8) self.diagnosis_confirmed_combo.setFixedWidth(126) self.department_combo.setFixedWidth(178) - self.secondary_filter_flow = FlowWidget(horizontal_spacing=40, vertical_spacing=8) - self.secondary_filter_flow.flow.addWidget( - self._filter_field("确认诊单:", self.diagnosis_confirmed_combo) - ) - department_field = self._filter_field("部门:", self.department_combo) - department_field.layout().addWidget(self.department_retry_button) - self.secondary_filter_flow.flow.addWidget(department_field) + self.secondary_filter_flow = FlowWidget(horizontal_spacing=40, vertical_spacing=8) + self.secondary_filter_flow.flow.addWidget( + self._filter_field("确认诊单:", self.diagnosis_confirmed_combo) + ) + department_field = self._filter_field("部门:", self.department_combo) + department_field.layout().addWidget(self.department_retry_button) + self.secondary_filter_flow.flow.addWidget(department_field) self.keyword_edit = QLineEdit(secondary_filters) self.keyword_edit.setObjectName("DiagnosisKeyword") self.keyword_edit.setPlaceholderText("搜索患者姓名、手机号、病历号") - self.keyword_edit.setClearButtonEnabled(True) - self.keyword_edit.addAction(icons.icon("search", "muted", 16), QLineEdit.ActionPosition.LeadingPosition) + self.keyword_edit.setClearButtonEnabled(True) + self.keyword_edit.addAction(icons.icon("search", "muted", 16), QLineEdit.ActionPosition.LeadingPosition) self.keyword_edit.setMinimumWidth(185) self.keyword_edit.setMaximumWidth(340) self.keyword_edit.returnPressed.connect(self._search) - self.keyword_edit.setFixedWidth(340) - self.secondary_filter_flow.flow.addWidget(self.keyword_edit) - secondary_layout.addWidget(self.secondary_filter_flow, 1) + self.keyword_edit.setFixedWidth(340) + self.secondary_filter_flow.flow.addWidget(self.keyword_edit) + secondary_layout.addWidget(self.secondary_filter_flow, 1) self.more_filter_button = QToolButton(secondary_filters) self.more_filter_button.setObjectName("DiagnosisMoreFilter") self.more_filter_button.setText("更多筛选") @@ -1349,10 +1452,10 @@ class ConsultationsPage(QWidget): advanced_layout.addWidget(self.advanced_filter_flow) self.advanced_filters.hide() filter_layout.addWidget(self.advanced_filters) - filters.setFixedHeight(_FILTERS_BASE_HEIGHT) - page_layout.addWidget(filters) - self.filter_disclosure = FilterDisclosure(self, [filters]) - self.page_header.add_action(self.filter_disclosure.button) + filters.setFixedHeight(_FILTERS_BASE_HEIGHT) + page_layout.addWidget(filters) + self.filter_disclosure = FilterDisclosure(self, [filters]) + self.page_header.add_action(self.filter_disclosure.button) card = QFrame() card.setObjectName("DiagnosisListCard") @@ -1473,20 +1576,20 @@ class ConsultationsPage(QWidget): self.delete_button.setVisible(_canonical_allowed(permissions, "tcm.diagnosis/delete")) self.delete_button.clicked.connect(self._delete_selected) self.refresh_button = _tool_icon(QPushButton("刷新", toolbar), "refresh") - self.refresh_button.clicked.connect(lambda: self.refresh()) - toolbar_layout.addWidget(self.refresh_button) - self.toolbar_flow = FlowWidget(horizontal_spacing=8, vertical_spacing=8) - for index in reversed(range(toolbar_layout.count())): - if toolbar_layout.itemAt(index).spacerItem() is not None: - toolbar_layout.takeAt(index) - for button in ( - self.add_button, self.video_qr_toolbar_button, self.call_toolbar_button, - self.complete_toolbar_button, self.prescription_toolbar_button, - self.case_toolbar_button, self.cancel_toolbar_button, - ): - toolbar_layout.removeWidget(button) - self.toolbar_flow.flow.addWidget(button) - toolbar_layout.insertWidget(0, self.toolbar_flow, 1) + self.refresh_button.clicked.connect(lambda: self.refresh()) + toolbar_layout.addWidget(self.refresh_button) + self.toolbar_flow = FlowWidget(horizontal_spacing=8, vertical_spacing=8) + for index in reversed(range(toolbar_layout.count())): + if toolbar_layout.itemAt(index).spacerItem() is not None: + toolbar_layout.takeAt(index) + for button in ( + self.add_button, self.video_qr_toolbar_button, self.call_toolbar_button, + self.complete_toolbar_button, self.prescription_toolbar_button, + self.case_toolbar_button, self.cancel_toolbar_button, + ): + toolbar_layout.removeWidget(button) + self.toolbar_flow.flow.addWidget(button) + toolbar_layout.insertWidget(0, self.toolbar_flow, 1) table_wrap = QWidget() table_wrap.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) @@ -1495,7 +1598,7 @@ class ConsultationsPage(QWidget): table_wrap_layout.setSpacing(0) self.table_host = DiagnosisTableHost( tech_blue=True, - video_entry_allowed=self._can_enter_list_call, + video_entry_allowed=self._can_enter_list_call, action_policy={ "view": _canonical_allowed(permissions, "tcm.diagnosis/readonlyDetail"), "edit": _canonical_allowed(permissions, "tcm.diagnosis/edit"), @@ -1542,8 +1645,8 @@ class ConsultationsPage(QWidget): table_wrap_layout.addWidget(self.table_host, 1) self.loading_overlay = DiagnosisLoadingOverlay(self.table_host) card_layout.addWidget(table_wrap, 1) - self.pager = InfiniteList(self._page_size) - self.pager.bind(self.table) + self.pager = InfiniteList(self._page_size) + self.pager.bind(self.table) card_layout.addWidget(self.pager) page_layout.addWidget(card, 1) @@ -1593,9 +1696,9 @@ class ConsultationsPage(QWidget): layout = QHBoxLayout(host) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(5) - label = self._filter_label(label_text) - label.setMinimumWidth(85 if label_text == "确认诊单:" else 46) - layout.addWidget(label) + label = self._filter_label(label_text) + label.setMinimumWidth(85 if label_text == "确认诊单:" else 46) + layout.addWidget(label) layout.addWidget(control) return host @@ -1706,55 +1809,55 @@ class ConsultationsPage(QWidget): if hasattr(self, "table_host"): self.table_host.set_sort_direction(direction) - def _toggle_advanced_filters(self, checked: bool) -> None: - self.advanced_filters.setVisible(checked) + def _toggle_advanced_filters(self, checked: bool) -> None: + self.advanced_filters.setVisible(checked) self.more_filter_button.setText("收起" if checked else "更多筛选") self.more_filter_button.setIcon( icons.icon("up" if checked else "down", "muted", 14) ) - self.main_chip_flow.updateGeometry() - self.quick_filter_flow.updateGeometry() - self._apply_responsive_layout() - - def resizeEvent(self, event: Any) -> None: - super().resizeEvent(event) - if hasattr(self, "pager"): - self._apply_responsive_layout() - - def _apply_responsive_layout(self) -> None: - """Retain reference geometry while letting dense filters wrap on small windows.""" - compact = self.height() < 800 - narrow = self.width() < 1050 - layout = self.page_scroll.widget().layout() - layout.setContentsMargins(20 if narrow else 27, 16 if compact else 24, - 20 if narrow else 26, 8) - self.diagnosis_confirmed_combo.setFixedWidth(100 if narrow else 154) - self.department_combo.setFixedWidth(135 if narrow else 201) - self.keyword_edit.setFixedWidth(225 if narrow else 354) - self.secondary_filter_flow.flow._horizontal_spacing = 16 if narrow else 40 - self.status_card.setFixedHeight(48 if compact else _STATUS_CARD_HEIGHT) - self.date_filters.setMinimumHeight(40 if compact else 48) - self.filters_card.layout().setSpacing(5 if compact else 8) - self.filters_card.layout().setContentsMargins(18, 6 if compact else 8, - 18, 8 if compact else 12) - # Reserve the page scrollbar even before Qt has resolved its visibility. - # Otherwise the last field can wrap only after the height was measured. - usable = max(320, self.width() - (40 if narrow else 53) - 45) - date_height = max(40 if compact else 48, - self.main_chip_flow.flow.heightForWidth(usable - 298)) - secondary_height = max(46, self.secondary_filter_flow.flow.heightForWidth(usable - 105)) - self.date_filters.setFixedHeight(date_height) - self.secondary_filters.setFixedHeight(secondary_height) - filter_height = (44 + (5 if compact else 8) - + (48 if compact else 54) + date_height + secondary_height - + (24 if compact else 36)) - if not self.advanced_filters.isHidden(): - advanced_height = (self.quick_filter_flow.flow.heightForWidth(usable) - + self.advanced_filter_flow.flow.heightForWidth(usable) + 25) - filter_height += advanced_height - self.filters_card.setFixedHeight(filter_height) - action_width = max(200, usable - self.refresh_button.sizeHint().width() - 8) - self.list_toolbar.setFixedHeight(self.toolbar_flow.flow.heightForWidth(action_width) + 24) + self.main_chip_flow.updateGeometry() + self.quick_filter_flow.updateGeometry() + self._apply_responsive_layout() + + def resizeEvent(self, event: Any) -> None: + super().resizeEvent(event) + if hasattr(self, "pager"): + self._apply_responsive_layout() + + def _apply_responsive_layout(self) -> None: + """Retain reference geometry while letting dense filters wrap on small windows.""" + compact = self.height() < 800 + narrow = self.width() < 1050 + layout = self.page_scroll.widget().layout() + layout.setContentsMargins(20 if narrow else 27, 16 if compact else 24, + 20 if narrow else 26, 8) + self.diagnosis_confirmed_combo.setFixedWidth(100 if narrow else 154) + self.department_combo.setFixedWidth(135 if narrow else 201) + self.keyword_edit.setFixedWidth(225 if narrow else 354) + self.secondary_filter_flow.flow._horizontal_spacing = 16 if narrow else 40 + self.status_card.setFixedHeight(48 if compact else _STATUS_CARD_HEIGHT) + self.date_filters.setMinimumHeight(40 if compact else 48) + self.filters_card.layout().setSpacing(5 if compact else 8) + self.filters_card.layout().setContentsMargins(18, 6 if compact else 8, + 18, 8 if compact else 12) + # Reserve the page scrollbar even before Qt has resolved its visibility. + # Otherwise the last field can wrap only after the height was measured. + usable = max(320, self.width() - (40 if narrow else 53) - 45) + date_height = max(40 if compact else 48, + self.main_chip_flow.flow.heightForWidth(usable - 298)) + secondary_height = max(46, self.secondary_filter_flow.flow.heightForWidth(usable - 105)) + self.date_filters.setFixedHeight(date_height) + self.secondary_filters.setFixedHeight(secondary_height) + filter_height = (44 + (5 if compact else 8) + + (48 if compact else 54) + date_height + secondary_height + + (24 if compact else 36)) + if not self.advanced_filters.isHidden(): + advanced_height = (self.quick_filter_flow.flow.heightForWidth(usable) + + self.advanced_filter_flow.flow.heightForWidth(usable) + 25) + filter_height += advanced_height + self.filters_card.setFixedHeight(filter_height) + action_width = max(200, usable - self.refresh_button.sizeHint().width() - 8) + self.list_toolbar.setFixedHeight(self.toolbar_flow.flow.heightForWidth(action_width) + 24) def _server_sort_changed(self, _index: int) -> None: if not hasattr(self, "table_host"): @@ -1848,23 +1951,23 @@ class ConsultationsPage(QWidget): f"待分配医助 {assign_count}" if assign_count is not None else "待分配医助" ) self.pending_assign_filters.setVisible(bool(self._pending_assign)) - for flow in (self.main_chip_flow, self.quick_filter_flow): - flow.updateGeometry() - if hasattr(self, "pager") and self.isVisible(): - self._apply_responsive_layout() + for flow in (self.main_chip_flow, self.quick_filter_flow): + flow.updateGeometry() + if hasattr(self, "pager") and self.isVisible(): + self._apply_responsive_layout() def _clear_latest_appointment_filters(self) -> None: self.latest_appointment_start_date.setDate(_OPTIONAL_DATE_MINIMUM) self.latest_appointment_end_date.setDate(_OPTIONAL_DATE_MINIMUM) self.channel_combo.setCurrentIndex(0) - def search_patient(self, query: str) -> None: - """Search authorized diagnoses independently of the current queue filters.""" - self.pager.invalidate() - self._reset(keyword=query.strip()) - - def _reset(self, *, keyword: str = "") -> None: - self.keyword_edit.setText(keyword) + def search_patient(self, query: str) -> None: + """Search authorized diagnoses independently of the current queue filters.""" + self.pager.invalidate() + self._reset(keyword=query.strip()) + + def _reset(self, *, keyword: str = "") -> None: + self.keyword_edit.setText(keyword) self.patient_name_edit.clear() self.doctor_edit.clear() for combo in ( @@ -1877,10 +1980,10 @@ class ConsultationsPage(QWidget): self.channel_combo, self.unserved_sort_combo, ): - blocked = combo.blockSignals(True) + blocked = combo.blockSignals(True) combo.setCurrentIndex(0) - combo.blockSignals(blocked) - self.table_host.set_sort_direction("") + combo.blockSignals(blocked) + self.table_host.set_sort_direction("") for editor in ( self.latest_appointment_start_date, self.latest_appointment_end_date, @@ -1905,16 +2008,16 @@ class ConsultationsPage(QWidget): self._page = 1 self.refresh() - def _validate_ranges(self) -> bool: - if ( - self.department_combo.isEnabled() - and self.department_combo.currentText().strip() - and self.department_combo.currentText() != self.department_combo.itemText( - self.department_combo.currentIndex() - ) - ): - self.banner.show_message("请从部门搜索结果中选择部门,或清空部门筛选。", "warning") - return False + def _validate_ranges(self) -> bool: + if ( + self.department_combo.isEnabled() + and self.department_combo.currentText().strip() + and self.department_combo.currentText() != self.department_combo.itemText( + self.department_combo.currentIndex() + ) + ): + self.banner.show_message("请从部门搜索结果中选择部门,或清空部门筛选。", "warning") + return False pairs = ( ( self._date_value(self.latest_appointment_start_date), @@ -1968,11 +2071,11 @@ class ConsultationsPage(QWidget): "keyword": self.keyword_edit.text().strip(), "patient_name": self.patient_name_edit.text().strip(), "doctor_name": self.doctor_edit.text().strip(), - "assistant_dept_id": ( - self.department_combo.currentData() or "" - if self.department_combo.currentText().strip() - else "" - ), + "assistant_dept_id": ( + self.department_combo.currentData() or "" + if self.department_combo.currentText().strip() + else "" + ), "has_appointment": self._combo_value(self.has_appointment_combo), "diagnosis_confirmed": self._combo_value(self.diagnosis_confirmed_combo), "diagnosis_type": self._combo_value(self.diagnosis_type_combo), @@ -2007,13 +2110,13 @@ class ConsultationsPage(QWidget): self.patient_name_edit.text().strip() or self.keyword_edit.text().strip() ) if pending_keyword or keyword: - pending_filters = { + pending_filters = { "pending_assign": "1", "pending_assign_keyword": pending_keyword or keyword, } - if filters["doctor_name"]: - pending_filters["doctor_name"] = filters["doctor_name"] - return pending_filters + if filters["doctor_name"]: + pending_filters["doctor_name"] = filters["doctor_name"] + return pending_filters filters["pending_assign_order_month"] = self._pending_assign_month_value() filters["pending_assign_keyword"] = "" return filters @@ -2031,7 +2134,7 @@ class ConsultationsPage(QWidget): self._loading = True self.refresh_button.setEnabled(False) filters = MappingProxyType(self._filters()) - page_size = self._page_size + page_size = self._page_size if not silent: self._visible_loading_generation = generation self.table_host.begin_loading() @@ -2039,19 +2142,19 @@ class ConsultationsPage(QWidget): self._refresh_counts() elif self.loading_overlay.isVisible(): self._visible_loading_generation = generation - self.pager.reload( - lambda page: invoke( + self.pager.reload( + lambda page: invoke( self.repository, "consultations", **filters, page=page, - page_size=page_size, - ), - apply=lambda result: self._apply_result(result, generation), - on_error=lambda error: self._load_error(error, generation), - runner=run_async, - query_key=filters, - on_finished=lambda: self._load_finished(generation), + page_size=page_size, + ), + apply=lambda result: self._apply_result(result, generation), + on_error=lambda error: self._load_error(error, generation), + runner=run_async, + query_key=filters, + on_finished=lambda: self._load_finished(generation), ) def _apply_result(self, result: Any, generation: int) -> None: @@ -2059,12 +2162,12 @@ class ConsultationsPage(QWidget): return rows = page_items(result) total = page_total(result, len(rows)) - self._page = self.pager.page + self._page = self.pager.page self.table_host.force_open_prescription = bool(self._pending_assign) self.table_host.set_rows(rows) self.pager.update_state(self._page, total) self.summary_label.setText( - f"共 {total} 条 · 已加载 {len(rows)} 条" + f"共 {total} 条 · 已加载 {len(rows)} 条" ) self.banner.clear() self._selection_changed() @@ -2127,16 +2230,16 @@ class ConsultationsPage(QWidget): requests.append(("pending_booking", MappingProxyType(pending))) if _canonical_allowed(self.permissions, "tcm.diagnosis/assign"): pending_keyword = self.pending_assign_keyword.text().strip() - shared_keyword = ( - self.patient_name_edit.text().strip() or self.keyword_edit.text().strip() - ) + shared_keyword = ( + self.patient_name_edit.text().strip() or self.keyword_edit.text().strip() + ) if self._pending_assign and (pending_keyword or shared_keyword): assign = { "pending_assign": "1", "pending_assign_keyword": pending_keyword or shared_keyword, } - if shared["doctor_name"]: - assign["doctor_name"] = shared["doctor_name"] + if shared["doctor_name"]: + assign["doctor_name"] = shared["doctor_name"] else: assign = dict(shared) assign.update( @@ -2191,66 +2294,66 @@ class ConsultationsPage(QWidget): } self._update_quick_buttons() - def _load_departments(self, *, force: bool = False) -> None: - if not force and (self._departments_loaded or self._departments_loading): - return - self._departments_generation += 1 - generation = self._departments_generation - self._departments_loading = True - self.department_combo.setEnabled(False) - self.department_combo.setToolTip("正在加载可选部门…") - self.department_retry_button.hide() - - def load() -> list[tuple[int, str]]: - # Call directly: invoke() can discard unsupported kwargs, which would - # silently remove the permission scope on an older repository. - return _department_options(self.repository.list_departments(apply_data_scope=True)) - - run_async( - load, - on_success=lambda options: self._apply_departments(options, generation), - on_error=lambda error: self._departments_error(error, generation), - ) - - def _apply_departments(self, options: list[tuple[int, str]], generation: int) -> None: - if generation != self._departments_generation: - return - current = self.department_combo.currentData() - blocked = self.department_combo.blockSignals(True) - self.department_combo.clear() - self.department_combo.addItem("全部部门" if options else "暂无可选部门", "") - for department_id, label in options: - self.department_combo.addItem(label, department_id) - self.department_combo.setCurrentIndex(max(0, self.department_combo.findData(current))) - self.department_combo.blockSignals(blocked) - self._departments_loaded = True - self._departments_loading = False - self.department_combo.setEnabled(bool(options)) - self.department_combo.setToolTip( - "输入部门名称搜索;选择父级包含下级部门" if options else "当前账号暂无可选部门" - ) - self.department_retry_button.setVisible(not options) - - def _departments_error(self, error: Exception, generation: int) -> None: - if generation != self._departments_generation: - return - self._departments_loading = False - self._departments_loaded = False - self.department_combo.clear() - permission_denied = isinstance(error, ApiBusinessError) and any( - text in str(error) for text in ("权限不足", "无权限", "无权") - ) - self.department_combo.addItem("暂无部门筛选权限" if permission_denied else "部门加载失败", "") - self.department_combo.setEnabled(False) - message = ( - "当前账号无权读取部门,请联系管理员检查部门筛选权限,处理后点击重试。" - if permission_denied else f"部门加载失败:{friendly_error(error)}。点击重试。" - ) - self.department_combo.setToolTip(message) - self.department_retry_button.setToolTip(message) - self.department_retry_button.show() - - def _load_filter_options(self) -> None: + def _load_departments(self, *, force: bool = False) -> None: + if not force and (self._departments_loaded or self._departments_loading): + return + self._departments_generation += 1 + generation = self._departments_generation + self._departments_loading = True + self.department_combo.setEnabled(False) + self.department_combo.setToolTip("正在加载可选部门…") + self.department_retry_button.hide() + + def load() -> list[tuple[int, str]]: + # Call directly: invoke() can discard unsupported kwargs, which would + # silently remove the permission scope on an older repository. + return _department_options(self.repository.list_departments(apply_data_scope=True)) + + run_async( + load, + on_success=lambda options: self._apply_departments(options, generation), + on_error=lambda error: self._departments_error(error, generation), + ) + + def _apply_departments(self, options: list[tuple[int, str]], generation: int) -> None: + if generation != self._departments_generation: + return + current = self.department_combo.currentData() + blocked = self.department_combo.blockSignals(True) + self.department_combo.clear() + self.department_combo.addItem("全部部门" if options else "暂无可选部门", "") + for department_id, label in options: + self.department_combo.addItem(label, department_id) + self.department_combo.setCurrentIndex(max(0, self.department_combo.findData(current))) + self.department_combo.blockSignals(blocked) + self._departments_loaded = True + self._departments_loading = False + self.department_combo.setEnabled(bool(options)) + self.department_combo.setToolTip( + "输入部门名称搜索;选择父级包含下级部门" if options else "当前账号暂无可选部门" + ) + self.department_retry_button.setVisible(not options) + + def _departments_error(self, error: Exception, generation: int) -> None: + if generation != self._departments_generation: + return + self._departments_loading = False + self._departments_loaded = False + self.department_combo.clear() + permission_denied = isinstance(error, ApiBusinessError) and any( + text in str(error) for text in ("权限不足", "无权限", "无权") + ) + self.department_combo.addItem("暂无部门筛选权限" if permission_denied else "部门加载失败", "") + self.department_combo.setEnabled(False) + message = ( + "当前账号无权读取部门,请联系管理员检查部门筛选权限,处理后点击重试。" + if permission_denied else f"部门加载失败:{friendly_error(error)}。点击重试。" + ) + self.department_combo.setToolTip(message) + self.department_retry_button.setToolTip(message) + self.department_retry_button.show() + + def _load_filter_options(self) -> None: if self._options_loaded: return self._options_loaded = True @@ -2328,12 +2431,12 @@ class ConsultationsPage(QWidget): combo.setEditText(str(current)) self._assistant_names = { _as_int(first_value(row, "id", "value")): display_text( - first_value(row, "name", "label"), "" + first_value(row, "name", "label"), "" ) for row in options.get("assistants", []) if _as_int(first_value(row, "id", "value")) > 0 } - self.table_host.set_assistant_names(self._assistant_names) + self.table_host.set_assistant_names(self._assistant_names) def _checked_changed(self, count: int) -> None: self.selected_label.setText(f"已选 {count} 条") @@ -2365,7 +2468,7 @@ class ConsultationsPage(QWidget): "view": self._open_readonly, "edit": self._open_edit, "prescription": self._open_prescription, - "void_prescription": self._void_selected_prescription, + "void_prescription": self._void_selected_prescription, "ai_consult": self._open_ai_consult, "appointment": self._book_selected_appointment, "fill_id_card": self._fill_selected_id_card, @@ -2428,7 +2531,7 @@ class ConsultationsPage(QWidget): } options = {key: value for key, value in options.items() if value} self._assistant_names.update(options) - self.table_host.set_assistant_names(self._assistant_names) + self.table_host.set_assistant_names(self._assistant_names) self._show_assistant_picker(records, options) def _show_assistant_picker( @@ -2677,11 +2780,11 @@ class ConsultationsPage(QWidget): or "" ).strip() - def _request_video_qr(self) -> None: - record = self.table.current_data() - if record is not None and not can_appointment_video(appointment_type_value(record)): - show_toast(self, "本次挂号不支持视频问诊二维码。", "warning") - return + def _request_video_qr(self) -> None: + record = self.table.current_data() + if record is not None and not can_appointment_video(appointment_type_value(record)): + show_toast(self, "本次挂号不支持视频问诊二维码。", "warning") + return self._request_qr( capability="video_qr", permission="tcm.diagnosis/videoQr", @@ -2750,7 +2853,7 @@ class ConsultationsPage(QWidget): if not qrcode_url: show_toast(self, "服务器未返回可用的二维码地址。", "danger", 4200) return - dialog = _QrResultDialog(title, record, qrcode_url, self) + dialog = _QrResultDialog(title, record, qrcode_url, self, repository=self.repository) self._qr_result_dialog = dialog dialog.finished.connect(lambda _code: setattr(self, "_qr_result_dialog", None)) dialog.open() @@ -3073,17 +3176,17 @@ class ConsultationsPage(QWidget): _as_int(payload.get(key), 0) > 0 for key in ("appointment_id", "patient_id", "diagnosis_id") ) - entry_allowed = has_record and self._can_enter_list_call(record) - self.video_button.setVisible(entry_allowed) - self.call_toolbar_button.setVisible(entry_allowed) + entry_allowed = has_record and self._can_enter_list_call(record) + self.video_button.setVisible(entry_allowed) + self.call_toolbar_button.setVisible(entry_allowed) self.video_button.setEnabled( - entry_allowed + entry_allowed and is_video_available(record) - and (appointment_type_value(record) == "text" or video_call_is_live(record)) + and (appointment_type_value(record) == "text" or video_call_is_live(record)) and valid_ids ) self.call_toolbar_button.setEnabled(self.video_button.isEnabled()) - self.video_qr_toolbar_button.setEnabled(has_record and can_appointment_video(appointment_type_value(record))) + self.video_qr_toolbar_button.setEnabled(has_record and can_appointment_video(appointment_type_value(record))) self.complete_toolbar_button.setEnabled(has_record) self.case_toolbar_button.setEnabled(has_record) self.prescription_toolbar_button.setEnabled(has_record and not self._prescription_busy) @@ -3227,7 +3330,7 @@ class ConsultationsPage(QWidget): return deepcopy(detail) def _open_prescription(self) -> None: - if self._mutation_pending or self._prescription_busy or not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"): + if self._mutation_pending or self._prescription_busy or not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"): return record = self.table.current_data() if _as_int(first_value(record, "diagnosis_id", "id", default=0)) <= 0: @@ -3239,7 +3342,7 @@ class ConsultationsPage(QWidget): self._begin_prescription_load(record, mode=mode) def _void_selected_prescription(self) -> None: - if self._mutation_pending or self._prescription_busy or not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"): + if self._mutation_pending or self._prescription_busy or not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"): return record = self.table.current_data() if record is None or not can_void_prescription(record): @@ -3270,30 +3373,30 @@ class ConsultationsPage(QWidget): self._last_prescription = existing if existing is not None: approved = _as_int(first_value(existing, "audit_status", "status"), -1) == 1 - voided = prescription_is_voided(existing) + voided = prescription_is_voided(existing) actual_id = _as_int(first_value(existing, "id", "prescription_id", default=0)) expected_id = _as_int( first_value(record, "current_prescription_id", default=0) ) - if not prescription_matches_appointment( - existing, appointment_id=_appointment_id(record), - diagnosis_id=_as_int(first_value(record, "diagnosis_id", "id")), previous_id=expected_id, - ): - self.banner.show_message("返回的处方与当前挂号不一致,已停止操作。", "warning") - return - if mode == "view" and (not approved or voided): + if not prescription_matches_appointment( + existing, appointment_id=_appointment_id(record), + diagnosis_id=_as_int(first_value(record, "diagnosis_id", "id")), previous_id=expected_id, + ): + self.banner.show_message("返回的处方与当前挂号不一致,已停止操作。", "warning") + return + if mode == "view" and (not approved or voided): self.banner.show_message( "当前挂号的处方状态已变化,请刷新列表后重试。", "warning", ) return - current_changed = expected_id > 0 and actual_id != expected_id - if mode == "void": - self._confirm_void(existing, current_changed=current_changed) - return - if voided and can_reissue_prescription(existing, self.current_user, self.permissions): - self._open_new_prescription(reissue_prescription_seed(existing)) - elif not approved and not prescription_edit_is_locked(existing): + current_changed = expected_id > 0 and actual_id != expected_id + if mode == "void": + self._confirm_void(existing, current_changed=current_changed) + return + if voided and can_reissue_prescription(existing, self.current_user, self.permissions): + self._open_new_prescription(reissue_prescription_seed(existing)) + elif not approved and not prescription_edit_is_locked(existing): self._open_existing_prescription_editor(existing) else: detail = PrescriptionDetailDialog( @@ -3301,16 +3404,16 @@ class ConsultationsPage(QWidget): can_open_diagnosis=_canonical_allowed( self.permissions, "tcm.diagnosis/readonlyDetail" ), - allow_void=True, + allow_void=True, parent=self, ) detail.diagnosis_requested.connect(self._open_diagnosis_id) - if detail.exec() == PRESCRIPTION_VOIDED_RESULT: - self._after_prescription_void() - if current_changed and not self._mutation_pending: - self.refresh(silent=True) + if detail.exec() == PRESCRIPTION_VOIDED_RESULT: + self._after_prescription_void() + if current_changed and not self._mutation_pending: + self.refresh(silent=True) return - if mode in {"view", "void", "reissue"}: + if mode in {"view", "void", "reissue"}: self.banner.show_message( "当前挂号没有可查看的处方,请刷新列表后重试。", "warning", @@ -3323,29 +3426,29 @@ class ConsultationsPage(QWidget): if prescription_id <= 0: self.banner.show_message("处方编号不完整,无法编辑。", "danger") return - - def save_changes(payload: Any) -> Any: - return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload) - + + def save_changes(payload: Any) -> Any: + return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload) + dialog = PrescriptionEditorDialog( self.repository, prescription, mode="edit", current_user=self.current_user, - save_draft=save_changes, - allow_void=True, + save_draft=save_changes, + allow_void=True, parent=self, ) diagnosis_signal = getattr(dialog, "diagnosis_requested", None) if diagnosis_signal is not None: diagnosis_signal.connect(self._open_diagnosis_id) - result = dialog.exec() - if result == PRESCRIPTION_VOIDED_RESULT: - self._after_prescription_void() + result = dialog.exec() + if result == PRESCRIPTION_VOIDED_RESULT: + self._after_prescription_void() return - if result != QDialog.DialogCode.Accepted: - return - self._finish_prescription_edit(dialog, save_changes, "处方已保存并重新进入待审核。") + if result != QDialog.DialogCode.Accepted: + return + self._finish_prescription_edit(dialog, save_changes, "处方已保存并重新进入待审核。") def _begin_case_record_load(self, record: Any) -> None: record_snapshot = deepcopy(record) @@ -3430,20 +3533,20 @@ class ConsultationsPage(QWidget): } def _open_prescription_editor(self, record: Any, case_record: Any) -> None: - self._open_new_prescription(self._prescription_seed(record, case_record)) - - def _open_new_prescription(self, seed: dict[str, Any]) -> None: - linked_fields = {key: seed[key] for key in ("diagnosis_id", "appointment_id", "case_record") if key in seed} - - def save_new(payload: dict[str, Any]) -> Any: - return invoke(self.repository, "create_prescription", prescription=MappingProxyType(dict(payload) | linked_fields)) - + self._open_new_prescription(self._prescription_seed(record, case_record)) + + def _open_new_prescription(self, seed: dict[str, Any]) -> None: + linked_fields = {key: seed[key] for key in ("diagnosis_id", "appointment_id", "case_record") if key in seed} + + def save_new(payload: dict[str, Any]) -> Any: + return invoke(self.repository, "create_prescription", prescription=MappingProxyType(dict(payload) | linked_fields)) + dialog = PrescriptionEditorDialog( self.repository, seed, mode="add", current_user=self.current_user, - save_draft=save_new, + save_draft=save_new, parent=self, ) diagnosis_signal = getattr(dialog, "diagnosis_requested", None) @@ -3451,27 +3554,27 @@ class ConsultationsPage(QWidget): diagnosis_signal.connect(self._open_diagnosis_id) if dialog.exec() != QDialog.DialogCode.Accepted: return - self._finish_prescription_edit(dialog, save_new, "处方已开具并提交审核。") - - def _finish_prescription_edit(self, dialog: PrescriptionEditorDialog, save: Any, message: str) -> None: - saved = getattr(dialog, "saved_draft", None) - if saved is not None: - self._prescription_saved(saved, message) - return - payload = MappingProxyType(dialog.payload()) - self._run_mutation(lambda: save(payload), message, on_saved=self._prescription_saved) - - def _prescription_saved(self, prescription: Any, fallback: str) -> None: - message, kind = saved_prescription_message(prescription, fallback) - show_toast(self, message, kind) - resume_saved_prescription(self.repository, prescription, self) - self.refresh(silent=True) - - def _after_prescription_void(self) -> None: - show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success") - self.refresh(silent=True) + self._finish_prescription_edit(dialog, save_new, "处方已开具并提交审核。") - def _confirm_void(self, prescription: Any, *, current_changed: bool = False) -> None: + def _finish_prescription_edit(self, dialog: PrescriptionEditorDialog, save: Any, message: str) -> None: + saved = getattr(dialog, "saved_draft", None) + if saved is not None: + self._prescription_saved(saved, message) + return + payload = MappingProxyType(dialog.payload()) + self._run_mutation(lambda: save(payload), message, on_saved=self._prescription_saved) + + def _prescription_saved(self, prescription: Any, fallback: str) -> None: + message, kind = saved_prescription_message(prescription, fallback) + show_toast(self, message, kind) + resume_saved_prescription(self.repository, prescription, self) + self.refresh(silent=True) + + def _after_prescription_void(self) -> None: + show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success") + self.refresh(silent=True) + + def _confirm_void(self, prescription: Any, *, current_changed: bool = False) -> None: if prescription is None: self.banner.show_message("当前诊单没有可作废的处方。", "warning") return @@ -3485,10 +3588,10 @@ class ConsultationsPage(QWidget): if prescription_id <= 0: self.banner.show_message("处方信息不完整,无法作废。", "warning") return - if not can_void_issued_prescription(prescription): - self.banner.show_message("当前处方不可作废,请核对操作权限和订单状态。", "warning") - return - if not confirm_prescription_void(self, prescription, current_changed=current_changed): + if not can_void_issued_prescription(prescription): + self.banner.show_message("当前处方不可作废,请核对操作权限和订单状态。", "warning") + return + if not confirm_prescription_void(self, prescription, current_changed=current_changed): return self._run_mutation( lambda: invoke( @@ -3497,26 +3600,26 @@ class ConsultationsPage(QWidget): prescription_id=prescription_id, id=prescription_id, ), - "处方已作废。需要再次开具时,请选择「重新开方」。", + "处方已作废。需要再次开具时,请选择「重新开方」。", ) - def _run_mutation(self, operation: Any, success_message: str, *, on_saved: Any = None) -> None: + def _run_mutation(self, operation: Any, success_message: str, *, on_saved: Any = None) -> None: self._mutation_generation += 1 generation = self._mutation_generation self._mutation_pending = True self.table_host.setEnabled(False) self._checked_changed(len(self.table_host.selected_records())) self._selection_changed() - def succeeded(result: Any) -> None: - if on_saved is None: - self._mutation_success(success_message, generation) - elif generation == self._mutation_generation: - self.table_host.clear_checks() - on_saved(result, success_message) - + def succeeded(result: Any) -> None: + if on_saved is None: + self._mutation_success(success_message, generation) + elif generation == self._mutation_generation: + self.table_host.clear_checks() + on_saved(result, success_message) + run_async( operation, - on_success=succeeded, + on_success=succeeded, on_error=lambda error: self._mutation_error(error, generation), on_finished=lambda: self._mutation_finished(generation), ) @@ -3539,28 +3642,28 @@ class ConsultationsPage(QWidget): self._checked_changed(len(self.table_host.selected_records())) self._selection_changed() - def _can_enter_list_call(self, record: Any) -> bool: - if not self._native_video_capable or record is None: - return False - # Text appointments retain their IM entry; this restriction concerns - # receiving an existing video call from the diagnosis list. - if appointment_type_value(record) == "text": - return True - if not can_appointment_video(appointment_type_value(record)): - return False - roles = UserProfile.from_dict({ - "role_ids": first_value(self.current_user, "role_ids", "role_id", "roles", default=[]) - }).role_ids - if 1 in roles: - return False - user_id = _as_int(first_value(self.current_user, "id", "user_id", default=0)) - assistant_id = _as_int(first_value(record, "assistant_id", "assistant", default=0)) - return bool( - user_id > 0 - and assistant_id == user_id - and _canonical_allowed(self.permissions, "tcm.diagnosis/watchCall") - ) - + def _can_enter_list_call(self, record: Any) -> bool: + if not self._native_video_capable or record is None: + return False + # Text appointments retain their IM entry; this restriction concerns + # receiving an existing video call from the diagnosis list. + if appointment_type_value(record) == "text": + return True + if not can_appointment_video(appointment_type_value(record)): + return False + roles = UserProfile.from_dict({ + "role_ids": first_value(self.current_user, "role_ids", "role_id", "roles", default=[]) + }).role_ids + if 1 in roles: + return False + user_id = _as_int(first_value(self.current_user, "id", "user_id", default=0)) + assistant_id = _as_int(first_value(record, "assistant_id", "assistant", default=0)) + return bool( + user_id > 0 + and assistant_id == user_id + and _canonical_allowed(self.permissions, "tcm.diagnosis/watchCall") + ) + def _request_video(self) -> None: record = self.table.current_data() if not self._native_video_capable: @@ -3568,11 +3671,11 @@ class ConsultationsPage(QWidget): return if record is None or not is_video_available(record): self.banner.show_message("仅当前“已预约”的挂号可进入视频问诊。", "warning") - return - if not self._can_enter_list_call(record): - self.banner.show_message("仅本诊单指派且具有旁观权限的医助可进入视频会话。", "warning") return - if appointment_type_value(record) != "text" and not video_call_is_live(record): + if not self._can_enter_list_call(record): + self.banner.show_message("仅本诊单指派且具有旁观权限的医助可进入视频会话。", "warning") + return + if appointment_type_value(record) != "text" and not video_call_is_live(record): self.banner.show_message("医生尚未发起视频会话,请等待会话开始。", "warning") return payload = _video_payload(record) @@ -3589,17 +3692,17 @@ class ConsultationsPage(QWidget): if ( not self.isVisible() - or self.pager.loading + or self.pager.loading or self._order_flow_generation is not None ): return self.refresh(silent=True) self._refresh_counts() - def showEvent(self, event: Any) -> None: - super().showEvent(event) - self._load_departments() - self._load_filter_options() + def showEvent(self, event: Any) -> None: + super().showEvent(event) + self._load_departments() + self._load_filter_options() if not self.poll_timer.isActive(): self.poll_timer.start() if self.table.rowCount() == 0 and not self._loading: diff --git a/app/src/doctor_workstation/ui/pages/patients.py b/app/src/doctor_workstation/ui/pages/patients.py index b5962e94e..35a68e2f1 100755 --- a/app/src/doctor_workstation/ui/pages/patients.py +++ b/app/src/doctor_workstation/ui/pages/patients.py @@ -1466,15 +1466,15 @@ class PatientListWorkspace(QWidget): target.addWidget(self.custom_date_button) self.filter_card.setFixedHeight(194 if narrow else 148) self._narrow_dates = narrow - # Keep readable data and complete actions; narrow windows scroll horizontally. - widths = (46, 154, 100, 172, 136, 72, 108, 122, 138, 194) + # 优化列宽配比(总计 1106px),确保 1440px 视窗下右侧「操作」及「更多」按钮不被裁切 + widths = (40, 140, 86, 156, 126, 62, 92, 104, 124, 176) for column, width in enumerate(widths): if column != 1: self.table.setColumnWidth(column, width) header = self.table.horizontalHeader() - header.setSectionResizeMode(1, QHeaderView.ResizeMode.Interactive if self.width() < 1230 else QHeaderView.ResizeMode.Stretch) - if self.width() < 1230: - self.table.setColumnWidth(1, 154) + header.setSectionResizeMode(1, QHeaderView.ResizeMode.Interactive if self.width() < 1180 else QHeaderView.ResizeMode.Stretch) + if self.width() < 1180: + self.table.setColumnWidth(1, 140) def _build_filters(self) -> QWidget: card = QFrame() diff --git a/app/src/doctor_workstation/ui/pages/prescriptions.py b/app/src/doctor_workstation/ui/pages/prescriptions.py index 5f878abf4..bc53917ce 100755 --- a/app/src/doctor_workstation/ui/pages/prescriptions.py +++ b/app/src/doctor_workstation/ui/pages/prescriptions.py @@ -1511,7 +1511,8 @@ class PrescriptionsPage(QWidget): self.table.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive) self.table.horizontalHeader().moveSection(2, 10) - for column, width in enumerate((42, 192, 144, 108, 94, 144, 108, 80, 137, 83, 128)): + # 紧凑配比列宽(总计 1124px),确保 1440px 与 1536px 桌面视窗下右侧「操作」列完整呈现无横向溢出 + for column, width in enumerate((40, 174, 134, 88, 76, 132, 92, 64, 122, 78, 124)): self.table.setColumnWidth(column, width) self.table.setColumnHidden(11, True) self.table.setColumnHidden(12, True) diff --git a/app/src/doctor_workstation/ui/pages/reception.py b/app/src/doctor_workstation/ui/pages/reception.py index a1d0ecc09..07f4b31d5 100755 --- a/app/src/doctor_workstation/ui/pages/reception.py +++ b/app/src/doctor_workstation/ui/pages/reception.py @@ -1177,13 +1177,47 @@ QWidget#ReceptionPage QPushButton#ReceptionHistoryButton, QWidget#ReceptionPage QPushButton#ReceptionImButton, QWidget#ReceptionPage QPushButton#ReceptionMoreButton, QWidget#ReceptionPage QPushButton#ReceptionCompleteButton { - min-height: 38px; - max-height: 38px; - padding: 0 12px; + min-height: 36px; + max-height: 36px; + padding: 0 13px; font-size: 13px; - border-radius: 5px; + font-weight: 500; + border-radius: 8px; +} +QWidget#ReceptionPage QPushButton#ReceptionNotifyButton:enabled, +QWidget#ReceptionPage QPushButton#ReceptionHistoryButton:enabled, +QWidget#ReceptionPage QPushButton#ReceptionMoreButton:enabled { + color: #16302E; + background-color: #FFFFFF; + border: 1px solid #C6D8D5; +} +QWidget#ReceptionPage QPushButton#ReceptionNotifyButton:enabled:hover, +QWidget#ReceptionPage QPushButton#ReceptionHistoryButton:enabled:hover, +QWidget#ReceptionPage QPushButton#ReceptionMoreButton:enabled:hover { + color: #0B6E68; + background-color: #EAF6F4; + border-color: #8FC8C0; +} +QWidget#ReceptionPage QPushButton#ReceptionNotifyButton:enabled:pressed, +QWidget#ReceptionPage QPushButton#ReceptionHistoryButton:enabled:pressed, +QWidget#ReceptionPage QPushButton#ReceptionMoreButton:enabled:pressed { + background-color: #D7EDE9; + border-color: #0B6E68; +} +QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled { + color: #C93B4E; + background-color: #FFF6F7; + border: 1px solid #F0BDC5; +} +QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled:hover { + color: #B42C3F; + background-color: #FDE8EB; + border-color: #DF8F9C; +} +QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled:pressed { + background-color: #FAD6DC; + border-color: #C93B4E; } -QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled { background-color: #FFFFFF; } QWidget#ReceptionPage QPushButton#ReceptionMoreButton { padding: 0 6px; } QWidget#ReceptionPage QTabBar#ReceptionDetailTabs { border-top-left-radius: 0; @@ -2419,15 +2453,21 @@ class _ReceptionCompleteButton(QPushButton): super().__init__("结束问诊", parent) self.setObjectName("ReceptionCompleteButton") self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setIcon(icons.icon("check_circle", "danger", 15)) + self.setIconSize(QSize(15, 15)) def changeEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API super().changeEvent(event) if event.type() == QEvent.Type.EnabledChange: + enabled = self.isEnabled() self.setCursor( Qt.CursorShape.PointingHandCursor - if self.isEnabled() + if enabled else Qt.CursorShape.ArrowCursor ) + self.setIcon( + icons.icon("check_circle", "danger" if enabled else "disabled", 15) + ) class _NoteAttachmentPreview(QPushButton): @@ -4448,7 +4488,7 @@ class ReceptionPage(QWidget): actions = QHBoxLayout() hero.actions_layout = actions actions.setContentsMargins(0, 0, 0, 0) - actions.setSpacing(14) + actions.setSpacing(10) actions.addStretch(1) action_group = QVBoxLayout() hero.action_group = action_group @@ -4468,14 +4508,20 @@ class ReceptionPage(QWidget): self.complete_button.setVisible(self._can_complete) self.notify_button = QPushButton("通知医助", hero) self.notify_button.setObjectName("ReceptionNotifyButton") + self.notify_button.setIcon(icons.icon("notification", "accent", 15)) + self.notify_button.setIconSize(QSize(15, 15)) self.notify_button.clicked.connect(self._notify_assistant) actions.addWidget(self.notify_button) self.history_button = QPushButton("查看历史", hero) self.history_button.setObjectName("ReceptionHistoryButton") + self.history_button.setIcon(icons.icon("followup", "muted", 15)) + self.history_button.setIconSize(QSize(15, 15)) self.history_button.clicked.connect(lambda: self.detail_tabs.setCurrentIndex(4)) actions.addWidget(self.history_button) self.video_button = QPushButton("IM 问诊", hero) self.video_button.setObjectName("ReceptionImButton") + self.video_button.setIcon(icons.icon("message", "inverse", 15)) + self.video_button.setIconSize(QSize(15, 15)) self.video_button.setToolTip("打开患者 IM,可发送消息并从会话中发起视频") self.video_button.setProperty("variant", "primary") self.video_button.clicked.connect(self._request_video) @@ -4486,7 +4532,7 @@ class ReceptionPage(QWidget): self.more_button.setToolTip("更多操作") self.more_button.setAccessibleName("更多操作") self.more_button.setObjectName("ReceptionMoreButton") - self.more_button.setFixedWidth(46) + self.more_button.setFixedWidth(40) hero.more_control = self.more_button more_menu = QMenu(self.more_button) edit_action = more_menu.addAction("编辑病历") @@ -4500,7 +4546,7 @@ class ReceptionPage(QWidget): consult_action.triggered.connect(self._open_ai_consult) self.more_button.setMenu(more_menu) actions.addWidget(self.more_button) - actions.addSpacing(16) + actions.addSpacing(8) hero.complete_gap = actions.itemAt(actions.count() - 1).spacerItem() actions.addWidget(self.complete_button) @@ -4572,11 +4618,33 @@ class ReceptionPage(QWidget): history_card.setObjectName("ReceptionHistoryCard") history_layout = QVBoxLayout(history_card) history_layout.setContentsMargins(0, 0, 0, 0) - history_layout.setSpacing(14) + history_layout.setSpacing(11) + history_head = QHBoxLayout() + history_head.setContentsMargins(0, 0, 0, 0) + history_head.setSpacing(8) history_title = QLabel("病情与用药", history_card) history_title.setObjectName("ReceptionCaseHeading") - history_layout.addWidget(history_title) + history_head.addWidget(history_title) + history_head.addStretch(1) + self.inline_edit_record_button = QPushButton("编辑四诊", history_card) + self.inline_edit_record_button.setObjectName("ReceptionInlineAction") + self.inline_edit_record_button.setIcon(icons.icon("edit", "accent", 14)) + self.inline_edit_record_button.setIconSize(QSize(14, 14)) + self.inline_edit_record_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.inline_edit_record_button.setVisible(self._can_edit) + self.inline_edit_record_button.clicked.connect(self._edit_diagnosis) + history_head.addWidget(self.inline_edit_record_button) + self.inline_ai_consult_button = QPushButton("AI 辨证", history_card) + self.inline_ai_consult_button.setObjectName("ReceptionInlineAiAction") + self.inline_ai_consult_button.setIcon(icons.icon("ai", "gold", 14)) + self.inline_ai_consult_button.setIconSize(QSize(14, 14)) + self.inline_ai_consult_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.inline_ai_consult_button.setVisible(self._can_ai_assistant) + self.inline_ai_consult_button.clicked.connect(self._open_ai_consult) + history_head.addWidget(self.inline_ai_consult_button) + history_layout.addLayout(history_head) self.case_labels: dict[str, QLabel] = {} + self._case_field_frames: dict[str, QFrame] = {} def add_case_field( target: QVBoxLayout, @@ -4587,10 +4655,17 @@ class ReceptionPage(QWidget): ) -> None: field = QFrame(history_card) field.setObjectName("ReceptionCaseField") + if key == "chief": + field.setProperty("chiefFocus", True) if stacked: field_layout = QVBoxLayout(field) - field_layout.setContentsMargins(0, 0, 0, 0) - field_layout.setSpacing(6) + field_layout.setContentsMargins( + 12 if key == "chief" else 0, + 9 if key == "chief" else 0, + 12 if key == "chief" else 0, + 9 if key == "chief" else 6, + ) + field_layout.setSpacing(5) title_label = QLabel(caption, field) title_label.setProperty("receptionBlockTitle", True) field_layout.addWidget(title_label) @@ -4599,7 +4674,7 @@ class ReceptionPage(QWidget): field_layout.addWidget(value_label) else: field_layout = QHBoxLayout(field) - field_layout.setContentsMargins(0, 0, 0, 0) + field_layout.setContentsMargins(0, 0, 0, 6) field_layout.setSpacing(10) title_label = QLabel(caption, field) title_label.setProperty("receptionInlineCaption", True) @@ -4611,6 +4686,7 @@ class ReceptionPage(QWidget): value_label.setProperty("receptionInlineValue", True) field_layout.addWidget(value_label, 1) self.case_labels[key] = value_label + self._case_field_frames[key] = field target.addWidget(field) add_case_field(history_layout, "chief", "本次主诉", stacked=True) @@ -4653,13 +4729,47 @@ class ReceptionPage(QWidget): history_layout.addWidget(lifestyle_field) add_case_field(history_layout, "diet", "饮食习惯") + + # W2 Bento 驾驶舱:将未填写的可选病史自动折叠为快捷补录胶囊,消除满屏空白「—」占位行 + self._missing_fields_host = QFrame(history_card) + self._missing_fields_host.setObjectName("ReceptionMissingFieldsBar") + missing_outer = QVBoxLayout(self._missing_fields_host) + missing_outer.setContentsMargins(0, 4, 0, 0) + missing_outer.setSpacing(6) + missing_caption = QLabel("待补录病史(点击快捷补录)", self._missing_fields_host) + missing_caption.setProperty("receptionInlineCaption", True) + missing_outer.addWidget(missing_caption) + missing_row = QHBoxLayout() + missing_row.setContentsMargins(0, 0, 0, 0) + missing_row.setSpacing(6) + self._missing_field_pills: dict[str, QPushButton] = {} + for key, label in ( + ("course", "+ 患病时长"), + ("past", "+ 既往史"), + ("family", "+ 家族史"), + ("allergy", "+ 过敏史"), + ("diet", "+ 饮食习惯"), + ): + pill = QPushButton(label, self._missing_fields_host) + pill.setProperty("receptionQuickFill", True) + pill.setCursor(Qt.CursorShape.PointingHandCursor) + pill.setEnabled(self._can_edit) + pill.setToolTip(f"打开四诊病历补录{label[2:]}") + pill.clicked.connect(self._edit_diagnosis) + self._missing_field_pills[key] = pill + missing_row.addWidget(pill) + missing_row.addStretch(1) + missing_outer.addLayout(missing_row) + self._missing_fields_host.hide() + history_layout.addWidget(self._missing_fields_host) + history_layout.addStretch(1) consultation_layout.addWidget(history_card, 1) right_clinical = QWidget(consultation_page) right_layout = QVBoxLayout(right_clinical) right_layout.setContentsMargins(0, 0, 0, 0) - right_layout.setSpacing(10) + right_layout.setSpacing(8) self.patient_summary_card, self.patient_summary_labels = self._field_card( "患者基本信息", @@ -4681,8 +4791,8 @@ class ReceptionPage(QWidget): vitals_card.setMinimumHeight(0) vitals_card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) vitals_layout = QVBoxLayout(vitals_card) - vitals_layout.setContentsMargins(14, 14, 14, 14) - vitals_layout.setSpacing(8) + vitals_layout.setContentsMargins(12, 10, 12, 10) + vitals_layout.setSpacing(6) vitals_title = QLabel("生命体征", vitals_card) vitals_title.setProperty("receptionBlockTitle", True) vitals_layout.addWidget(vitals_title) @@ -4746,8 +4856,8 @@ class ReceptionPage(QWidget): labs_card = QFrame(right_clinical) labs_card.setObjectName("ReceptionLabsCard") labs_layout = QVBoxLayout(labs_card) - labs_layout.setContentsMargins(14, 14, 14, 14) - labs_layout.setSpacing(9) + labs_layout.setContentsMargins(12, 10, 12, 10) + labs_layout.setSpacing(6) labs_title = QLabel("检查结果", labs_card) labs_title.setProperty("receptionBlockTitle", True) labs_layout.addWidget(labs_title) @@ -4757,7 +4867,7 @@ class ReceptionPage(QWidget): self._show_missing_labs = False labs_grid.setContentsMargins(0, 0, 0, 0) labs_grid.setHorizontalSpacing(7) - labs_grid.setVerticalSpacing(7) + labs_grid.setVerticalSpacing(5) self.lab_labels: dict[str, QLabel] = {} self.lab_state_labels: dict[str, QLabel] = {} lab_definitions = ( @@ -8624,6 +8734,7 @@ class ReceptionPage(QWidget): } for key, value in case_values.items(): self.case_labels[key].setText(display_text(value)) + self._sync_case_field_folding() self._set_patient_summary_value("course", case_values["course"]) self._set_patient_summary_value( "diagnosis", case_value("clinical_diagnosis", "diagnosis_name", "disease_name") @@ -9057,6 +9168,24 @@ class ReceptionPage(QWidget): button.setText("预览") show_toast(self, f"图片预览失败:{friendly_error(error)}", "danger", 5200) + def _sync_case_field_folding(self) -> None: + """将未录入的可选病史字段折叠为底部快捷补录胶囊,保持主病历画布清爽高密。""" + + if not hasattr(self, "_missing_field_pills"): + return + any_missing = False + for key, pill in self._missing_field_pills.items(): + label = self.case_labels.get(key) + frame = self._case_field_frames.get(key) + text = (label.text().strip() if label is not None else "") + is_empty = text in {"", "—", "-"} + if frame is not None: + frame.setVisible(not is_empty) + pill.setVisible(is_empty) + if is_empty: + any_missing = True + self._missing_fields_host.setVisible(any_missing) + def _reset_detail_content(self, seed: Any = None) -> None: for cancel_event in self._patient_ai_generation_cancel_events.values(): cancel_event.set() diff --git a/app/src/doctor_workstation/ui/patient_orders_style.py b/app/src/doctor_workstation/ui/patient_orders_style.py index 89d11ce25..0f641d01f 100755 --- a/app/src/doctor_workstation/ui/patient_orders_style.py +++ b/app/src/doctor_workstation/ui/patient_orders_style.py @@ -26,20 +26,25 @@ _ORDERS = """ } #PatientOrdersWorkspace QFrame#OrderSummaryStrip { background: transparent; border: 0; } #PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton { - min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid transparent; - border-radius: $ds_radius_control; background: $ds_surface_alt; color: $ds_text; + min-height: 36px; max-height: 36px; padding: 0 15px; border: 1px solid $ds_line_strong; + border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text; font-weight: 500; } #PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover { - background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; + background: $ds_accent_soft; border-color: #9CCFC7; color: $ds_accent; } -#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: $ds_accent_soft; } +#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: #D7EFEA; } #PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: $ds_focus; } #PatientOrdersWorkspace QPushButton#OrderSearchButton, #PatientOrdersWorkspace QPushButton#OrderDetailButton { - color: $ds_surface; background: $ds_accent; border-color: $ds_accent; + color: $ds_surface; + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent); + border-color: $ds_accent; } #PatientOrdersWorkspace QPushButton#OrderSearchButton:hover, -#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; } +#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover); + border-color: $ds_accent_hover; +} #PatientOrdersWorkspace QPushButton#OrderSearchButton:pressed, #PatientOrdersWorkspace QPushButton#OrderDetailButton:pressed { background: $ds_accent_pressed; border-color: $ds_accent_pressed; } #PatientOrdersWorkspace QPushButton#OrderSearchButton:focus, diff --git a/app/src/doctor_workstation/ui/patients_style.py b/app/src/doctor_workstation/ui/patients_style.py index 545c4e680..4ee7343f2 100755 --- a/app/src/doctor_workstation/ui/patients_style.py +++ b/app/src/doctor_workstation/ui/patients_style.py @@ -61,18 +61,22 @@ _LIST = """ } #PatientListWorkspace QFrame#PatientSummaryStrip { background: transparent; border: 0; } #PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton { - min-height: 38px; max-height: 38px; padding: 0 16px; - border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt; + min-height: 36px; max-height: 36px; padding: 0 15px; + border: 1px solid $ds_line_strong; border-radius: $ds_radius_control; background: $ds_surface; font-weight: 500; } #PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover { - color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; + color: $ds_accent; background: $ds_accent_soft; border-color: #9CCFC7; } -#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: $ds_accent_soft; } +#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: #D7EFEA; } #PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: $ds_focus; } #PatientSearchToolbar QPushButton#PatientSearchButton { - min-height: 38px; max-height: 38px; color: $ds_surface; background: $ds_accent; border-color: $ds_accent; + min-height: 36px; max-height: 36px; color: $ds_surface; + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent); + border-color: $ds_accent; +} +#PatientSearchToolbar QPushButton#PatientSearchButton:hover { + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover); } -#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: $ds_accent_hover; } #PatientSearchToolbar QPushButton#PatientSearchButton:pressed { background: $ds_accent_pressed; } #PatientSearchToolbar QPushButton#PatientSearchButton:focus { border-color: $ds_focus; } #PatientSearchToolbar QLineEdit { diff --git a/app/src/doctor_workstation/ui/prescription_library_style.py b/app/src/doctor_workstation/ui/prescription_library_style.py index 3d018330e..d731ff6f6 100755 --- a/app/src/doctor_workstation/ui/prescription_library_style.py +++ b/app/src/doctor_workstation/ui/prescription_library_style.py @@ -323,19 +323,21 @@ _LIBRARY = """ border: 0; border-radius: 0; background: transparent; } #PrescriptionLibraryPage QPushButton { - min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control; - border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text; + min-height: 36px; max-height: 36px; padding: 0 15px; border-radius: $ds_radius_control; + border: 1px solid $ds_line_strong; background: $ds_surface; color: $ds_text; font-weight: 500; } -#PrescriptionLibraryPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; } -#PrescriptionLibraryPage QPushButton:pressed { background: $ds_accent_soft; } +#PrescriptionLibraryPage QPushButton:hover { background: $ds_accent_soft; border-color: #9CCFC7; color: $ds_accent; } +#PrescriptionLibraryPage QPushButton:pressed { background: #D7EFEA; } #PrescriptionLibraryPage QPushButton:focus { border-color: $ds_focus; } #PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton, #PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton { - background: $ds_accent; border-color: $ds_accent; color: $ds_surface; + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent); + border-color: $ds_accent; color: $ds_surface; } #PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover, #PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover { - background: $ds_accent_hover; border-color: $ds_accent_hover; + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover); + border-color: $ds_accent_hover; } #PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed, #PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed { @@ -343,7 +345,7 @@ _LIBRARY = """ } #PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:focus, #PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:focus { border-color: $ds_focus; } -#PrescriptionLibraryPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; } +#PrescriptionLibraryPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: #F5C8CD; } #PrescriptionLibraryPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; } #PrescriptionLibraryPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; } #PrescriptionLibraryPage QPushButton:disabled, diff --git a/app/src/doctor_workstation/ui/prescriptions_style.py b/app/src/doctor_workstation/ui/prescriptions_style.py index 9d452dfcf..12d9ad677 100755 --- a/app/src/doctor_workstation/ui/prescriptions_style.py +++ b/app/src/doctor_workstation/ui/prescriptions_style.py @@ -31,24 +31,26 @@ _PRESCRIPTIONS = """ } #PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; } #PrescriptionsPage QPushButton { - min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control; - border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text; + min-height: 36px; max-height: 36px; padding: 0 15px; border-radius: $ds_radius_control; + border: 1px solid $ds_line_strong; background: $ds_surface; color: $ds_text; font-weight: 500; } -#PrescriptionsPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; } -#PrescriptionsPage QPushButton:pressed { background: $ds_accent_soft; } +#PrescriptionsPage QPushButton:hover { background: $ds_accent_soft; border-color: #9CCFC7; color: $ds_accent; } +#PrescriptionsPage QPushButton:pressed { background: #D7EFEA; } #PrescriptionsPage QPushButton:focus { border-color: $ds_focus; } #PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton { - background: $ds_accent; color: $ds_surface; border-color: $ds_accent; + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent); + color: $ds_surface; border-color: $ds_accent; } #PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover { - background: $ds_accent_hover; border-color: $ds_accent_hover; + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover); + border-color: $ds_accent_hover; } #PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed { background: $ds_accent_pressed; border-color: $ds_accent_pressed; } #PrescriptionsPage QPushButton#PrescriptionAddButton:focus, #PrescriptionsPage QPushButton#PrescriptionQueryButton:focus { border-color: $ds_focus; } -#PrescriptionsPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; } +#PrescriptionsPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: #F5C8CD; } #PrescriptionsPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; } #PrescriptionsPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; } #PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled, diff --git a/app/src/doctor_workstation/ui/reception_workspace.py b/app/src/doctor_workstation/ui/reception_workspace.py index 6357fd1d3..0dd023b4d 100644 --- a/app/src/doctor_workstation/ui/reception_workspace.py +++ b/app/src/doctor_workstation/ui/reception_workspace.py @@ -169,23 +169,24 @@ QWidget#ReceptionPage QStackedWidget#ReceptionNarrowWorkspace { border: 0; } QWidget#ReceptionPage QFrame#ReceptionQueuePanel { - background-color: #FFFFFF; - border: 1px solid #EDF0F5; - border-radius: 16px; + background-color: $ds_surface; + border: 1px solid $ds_line; + border-radius: $ds_radius_panel; } QWidget#ReceptionPage QLabel#ReceptionQueueTitle { - font-size: 18px; + color: $ds_heading; + font-size: 17px; font-weight: 600; } QWidget#ReceptionPage QLabel#ReceptionQueueName { font-size: 15px; - font-weight: 500; + font-weight: 600; } QWidget#ReceptionPage QLabel#ReceptionQueueMeta, QWidget#ReceptionPage QLabel#ReceptionQueueTime, QWidget#ReceptionPage QLabel#ReceptionQueueSubline, QWidget#ReceptionPage QLabel#ReceptionQueueSummary { - color: #5D6B80; + color: $ds_muted; font-size: 12px; font-weight: 400; } @@ -193,79 +194,137 @@ QWidget#ReceptionPage QLabel#ReceptionQueueMetric { font-size: 13px; } QWidget#ReceptionPage QLabel#ReceptionQueueMetric[tone="description"] { - color: #5D6B80; + color: $ds_muted; font-size: 12px; } QWidget#ReceptionPage QFrame#ReceptionHero, QWidget#ReceptionPage QFrame#ReceptionClinicalCard { min-height: 0; - background-color: #FFFFFF; - border: 1px solid #EDF0F5; - border-radius: 16px; + background-color: $ds_surface; + border: 1px solid $ds_line; + border-radius: $ds_radius_panel; } QWidget#ReceptionPage QLabel#ReceptionPatientName { + color: $ds_heading; font-size: 20px; font-weight: 600; } QWidget#ReceptionPage QLabel#ReceptionPatientMeta { - color: #5D6B80; + color: $ds_muted; font-size: 13px; } QWidget#ReceptionPage QLabel#ReceptionAvatar { - color: #1555B6; - background-color: #EAF2FF; + color: $ds_accent; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #E9F6F4, stop:1 #CDEAE5); + border: 1px solid #DFC793; border-radius: 12px; font-size: 20px; font-weight: 600; } QWidget#ReceptionPage QTabBar#ReceptionDetailTabs, QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs { - background-color: #FFFFFF; + background-color: $ds_surface_alt; border: 0; - border-bottom: 1px solid #E5ECF6; - border-top-left-radius: 16px; - border-top-right-radius: 16px; + border-bottom: 1px solid $ds_line; + border-top-left-radius: $ds_radius_panel; + border-top-right-radius: $ds_radius_panel; } QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab, QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab { min-height: 40px; margin: 0; - padding: 0 14px; - color: #5D6B80; + padding: 0 15px; + color: $ds_muted; background-color: transparent; border: 0; border-bottom: 2px solid transparent; border-radius: 0; font-size: 13px; - font-weight: 400; + font-weight: 500; } QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:first { margin-left: 0; - padding-left: 14px; + padding-left: 15px; } QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:hover, QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:hover { - color: #1769E8; - background-color: #F3F7FD; + color: $ds_accent; + background-color: rgba(11, 110, 104, 14); } QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:selected, QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:selected { - color: #1769E8; + color: $ds_accent; background-color: transparent; - border-bottom: 2px solid #1769E8; - font-weight: 500; + border-bottom: 2px solid $ds_accent; + font-weight: 600; } QWidget#ReceptionPage QFrame#ReceptionHistoryCard { background-color: #FFFFFF; border: 0; border-radius: 0; } -QWidget#ReceptionPage QWidget#ReceptionCaseField { +QWidget#ReceptionPage QWidget#ReceptionCaseField, +QWidget#ReceptionPage QFrame#ReceptionCaseField { background-color: transparent; border: 0; - border-bottom: 1px solid #EDF1F7; + border-bottom: 1px solid $ds_line; border-radius: 0; } +QWidget#ReceptionPage QFrame#ReceptionCaseField[chiefFocus="true"] { + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #EEF9F7, stop:1 #FFFFFF); + border: 1px solid #C6E3DE; + border-left: 3px solid $ds_accent; + border-radius: 10px; +} +QWidget#ReceptionPage QPushButton#ReceptionInlineAction { + min-height: 28px; + max-height: 28px; + padding: 0 10px; + border-radius: 7px; + background-color: $ds_surface; + border: 1px solid $ds_line_strong; + color: $ds_accent; + font-size: 12px; + font-weight: 500; +} +QWidget#ReceptionPage QPushButton#ReceptionInlineAction:hover { + background-color: $ds_accent_soft; + border-color: #8FC8C0; +} +QWidget#ReceptionPage QPushButton#ReceptionInlineAiAction { + min-height: 28px; + max-height: 28px; + padding: 0 10px; + border-radius: 7px; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #123433, stop:1 #091E1E); + border: 1px solid rgba(223, 199, 147, 120); + color: #DFC793; + font-size: 12px; + font-weight: 600; +} +QWidget#ReceptionPage QPushButton#ReceptionInlineAiAction:hover { + background-color: #174240; + color: #FFFFFF; +} +QWidget#ReceptionPage QFrame#ReceptionMissingFieldsBar { + background-color: transparent; + border: 0; +} +QWidget#ReceptionPage QPushButton[receptionQuickFill="true"] { + min-height: 26px; + max-height: 26px; + padding: 0 10px; + border-radius: 13px; + background-color: $ds_surface_alt; + border: 1px dashed $ds_line_strong; + color: $ds_muted; + font-size: 11.5px; +} +QWidget#ReceptionPage QPushButton[receptionQuickFill="true"]:hover { + background-color: $ds_accent_soft; + border: 1px solid $ds_accent; + color: $ds_accent; +} QWidget#ReceptionPage QLabel#ReceptionCaseHeading { color: #202C3F; font-size: 16px; @@ -294,17 +353,17 @@ QWidget#ReceptionPage QLabel[receptionLifestyleChip="true"] { QWidget#ReceptionPage QFrame#ReceptionPatientSummaryCard, QWidget#ReceptionPage QFrame#ReceptionVitalsCard, QWidget#ReceptionPage QFrame#ReceptionLabsCard { - background-color: #FFFFFF; - border: 1px solid #EDF0F5; - border-radius: 16px; + background-color: $ds_surface; + border: 1px solid $ds_line; + border-radius: $ds_radius_panel; } QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue { - color: #24334A; + color: $ds_heading; font-size: 13px; font-weight: 500; } QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] { - color: #697386; + color: $ds_muted; font-weight: 400; } QWidget#ReceptionPage QFrame#ReceptionMetricCell, @@ -316,76 +375,109 @@ QWidget#ReceptionPage QFrame#ReceptionMetricCell[firstMetric="true"] { QWidget#ReceptionPage QLabel[receptionMetricCaption="true"], QWidget#ReceptionPage QLabel[receptionMetricUnit="true"], QWidget#ReceptionPage QLabel[receptionBmiState="true"] { - color: #5D6B80; + color: $ds_muted; font-size: 12px; font-weight: 400; } QWidget#ReceptionPage QFrame#ReceptionMetricCell QLabel[receptionMetricValue="true"] { + color: $ds_heading; font-size: 18px; - font-weight: 500; + font-weight: 600; } QWidget#ReceptionPage QFrame#ReceptionLabCell { min-height: 0; padding: 0; - background-color: #FFFFFF; + background-color: $ds_surface; border: 0; - border-bottom: 1px solid #EDF1F7; + border-bottom: 1px solid $ds_line; border-radius: 0; } QWidget#ReceptionPage QFrame#ReceptionLabCell QLabel[receptionMetricValue="true"] { font-size: 13px; - font-weight: 400; + font-weight: 500; } QWidget#ReceptionPage QPushButton#ReceptionMissingLabsButton { min-height: 28px; max-height: 28px; padding: 0; - color: #1769E8; + color: $ds_accent; background: transparent; border: 0; text-align: left; font-size: 12px; + font-weight: 500; } QWidget#ReceptionPage QLabel[receptionMetricState="true"] { min-height: 18px; - padding: 0 5px; - background-color: #F0F5FD; - border: 0; - border-radius: 4px; + padding: 0 6px; + background-color: $ds_accent_soft; + border: 1px solid #C5E2DE; + border-radius: $ds_radius_small; font-size: 12px; - font-weight: 400; + font-weight: 500; } QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"] { - color: #BE4B58; - background-color: #FFF4F5; + color: $ds_danger; + background-color: $ds_danger_soft; + border-color: #F5C8CD; } QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"][warning="true"] { - color: #A9691D; - background-color: #FFF9EF; - border-radius: 4px; + color: $ds_warning; + background-color: $ds_warning_soft; + border-color: #F7DFB7; + border-radius: $ds_radius_small; } QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard, QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard { - background-color: #FFFFFF; - border: 1px solid $ds_line; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #103231, stop:0.6 #092020, stop:1 #061515); + border: 1px solid rgba(223, 199, 147, 108); border-radius: $ds_radius_panel; } +QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard QLabel, +QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard QLabel { + color: #DDF0ED; + background: transparent; +} +QWidget#ReceptionPage QStackedWidget#ReceptionAiAnalysisStack, +QWidget#ReceptionPage QStackedWidget#ReceptionAiAnalysisStack > QWidget, +QWidget#ReceptionPage QWidget#ReceptionAiAnalysisSections { + background: transparent; + border: 0; +} QWidget#ReceptionPage QLabel#ReceptionAiTitle, QWidget#ReceptionPage QPushButton#ReceptionAiTitle { + color: #DFC793; font-size: 14px; - font-weight: 500; + font-weight: 600; + background: transparent; + border: 0; } +QWidget#ReceptionPage QLabel#ReceptionAiAnalysisSnapshotMeta, QWidget#ReceptionPage QLabel#ReceptionAiAssistantHint { - color: #5D6B80; - font-size: 13px; + color: #93B8B4; + font-size: 12px; font-weight: 400; } +QWidget#ReceptionPage QComboBox#ReceptionAiAnalysisModelSelector { + background-color: rgba(255, 255, 255, 22); + border: 1px solid rgba(223, 199, 147, 92); + border-radius: 7px; + color: #F2FAF9; + padding: 2px 8px; +} QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] { min-height: 28px; max-height: 28px; - padding: 0 8px; + padding: 0 9px; font-size: 12px; - border-radius: 6px; + border-radius: 7px; + background-color: rgba(24, 176, 165, 42); + border: 1px solid rgba(84, 230, 193, 96); + color: #A8F3DF; +} +QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"]:hover { + background-color: rgba(24, 176, 165, 86); + color: #FFFFFF; } QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll { background-color: transparent; diff --git a/app/src/doctor_workstation/ui/shell.py b/app/src/doctor_workstation/ui/shell.py index 6eab869f0..198f82c84 100755 --- a/app/src/doctor_workstation/ui/shell.py +++ b/app/src/doctor_workstation/ui/shell.py @@ -1,2281 +1,2715 @@ -"""Authenticated application shell with permission-aware navigation.""" - -from __future__ import annotations - -import math -import sqlite3 -from collections.abc import Callable, Mapping, Sequence -from dataclasses import dataclass -from functools import wraps -from typing import Any - -from PySide6.QtCore import ( - QElapsedTimer, - QPointF, - QRectF, - QSize, - Qt, - QTimer, - Signal, -) -from PySide6.QtGui import ( - QColor, - QFont, - QIcon, - QKeySequence, - QMouseEvent, - QPainter, - QPainterPath, - QPen, - QPixmap, - QShortcut, -) -from PySide6.QtWidgets import ( - QApplication, - QButtonGroup, - QFrame, - QHBoxLayout, - QLabel, - QLineEdit, - QMainWindow, - QMenu, - QPushButton, - QSizePolicy, - QStackedWidget, - QStyle, - QStyleOptionButton, - QTabBar, - QToolButton, - QVBoxLayout, - QWidget, -) - -from doctor_workstation.resources import app_icon_path - -from . import icons, motion -from .chat_notifications import ( - CONSULTATION_COMPLETE, - PATIENT_OPENED_CHAT, - ChatNotification, - ChatNotificationCenter, -) -from .design_system import PALETTE, clinical_stylesheet -from .dialogs.ai_consult import can_open_ai_consult -from .dialogs.ai_consult_picker import select_and_present_ai_consult -from .dialogs.diagnosis import DiagnosisDialog -from .dialogs.esign_doctor import EsignDoctorDialog -from .dialogs.local_audio_queue import LocalAudioQueueDialog -from .dialogs.prescription_esign import can_open_esign_doctor -from .pages import ( - AppointmentsPage, - ConsultationsPage, - PatientsPage, - PrescriptionLibraryPage, - PrescriptionsPage, - ReceptionPage, -) -from .reception_style import TECH_BLUE, body_family, heading_family, number_family -from .theme import COLORS, METRICS, TYPE, crisp_pixmap -from .widgets import ( - EmptyState, - StatusBadge, - display_text, - first_value, - get_value, - has_permission, - show_toast, -) - -_SHELL_EXPANDED_WIDTH = 190 -_SHELL_COLLAPSED_WIDTH = 68 -_SHELL_TOPBAR_HEIGHT = 62 -_SHELL_TABS_HEIGHT = 0 -_SHELL_OUTER_GUTTER = 13 -_SHELL_PANEL_GAP = 0 -_SHELL_DESIGN_SIZE = QSize(1710, 920) -_SHELL_MINIMUM_SIZE = QSize(1024, 640) -_RECEPTION_SIDEBAR_WIDTH = 208 -_RECEPTION_TOPBAR_HEIGHT = 76 -_RECEPTION_SIDEBAR_COLOR = PALETTE["sidebar"] -_RECEPTION_CHROME_LINE = PALETTE["line"] -# Approved pages share one chrome state, so navigation among them keeps it intact. -_TECH_BLUE_PAGES = frozenset({"appointments", "consultations", "patients", "prescriptions", "prescription_library", "reception"}) - - -def _bounded_initial_window_size(available_size: QSize | None) -> QSize: - """Fit the design viewport inside the screen's logical available geometry.""" - - if available_size is None or not available_size.isValid(): - return QSize(_SHELL_DESIGN_SIZE.width(), _SHELL_DESIGN_SIZE.height()) - return QSize( - max( - _SHELL_MINIMUM_SIZE.width(), - min(_SHELL_DESIGN_SIZE.width(), available_size.width()), - ), - max( - _SHELL_MINIMUM_SIZE.height(), - min(_SHELL_DESIGN_SIZE.height(), available_size.height()), - ), - ) - - -@dataclass(frozen=True) -class NavigationItem: - key: str - title: str - glyph: str - page_type: type[QWidget] - permissions: tuple[str, ...] - - -NAVIGATION = ( - NavigationItem( - # 挂号与诊单是两条独立队列,早期两项都叫“问诊列表”,侧边栏出现两个同名 - # 入口,医生无法判断该点哪个。按各自的业务对象命名以消除歧义。 - "appointments", - "挂号列表", - "号", - AppointmentsPage, - ("doctor.appointment/lists",), - ), - NavigationItem( - "reception", - "接诊台", - "◎", - ReceptionPage, - ("doctor.appointment/lists",), - ), - NavigationItem( - "prescription_library", - "处方库", - "方", - PrescriptionLibraryPage, - ("tcm.prescriptionLibrary/lists",), - ), - NavigationItem( - "prescriptions", - "已开处方", - "笺", - PrescriptionsPage, - ("tcm.prescription/lists",), - ), - NavigationItem( - "patients", - "我的患者", - "患", - PatientsPage, - ("firstvisit.myPatient/lists",), - ), - NavigationItem( - "consultations", - "问诊列表", - "询", - ConsultationsPage, - ("tcm.diagnosis/lists",), - ), -) - - -# Shared ``doctor.appointment/lists`` is intentionally mapped only to reception; -# the appointment list page is resolved by menu route/component identity. -_NAVIGATION_BY_PERMISSION = { - item.permissions[0]: item for item in NAVIGATION if item.key != "appointments" -} -_MENU_ROUTE_IDENTIFIERS = { - "reception": { - "reception", - "patient/reception", - "patient/reception/index", - }, - "appointments": { - "appointments", - "tcm/appointment", - "tcm/appointment/list", - "appointment/list", - }, - "prescription_library": { - "prescription-library", - "prescription_library", - "consumer/prescription/list", - }, - "prescriptions": { - "prescriptions", - "consumer/prescription/index", - }, - "patients": { - "patients", - "first_visit/my_patients", - "first_visit/my_patients/index", - }, - "consultations": { - "consultations", - "tcm/diagnosis", - "tcm/diagnosis/index", - }, -} - - -def _canonical_allowed(permissions: Any, code: str) -> bool: - """Apply the core exact/wildcard semantics without slash-dot aliases.""" - - if permissions is None: - return True - for method_name in ("allows", "has", "can_access_page", "has_page", "can"): - method = getattr(permissions, method_name, None) - if callable(method): - try: - return bool(method(code)) - except (TypeError, ValueError): - continue - raw = permissions - for attr in ("codes", "permissions", "values"): - candidate = getattr(permissions, attr, None) - if candidate is not None and not callable(candidate): - raw = candidate - break - if isinstance(raw, Mapping): - nested = first_value(raw, "codes", "permissions", "values", default=None) - if nested is not None: - raw = nested - if isinstance(raw, Mapping): - available = {str(key) for key, enabled in raw.items() if enabled} - elif isinstance(raw, str): - available = {raw} - else: - try: - available = {str(value) for value in raw} - except TypeError: - return False - if "*" in available or code in available: - return True - return any( - grant.endswith("/*") and code.startswith(grant[:-1]) for grant in available - ) - - -def _menu_rows(value: Any) -> list[Mapping[str, Any]]: - if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)): - return [] - return [row for row in value if isinstance(row, Mapping)] - - -def _menu_visible(row: Mapping[str, Any]) -> bool: - value = get_value(row, "is_show", 1) - if isinstance(value, str): - return value.strip().lower() not in {"0", "false", "hidden", "no"} - return value != 0 - - -def _menu_enabled(row: Mapping[str, Any]) -> bool: - value = get_value(row, "is_disable", 0) - if isinstance(value, str): - return value.strip().lower() not in {"1", "true", "disabled", "yes"} - return value != 1 - - -def _menu_sort(row: Mapping[str, Any]) -> float: - try: - return float(first_value(row, "sort", "sort_order", "order", default=0)) - except (TypeError, ValueError): - return 0.0 - - -def _visible_menu_nodes(value: Any) -> list[Mapping[str, Any]]: - """Flatten visible, enabled nodes; larger admin sort values come first.""" - - nodes = _menu_rows(value) - ordered = sorted(enumerate(nodes), key=lambda pair: (-_menu_sort(pair[1]), pair[0])) - result: list[Mapping[str, Any]] = [] - for _index, node in ordered: - if not _menu_visible(node) or not _menu_enabled(node): - continue - result.append(node) - children = first_value(node, "children", "child", "childs", default=[]) - result.extend(_visible_menu_nodes(children)) - return result - - -def _normalise_route(value: Any) -> str: - route = str(value or "").strip().replace("\\", "/").lower() - route = route.split("?", 1)[0].split("#", 1)[0].strip("/") - if route.endswith(".vue"): - route = route[:-4] - return route - - -def _menu_permissions(row: Mapping[str, Any]) -> tuple[str, ...]: - value = first_value(row, "perms", "permission", "meta.perms", default="") - if isinstance(value, str): - return (value.strip(),) if value.strip() else () - if isinstance(value, Sequence): - return tuple(str(item).strip() for item in value if str(item).strip()) - return () - - -def _match_navigation(row: Mapping[str, Any]) -> NavigationItem | None: - """Prefer route/component identity when pages share the same permission code.""" - - identifiers = { - _normalise_route(first_value(row, "paths", "path")), - _normalise_route(get_value(row, "component", "")), - } - identifiers.discard("") - for item in NAVIGATION: - if identifiers & _MENU_ROUTE_IDENTIFIERS.get(item.key, set()): - return item - for permission in _menu_permissions(row): - item = _NAVIGATION_BY_PERMISSION.get(permission) - if item is not None: - return item - return None - - -def _resolve_navigation( - menu: Any, - permissions: Any, - *, - demo_mode: bool, -) -> list[tuple[NavigationItem, str]]: - """Resolve only locally supported pages from the authoritative menu tree.""" - - rows = _menu_rows(menu) - if rows: - resolved: list[tuple[NavigationItem, str]] = [] - seen: set[str] = set() - for row in _visible_menu_nodes(rows): - item = _match_navigation(row) - if item is None or item.key in seen: - continue - if not _canonical_allowed(permissions, item.permissions[0]): - continue - if item.key in {"appointments", "reception", "patients"}: - # Keep the product-facing navigation titles stable even when - # the server still carries an older menu label. - title = item.title - else: - title_value = first_value( - row, "name", "title", "meta.title", default=item.title - ) - title = str(title_value).strip() or item.title - resolved.append((item, title)) - seen.add(item.key) - resolved.sort(key=lambda entry: entry[0].key != "appointments") - return resolved - if demo_mode: - return [ - (item, item.title) - for item in NAVIGATION - if _canonical_allowed(permissions, item.permissions[0]) - ] - return [] - - -def _painted_shell_icon(kind: str, size: int = 18, *, reception: bool = False) -> QIcon: - """Return a shell chrome icon from the shared 24-unit icon grid.""" - - color = "accent" if kind == "ai" else "muted" - if reception: - color = TECH_BLUE["accent" if kind == "ai" else "text"] - if kind in {"settings", "fullscreen"}: - canvas = crisp_pixmap(size) - painter = QPainter(canvas) - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - painter.scale(size / 24.0, size / 24.0) - painter.setPen(QPen(QColor(color), 1.55, Qt.PenStyle.SolidLine, - Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin)) - painter.setBrush(Qt.BrushStyle.NoBrush) - if kind == "fullscreen": - painter.drawRoundedRect(QRectF(4, 4, 16, 16), 1, 1) - else: - gear = QPainterPath() - for index in range(48): - radius = (10, 10, 7.9, 7.9, 10, 10)[index % 6] - angle = index * math.pi / 24.0 - point = QPointF(12 + radius * math.cos(angle), 12 + radius * math.sin(angle)) - if index == 0: - gear.moveTo(point) - else: - gear.lineTo(point) - gear.closeSubpath() - painter.drawPath(gear) - painter.drawEllipse(QRectF(8.6, 8.6, 6.8, 6.8)) - painter.end() - return QIcon(canvas) - return icons.icon(kind, color, size) - - -def _painted_navigation_icon(kind: str, size: int = 18, *, reception: bool = False) -> QIcon: - """Return a navigation icon that carries its own selected/hover colours.""" - - return icons.state_icon( - kind, - size=size, - normal=TECH_BLUE["text"] if reception else "muted", - active=TECH_BLUE["heading"] if reception else "strong", - checked=TECH_BLUE["selected_text"] if reception else "on_accent", - disabled="disabled", - ) - - -class _ShellBrandMark(QWidget): - """Render the approved application brand mark in the navigation rail.""" - - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - self._brand_pixmap = QPixmap(str(app_icon_path())) - - #: The brand PNG carries an opaque white field behind the logo, so drawing it - #: straight put a hard-cornered white square inside a rail whose every other - #: edge is rounded. Clipping the tile is enough - the artwork is untouched. - _TILE_RADIUS = 10.0 - - def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - del event - reception = bool(self.property("receptionTechBlue")) - if not reception and self._brand_pixmap.isNull(): - return - painter = QPainter(self) - painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - rect = QRectF(self.rect()).adjusted(0.75, 0.75, -0.75, -0.75) - if reception: - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(TECH_BLUE["accent"])) - painter.drawEllipse(rect) - painter.scale(self.width() / 36.0, self.height() / 36.0) - cross = QPainterPath() - cross.moveTo(16, 9) - for x, y in ((20, 9), (20, 15), (26, 15), (26, 20), (20, 20), - (20, 26), (15, 26), (15, 20), (9, 20), (9, 15), (15, 15), (15, 9)): - cross.lineTo(x, y) - cross.closeSubpath() - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.setPen(QPen(QColor(TECH_BLUE["surface"]), 2.0, - Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap, - Qt.PenJoinStyle.RoundJoin)) - painter.drawPath(cross) - return - clip = QPainterPath() - clip.addRoundedRect(rect, self._TILE_RADIUS, self._TILE_RADIUS) - painter.setClipPath(clip) - painter.drawPixmap(rect, self._brand_pixmap, QRectF(self._brand_pixmap.rect())) - - -class _ShellNavigationButton(QPushButton): - """Use the approved icon-to-label spacing in the shared blue chrome.""" - - def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - if not self.property("receptionTechBlue"): - super().paintEvent(event) - return - option = QStyleOptionButton() - self.initStyleOption(option) - painter = QPainter(self) - self.style().drawControl(QStyle.ControlElement.CE_PushButtonBevel, option, painter, self) - collapsed = bool(self.property("collapsed")) - settings = self.objectName() == "ShellSettingsButton" - x = (self.width() - 20) // 2 if collapsed else (30 if settings else 22) - self.icon().paint( - painter, x, (self.height() - 20) // 2, 20, 20, - Qt.AlignmentFlag.AlignCenter, - QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled, - QIcon.State.On if self.isChecked() else QIcon.State.Off, - ) - if not collapsed: - painter.setFont(self.font()) - painter.setPen(QColor(TECH_BLUE["selected_text"] if self.isChecked() else TECH_BLUE["text"])) - painter.drawText( - QRectF(65 if settings else 56, 0, self.width() - 69, self.height()), - Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, - "设置" if settings else self.text(), - ) - if settings: - _painted_shell_icon("right", 16, reception=True).paint( - painter, 112, (self.height() - 16) // 2, 16, 16 - ) - - -class _AssistantRobot(QWidget): - """Legacy illustration, with the approved AI tile in the shared blue chrome.""" - - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - self.setFixedSize(56, 56) - - def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - del event - painter = QPainter(self) - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - painter.setPen(Qt.PenStyle.NoPen) - if self.property("receptionTechBlue"): - painter.setBrush(QColor(TECH_BLUE["accent"])) - tile = QRectF(6, 6, 36, 36) - painter.drawRoundedRect(tile, 6, 6) - painter.setPen(QColor(TECH_BLUE["surface"])) - font = QFont(number_family()) - font.setPixelSize(18) - font.setWeight(QFont.Weight.DemiBold) - painter.setFont(font) - painter.drawText(tile, Qt.AlignmentFlag.AlignCenter, "AI") - return - painter.setBrush(QColor(COLORS["indigo_pale"])) - painter.drawEllipse(QRectF(1, 1, 54, 54)) - painter.setBrush(QColor("#E4E4E5")) - painter.drawEllipse(QRectF(9, 13, 38, 36)) - - pen = QPen(QColor(COLORS["indigo"]), 1.5) - pen.setCapStyle(Qt.PenCapStyle.RoundCap) - pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) - painter.setPen(pen) - painter.setBrush(QColor("#FFFFFF")) - painter.drawRoundedRect(QRectF(12, 17, 32, 25), 9, 9) - painter.setBrush(QColor("#223D83")) - painter.drawRoundedRect(QRectF(16, 22, 24, 13), 6, 6) - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#65D7F0")) - painter.drawEllipse(QRectF(21, 26, 3.5, 3.5)) - painter.drawEllipse(QRectF(31.5, 26, 3.5, 3.5)) - painter.setBrush(QColor(COLORS["indigo"])) - painter.drawRoundedRect(QRectF(19, 40, 18, 9), 4, 4) - painter.setPen(pen) - painter.drawLine(QPointF(28, 17), QPointF(28, 10)) - painter.setBrush(QColor(COLORS["indigo"])) - painter.drawEllipse(QRectF(25.5, 6.5, 5, 5)) - painter.drawLine(QPointF(12, 28), QPointF(7.5, 31)) - painter.drawLine(QPointF(44, 28), QPointF(48.5, 31)) - - -class _AssistantStatus(QLabel): - """Status copy with a painted dot instead of a Unicode circle glyph.""" - - def __init__(self, text: str, parent: QWidget | None = None) -> None: - super().__init__(text, parent) - self._online = True - self.setFixedHeight(18) - - def set_online(self, online: bool) -> None: - self._online = online - self.update() - - def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - del event - painter = QPainter(self) - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - reception = bool(self.property("receptionTechBlue")) - online_color = TECH_BLUE["accent"] if reception else "#28B98B" - color = QColor(online_color if self._online else "#EC5266") - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(color) - diameter = 6 - painter.drawEllipse(QRectF(1, (self.height() - diameter) / 2, diameter, diameter)) - painter.setPen(color) - painter.setFont(self.font()) - painter.drawText( - QRectF(12, 0, self.width() - 12, self.height()), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - self.text(), - ) - - -class _PaintedIconButton(QToolButton): - """Font-independent shell icon used for every directional affordance.""" - - def __init__( - self, - kind: str, - *, - size: int = 42, - parent: QWidget | None = None, - ) -> None: - super().__init__(parent) - self.kind = kind - # The close glyph used to be drawn at 12 px next to 18 px siblings, so - # the title bar's three controls never lined up optically. All of - # them are authored on the same grid now, so they share one size. - icon_size = 18 - self.setObjectName("ShellPaintedIconButton") - self.setCursor(Qt.CursorShape.PointingHandCursor) - self.setAutoRaise(True) - self.setFixedSize(size, size) - self.setIcon(_painted_shell_icon(kind, icon_size)) - self.setIconSize(QSize(icon_size, icon_size)) - content_size = max(0, size - 2) - self.setStyleSheet( - f""" - QToolButton#ShellPaintedIconButton {{ - min-width: {content_size}px; - max-width: {content_size}px; - min-height: {content_size}px; - max-height: {content_size}px; - background: transparent; - border: 1px solid transparent; - border-radius: 9px; - }} - QToolButton#ShellPaintedIconButton:hover {{ - background: #F7F7F7; - border-color: #EDEDEE; - }} - QToolButton#ShellPaintedIconButton:pressed {{ background: #F0F0F0; }} - QToolButton#ShellPaintedIconButton:focus {{ border-color: #8B9AD9; }} - QToolButton#ShellPaintedIconButton[windowControl="close"]:hover {{ - background: #FFF0F2; - border-color: #F4C4CC; - }} - QToolButton#ShellPaintedIconButton::menu-indicator {{ image: none; width: 0; }} - """ - ) - - -class _UserMenuButton(QToolButton): - """Compact admin-style user dropdown without font-glyph arrows.""" - - def __init__(self, display_name: str, parent: QWidget | None = None) -> None: - super().__init__(parent) - self.display_name = display_name or "医生" - self.setObjectName("ShellUserMenu") - self.setCursor(Qt.CursorShape.PointingHandCursor) - self.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) - self.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) - self.setFixedHeight(_SHELL_TOPBAR_HEIGHT) - name_width = self.fontMetrics().horizontalAdvance(self.display_name) - self.setFixedWidth(max(104, min(174, name_width + 72))) - self.setAccessibleName(f"用户菜单:{self.display_name}") - self.setText(self.display_name) - avatar = crisp_pixmap(34) - painter = QPainter(avatar) - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(COLORS["indigo_pale"])) - painter.drawEllipse(QRectF(0, 0, 34, 34)) - painter.setPen(QColor(COLORS["indigo"])) - avatar_font = QFont(painter.font()) - avatar_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(avatar_font) - painter.drawText( - QRectF(0, 0, 34, 34), Qt.AlignmentFlag.AlignCenter, self.display_name[:1] - ) - painter.end() - self.setIcon(QIcon(avatar)) - self._legacy_avatar = self.icon() - self.setIconSize(QSize(34, 34)) - self.setStyleSheet( - """ - QToolButton#ShellUserMenu { - color: #1A1C1F; - background: transparent; - border: 1px solid transparent; - border-radius: 9px; - padding: 0 18px 0 7px; - font-size: 13px; - font-weight: 500; - } - QToolButton#ShellUserMenu:hover { background: #F7F7F7; border-color: #EDEDEE; } - QToolButton#ShellUserMenu:pressed { background: #F0F0F0; } - QToolButton#ShellUserMenu:focus { border-color: #8B9AD9; } - QToolButton#ShellUserMenu::menu-indicator { - subcontrol-origin: padding; - subcontrol-position: right center; - right: 7px; - } - """ - ) - - def set_reception_avatar(self, active: bool) -> None: - if not active: - self.setIcon(self._legacy_avatar) - self.setIconSize(QSize(34, 34)) - return - avatar = crisp_pixmap(44) - painter = QPainter(avatar) - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(TECH_BLUE["selection"])) - painter.drawEllipse(QRectF(0, 0, 44, 44)) - painter.setPen(QColor(TECH_BLUE["accent"])) - font = QFont(heading_family()) - font.setPixelSize(17) - font.setWeight(QFont.Weight.DemiBold) - painter.setFont(font) - painter.drawText( - QRectF(0, 0, 44, 44), Qt.AlignmentFlag.AlignCenter, self.display_name[:1] - ) - painter.end() - self.setIcon(QIcon(avatar)) - self.setIconSize(QSize(44, 44)) - - -class _RefreshButton(_PaintedIconButton): - """Top-bar refresh whose icon turns while the page is reloading. - - List loads are silent - they no longer raise a banner into the layout - so - this button is the only place left that can say "your click did something". - Without it a refresh on a slow query looks like a dead control. - """ - - _FRAMES = 12 - _FRAME_MS = 55 - #: Spin for at least this long even if the reload was instant, or a fast - #: refresh flickers once and reads as a glitch rather than as feedback. - _MIN_MS = 420 - #: And never longer than this, so a page that forgets to clear its loading - #: flag cannot leave the icon spinning for the rest of the session. - _CAP_MS = 10_000 - - def __init__(self, *, size: int = 38, parent: QWidget | None = None) -> None: - super().__init__("refresh", size=size, parent=parent) - self._is_busy: Callable[[], bool] = lambda: False - self._resting = self.icon() - self._frames = [ - QIcon(self._rotated(index * 360 / self._FRAMES)) for index in range(self._FRAMES) - ] - self._frame = 0 - self._elapsed = QElapsedTimer() - self._timer = QTimer(self) - self._timer.setInterval(self._FRAME_MS) - self._timer.timeout.connect(self._tick) - - def _rotated(self, angle: float) -> QPixmap: - color = TECH_BLUE["text"] if self.property("receptionTechBlue") else "muted" - source = icons.pixmap("refresh", color, self.iconSize().width()) - size = self.iconSize().width() - canvas = crisp_pixmap(size) - painter = QPainter(canvas) - painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) - painter.translate(size / 2.0, size / 2.0) - painter.rotate(angle) - painter.translate(-size / 2.0, -size / 2.0) - painter.drawPixmap(QRectF(0, 0, size, size), source, QRectF(source.rect())) - painter.end() - return canvas - - def set_busy_probe(self, probe: Callable[[], bool]) -> None: - self._is_busy = probe - - def set_reception_palette(self, active: bool) -> None: - self.setProperty("receptionTechBlue", active) - self._resting = _painted_shell_icon("refresh", self.iconSize().width(), reception=active) - self._frames = [ - QIcon(self._rotated(index * 360 / self._FRAMES)) for index in range(self._FRAMES) - ] - self.setIcon(self._frames[self._frame] if self._timer.isActive() else self._resting) - - def start_spin(self) -> None: - self._frame = 0 - self._elapsed.restart() - if not self._timer.isActive(): - self._timer.start() - - def _tick(self) -> None: - elapsed = self._elapsed.elapsed() - if elapsed >= self._CAP_MS or (elapsed >= self._MIN_MS and not self._is_busy()): - self._timer.stop() - self.setIcon(self._resting) - return - self._frame = (self._frame + 1) % self._FRAMES - self.setIcon(self._frames[self._frame]) - - -class _ShellCanvas(QWidget): - """Outer frameless-window ground, with native edge resizing. - - This is the bottom-most layer of the application, so it is the one that - carries the window's corner. It used to be a plain square fill from the - global ``QMainWindow`` rule, which meant the only rounded things at the - window edge were the panels sitting on top of it - a corner inside a corner. - """ - - _RESIZE_MARGIN = 8 - - #: The workspace card is inset by the gutter and rounded at ``r_xl``; a - #: concentric outer corner is therefore that radius plus the gutter, which - #: is what keeps the two curves parallel instead of merely both-rounded. - _RADIUS = 16.0 + _SHELL_OUTER_GUTTER - - def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - del event - painter = QPainter(self) - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - painter.setPen(Qt.PenStyle.NoPen) - reception = bool(self.property("receptionTechBlue")) - color = TECH_BLUE["surface"] if reception else COLORS["canvas"] - painter.setBrush(QColor(color)) - if reception: - painter.drawRect(self.rect()) - else: - painter.drawRoundedRect(QRectF(self.rect()), self._RADIUS, self._RADIUS) - - def _resize_edges(self, position: QPointF) -> Qt.Edge: - edges = Qt.Edge(0) - if position.x() <= self._RESIZE_MARGIN: - edges |= Qt.Edge.LeftEdge - elif position.x() >= self.width() - self._RESIZE_MARGIN: - edges |= Qt.Edge.RightEdge - if position.y() <= self._RESIZE_MARGIN: - edges |= Qt.Edge.TopEdge - elif position.y() >= self.height() - self._RESIZE_MARGIN: - edges |= Qt.Edge.BottomEdge - return edges - - def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual - edges = self._resize_edges(event.position()) - diagonal_down = Qt.Edge.LeftEdge | Qt.Edge.TopEdge - diagonal_up = Qt.Edge.LeftEdge | Qt.Edge.BottomEdge - if edges in (diagonal_down, Qt.Edge.RightEdge | Qt.Edge.BottomEdge): - self.setCursor(Qt.CursorShape.SizeFDiagCursor) - elif edges in (diagonal_up, Qt.Edge.RightEdge | Qt.Edge.TopEdge): - self.setCursor(Qt.CursorShape.SizeBDiagCursor) - elif edges in (Qt.Edge.LeftEdge, Qt.Edge.RightEdge): - self.setCursor(Qt.CursorShape.SizeHorCursor) - elif edges in (Qt.Edge.TopEdge, Qt.Edge.BottomEdge): - self.setCursor(Qt.CursorShape.SizeVerCursor) - else: - self.unsetCursor() - super().mouseMoveEvent(event) - - def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual - if event.button() == Qt.MouseButton.LeftButton: - edges = self._resize_edges(event.position()) - handle = self.window().windowHandle() - if edges and handle is not None and handle.startSystemResize(edges): - event.accept() - return - super().mousePressEvent(event) - - -class _ShellTopBar(QFrame): - """Integrated title bar that retains native system move/maximize behavior.""" - - def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual - if event.button() == Qt.MouseButton.LeftButton: - window = self.window() - handle = window.windowHandle() - if handle is not None and handle.startSystemMove(): - event.accept() - return - super().mousePressEvent(event) - - def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual - if event.button() == Qt.MouseButton.LeftButton: - window = self.window() - if window.isMaximized(): - window.showNormal() - else: - window.showMaximized() - event.accept() - return - super().mouseDoubleClickEvent(event) - - -class ShellWindow(QMainWindow): - """Main workstation window. - - The expected construction signature is ``ShellWindow(repository, session, - permissions=None)``. ``session`` may be a Session dataclass, the payload - emitted by :class:`LoginWindow`, or a plain mapping. - """ - - logout_requested = Signal() - close_requested = Signal() - video_requested = Signal(dict) - page_changed = Signal(str) - update_check_requested = Signal() - - def __init__( - self, - repository: Any, - session: Any, - permissions: Any = None, - parent: QWidget | None = None, - ) -> None: - super().__init__(parent) - self.setProperty("doctorMainWindow", True) - self.setWindowTitle("甄养堂 · 问诊中心") - self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True) - # The ground paints its own rounded corner, so everything outside that - # corner has to be genuinely empty rather than filled by the global - # QMainWindow background. - self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) - self.setStyleSheet("QMainWindow { background: transparent; }") - self.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True) - self.repository = repository - self.login_payload = session - self.session = get_value(session, "session", None) or session - self.current_user = ( - get_value(session, "user", None) - or get_value(self.session, "user", None) - or get_value(session, "current_user", None) - or session - ) - if permissions is not None: - self.permissions = permissions - else: - session_permissions = get_value(self.session, "permissions", None) - self.permissions = ( - session_permissions - if session_permissions is not None - else get_value(self.current_user, "permissions", None) - ) - self._can_ai_assistant = can_open_ai_consult(self.permissions) - session_menu = get_value(self.session, "menu", None) - self.menu = ( - session_menu if session_menu is not None else get_value(session, "menu", []) - ) - self.demo_mode = bool( - get_value(session, "demo_mode", False) - or get_value(self.session, "metadata.demo", False) - or get_value(self.session, "metadata.demo_mode", False) - ) - self.navigation = _resolve_navigation( - self.menu, - self.permissions, - demo_mode=self.demo_mode, - ) - self.pages: dict[str, QWidget] = {} - self.nav_buttons: dict[str, QPushButton] = {} - self.page_titles: dict[int, str] = {} - self._fixed_tab_key: str | None = None - self._sidebar_collapsed = False - self._reception_chrome_active = False - self._active_page_key: str | None = None - self._activation_page: QWidget | None = None - self._activation_generation = 0 - self._activation_refreshed = False - self._local_audio_settings_dialog: LocalAudioQueueDialog | None = None - self._global_diagnosis_dialog: DiagnosisDialog | None = None - # 与后台 chat-notify-toast 同一份数据源,登录后常驻轮询。 - self.chat_notifications = ChatNotificationCenter(repository, self) - self.chat_notifications.notification_activated.connect( - self._open_chat_notification - ) - - self.setMinimumSize(_SHELL_MINIMUM_SIZE) - screen = self.screen() or QApplication.primaryScreen() - available_size = screen.availableGeometry().size() if screen is not None else None - self.resize(_bounded_initial_window_size(available_size)) - - canvas = _ShellCanvas(self) - canvas.setObjectName("AppCanvas") - canvas.setMouseTracking(True) - self.setCentralWidget(canvas) - root = QHBoxLayout(canvas) - root.setContentsMargins( - _SHELL_OUTER_GUTTER, - _SHELL_OUTER_GUTTER, - _SHELL_OUTER_GUTTER, - _SHELL_OUTER_GUTTER, - ) - root.setSpacing(_SHELL_PANEL_GAP) - self.sidebar = self._build_sidebar() - root.addWidget(self.sidebar) - - self.workspace = QWidget() - self.workspace.setObjectName("ShellWorkspace") - self.workspace.setStyleSheet( - """ - QWidget#ShellWorkspace { - background-color: #FFFFFF; - border: 0; - border-radius: 16px; - } - """ - ) - workspace_layout = QVBoxLayout(self.workspace) - workspace_layout.setContentsMargins(0, 0, 0, 0) - workspace_layout.setSpacing(0) - self.topbar = self._build_topbar() - workspace_layout.addWidget(self.topbar) - self.tabs_host = self._build_tab_strip() - workspace_layout.addWidget(self.tabs_host) - self.stack = QStackedWidget() - self.stack.setObjectName("ShellPageStack") - self.stack.setStyleSheet( - "QStackedWidget#ShellPageStack {" - " background-color: #FFFFFF; border: 0;" - " border-bottom-left-radius: 16px; border-bottom-right-radius: 16px;" - " }" - ) - workspace_layout.addWidget(self.stack, 1) - root.addWidget(self.workspace, 1) - # Deliberately no shadow layer here. The window is itself a rounded - # floating surface, so a shadow around the two panels inside it stacks a - # third rounded outline into a 13 px gutter and each window corner ends - # up showing three nested edges. Elevation belongs to the cards inside a - # page, where there is a real surface behind them to lift off. - - # Every override targets a chrome object by ID, so page fonts and - # dialogs remain independent of the reception appearance. - chrome_widgets = [self.sidebar, self.workspace, self.stack, self.topbar, - self.tabs_host, self.user_menu_button] - chrome_widgets.extend(self.topbar.findChildren(_PaintedIconButton)) - chrome_widgets.append(self.tabs_menu_button) - self._legacy_chrome_styles = { - widget: clinical_stylesheet(widget.styleSheet()) for widget in chrome_widgets - } - self._register_pages() - self.search_shortcut = QShortcut(QKeySequence("Ctrl+K"), self) - self.search_shortcut.activated.connect(self._focus_global_search) - - def _build_sidebar(self) -> QWidget: - sidebar = QWidget() - sidebar.setObjectName("Sidebar") - sidebar.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) - sidebar.setFixedWidth(_SHELL_EXPANDED_WIDTH) - sidebar.setStyleSheet( - """ - /* The rail is the ground, not a panel on it. It used to carry a - diagonal gradient against a flat canvas - canvas, so it never matched at any point along its own left edge - - a permanent faint seam down the window, and a second rounded - corner nested inside the window's own. Painting nothing lets the - canvas show through, which makes the two one surface and leaves - the bottom-most layer as the only thing with a corner. */ - QWidget#Sidebar { - background-color: transparent; - border: 0; - border-radius: 0; - } - QFrame#ShellBrand { - background-color: transparent; - border: 0; - border-radius: 0; - } - QLabel#ShellBrandName { color: #1A1C1F; font-size: 15px; font-weight: 600; } - QLabel#ShellBrandSubtitle { color: #6A6B6D; font-size: 12px; } - QPushButton#ShellNavButton { - min-height: 45px; - max-height: 45px; - padding: 0 14px; - margin: 0; - border: 1px solid transparent; - border-radius: 8px; - background-color: transparent; - color: #606163; - text-align: left; - font-size: 14px; - font-weight: 500; - } - QPushButton#ShellNavButton:hover { - background-color: #EEF1FA; - border-color: #DEE4F6; - color: #1A1C1F; - } - QPushButton#ShellNavButton:pressed { background-color: #E3E8F8; } - QPushButton#ShellNavButton:focus { border-color: #8B9AD9; } - QPushButton#ShellNavButton:checked { - color: #FFFFFF; - background-color: #4F63D9; - border-color: transparent; - font-weight: 500; - } - QPushButton#ShellNavButton:checked:hover { background-color: #4156C4; } - QPushButton#ShellNavButton:checked:pressed { background-color: #354BB4; } - QPushButton#ShellNavButton[collapsed="true"] { - padding: 0; - text-align: center; - margin: 0; - } - QFrame#ShellAssistantCard { - background-color: rgba(255, 255, 255, 230); - border: 1px solid #EDEDEE; - border-radius: 12px; - } - QLabel#ShellAssistantGlyph { - color: #4F63D9; - background-color: #EEF1FA; - border: 1px solid rgba(82, 101, 246, 48); - border-radius: 18px; - font-size: 13px; - font-weight: 600; - } - QLabel#ShellAssistantName { color: #1A1C1F; font-size: 13px; font-weight: 500; } - QLabel#ShellAssistantStatus { color: #287B65; font-size: 12px; } - QPushButton#ShellAssistantButton { - min-height: 34px; - color: #FFFFFF; - background-color: #4F63D9; - border: 0; - border-radius: 9px; - font-weight: 500; - } - QPushButton#ShellAssistantButton:hover { background-color: #4156C4; } - QPushButton#ShellAssistantButton:pressed { background-color: #354BB4; } - QPushButton#ShellSettingsButton { - min-height: 42px; - color: #606163; - font-size: 13px; - font-weight: 500; - background-color: transparent; - border: 1px solid transparent; - border-radius: 10px; - } - QPushButton#ShellSettingsButton:hover { - color: #1A1C1F; - background-color: #F0F0F0; - } - QPushButton#ShellSettingsButton:focus { border-color: #8B9AD9; } - """ - ) - layout = QVBoxLayout(sidebar) - layout.setContentsMargins(0, 0, 0, 0) - layout.setSpacing(0) - - brand = QFrame(sidebar) - self.brand = brand - brand.setObjectName("ShellBrand") - brand.setFixedHeight(75) - brand_layout = QHBoxLayout(brand) - self.brand_layout = brand_layout - brand_layout.setContentsMargins(21, 17, 10, 8) - brand_layout.setSpacing(10) - self.brand_mark = _ShellBrandMark(brand) - self.brand_mark.setObjectName("ShellBrandMark") - self.brand_mark.setFixedSize(36, 36) - brand_layout.addWidget(self.brand_mark) - self.brand_copy = QWidget(brand) - brand_copy_layout = QVBoxLayout(self.brand_copy) - brand_copy_layout.setContentsMargins(0, 0, 0, 0) - brand_copy_layout.setSpacing(1) - self.brand_name = QLabel("问诊中心", self.brand_copy) - self.brand_name.setObjectName("ShellBrandName") - brand_copy_layout.addWidget(self.brand_name) - self.brand_subtitle = QLabel("糖尿病专科版", self.brand_copy) - self.brand_subtitle.setObjectName("ShellBrandSubtitle") - brand_copy_layout.addWidget(self.brand_subtitle) - brand_layout.addWidget(self.brand_copy, 1) - layout.addWidget(brand) - - self.nav_layout = QVBoxLayout() - self.nav_layout.setContentsMargins(12, 19, 12, 0) - self.nav_layout.setSpacing(0) - layout.addLayout(self.nav_layout) - layout.addStretch(1) - - self.assistant_card = QFrame(sidebar) - self.assistant_card.setObjectName("ShellAssistantCard") - self.assistant_card.setFixedHeight(157) - assistant_layout = QVBoxLayout(self.assistant_card) - self.assistant_layout = assistant_layout - assistant_layout.setContentsMargins(12, 12, 12, 20) - assistant_layout.setSpacing(0) - assistant_head_host = QWidget(self.assistant_card) - assistant_head_host.setFixedHeight(60) - assistant_head = QHBoxLayout(assistant_head_host) - self.assistant_head_layout = assistant_head - assistant_head.setContentsMargins(0, 0, 0, 0) - assistant_head.setSpacing(9) - self.assistant_glyph = _AssistantRobot(assistant_head_host) - assistant_head.addWidget(self.assistant_glyph) - assistant_copy = QVBoxLayout() - assistant_copy.setContentsMargins(0, 5, 0, 5) - assistant_copy.setSpacing(1) - assistant_name = QLabel("AI 助手", self.assistant_card) - assistant_name.setObjectName("ShellAssistantName") - assistant_copy.addWidget(assistant_name) - self.assistant_status = _AssistantStatus("在线", assistant_head_host) - self.assistant_status.setObjectName("ShellAssistantStatus") - assistant_copy.addWidget(self.assistant_status) - assistant_head.addLayout(assistant_copy, 1) - assistant_layout.addWidget(assistant_head_host) - assistant_layout.addStretch(1) - self.assistant_button = QPushButton("开始对话", self.assistant_card) - self.assistant_button.setObjectName("ShellAssistantButton") - self.assistant_button.setCursor(Qt.CursorShape.PointingHandCursor) - self.assistant_button.setFixedHeight(36) - self.assistant_button.clicked.connect(self._open_ai_assistant) - assistant_layout.addWidget(self.assistant_button) - outer_assistant = QHBoxLayout() - self.assistant_outer_layout = outer_assistant - outer_assistant.setContentsMargins(13, 0, 13, 0) - outer_assistant.addWidget(self.assistant_card) - layout.addLayout(outer_assistant) - self.assistant_card.setVisible(self._can_ai_assistant) - - self.upload_settings_button = _ShellNavigationButton("设置 ›", sidebar) - self.upload_settings_button.setObjectName("ShellSettingsButton") - self.upload_settings_button.setAccessibleName("本机录音上传设置") - self.upload_settings_button.setToolTip("查看本机录音上传记录") - self.upload_settings_button.setCursor(Qt.CursorShape.PointingHandCursor) - self.upload_settings_button.setFixedHeight(76) - self.upload_settings_button.clicked.connect(self._open_local_audio_settings) - # Keep the former attribute as a compatibility alias for integrations - # that inspect the bottom sidebar control. - self.model_label = self.upload_settings_button - layout.addWidget(self.upload_settings_button) - return sidebar - - def _build_topbar(self) -> QWidget: - topbar = _ShellTopBar(self.workspace) - topbar.setObjectName("TopBar") - topbar.setFixedHeight(_SHELL_TOPBAR_HEIGHT) - topbar.setStyleSheet( - """ - QFrame#TopBar { - background-color: #FFFFFF; - border: 0; - border-bottom: 1px solid #F0F0F0; - border-top-left-radius: 16px; - border-top-right-radius: 16px; - } - QFrame#ShellGlobalSearch { - background-color: #FFFFFF; - border: 1px solid #EDEDEE; - border-radius: 10px; - } - QLineEdit#ShellGlobalSearchInput { - min-height: 34px; - max-height: 34px; - padding: 0 8px; - color: #606163; - background-color: transparent; - border: 0; - border-radius: 9px; - } - QLineEdit#ShellGlobalSearchInput QToolButton { - min-width: 22px; - max-width: 22px; - min-height: 18px; - max-height: 18px; - margin: 0; - padding: 0; - background-color: transparent; - border: 0; - border-radius: 0; - } - QLineEdit#ShellGlobalSearchInput QToolButton:hover, - QLineEdit#ShellGlobalSearchInput QToolButton:pressed, - QLineEdit#ShellGlobalSearchInput QToolButton:focus { - background-color: transparent; - border: 0; - } - QLabel#ShellShortcutHint { - color: #6A6B6D; - background-color: #F7F7F7; - border: 1px solid #EDEDEE; - border-radius: 6px; - padding: 2px 6px; - font-size: 10px; - } - QPushButton#ShellAiEntry { - min-width: 38px; - max-width: 38px; - min-height: 38px; - max-height: 38px; - padding: 0; - color: #4F63D9; - background-color: transparent; - border: 0; - border-radius: 9px; - font-weight: 500; - } - QPushButton#ShellAiEntry:hover { background-color: #EEF1FA; } - QLabel#ShellConnectionBadge { - color: #606163; - background-color: #FFFFFF; - border: 1px solid #EDEDEE; - border-radius: 10px; - padding: 4px 10px; - font-size: 13px; - font-weight: 500; - } - QLabel#ShellConnectionBadge[kind="success"] { - color: #287B65; - background-color: #E8F6F1; - border-color: #B9E3D7; - } - QLabel#ShellConnectionBadge[kind="danger"] { - color: #EC5266; - background-color: #FFF0F2; - border-color: #F4C4CC; - } - QToolButton#ShellPaintedIconButton[windowControl="close"]:hover { - background-color: #FFF0F2; - border-color: #F4C4CC; - } - QMenu { - color: #1A1C1F; - background-color: #FFFFFF; - border: 1px solid #EDEDEE; - border-radius: 10px; - padding: 6px; - } - QMenu::item { min-width: 112px; min-height: 32px; padding: 0 12px; border-radius: 6px; } - QMenu::item:selected { color: #1A1C1F; background-color: #EEF1FA; } - QMenu::item:disabled { color: #8E8F90; } - QMenu::separator { height: 1px; background: #EDEDEE; margin: 5px 8px; } - """ - ) - layout = QHBoxLayout(topbar) - layout.setContentsMargins(20, 0, 10, 0) - layout.setSpacing(5) - - self.fold_button = _PaintedIconButton("fold", size=38, parent=topbar) - self.fold_button.setToolTip("收起或展开菜单") - self.fold_button.setAccessibleName("收起或展开菜单") - self.fold_button.clicked.connect(self.toggle_sidebar) - layout.addWidget(self.fold_button) - layout.addSpacing(9) - self._fold_spacing = layout.itemAt(layout.count() - 1).spacerItem() - search_host = QFrame(topbar) - self.search_host = search_host - search_host.setObjectName("ShellGlobalSearch") - search_host.setFixedSize(265, 36) - search_layout = QHBoxLayout(search_host) - search_layout.setContentsMargins(4, 0, 7, 0) - search_layout.setSpacing(3) - self.search_mark = QToolButton(search_host) - self.search_mark.setObjectName("ShellSearchMark") - self.search_mark.setFixedSize(20, 20) - self.search_mark.setAutoRaise(True) - self.search_mark.setCursor(Qt.CursorShape.PointingHandCursor) - self.search_mark.setAccessibleName("搜索患者") - self.search_mark.setToolTip("搜索患者(回车)") - self.search_mark.setStyleSheet("background: transparent; border: 0; padding: 0;") - self.search_mark.clicked.connect(self._run_global_search) - self.search_mark.hide() - search_layout.addWidget(self.search_mark) - self.global_search = QLineEdit(search_host) - self.global_search.setObjectName("ShellGlobalSearchInput") - self.global_search.setSizePolicy( - QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed - ) - self.global_search.setPlaceholderText("搜索患者姓名、手机号...") - self.global_search.setToolTip("输入患者姓名或手机号,按回车或点击放大镜搜索") - self.global_search.setClearButtonEnabled(True) - self._global_search_icon_action = self.global_search.addAction( - _painted_shell_icon("search", 16), - QLineEdit.ActionPosition.LeadingPosition, - ) - self._global_search_icon_action.setToolTip("搜索患者(回车)") - self._global_search_icon_action.triggered.connect(self._run_global_search) - self.global_search.returnPressed.connect(self._run_global_search) - search_layout.addWidget(self.global_search, 1) - shortcut_hint = QLabel("Ctrl K", search_host) - self.search_shortcut_hint = shortcut_hint - shortcut_hint.setObjectName("ShellShortcutHint") - shortcut_hint.setAlignment(Qt.AlignmentFlag.AlignCenter) - shortcut_hint.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) - search_layout.addWidget(shortcut_hint, 0, Qt.AlignmentFlag.AlignVCenter) - layout.addWidget(search_host) - - self.context_label = QLabel("工作台", topbar) - self.context_label.setObjectName("ShellBreadcrumbCurrent") - self.context_label.hide() - layout.addStretch(1) - - self.refresh_button = _RefreshButton(size=38, parent=topbar) - self.refresh_button.setToolTip("刷新当前页面(F5)") - self.refresh_button.setAccessibleName("刷新当前页面") - self.refresh_button.set_busy_probe(self._current_page_is_loading) - self.refresh_button.clicked.connect(self.refresh_current_page) - layout.addWidget(self.refresh_button) - - self.ai_top_button = QPushButton("", topbar) - self.ai_top_button.setObjectName("ShellAiEntry") - self.ai_top_button.setIcon(_painted_shell_icon("ai", 18)) - self.ai_top_button.setIconSize(QSize(18, 18)) - self.ai_top_button.setCursor(Qt.CursorShape.PointingHandCursor) - self.ai_top_button.setToolTip("AI 助手") - self.ai_top_button.setAccessibleName("AI 助手") - self.ai_top_button.clicked.connect(self._open_ai_assistant) - layout.addWidget(self.ai_top_button) - self.ai_top_button.setVisible(self._can_ai_assistant) - - self.notification_button = _PaintedIconButton( - "notification", size=38, parent=topbar - ) - self.notification_button.setToolTip("消息通知") - self.notification_button.clicked.connect(self._show_chat_notification_summary) - layout.addWidget(self.notification_button) - self.settings_button = _PaintedIconButton("settings", size=38, parent=topbar) - self.settings_button.setToolTip("设置中心") - self.settings_button.clicked.connect( - lambda: show_toast(self, "设置中心将沿用当前账号的系统配置。", "info") - ) - layout.addWidget(self.settings_button) - self.user_separator = QFrame(topbar) - self.user_separator.setObjectName("ShellUserSeparator") - self.user_separator.setFixedSize(1, 44) - self.user_separator.hide() - layout.addWidget(self.user_separator) - - self.connection_badge = StatusBadge("服务正常", "success", topbar) - self.connection_badge.setObjectName("ShellConnectionBadge") - self.connection_badge.hide() - - display_name = display_text( - first_value( - self.current_user, - "name", - "display_name", - "nickname", - "account", - default="医生", - ) - ) - self.user_menu_button = _UserMenuButton(display_name, topbar) - self.user_menu_button.setToolTip(f"{display_name} · {self._role_text()}") - user_menu = QMenu(self.user_menu_button) - account_action = user_menu.addAction(self._role_text()) - account_action.setEnabled(False) - user_menu.addSeparator() - self.menu_sidebar_action = user_menu.addAction("收起或展开菜单") - self.menu_sidebar_action.triggered.connect(self.toggle_sidebar) - self.menu_sidebar_action.setVisible(False) - self.menu_ai_action = user_menu.addAction("AI 助手") - self.menu_ai_action.triggered.connect(self._open_ai_assistant) - self.menu_ai_action.setVisible(False) - if "1" in self._role_ids() and can_open_esign_doctor(self.repository, self.permissions): - user_menu.addAction("医生电子签署身份", self._open_esign_doctor) - update_action = user_menu.addAction("检查更新") - update_action.triggered.connect(self.update_check_requested.emit) - user_menu.addSeparator() - logout_action = user_menu.addAction("退出登录") - logout_action.triggered.connect(lambda: self.logout_requested.emit()) - self.user_menu_button.setMenu(user_menu) - layout.addWidget(self.user_menu_button) - - self.minimize_button = _PaintedIconButton("minimize", size=34, parent=topbar) - self.minimize_button.setToolTip("最小化") - self.minimize_button.clicked.connect(self.showMinimized) - layout.addWidget(self.minimize_button) - self.fullscreen_button = _PaintedIconButton( - "fullscreen", size=34, parent=topbar - ) - self.fullscreen_button.setToolTip("最大化") - self.fullscreen_button.setAccessibleName("切换最大化") - self.fullscreen_button.clicked.connect(self._toggle_maximized) - layout.addWidget(self.fullscreen_button) - self.close_button = _PaintedIconButton("close", size=34, parent=topbar) - self.close_button.setProperty("windowControl", "close") - self.close_button.setToolTip("关闭") - self.close_button.clicked.connect(self.close) - layout.addWidget(self.close_button) - return topbar - - def _build_tab_strip(self) -> QWidget: - tabs_host = QFrame() - tabs_host.setObjectName("MultipleTabs") - tabs_host.setFixedHeight(_SHELL_TABS_HEIGHT) - tabs_host.setStyleSheet( - """ - QFrame#MultipleTabs { - background-color: #FFFFFF; - border-top: 0; - border-bottom: 1px solid #E4E4E5; - } - QTabBar#ShellTabs { background-color: #FFFFFF; } - QTabBar#ShellTabs::tab { - min-height: 40px; - max-height: 40px; - min-width: 84px; - padding: 0 14px; - margin: 0 2px; - color: #606163; - background-color: transparent; - border: 0; - border-bottom: 2px solid transparent; - border-radius: 0; - font-size: 13px; - font-weight: 500; - } - QTabBar#ShellTabs::tab:hover { color: #1A1C1F; background-color: #F7F7F7; } - QTabBar#ShellTabs::tab:selected { - color: #4F63D9; - background-color: #EEF1FA; - border-bottom: 2px solid #4F63D9; - font-weight: 500; - } - QMenu { - color: #1A1C1F; - background-color: #FFFFFF; - border: 1px solid #E4E4E5; - border-radius: 10px; - padding: 6px; - } - QMenu::item { min-width: 112px; min-height: 32px; padding: 0 12px; border-radius: 6px; } - QMenu::item:selected { color: #1A1C1F; background-color: #EEF1FA; } - QMenu::item:disabled { color: #8E8F90; } - QMenu::separator { height: 1px; background: #E4E4E5; margin: 5px 8px; } - """ - ) - layout = QHBoxLayout(tabs_host) - layout.setContentsMargins(16, 0, 0, 0) - layout.setSpacing(0) - - self.tab_bar = QTabBar() - self.tab_bar.setObjectName("ShellTabs") - self.tab_bar.setDocumentMode(True) - self.tab_bar.setDrawBase(False) - self.tab_bar.setExpanding(False) - self.tab_bar.setUsesScrollButtons(True) - self.tab_bar.setElideMode(Qt.TextElideMode.ElideRight) - self.tab_bar.setSizePolicy( - QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed - ) - self.tab_bar.currentChanged.connect(self._tab_selected) - layout.addWidget(self.tab_bar, 1) - - self.tabs_menu_button = _PaintedIconButton("down") - self.tabs_menu_button.setToolTip("标签页操作") - self.tabs_menu_button.setAccessibleName("标签页操作") - self.tabs_menu_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) - tabs_menu = QMenu(self.tabs_menu_button) - self.close_current_action = tabs_menu.addAction("关闭当前") - self.close_current_action.triggered.connect(self.close_current_tab) - self.close_other_action = tabs_menu.addAction("关闭其他") - self.close_other_action.triggered.connect(self.close_other_tabs) - self.close_all_action = tabs_menu.addAction("关闭全部") - self.close_all_action.triggered.connect(self.close_all_tabs) - self.tabs_menu_button.setMenu(tabs_menu) - layout.addWidget(self.tabs_menu_button) - self._update_tab_actions() - tabs_host.hide() - return tabs_host - - def _role_text(self) -> str: - department = first_value( - self.current_user, "department_name", "department.name", default="" - ) - role_values = self._role_ids() - role = ( - "医生" - if "1" in role_values - else "医助" - if "2" in role_values - else "医疗人员" - ) - return f"{department} · {role}" if department else role - - def _role_ids(self) -> set[str]: - role_ids = first_value(self.current_user, "role_ids", "role_id", default=[]) or [] - if not isinstance(role_ids, (list, tuple, set, frozenset)): - role_ids = [role_ids] - return {str(value) for value in role_ids} - - def toggle_sidebar(self) -> None: - """Toggle the admin-style compact menu while preserving the page state.""" - - self._sidebar_collapsed = not self._sidebar_collapsed - self.sidebar.setFixedWidth( - _SHELL_COLLAPSED_WIDTH - if self._sidebar_collapsed - else self._expanded_sidebar_width() - ) - self.brand_copy.setVisible(not self._sidebar_collapsed) - self.assistant_card.setVisible( - self._can_ai_assistant and not self._sidebar_collapsed - ) - self.upload_settings_button.setVisible(not self._sidebar_collapsed) - margins = self._navigation_margins() - self.nav_layout.setContentsMargins(*margins) - self.fold_button.kind = "expand" if self._sidebar_collapsed else "fold" - self.fold_button.setIcon( - _painted_shell_icon(self.fold_button.kind, reception=self._reception_chrome_active) - ) - for button in self.nav_buttons.values(): - title = str(button.property("navTitle") or "") - button.setText("" if self._sidebar_collapsed else title) - button.setToolTip(title if self._sidebar_collapsed else "") - button.setProperty("collapsed", self._sidebar_collapsed) - button.style().unpolish(button) - button.style().polish(button) - self._set_reception_geometry(self._reception_chrome_active) - - def _expanded_sidebar_width(self, key: str | None = None) -> int: - reception = key in _TECH_BLUE_PAGES if key is not None else self._reception_chrome_active - return _RECEPTION_SIDEBAR_WIDTH if reception else _SHELL_EXPANDED_WIDTH - - def _navigation_margins(self) -> tuple[int, int, int, int]: - if self._sidebar_collapsed: - return (7, 19 if self._reception_chrome_active else 14, 7, 0) - return (9, 19, 10, 0) if self._reception_chrome_active else (12, 19, 12, 0) - - def _set_reception_geometry(self, active: bool) -> None: - """Keep the approved geometry page-local, including compact-rail state.""" - - gutter = 0 if active else _SHELL_OUTER_GUTTER - self.centralWidget().layout().setContentsMargins(gutter, gutter, gutter, gutter) - self.sidebar.setFixedWidth( - _SHELL_COLLAPSED_WIDTH if self._sidebar_collapsed else self._expanded_sidebar_width() - ) - self.topbar.setFixedHeight(_RECEPTION_TOPBAR_HEIGHT if active else _SHELL_TOPBAR_HEIGHT) - self.brand.setFixedHeight(80 if active else 75) - brand_margins = (26, 14, 10, 9) if active else (21, 17, 10, 8) - if active and self._sidebar_collapsed: - brand_margins = (15, 14, 15, 9) - self.brand_layout.setContentsMargins(*brand_margins) - self.brand_layout.setSpacing(13 if active else 10) - self.brand_mark.setFixedSize(38 if active else 36, 38 if active else 36) - self.nav_layout.setContentsMargins(*self._navigation_margins()) - self.nav_layout.setSpacing(4 if active else 0) - self.assistant_card.setFixedHeight(132 if active else 157) - self.assistant_layout.setContentsMargins(*(13, 12, 13, 12) if active else (12, 12, 12, 20)) - self.assistant_head_layout.setContentsMargins(4 if active else 0, 0, 0, 0) - self.assistant_head_layout.setSpacing(8 if active else 9) - self.assistant_glyph.setFixedSize(48 if active else 56, 48 if active else 56) - self.assistant_outer_layout.setContentsMargins(*(20, 0, 20, 0) if active else (13, 0, 13, 0)) - self.assistant_status.setFixedHeight(18) - self.assistant_button.setFixedHeight(36 if active else 34) - self.upload_settings_button.setFixedHeight(52 if active else 44) - self.upload_settings_button.setIcon(_painted_shell_icon("settings", 20, reception=True) if active else QIcon()) - self.upload_settings_button.setIconSize(QSize(20, 20) if active else QSize(16, 16)) - self.upload_settings_button.setText("设置 ›" if active else "设置 ›") - self.topbar.layout().setContentsMargins(*(26, 0, 8, 0) if active else (20, 0, 10, 0)) - self.topbar.layout().setSpacing(7 if active else 5) - self.fold_button.setVisible(not active) - self._fold_spacing.changeSize(0 if active else 9, 0) - self.search_host.setFixedSize(QSize(384, 44) if active else QSize(265, 36)) - self.search_host.layout().setContentsMargins(*(20, 0, 9, 0) if active else (4, 0, 7, 0)) - self.search_host.layout().setSpacing(6 if active else 3) - self.search_mark.setVisible(active) - self._global_search_icon_action.setVisible(not active) - self.global_search.setPlaceholderText("搜索患者姓名、手机号...") - self.search_shortcut_hint.setText("Ctrl K") - self.ai_top_button.setVisible(self._can_ai_assistant and not active) - self.menu_sidebar_action.setVisible(active) - self.menu_ai_action.setVisible(active and self._can_ai_assistant) - self.user_separator.setVisible(active) - if active: - self.user_menu_button.setFixedSize(179, _RECEPTION_TOPBAR_HEIGHT) - elif hasattr(self, "_legacy_user_menu_size"): - self.user_menu_button.setFixedSize(self._legacy_user_menu_size) - self.topbar.layout().invalidate() - self._fit_reception_search() - - def _fit_reception_search(self) -> None: - if not self._reception_chrome_active: - return - # Preserve every user/window action at the supported 1024 px minimum; - # the approved 384 px field fits unchanged at 1280 px and above. - controls_width = 26 + 8 + 3 * 50 + 179 + 3 * 34 + 1 + 8 * 7 - width = self.width() - self.sidebar.width() - controls_width - self.search_host.setFixedWidth(min(384, max(220, width))) - - def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - super().resizeEvent(event) - if getattr(self, "_reception_chrome_active", False): - self._fit_reception_search() - - def _set_reception_chrome(self, active: bool) -> None: - """Apply approved pages' shared chrome and restore the exact legacy QSS.""" - - if active == self._reception_chrome_active: - return - if active: - # Qt styles can adjust a fixed control by its border width during - # polish; restore the effective size that the user actually saw. - self._legacy_user_menu_size = self.user_menu_button.size() - self._reception_chrome_active = active - replacements = { - "#4F63D9": TECH_BLUE["accent"], - "#4156C4": TECH_BLUE["accent_hover"], - "#354BB4": TECH_BLUE["accent_pressed"], - "#EEF1FA": TECH_BLUE["selection"], - "#E3E8F8": TECH_BLUE["selection"], - "#DEE4F6": TECH_BLUE["line"], - "#8B9AD9": TECH_BLUE["focus"], - "#1A1C1F": TECH_BLUE["heading"], - "#606163": TECH_BLUE["text"], - "#6A6B6D": TECH_BLUE["muted"], - "#F7F7F7": TECH_BLUE["raised"], - "#F0F0F0": TECH_BLUE["line"], - "#EDEDEE": TECH_BLUE["line"], - "#E4E4E5": TECH_BLUE["line"], - "#287B65": TECH_BLUE["selected_text"], - "#E8F6F1": TECH_BLUE["selection"], - "#B9E3D7": TECH_BLUE["line"], - } - for widget, original in self._legacy_chrome_styles.items(): - stylesheet = original - if active: - for old_color, new_color in replacements.items(): - stylesheet = stylesheet.replace(old_color, new_color) - if widget in (self.sidebar, self.topbar, self.tabs_host): - stylesheet += f""" - QWidget {{ font-family: "{body_family()}"; font-weight: 400; }} - """ - if widget is self.sidebar: - stylesheet += f""" - QWidget#Sidebar {{ - background-color: {_RECEPTION_SIDEBAR_COLOR}; - border-right: 1px solid {_RECEPTION_CHROME_LINE}; - }} - QLabel#ShellBrandName {{ - font-family: "{heading_family()}"; font-weight: 600; - color: {TECH_BLUE['heading']}; font-size: {TYPE['fs_section']}; - }} - QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['muted']}; font-size: {TYPE['fs_small']}; }} - QPushButton#ShellNavButton {{ - font-family: "{body_family()}"; font-weight: 400; - min-height: 44px; max-height: 44px; - border: 0; border-left: 5px solid transparent; - border-radius: {METRICS["r_md"]}; - padding: 0 16px; font-size: {TYPE['fs_body']}; - color: {TECH_BLUE['text']}; - }} - QPushButton#ShellNavButton:checked, - QPushButton#ShellNavButton:checked:hover, - QPushButton#ShellNavButton:checked:pressed {{ - color: {TECH_BLUE['selected_text']}; - background-color: {TECH_BLUE['selection']}; - border-left: 5px solid {TECH_BLUE['accent']}; - font-weight: 400; - }} - QPushButton#ShellNavButton:focus {{ - border: 1px solid {TECH_BLUE['focus']}; - border-left: 5px solid {TECH_BLUE['accent']}; - }} - QPushButton#ShellNavButton[collapsed="true"] {{ padding: 0; }} - QFrame#ShellAssistantCard {{ - background-color: {TECH_BLUE['surface']}; border-radius: {METRICS["r_lg"]}; - border: 1px solid {_RECEPTION_CHROME_LINE}; - }} - QLabel#ShellAssistantName {{ - font-family: "{heading_family()}"; font-weight: 500; font-size: {TYPE['fs_body']}; - }} - QLabel#ShellAssistantStatus {{ - font-size: {TYPE['fs_small']}; - }} - QPushButton#ShellAssistantButton, QPushButton#ShellSettingsButton {{ - font-family: "{body_family()}"; font-weight: 400; font-size: {TYPE['fs_body']}; - }} - QPushButton#ShellAssistantButton {{ border-radius: {METRICS["r_md"]}; }} - QPushButton#ShellSettingsButton {{ - min-height: 50px; max-height: 50px; - text-align: left; padding: 0 32px; - }} - QPushButton#ShellAssistantButton:focus {{ - border: 2px solid {TECH_BLUE['focus']}; - }} - """ - if widget is self.topbar: - stylesheet += f""" - QFrame#TopBar {{ - border-radius: 0; - border-bottom: 1px solid {_RECEPTION_CHROME_LINE}; - }} - QFrame#ShellGlobalSearch {{ background-color: {PALETTE["surface_alt"]}; border: 1px solid transparent; border-radius: {METRICS["r_md"]}; }} - QFrame#ShellUserSeparator {{ background: {_RECEPTION_CHROME_LINE}; border: 0; }} - QLabel#ShellShortcutHint {{ - font-family: "{number_family()}"; font-size: {TYPE['fs_small']}; - padding: 4px 9px; border-radius: 4px; - border: 1px solid {_RECEPTION_CHROME_LINE}; - }} - QLineEdit#ShellGlobalSearchInput {{ - color: {TECH_BLUE['text']}; font-size: {TYPE['fs_body']}; - min-height: 40px; max-height: 40px; - }} - QPushButton#ShellAiEntry:pressed {{ background: {TECH_BLUE['selection']}; }} - QPushButton#ShellAiEntry:focus {{ border: 1px solid {TECH_BLUE['focus']}; }} - QLabel#ShellConnectionBadge {{ font-weight: 400; }} - """ - if widget is self.user_menu_button: - stylesheet += f""" - QToolButton#ShellUserMenu {{ - font-family: "{body_family()}"; font-weight: 400; - color: {TECH_BLUE['heading']}; font-size: 13px; - }} - """ - if widget is self.workspace: - stylesheet += "QWidget#ShellWorkspace { border-radius: 0; }" - if widget is self.stack: - stylesheet += "QStackedWidget#ShellPageStack { border-radius: 0; }" - if isinstance(widget, _PaintedIconButton): - side = 50 if widget in (self.refresh_button, self.notification_button, self.settings_button) else 34 - stylesheet += f"QToolButton#ShellPaintedIconButton {{ min-width: {side - 2}px; max-width: {side - 2}px; min-height: {side - 2}px; max-height: {side - 2}px; }}" - widget.setStyleSheet(clinical_stylesheet(stylesheet)) - - self._set_reception_geometry(active) - for widget in ( - self.centralWidget(), self.brand_mark, self.assistant_glyph, self.assistant_status, - self.upload_settings_button, - ): - widget.setProperty("receptionTechBlue", active) - widget.update() - self.user_menu_button.set_reception_avatar(active) - for widget in self.topbar.findChildren(_PaintedIconButton): - size = 20 if active else 18 - widget.setIconSize(QSize(size, size)) - if isinstance(widget, _RefreshButton): - widget.set_reception_palette(active) - else: - widget.setIcon(_painted_shell_icon(widget.kind, size, reception=active)) - self.ai_top_button.setIcon(_painted_shell_icon("ai", reception=active)) - self._global_search_icon_action.setIcon( - _painted_shell_icon("search", 20 if active else 16, reception=active) - ) - self.search_mark.setIcon(_painted_shell_icon("search", 20, reception=True)) - self.search_mark.setIconSize(QSize(20, 20)) - for key, button in self.nav_buttons.items(): - size = 20 if active else 18 - button.setProperty("receptionTechBlue", active) - button.setIconSize(QSize(size, size)) - button.setIcon(_painted_navigation_icon(key, size, reception=active)) - button.update() - - def _toggle_maximized(self) -> None: - if self.isMaximized(): - self.showNormal() - self.fullscreen_button.setToolTip("最大化") - else: - self.showMaximized() - self.fullscreen_button.setToolTip("还原") - - def _toggle_fullscreen(self) -> None: - if self.isFullScreen(): - self.showNormal() - self.fullscreen_button.setToolTip("全屏模式") - else: - self.showFullScreen() - self.fullscreen_button.setToolTip("退出全屏") - - def _focus_global_search(self) -> None: - self.global_search.setFocus(Qt.FocusReason.ShortcutFocusReason) - self.global_search.selectAll() - - def _run_global_search(self) -> None: - query = self.global_search.text().strip() - keys = ("patients", "consultations") if self._active_page_key == "patients" else ( - "consultations", "patients", - ) - for key in keys: - # Only use patient pages already registered by permission-aware navigation. - page = self.pages.get(key) - search = getattr(page, "search_patient", None) - if page is None or key not in self.nav_buttons or not callable(search): - continue - self._navigate( - self.stack.indexOf(page), key, on_activate=lambda search=search: search(query), - ) - return - show_toast(self, "当前账号没有可用的患者搜索页面。", "warning") - - def _open_ai_assistant(self) -> None: - if not self._can_ai_assistant: - show_toast(self, "当前账号没有使用 AI 问诊助手的权限。", "danger") - return - - # The shell assistant is the global entry point. Always let the doctor - # choose from the complete permission-scoped patient list, even when a - # page happens to retain a selected row. Page-level AI actions keep the - # faster "open the selected patient" behaviour. - select_and_present_ai_consult( - self.repository, - self.permissions, - self, - initial_query=self.global_search.text().strip(), - ) - - def _open_esign_doctor(self) -> None: - dialog = EsignDoctorDialog(self.repository, parent=self) - dialog.exec() - dialog.deleteLater() - - def _open_local_audio_settings(self) -> None: - current = self._local_audio_settings_dialog - if current is not None and current.isVisible(): - current.raise_() - current.activateWindow() - return - try: - dialog = LocalAudioQueueDialog(self.repository, None, self) - except (OSError, RuntimeError, ValueError, sqlite3.Error) as error: - show_toast(self, f"无法打开本机录音上传设置:{error}", "error") - return - self._local_audio_settings_dialog = dialog - - def clear_dialog(_result: int) -> None: - if self._local_audio_settings_dialog is dialog: - self._local_audio_settings_dialog = None - - dialog.finished.connect(clear_dialog) - dialog.open() - - def _tab_index_for_key(self, key: str) -> int: - for index in range(self.tab_bar.count()): - if self.tab_bar.tabData(index) == key: - return index - return -1 - - def visited_tab_keys(self) -> tuple[str, ...]: - """Return open tabs in visit order for tests and session diagnostics.""" - - return tuple( - str(self.tab_bar.tabData(index)) for index in range(self.tab_bar.count()) - ) - - def _ensure_tab(self, key: str, title: str) -> int: - index = self._tab_index_for_key(key) - if index >= 0: - self.tab_bar.setTabText(index, title) - return index - index = self.tab_bar.addTab(title) - self.tab_bar.setTabData(index, key) - if self._fixed_tab_key is None: - self._fixed_tab_key = key - else: - close_button = _PaintedIconButton("close", size=18, parent=self.tab_bar) - close_button.setToolTip(f"关闭 {title}") - close_button.setAccessibleName(f"关闭标签页:{title}") - close_button.clicked.connect( - lambda _checked=False, page_key=key: self.close_tab(page_key) - ) - self.tab_bar.setTabButton( - index, QTabBar.ButtonPosition.RightSide, close_button - ) - self._update_tab_actions() - return index - - def _set_current_tab(self, key: str) -> None: - index = self._tab_index_for_key(key) - if index < 0: - return - blocked = self.tab_bar.blockSignals(True) - self.tab_bar.setCurrentIndex(index) - self.tab_bar.blockSignals(blocked) - self._update_tab_actions() - - def _tab_selected(self, index: int) -> None: - if index < 0: - return - key = str(self.tab_bar.tabData(index) or "") - page = self.pages.get(key) - if page is None: - return - self._navigate(self.stack.indexOf(page), key) - - def _update_tab_actions(self) -> None: - if not hasattr(self, "close_current_action"): - return - current_index = self.tab_bar.currentIndex() - current_key = ( - str(self.tab_bar.tabData(current_index) or "") if current_index >= 0 else "" - ) - removable = [ - key for key in self.visited_tab_keys() if key != self._fixed_tab_key - ] - self.close_current_action.setEnabled( - bool(current_key and current_key != self._fixed_tab_key) - ) - self.close_other_action.setEnabled(any(key != current_key for key in removable)) - self.close_all_action.setEnabled(bool(removable)) - - def close_tab(self, key: str) -> bool: - """Close one non-fixed visited page and re-route if it was active.""" - - index = self._tab_index_for_key(key) - if index < 0 or key == self._fixed_tab_key: - return False - active_key = "" - if self.tab_bar.currentIndex() >= 0: - active_key = str(self.tab_bar.tabData(self.tab_bar.currentIndex()) or "") - keys = list(self.visited_tab_keys()) - fallback = keys[index - 1] if index > 0 else keys[index + 1] - - close_button = self.tab_bar.tabButton(index, QTabBar.ButtonPosition.RightSide) - blocked = self.tab_bar.blockSignals(True) - self.tab_bar.removeTab(index) - self.tab_bar.blockSignals(blocked) - if close_button is not None: - close_button.deleteLater() - - if active_key == key: - self.navigate(fallback) - else: - self._set_current_tab(active_key) - self._update_tab_actions() - return True - - def close_current_tab(self) -> bool: - index = self.tab_bar.currentIndex() - if index < 0: - return False - return self.close_tab(str(self.tab_bar.tabData(index) or "")) - - def close_other_tabs(self) -> None: - current_index = self.tab_bar.currentIndex() - current_key = ( - str(self.tab_bar.tabData(current_index) or "") if current_index >= 0 else "" - ) - keep = {current_key, self._fixed_tab_key} - for key in reversed(self.visited_tab_keys()): - if key not in keep: - self.close_tab(key) - if current_key: - self._set_current_tab(current_key) - self._update_tab_actions() - - def close_all_tabs(self) -> None: - for key in reversed(self.visited_tab_keys()): - if key != self._fixed_tab_key: - self.close_tab(key) - if self._fixed_tab_key: - self.navigate(self._fixed_tab_key) - self._update_tab_actions() - - def _register_pages(self) -> None: - self.nav_group = QButtonGroup(self) - self.nav_group.setExclusive(True) - first_button: QPushButton | None = None - for item, title in self.navigation: - page = item.page_type( - self.repository, - permissions=self.permissions, - current_user=self.current_user, - parent=self.stack, - ) - self._install_activation_refresh_gate(page) - if hasattr(page, "video_requested"): - page.video_requested.connect( - lambda payload: self.video_requested.emit(payload) - ) - index = self.stack.addWidget(page) - self.pages[item.key] = page - self.page_titles[index] = title - - button = _ShellNavigationButton(title) - button.setObjectName("ShellNavButton") - button.setIcon(_painted_navigation_icon(item.key)) - button.setIconSize(QSize(18, 18)) - button.setProperty("navGlyph", item.glyph) - button.setProperty("navTitle", title) - button.setCheckable(True) - button.setCursor(Qt.CursorShape.PointingHandCursor) - button.clicked.connect( - lambda _checked=False, page_index=index, key=item.key: self._navigate( - page_index, key - ) - ) - self.nav_group.addButton(button, index) - self.nav_layout.addWidget(button) - self.nav_buttons[item.key] = button - if first_button is None: - first_button = button - - if first_button is None: - denied = EmptyState( - "暂无可用工作区", - "当前账号没有医生工作站页面权限,请联系管理员调整授权。", - ) - index = self.stack.addWidget(denied) - self.page_titles[index] = "权限受限" - self.stack.setCurrentIndex(index) - self.context_label.setText("权限受限") - return - first_button.setChecked(True) - first_index = self.nav_group.id(first_button) - self._navigate( - first_index, - next( - key - for key, button in self.nav_buttons.items() - if button is first_button - ), - ) - - def _install_activation_refresh_gate(self, page: QWidget) -> None: - """Coalesce lifecycle and shell refreshes during one page activation.""" - - refresh = getattr(page, "refresh", None) - if not callable(refresh): - return - - @wraps(refresh) - def activation_refresh(*args: Any, **kwargs: Any) -> Any: - if page is self._activation_page: - if self._activation_refreshed: - return None - self._activation_refreshed = True - return refresh(*args, **kwargs) - - page.refresh = activation_refresh # type: ignore[attr-defined,method-assign] - - def _ensure_activation_refresh(self, page: QWidget, generation: int) -> None: - if generation != self._activation_generation or page is not self._activation_page: - return - if not self._activation_refreshed: - refresh = getattr(page, "refresh", None) - if callable(refresh): - refresh() - - def _finish_activation(self, page: QWidget, generation: int) -> None: - if generation != self._activation_generation or page is not self._activation_page: - return - self._ensure_activation_refresh(page, generation) - self._activation_page = None - - def _navigate( - self, index: int, key: str, *, on_activate: Callable[[], None] | None = None, - ) -> None: - if index < 0 or index >= self.stack.count(): - return - page = self.stack.widget(index) - if page is None: - return - if self._active_page_key == key and self.stack.currentWidget() is page: - if on_activate is not None: - self._activation_refreshed = False - on_activate() - return - self._activation_generation += 1 - activation_generation = self._activation_generation - self._activation_page = page - self._activation_refreshed = False - if on_activate is not None: - on_activate() - # A stack swap is otherwise a hard cut between two frames: this is the - # transition a doctor sees on every sidebar click all day. - motion.switch_stack(self.stack, index) - title = self.page_titles.get(index, "工作台") - self.context_label.setText(title) - self._ensure_tab(key, title) - self._set_current_tab(key) - button = self.nav_buttons.get(key) - if button is not None: - button.setChecked(True) - self._active_page_key = key - self._set_reception_chrome(key in _TECH_BLUE_PAGES) - self._ensure_activation_refresh(page, activation_generation) - if self.isVisible(): - QTimer.singleShot( - 0, - lambda page=page, generation=activation_generation: self._finish_activation( - page, generation - ), - ) - self.page_changed.emit(key) - - def navigate(self, key: str) -> bool: - """Navigate to a visible page by stable key; return whether it exists.""" - - button = self.nav_buttons.get(key) - page = self.pages.get(key) - if button is None or page is None: - return False - self._navigate(self.stack.indexOf(page), key) - return True - - #: Attributes the pages use to say "a request is in flight". Nothing forces - #: a page to have one, so a page without any of these simply gets the - #: minimum spin rather than an accurate one. - _LOADING_FLAGS = ("_loading", "_queue_loading", "_detail_loading") - - def _current_page_is_loading(self) -> bool: - page = self.stack.currentWidget() - return any(bool(getattr(page, flag, False)) for flag in self._LOADING_FLAGS) - - def refresh_current_page(self) -> None: - page = self.stack.currentWidget() - refresh = getattr(page, "refresh", None) - if not callable(refresh): - return - button = getattr(self, "refresh_button", None) - if isinstance(button, _RefreshButton): - button.start_spin() - refresh() - - def _ensure_global_diagnosis_dialog(self) -> DiagnosisDialog: - dialog = self._global_diagnosis_dialog - if dialog is None: - dialog = DiagnosisDialog( - self.repository, - self, - permissions=self.permissions, - ) - dialog.saved.connect(self.refresh_current_page) - self._global_diagnosis_dialog = dialog - else: - dialog.refresh_permissions(self.permissions) - return dialog - - def open_diagnosis_by_id( - self, - diagnosis_id: Any, - *, - modeless: bool = False, - ) -> DiagnosisDialog | None: - """Open one authoritative diagnosis in the strongest permitted mode.""" - - try: - normalized_id = int(diagnosis_id) - except (TypeError, ValueError): - normalized_id = 0 - if normalized_id <= 0: - show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600) - return None - - if has_permission(self.permissions, "tcm.diagnosis/edit", default=False): - dialog = self._ensure_global_diagnosis_dialog() - dialog.open_for(normalized_id, editable=True, modeless=modeless) - elif has_permission( - self.permissions, - "tcm.diagnosis/readonlyDetail", - default=False, - ): - dialog = self._ensure_global_diagnosis_dialog() - dialog.open_view_only(normalized_id, modeless=modeless) - else: - show_toast(self, "当前账号没有查看该诊单的权限。", "danger", 4200) - return None - - dialog.raise_() - dialog.activateWindow() - return dialog - - def showEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - super().showEvent(event) - # 登录后就开始轮询:不管医生停在哪个页面,患者进入会话都要提示。 - self.chat_notifications.start() - page = self.stack.currentWidget() - if page is None or page is not self._activation_page: - return - generation = self._activation_generation - QTimer.singleShot( - 0, - lambda page=page, generation=generation: self._finish_activation(page, generation), - ) - - def closeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - self.chat_notifications.stop() - super().closeEvent(event) - if event.isAccepted(): - self.close_requested.emit() - - def _open_chat_notification(self, notification: ChatNotification) -> None: - """Take the doctor where the notification's work actually lives.""" - - if notification.kind == CONSULTATION_COMPLETE and notification.diagnosis_id > 0: - self.open_diagnosis_by_id(notification.diagnosis_id, modeless=True) - return - if notification.kind == PATIENT_OPENED_CHAT and self.navigate("reception"): - return - show_toast(self, notification.description, "info", 4200) - - def _show_chat_notification_summary(self) -> None: - pending = self.chat_notifications.pending - if not pending: - show_toast(self, "当前没有新的系统通知。", "info") - return - latest = pending[0] - show_toast( - self, - f"待处理通知 {len(pending)} 条,最新:{latest.title} · {latest.description}", - "info", - 4200, - ) - - def setVisible(self, visible: bool) -> None: # noqa: N802 - Qt API - if visible: - self.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, False) - super().setVisible(visible) - - def set_connection_state(self, online: bool, message: str = "") -> None: - self.connection_badge.set_status( - message or ("服务正常" if online else "连接中断"), - "success" if online else "danger", - ) - self.assistant_status.setText("在线" if online else "服务离线") - self.assistant_status.set_online(online) - - -__all__ = ["NAVIGATION", "NavigationItem", "ShellWindow"] +"""Authenticated application shell with permission-aware navigation.""" + +from __future__ import annotations + +import sqlite3 +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from functools import wraps +from typing import Any + +from PySide6.QtCore import ( + QElapsedTimer, + QEvent, + QPointF, + QRectF, + QSize, + Qt, + QTimer, + Signal, +) +from PySide6.QtGui import ( + QColor, + QFont, + QIcon, + QKeySequence, + QLinearGradient, + QMouseEvent, + QPainter, + QPainterPath, + QPen, + QPixmap, + QShortcut, +) +from PySide6.QtWidgets import ( + QApplication, + QButtonGroup, + QFrame, + QHBoxLayout, + QLabel, + QLineEdit, + QMainWindow, + QMenu, + QPushButton, + QSizePolicy, + QStackedWidget, + QStyle, + QStyleOptionButton, + QTabBar, + QToolButton, + QVBoxLayout, + QWidget, +) + +from doctor_workstation.resources import app_icon_path + +from . import icons, motion +from .chat_notifications import ( + CONSULTATION_COMPLETE, + PATIENT_OPENED_CHAT, + ChatNotification, + ChatNotificationCenter, +) +from .command_palette import CommandEntry, CommandPaletteDialog +from .design_system import PALETTE, clinical_stylesheet +from .dialogs.ai_consult import can_open_ai_consult +from .dialogs.ai_consult_picker import select_and_present_ai_consult +from .dialogs.diagnosis import DiagnosisDialog +from .dialogs.esign_doctor import EsignDoctorDialog +from .dialogs.local_audio_queue import LocalAudioQueueDialog +from .dialogs.prescription_esign import can_open_esign_doctor +from .pages import ( + AppointmentsPage, + ConsultationsPage, + PatientsPage, + PrescriptionLibraryPage, + PrescriptionsPage, + ReceptionPage, +) +from .reception_style import TECH_BLUE, body_family, heading_family, number_family +from .theme import COLORS, TYPE, crisp_pixmap +from .widgets import ( + EmptyState, + StatusBadge, + display_text, + first_value, + get_value, + has_permission, + show_toast, +) +from .window_primitives import ClinicalAccentBar + +_SHELL_EXPANDED_WIDTH = 190 +_SHELL_COLLAPSED_WIDTH = 68 +_SHELL_TOPBAR_HEIGHT = 62 +_SHELL_TABS_HEIGHT = 0 +_SHELL_OUTER_GUTTER = 13 +_SHELL_PANEL_GAP = 0 +_SHELL_DESIGN_SIZE = QSize(1710, 920) +_SHELL_MINIMUM_SIZE = QSize(1024, 640) +_RECEPTION_SIDEBAR_WIDTH = 208 +_RECEPTION_TOPBAR_HEIGHT = 60 +_RECEPTION_SIDEBAR_COLOR = PALETTE["sidebar"] +_RECEPTION_CHROME_LINE = PALETTE["line"] +# Approved pages share one chrome state, so navigation among them keeps it intact. +_TECH_BLUE_PAGES = frozenset({"appointments", "consultations", "patients", "prescriptions", "prescription_library", "reception"}) + + +def _bounded_initial_window_size(available_size: QSize | None) -> QSize: + """Fit the design viewport inside the screen's logical available geometry.""" + + if available_size is None or not available_size.isValid(): + return QSize(_SHELL_DESIGN_SIZE.width(), _SHELL_DESIGN_SIZE.height()) + return QSize( + max( + _SHELL_MINIMUM_SIZE.width(), + min(_SHELL_DESIGN_SIZE.width(), available_size.width()), + ), + max( + _SHELL_MINIMUM_SIZE.height(), + min(_SHELL_DESIGN_SIZE.height(), available_size.height()), + ), + ) + + +@dataclass(frozen=True) +class NavigationItem: + key: str + title: str + glyph: str + page_type: type[QWidget] + permissions: tuple[str, ...] + + +NAVIGATION = ( + NavigationItem( + # 挂号与诊单是两条独立队列,早期两项都叫“问诊列表”,侧边栏出现两个同名 + # 入口,医生无法判断该点哪个。按各自的业务对象命名以消除歧义。 + "appointments", + "挂号列表", + "号", + AppointmentsPage, + ("doctor.appointment/lists",), + ), + NavigationItem( + "reception", + "接诊台", + "◎", + ReceptionPage, + ("doctor.appointment/lists",), + ), + NavigationItem( + "prescription_library", + "处方库", + "方", + PrescriptionLibraryPage, + ("tcm.prescriptionLibrary/lists",), + ), + NavigationItem( + "prescriptions", + "已开处方", + "笺", + PrescriptionsPage, + ("tcm.prescription/lists",), + ), + NavigationItem( + "patients", + "我的患者", + "患", + PatientsPage, + ("firstvisit.myPatient/lists",), + ), + NavigationItem( + "consultations", + "问诊列表", + "询", + ConsultationsPage, + ("tcm.diagnosis/lists",), + ), +) + + +# Shared ``doctor.appointment/lists`` is intentionally mapped only to reception; +# the appointment list page is resolved by menu route/component identity. +_NAVIGATION_BY_PERMISSION = { + item.permissions[0]: item for item in NAVIGATION if item.key != "appointments" +} +_MENU_ROUTE_IDENTIFIERS = { + "reception": { + "reception", + "patient/reception", + "patient/reception/index", + }, + "appointments": { + "appointments", + "tcm/appointment", + "tcm/appointment/list", + "appointment/list", + }, + "prescription_library": { + "prescription-library", + "prescription_library", + "consumer/prescription/list", + }, + "prescriptions": { + "prescriptions", + "consumer/prescription/index", + }, + "patients": { + "patients", + "first_visit/my_patients", + "first_visit/my_patients/index", + }, + "consultations": { + "consultations", + "tcm/diagnosis", + "tcm/diagnosis/index", + }, +} + + +def _canonical_allowed(permissions: Any, code: str) -> bool: + """Apply the core exact/wildcard semantics without slash-dot aliases.""" + + if permissions is None: + return True + for method_name in ("allows", "has", "can_access_page", "has_page", "can"): + method = getattr(permissions, method_name, None) + if callable(method): + try: + return bool(method(code)) + except (TypeError, ValueError): + continue + raw = permissions + for attr in ("codes", "permissions", "values"): + candidate = getattr(permissions, attr, None) + if candidate is not None and not callable(candidate): + raw = candidate + break + if isinstance(raw, Mapping): + nested = first_value(raw, "codes", "permissions", "values", default=None) + if nested is not None: + raw = nested + if isinstance(raw, Mapping): + available = {str(key) for key, enabled in raw.items() if enabled} + elif isinstance(raw, str): + available = {raw} + else: + try: + available = {str(value) for value in raw} + except TypeError: + return False + if "*" in available or code in available: + return True + return any( + grant.endswith("/*") and code.startswith(grant[:-1]) for grant in available + ) + + +def _menu_rows(value: Any) -> list[Mapping[str, Any]]: + if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)): + return [] + return [row for row in value if isinstance(row, Mapping)] + + +def _menu_visible(row: Mapping[str, Any]) -> bool: + value = get_value(row, "is_show", 1) + if isinstance(value, str): + return value.strip().lower() not in {"0", "false", "hidden", "no"} + return value != 0 + + +def _menu_enabled(row: Mapping[str, Any]) -> bool: + value = get_value(row, "is_disable", 0) + if isinstance(value, str): + return value.strip().lower() not in {"1", "true", "disabled", "yes"} + return value != 1 + + +def _menu_sort(row: Mapping[str, Any]) -> float: + try: + return float(first_value(row, "sort", "sort_order", "order", default=0)) + except (TypeError, ValueError): + return 0.0 + + +def _visible_menu_nodes(value: Any) -> list[Mapping[str, Any]]: + """Flatten visible, enabled nodes; larger admin sort values come first.""" + + nodes = _menu_rows(value) + ordered = sorted(enumerate(nodes), key=lambda pair: (-_menu_sort(pair[1]), pair[0])) + result: list[Mapping[str, Any]] = [] + for _index, node in ordered: + if not _menu_visible(node) or not _menu_enabled(node): + continue + result.append(node) + children = first_value(node, "children", "child", "childs", default=[]) + result.extend(_visible_menu_nodes(children)) + return result + + +def _normalise_route(value: Any) -> str: + route = str(value or "").strip().replace("\\", "/").lower() + route = route.split("?", 1)[0].split("#", 1)[0].strip("/") + if route.endswith(".vue"): + route = route[:-4] + return route + + +def _menu_permissions(row: Mapping[str, Any]) -> tuple[str, ...]: + value = first_value(row, "perms", "permission", "meta.perms", default="") + if isinstance(value, str): + return (value.strip(),) if value.strip() else () + if isinstance(value, Sequence): + return tuple(str(item).strip() for item in value if str(item).strip()) + return () + + +def _match_navigation(row: Mapping[str, Any]) -> NavigationItem | None: + """Prefer route/component identity when pages share the same permission code.""" + + identifiers = { + _normalise_route(first_value(row, "paths", "path")), + _normalise_route(get_value(row, "component", "")), + } + identifiers.discard("") + for item in NAVIGATION: + if identifiers & _MENU_ROUTE_IDENTIFIERS.get(item.key, set()): + return item + for permission in _menu_permissions(row): + item = _NAVIGATION_BY_PERMISSION.get(permission) + if item is not None: + return item + return None + + +def _resolve_navigation( + menu: Any, + permissions: Any, + *, + demo_mode: bool, +) -> list[tuple[NavigationItem, str]]: + """Resolve only locally supported pages from the authoritative menu tree.""" + + rows = _menu_rows(menu) + if rows: + resolved: list[tuple[NavigationItem, str]] = [] + seen: set[str] = set() + for row in _visible_menu_nodes(rows): + item = _match_navigation(row) + if item is None or item.key in seen: + continue + if not _canonical_allowed(permissions, item.permissions[0]): + continue + if item.key in {"appointments", "reception", "patients"}: + # Keep the product-facing navigation titles stable even when + # the server still carries an older menu label. + title = item.title + else: + title_value = first_value( + row, "name", "title", "meta.title", default=item.title + ) + title = str(title_value).strip() or item.title + resolved.append((item, title)) + seen.add(item.key) + resolved.sort(key=lambda entry: entry[0].key != "appointments") + return resolved + if demo_mode: + return [ + (item, item.title) + for item in NAVIGATION + if _canonical_allowed(permissions, item.permissions[0]) + ] + return [] + + +def _painted_shell_icon(kind: str, size: int = 18, *, reception: bool = False) -> QIcon: + """Return a shell chrome icon from the shared 24-unit duotone icon grid.""" + + color = "accent" if kind == "ai" else "muted" + if reception: + color = TECH_BLUE["accent" if kind == "ai" else "text"] + return icons.icon(kind, color, size) + + +def _painted_navigation_icon(kind: str, size: int = 18, *, reception: bool = False) -> QIcon: + """Return a navigation icon that carries its own selected/hover colours.""" + + return icons.state_icon( + kind, + size=size, + normal=TECH_BLUE["text"] if reception else "muted", + active=TECH_BLUE["heading"] if reception else "strong", + checked=TECH_BLUE["accent"] if reception else "on_accent", + disabled="disabled", + ) + + +class _ShellBrandMark(QWidget): + """Render the Zhenyangtang Luxury MedTech Jade-Gold brand emblem.""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self._brand_pixmap = QPixmap(str(app_icon_path())) + + _TILE_RADIUS = 10.0 + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + del event + reception = bool(self.property("receptionTechBlue")) + if not reception and self._brand_pixmap.isNull(): + return + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + rect = QRectF(self.rect()).adjusted(0.75, 0.75, -0.75, -0.75) + if reception: + # 御瓷智医高定品牌方盾:翡翠青渐变 + 1px 香槟鎏金奢雅切边 + 半透明医学十字 + 血糖脉冲水滴 + gradient = QLinearGradient(rect.topLeft(), rect.bottomRight()) + gradient.setColorAt(0.0, QColor("#15A398")) + gradient.setColorAt(0.55, QColor(TECH_BLUE["accent"])) + gradient.setColorAt(1.0, QColor("#074E4A")) + painter.setBrush(gradient) + painter.setPen(QPen(QColor(PALETTE["gold_light"]), 1.15)) + painter.drawRoundedRect(rect, 10.0, 10.0) + + painter.save() + painter.scale(self.width() / 38.0, self.height() / 38.0) + cross = QPainterPath() + cross.moveTo(15.5, 7.5) + for x, y in ( + (22.5, 7.5), (22.5, 15.5), (30.5, 15.5), (30.5, 22.5), + (22.5, 22.5), (22.5, 30.5), (15.5, 30.5), (15.5, 22.5), + (7.5, 22.5), (7.5, 15.5), (15.5, 15.5), + ): + cross.lineTo(x, y) + cross.closeSubpath() + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(255, 255, 255, 52)) + painter.drawPath(cross) + + drop = QPainterPath(QPointF(19.0, 7.2)) + drop.cubicTo(QPointF(14.6, 13.0), QPointF(10.8, 17.6), QPointF(10.8, 22.4)) + drop.cubicTo(QPointF(10.8, 27.1), QPointF(14.5, 30.8), QPointF(19.0, 30.8)) + drop.cubicTo(QPointF(23.5, 30.8), QPointF(27.2, 27.1), QPointF(27.2, 22.4)) + drop.cubicTo(QPointF(27.2, 17.6), QPointF(23.4, 13.0), QPointF(19.0, 7.2)) + drop.closeSubpath() + painter.setBrush(QColor(255, 255, 255, 245)) + painter.drawPath(drop) + + pulse = QPainterPath(QPointF(13.2, 22.6)) + pulse.lineTo(QPointF(16.0, 22.6)) + pulse.lineTo(QPointF(17.7, 18.6)) + pulse.lineTo(QPointF(20.1, 25.8)) + pulse.lineTo(QPointF(21.7, 22.6)) + pulse.lineTo(QPointF(24.8, 22.6)) + pulse_pen = QPen(QColor(TECH_BLUE["accent"]), 2.0, + Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap, + Qt.PenJoinStyle.RoundJoin) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.setPen(pulse_pen) + painter.drawPath(pulse) + painter.restore() + return + clip = QPainterPath() + clip.addRoundedRect(rect, self._TILE_RADIUS, self._TILE_RADIUS) + painter.setClipPath(clip) + painter.drawPixmap(rect, self._brand_pixmap, QRectF(self._brand_pixmap.rect())) + + +class _ShellNavigationButton(QPushButton): + """Refined navigation row with clean optical spacing and crisp active indicator.""" + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + if not self.property("receptionTechBlue"): + super().paintEvent(event) + return + option = QStyleOptionButton() + self.initStyleOption(option) + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + self.style().drawControl(QStyle.ControlElement.CE_PushButtonBevel, option, painter, self) + collapsed = bool(self.property("collapsed")) + settings = self.objectName() == "ShellSettingsButton" + if self.isChecked() and not settings: + bar_rect = QRectF(1.5, 9.0, 3.2, max(12.0, self.height() - 18.0)) + bar_grad = QLinearGradient(bar_rect.topLeft(), bar_rect.bottomLeft()) + bar_grad.setColorAt(0.0, QColor("#18B0A5")) + bar_grad.setColorAt(1.0, QColor(TECH_BLUE["accent"])) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(bar_grad) + painter.drawRoundedRect(bar_rect, 1.6, 1.6) + x = (self.width() - 20) // 2 if collapsed else (25 if settings else 16) + self.icon().paint( + painter, x, (self.height() - 20) // 2, 20, 20, + Qt.AlignmentFlag.AlignCenter, + QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled, + QIcon.State.On if self.isChecked() else QIcon.State.Off, + ) + if not collapsed: + font = QFont(self.font()) + if self.isChecked() and not settings: + font.setWeight(QFont.Weight.DemiBold) + painter.setFont(font) + painter.setPen(QColor(TECH_BLUE["accent"] if self.isChecked() else TECH_BLUE["text"])) + painter.drawText( + QRectF(55 if settings else 46, 0, self.width() - 62, self.height()), + Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, + "设置" if settings else self.text(), + ) + if settings: + _painted_shell_icon("right", 14, reception=True).paint( + painter, self.width() - 32, (self.height() - 14) // 2, 14, 14 + ) + + +class _AssistantRobot(QWidget): + """Precision Luxury MedTech Dual-Sparkle AI medallion.""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setFixedSize(56, 56) + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + del event + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + if self.property("receptionTechBlue"): + tile = QRectF(4, 4, 38, 38) + gradient = QLinearGradient(tile.topLeft(), tile.bottomRight()) + gradient.setColorAt(0.0, QColor("#18B0A5")) + gradient.setColorAt(0.55, QColor(TECH_BLUE["accent"])) + gradient.setColorAt(1.0, QColor("#074E4A")) + painter.setBrush(gradient) + painter.setPen(QPen(QColor(PALETTE["gold_light"]), 1.1)) + painter.drawRoundedRect(tile, 10.0, 10.0) + + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor("#FFFFFF")) + cx, cy, r = 20.5, 24.0, 9.2 + star = QPainterPath(QPointF(cx, cy - r)) + star.quadTo(QPointF(cx, cy), QPointF(cx + r, cy)) + star.quadTo(QPointF(cx, cy), QPointF(cx, cy + r)) + star.quadTo(QPointF(cx, cy), QPointF(cx - r, cy)) + star.quadTo(QPointF(cx, cy), QPointF(cx, cy - r)) + star.closeSubpath() + painter.drawPath(star) + + painter.setBrush(QColor("#F2D99B")) + sx, sy, sr = 31.0, 14.0, 4.6 + mini = QPainterPath(QPointF(sx, sy - sr)) + mini.quadTo(QPointF(sx, sy), QPointF(sx + sr, sy)) + mini.quadTo(QPointF(sx, sy), QPointF(sx, sy + sr)) + mini.quadTo(QPointF(sx, sy), QPointF(sx - sr, sy)) + mini.quadTo(QPointF(sx, sy), QPointF(sx, sy - sr)) + mini.closeSubpath() + painter.drawPath(mini) + return + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(COLORS["indigo_pale"])) + painter.drawEllipse(QRectF(1, 1, 54, 54)) + painter.setBrush(QColor("#E4E4E5")) + painter.drawEllipse(QRectF(9, 13, 38, 36)) + + pen = QPen(QColor(COLORS["indigo"]), 1.5) + pen.setCapStyle(Qt.PenCapStyle.RoundCap) + pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) + painter.setPen(pen) + painter.setBrush(QColor("#FFFFFF")) + painter.drawRoundedRect(QRectF(12, 17, 32, 25), 9, 9) + painter.setBrush(QColor("#0F2A29")) + painter.drawRoundedRect(QRectF(16, 22, 24, 13), 6, 6) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor("#5EEAD4")) + painter.drawEllipse(QRectF(21, 26, 3.5, 3.5)) + painter.drawEllipse(QRectF(31.5, 26, 3.5, 3.5)) + painter.setBrush(QColor(COLORS["indigo"])) + painter.drawRoundedRect(QRectF(19, 40, 18, 9), 4, 4) + painter.setPen(pen) + painter.drawLine(QPointF(28, 17), QPointF(28, 10)) + painter.setBrush(QColor(COLORS["indigo"])) + painter.drawEllipse(QRectF(25.5, 6.5, 5, 5)) + painter.drawLine(QPointF(12, 28), QPointF(7.5, 31)) + painter.drawLine(QPointF(44, 28), QPointF(48.5, 31)) + + +class _AssistantStatus(QLabel): + """Status copy with a luminous status indicator dot.""" + + def __init__(self, text: str, parent: QWidget | None = None) -> None: + super().__init__(text, parent) + self._online = True + self.setFixedHeight(18) + + def set_online(self, online: bool) -> None: + self._online = online + self.update() + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + del event + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + reception = bool(self.property("receptionTechBlue")) + online_color = "#54E6C1" if reception else PALETTE["success"] + color = QColor(online_color if self._online else "#F06A7B") + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(color) + diameter = 6 + painter.drawEllipse(QRectF(1, (self.height() - diameter) / 2, diameter, diameter)) + painter.setPen(color) + painter.setFont(self.font()) + painter.drawText( + QRectF(12, 0, self.width() - 12, self.height()), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + self.text(), + ) + + +class _PaintedIconButton(QToolButton): + """Font-independent shell icon used for every directional affordance.""" + + def __init__( + self, + kind: str, + *, + size: int = 42, + parent: QWidget | None = None, + ) -> None: + super().__init__(parent) + self.kind = kind + # The close glyph used to be drawn at 12 px next to 18 px siblings, so + # the title bar's three controls never lined up optically. All of + # them are authored on the same grid now, so they share one size. + icon_size = 18 + self.setObjectName("ShellPaintedIconButton") + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setAutoRaise(True) + self.setFixedSize(size, size) + self.setIcon(_painted_shell_icon(kind, icon_size)) + self.setIconSize(QSize(icon_size, icon_size)) + content_size = max(0, size - 2) + self.setStyleSheet( + f""" + QToolButton#ShellPaintedIconButton {{ + min-width: {content_size}px; + max-width: {content_size}px; + min-height: {content_size}px; + max-height: {content_size}px; + background: transparent; + border: 1px solid transparent; + border-radius: 9px; + }} + QToolButton#ShellPaintedIconButton:hover {{ + background: #F7F7F7; + border-color: #EDEDEE; + }} + QToolButton#ShellPaintedIconButton:pressed {{ background: #F0F0F0; }} + QToolButton#ShellPaintedIconButton:focus {{ border-color: #8B9AD9; }} + QToolButton#ShellPaintedIconButton[windowControl="close"]:hover {{ + background: #D63F4F; + border-color: #D63F4F; + }} + QToolButton#ShellPaintedIconButton[windowControl="close"]:pressed {{ + background: #B92E3D; + border-color: #B92E3D; + }} + QToolButton#ShellPaintedIconButton::menu-indicator {{ image: none; width: 0; }} + """ + ) + + def enterEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + if self.property("windowControl") == "close": + # 悬停在绯红关闭按钮上时切换纯白 × 图标,提升桌面窗体控件对比度 + self.setIcon(icons.icon("close", "inverse", self.iconSize().width())) + super().enterEvent(event) + + def leaveEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + if self.property("windowControl") == "close": + window = self.window() + reception = bool(getattr(window, "_reception_chrome_active", False)) + self.setIcon(_painted_shell_icon("close", self.iconSize().width(), reception=reception)) + super().leaveEvent(event) + + +class _UserMenuButton(QToolButton): + """Compact admin-style user dropdown without font-glyph arrows.""" + + def __init__(self, display_name: str, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.display_name = display_name or "医生" + self.setObjectName("ShellUserMenu") + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) + self.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) + self.setFixedHeight(_SHELL_TOPBAR_HEIGHT) + name_width = self.fontMetrics().horizontalAdvance(self.display_name) + self.setFixedWidth(max(104, min(174, name_width + 72))) + self.setAccessibleName(f"用户菜单:{self.display_name}") + self.setText(self.display_name) + avatar = crisp_pixmap(34) + painter = QPainter(avatar) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(COLORS["indigo_pale"])) + painter.drawEllipse(QRectF(0, 0, 34, 34)) + painter.setPen(QColor(COLORS["indigo"])) + avatar_font = QFont(painter.font()) + avatar_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(avatar_font) + painter.drawText( + QRectF(0, 0, 34, 34), Qt.AlignmentFlag.AlignCenter, self.display_name[:1] + ) + painter.end() + self.setIcon(QIcon(avatar)) + self._legacy_avatar = self.icon() + self.setIconSize(QSize(34, 34)) + self.setStyleSheet( + """ + QToolButton#ShellUserMenu { + color: #1A1C1F; + background: transparent; + border: 1px solid transparent; + border-radius: 9px; + padding: 0 18px 0 7px; + font-size: 13px; + font-weight: 500; + } + QToolButton#ShellUserMenu:hover { background: #F7F7F7; border-color: #EDEDEE; } + QToolButton#ShellUserMenu:pressed { background: #F0F0F0; } + QToolButton#ShellUserMenu:focus { border-color: #8B9AD9; } + QToolButton#ShellUserMenu::menu-indicator { + subcontrol-origin: padding; + subcontrol-position: right center; + right: 7px; + } + """ + ) + + def set_reception_avatar(self, active: bool) -> None: + if not active: + self.setIcon(self._legacy_avatar) + self.setIconSize(QSize(34, 34)) + return + avatar = crisp_pixmap(38) + painter = QPainter(avatar) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + rect = QRectF(1.0, 1.0, 36.0, 36.0) + gradient = QLinearGradient(rect.topLeft(), rect.bottomRight()) + gradient.setColorAt(0.0, QColor("#E9F6F4")) + gradient.setColorAt(1.0, QColor("#CFEAE5")) + painter.setBrush(gradient) + painter.setPen(QPen(QColor(PALETTE["gold_light"]), 1.25)) + painter.drawRoundedRect(rect, 11.0, 11.0) + painter.setPen(QColor(TECH_BLUE["accent"])) + font = QFont(heading_family()) + font.setPixelSize(15) + font.setWeight(QFont.Weight.DemiBold) + painter.setFont(font) + painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, self.display_name[:1]) + painter.end() + self.setIcon(QIcon(avatar)) + self.setIconSize(QSize(38, 38)) + + +class _RefreshButton(_PaintedIconButton): + """Top-bar refresh whose icon turns while the page is reloading. + + List loads are silent - they no longer raise a banner into the layout - so + this button is the only place left that can say "your click did something". + Without it a refresh on a slow query looks like a dead control. + """ + + _FRAMES = 12 + _FRAME_MS = 55 + #: Spin for at least this long even if the reload was instant, or a fast + #: refresh flickers once and reads as a glitch rather than as feedback. + _MIN_MS = 420 + #: And never longer than this, so a page that forgets to clear its loading + #: flag cannot leave the icon spinning for the rest of the session. + _CAP_MS = 10_000 + + def __init__(self, *, size: int = 38, parent: QWidget | None = None) -> None: + super().__init__("refresh", size=size, parent=parent) + self._is_busy: Callable[[], bool] = lambda: False + self._resting = self.icon() + self._frames = [ + QIcon(self._rotated(index * 360 / self._FRAMES)) for index in range(self._FRAMES) + ] + self._frame = 0 + self._elapsed = QElapsedTimer() + self._timer = QTimer(self) + self._timer.setInterval(self._FRAME_MS) + self._timer.timeout.connect(self._tick) + + def _rotated(self, angle: float) -> QPixmap: + color = TECH_BLUE["text"] if self.property("receptionTechBlue") else "muted" + source = icons.pixmap("refresh", color, self.iconSize().width()) + size = self.iconSize().width() + canvas = crisp_pixmap(size) + painter = QPainter(canvas) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + painter.translate(size / 2.0, size / 2.0) + painter.rotate(angle) + painter.translate(-size / 2.0, -size / 2.0) + painter.drawPixmap(QRectF(0, 0, size, size), source, QRectF(source.rect())) + painter.end() + return canvas + + def set_busy_probe(self, probe: Callable[[], bool]) -> None: + self._is_busy = probe + + def set_reception_palette(self, active: bool) -> None: + self.setProperty("receptionTechBlue", active) + self._resting = _painted_shell_icon("refresh", self.iconSize().width(), reception=active) + self._frames = [ + QIcon(self._rotated(index * 360 / self._FRAMES)) for index in range(self._FRAMES) + ] + self.setIcon(self._frames[self._frame] if self._timer.isActive() else self._resting) + + def start_spin(self) -> None: + self._frame = 0 + self._elapsed.restart() + if not self._timer.isActive(): + self._timer.start() + + def _tick(self) -> None: + elapsed = self._elapsed.elapsed() + if elapsed >= self._CAP_MS or (elapsed >= self._MIN_MS and not self._is_busy()): + self._timer.stop() + self.setIcon(self._resting) + return + self._frame = (self._frame + 1) % self._FRAMES + self.setIcon(self._frames[self._frame]) + + +class _ShellCanvas(QWidget): + """Outer frameless-window ground, with native edge resizing. + + This is the bottom-most layer of the application, so it is the one that + carries the window's corner. It used to be a plain square fill from the + global ``QMainWindow`` rule, which meant the only rounded things at the + window edge were the panels sitting on top of it - a corner inside a corner. + """ + + _RESIZE_MARGIN = 8 + + #: The workspace card is inset by the gutter and rounded at ``r_xl``; a + #: concentric outer corner is therefore that radius plus the gutter, which + #: is what keeps the two curves parallel instead of merely both-rounded. + _RADIUS = 16.0 + _SHELL_OUTER_GUTTER + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + del event + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + reception = bool(self.property("receptionTechBlue")) + maximized = self.window().isMaximized() + color = TECH_BLUE["surface"] if reception else COLORS["canvas"] + painter.setBrush(QColor(color)) + if reception: + if maximized: + painter.setPen(Qt.PenStyle.NoPen) + painter.drawRect(self.rect()) + else: + # 非最大化时赋予无边框主视窗精致圆角与 1px 钛青金属外框,消除生硬贴边感 + rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + painter.setPen(QPen(QColor("#B3C9C5"), 1.0)) + painter.drawRoundedRect(rect, 14.0, 14.0) + else: + painter.setPen(Qt.PenStyle.NoPen) + painter.drawRoundedRect(QRectF(self.rect()), self._RADIUS, self._RADIUS) + + def _resize_edges(self, position: QPointF) -> Qt.Edge: + edges = Qt.Edge(0) + if position.x() <= self._RESIZE_MARGIN: + edges |= Qt.Edge.LeftEdge + elif position.x() >= self.width() - self._RESIZE_MARGIN: + edges |= Qt.Edge.RightEdge + if position.y() <= self._RESIZE_MARGIN: + edges |= Qt.Edge.TopEdge + elif position.y() >= self.height() - self._RESIZE_MARGIN: + edges |= Qt.Edge.BottomEdge + return edges + + def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual + edges = self._resize_edges(event.position()) + diagonal_down = Qt.Edge.LeftEdge | Qt.Edge.TopEdge + diagonal_up = Qt.Edge.LeftEdge | Qt.Edge.BottomEdge + if edges in (diagonal_down, Qt.Edge.RightEdge | Qt.Edge.BottomEdge): + self.setCursor(Qt.CursorShape.SizeFDiagCursor) + elif edges in (diagonal_up, Qt.Edge.RightEdge | Qt.Edge.TopEdge): + self.setCursor(Qt.CursorShape.SizeBDiagCursor) + elif edges in (Qt.Edge.LeftEdge, Qt.Edge.RightEdge): + self.setCursor(Qt.CursorShape.SizeHorCursor) + elif edges in (Qt.Edge.TopEdge, Qt.Edge.BottomEdge): + self.setCursor(Qt.CursorShape.SizeVerCursor) + else: + self.unsetCursor() + super().mouseMoveEvent(event) + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual + if event.button() == Qt.MouseButton.LeftButton: + edges = self._resize_edges(event.position()) + handle = self.window().windowHandle() + if edges and handle is not None and handle.startSystemResize(edges): + event.accept() + return + super().mousePressEvent(event) + + +class _ShellTopBar(QFrame): + """Integrated title bar that retains native system move/maximize behavior.""" + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual + if event.button() == Qt.MouseButton.LeftButton: + window = self.window() + handle = window.windowHandle() + if handle is not None and handle.startSystemMove(): + event.accept() + return + super().mousePressEvent(event) + + def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual + if event.button() == Qt.MouseButton.LeftButton: + window = self.window() + if window.isMaximized(): + window.showNormal() + else: + window.showMaximized() + event.accept() + return + super().mouseDoubleClickEvent(event) + + +class ShellWindow(QMainWindow): + """Main workstation window. + + The expected construction signature is ``ShellWindow(repository, session, + permissions=None)``. ``session`` may be a Session dataclass, the payload + emitted by :class:`LoginWindow`, or a plain mapping. + """ + + logout_requested = Signal() + close_requested = Signal() + video_requested = Signal(dict) + page_changed = Signal(str) + update_check_requested = Signal() + + def __init__( + self, + repository: Any, + session: Any, + permissions: Any = None, + parent: QWidget | None = None, + ) -> None: + super().__init__(parent) + self.setProperty("doctorMainWindow", True) + self.setWindowTitle("甄养堂 · 问诊中心") + self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True) + # The ground paints its own rounded corner, so everything outside that + # corner has to be genuinely empty rather than filled by the global + # QMainWindow background. + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setStyleSheet("QMainWindow { background: transparent; }") + self.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True) + self.repository = repository + self.login_payload = session + self.session = get_value(session, "session", None) or session + self.current_user = ( + get_value(session, "user", None) + or get_value(self.session, "user", None) + or get_value(session, "current_user", None) + or session + ) + if permissions is not None: + self.permissions = permissions + else: + session_permissions = get_value(self.session, "permissions", None) + self.permissions = ( + session_permissions + if session_permissions is not None + else get_value(self.current_user, "permissions", None) + ) + self._can_ai_assistant = can_open_ai_consult(self.permissions) + session_menu = get_value(self.session, "menu", None) + self.menu = ( + session_menu if session_menu is not None else get_value(session, "menu", []) + ) + self.demo_mode = bool( + get_value(session, "demo_mode", False) + or get_value(self.session, "metadata.demo", False) + or get_value(self.session, "metadata.demo_mode", False) + ) + self.navigation = _resolve_navigation( + self.menu, + self.permissions, + demo_mode=self.demo_mode, + ) + self.pages: dict[str, QWidget] = {} + self.nav_buttons: dict[str, QPushButton] = {} + self.page_titles: dict[int, str] = {} + self._fixed_tab_key: str | None = None + self._sidebar_collapsed = False + self._reception_chrome_active = False + self._active_page_key: str | None = None + self._activation_page: QWidget | None = None + self._activation_generation = 0 + self._activation_refreshed = False + self._local_audio_settings_dialog: LocalAudioQueueDialog | None = None + self._global_diagnosis_dialog: DiagnosisDialog | None = None + # 与后台 chat-notify-toast 同一份数据源,登录后常驻轮询。 + self.chat_notifications = ChatNotificationCenter(repository, self) + self.chat_notifications.notification_activated.connect( + self._open_chat_notification + ) + + self.setMinimumSize(_SHELL_MINIMUM_SIZE) + screen = self.screen() or QApplication.primaryScreen() + available_size = screen.availableGeometry().size() if screen is not None else None + self.resize(_bounded_initial_window_size(available_size)) + + canvas = _ShellCanvas(self) + canvas.setObjectName("AppCanvas") + canvas.setMouseTracking(True) + self.setCentralWidget(canvas) + root = QHBoxLayout(canvas) + root.setContentsMargins( + _SHELL_OUTER_GUTTER, + _SHELL_OUTER_GUTTER, + _SHELL_OUTER_GUTTER, + _SHELL_OUTER_GUTTER, + ) + root.setSpacing(_SHELL_PANEL_GAP) + self.sidebar = self._build_sidebar() + root.addWidget(self.sidebar) + + self.workspace = QWidget() + self.workspace.setObjectName("ShellWorkspace") + self.workspace.setStyleSheet( + """ + QWidget#ShellWorkspace { + background-color: #FFFFFF; + border: 0; + border-radius: 16px; + } + """ + ) + workspace_layout = QVBoxLayout(self.workspace) + workspace_layout.setContentsMargins(0, 0, 0, 0) + workspace_layout.setSpacing(0) + self.topbar = self._build_topbar() + workspace_layout.addWidget(self.topbar) + self.tabs_host = self._build_tab_strip() + workspace_layout.addWidget(self.tabs_host) + self.stack = QStackedWidget() + self.stack.setObjectName("ShellPageStack") + self.stack.setStyleSheet( + "QStackedWidget#ShellPageStack {" + " background-color: #FFFFFF; border: 0;" + " border-bottom-left-radius: 16px; border-bottom-right-radius: 16px;" + " }" + ) + # Clinical OS 2.0 主从工作体:左侧业务堆栈 + 右侧可折叠临床伴随舱(默认折叠不占主宽) + body_row = QHBoxLayout() + body_row.setContentsMargins(0, 0, 0, 0) + body_row.setSpacing(0) + body_row.addWidget(self.stack, 1) + self.companion_dock = self._build_companion_dock() + body_row.addWidget(self.companion_dock) + workspace_layout.addLayout(body_row, 1) + root.addWidget(self.workspace, 1) + # Deliberately no shadow layer here. The window is itself a rounded + # floating surface, so a shadow around the two panels inside it stacks a + # third rounded outline into a 13 px gutter and each window corner ends + # up showing three nested edges. Elevation belongs to the cards inside a + # page, where there is a real surface behind them to lift off. + + # Every override targets a chrome object by ID, so page fonts and + # dialogs remain independent of the reception appearance. + chrome_widgets = [self.sidebar, self.workspace, self.stack, self.topbar, + self.tabs_host, self.user_menu_button] + chrome_widgets.extend(self.topbar.findChildren(_PaintedIconButton)) + chrome_widgets.append(self.tabs_menu_button) + self._legacy_chrome_styles = { + widget: clinical_stylesheet(widget.styleSheet()) for widget in chrome_widgets + } + self._register_pages() + self.search_shortcut = QShortcut(QKeySequence("Ctrl+K"), self) + self.search_shortcut.activated.connect(self.open_command_palette) + self.palette_shortcut = QShortcut(QKeySequence("Ctrl+Shift+P"), self) + self.palette_shortcut.activated.connect(self.open_command_palette) + self.refresh_shortcut = QShortcut(QKeySequence("F5"), self) + self.refresh_shortcut.activated.connect(self.refresh_current_page) + self.sidebar_shortcut = QShortcut(QKeySequence("Ctrl+B"), self) + self.sidebar_shortcut.activated.connect(self.toggle_sidebar) + self.companion_shortcut = QShortcut(QKeySequence("Ctrl+]"), self) + self.companion_shortcut.activated.connect(self.toggle_companion_dock) + self._nav_shortcuts: list[QShortcut] = [] + for index, (item, _title) in enumerate(self.navigation[:6], start=1): + shortcut = QShortcut(QKeySequence(f"Alt+{index}"), self) + shortcut.activated.connect( + lambda page_key=item.key: self.navigate(page_key) + ) + self._nav_shortcuts.append(shortcut) + + def _build_sidebar(self) -> QWidget: + sidebar = QWidget() + sidebar.setObjectName("Sidebar") + sidebar.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + sidebar.setFixedWidth(_SHELL_EXPANDED_WIDTH) + sidebar.setStyleSheet( + """ + /* The rail is the ground, not a panel on it. It used to carry a + diagonal gradient against a flat canvas + canvas, so it never matched at any point along its own left edge - + a permanent faint seam down the window, and a second rounded + corner nested inside the window's own. Painting nothing lets the + canvas show through, which makes the two one surface and leaves + the bottom-most layer as the only thing with a corner. */ + QWidget#Sidebar { + background-color: transparent; + border: 0; + border-radius: 0; + } + QFrame#ShellBrand { + background-color: transparent; + border: 0; + border-radius: 0; + } + QLabel#ShellBrandName { color: #1A1C1F; font-size: 15px; font-weight: 600; } + QLabel#ShellBrandSubtitle { color: #6A6B6D; font-size: 12px; } + QPushButton#ShellNavButton { + min-height: 45px; + max-height: 45px; + padding: 0 14px; + margin: 0; + border: 1px solid transparent; + border-radius: 8px; + background-color: transparent; + color: #606163; + text-align: left; + font-size: 14px; + font-weight: 500; + } + QPushButton#ShellNavButton:hover { + background-color: #EEF1FA; + border-color: #DEE4F6; + color: #1A1C1F; + } + QPushButton#ShellNavButton:pressed { background-color: #E3E8F8; } + QPushButton#ShellNavButton:focus { border-color: #8B9AD9; } + QPushButton#ShellNavButton:checked { + color: #FFFFFF; + background-color: #4F63D9; + border-color: transparent; + font-weight: 500; + } + QPushButton#ShellNavButton:checked:hover { background-color: #4156C4; } + QPushButton#ShellNavButton:checked:pressed { background-color: #354BB4; } + QPushButton#ShellNavButton[collapsed="true"] { + padding: 0; + text-align: center; + margin: 0; + } + QFrame#ShellAssistantCard { + background-color: rgba(255, 255, 255, 230); + border: 1px solid #EDEDEE; + border-radius: 12px; + } + QLabel#ShellAssistantGlyph { + color: #4F63D9; + background-color: #EEF1FA; + border: 1px solid rgba(82, 101, 246, 48); + border-radius: 18px; + font-size: 13px; + font-weight: 600; + } + QLabel#ShellAssistantName { color: #1A1C1F; font-size: 13px; font-weight: 500; } + QLabel#ShellAssistantStatus { color: #287B65; font-size: 12px; } + QPushButton#ShellAssistantButton { + min-height: 34px; + color: #FFFFFF; + background-color: #4F63D9; + border: 0; + border-radius: 9px; + font-weight: 500; + } + QPushButton#ShellAssistantButton:hover { background-color: #4156C4; } + QPushButton#ShellAssistantButton:pressed { background-color: #354BB4; } + QPushButton#ShellSettingsButton { + min-height: 42px; + color: #606163; + font-size: 13px; + font-weight: 500; + background-color: transparent; + border: 1px solid transparent; + border-radius: 10px; + } + QPushButton#ShellSettingsButton:hover { + color: #1A1C1F; + background-color: #F0F0F0; + } + QPushButton#ShellSettingsButton:focus { border-color: #8B9AD9; } + """ + ) + layout = QVBoxLayout(sidebar) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(0) + + brand = QFrame(sidebar) + self.brand = brand + brand.setObjectName("ShellBrand") + brand.setFixedHeight(75) + brand_layout = QHBoxLayout(brand) + self.brand_layout = brand_layout + brand_layout.setContentsMargins(21, 17, 10, 8) + brand_layout.setSpacing(10) + self.brand_mark = _ShellBrandMark(brand) + self.brand_mark.setObjectName("ShellBrandMark") + self.brand_mark.setFixedSize(36, 36) + brand_layout.addWidget(self.brand_mark) + self.brand_copy = QWidget(brand) + brand_copy_layout = QVBoxLayout(self.brand_copy) + brand_copy_layout.setContentsMargins(0, 0, 0, 0) + brand_copy_layout.setSpacing(1) + self.brand_name = QLabel("甄养堂", self.brand_copy) + self.brand_name.setObjectName("ShellBrandName") + brand_copy_layout.addWidget(self.brand_name) + self.brand_subtitle = QLabel("糖尿病专科工作站", self.brand_copy) + self.brand_subtitle.setObjectName("ShellBrandSubtitle") + brand_copy_layout.addWidget(self.brand_subtitle) + brand_layout.addWidget(self.brand_copy, 1) + layout.addWidget(brand) + + self.nav_layout = QVBoxLayout() + self.nav_layout.setContentsMargins(12, 19, 12, 0) + self.nav_layout.setSpacing(0) + layout.addLayout(self.nav_layout) + layout.addStretch(1) + + self.assistant_card = QFrame(sidebar) + self.assistant_card.setObjectName("ShellAssistantCard") + self.assistant_card.setFixedHeight(157) + assistant_layout = QVBoxLayout(self.assistant_card) + self.assistant_layout = assistant_layout + assistant_layout.setContentsMargins(12, 12, 12, 20) + assistant_layout.setSpacing(0) + assistant_head_host = QWidget(self.assistant_card) + assistant_head_host.setFixedHeight(60) + assistant_head = QHBoxLayout(assistant_head_host) + self.assistant_head_layout = assistant_head + assistant_head.setContentsMargins(0, 0, 0, 0) + assistant_head.setSpacing(9) + self.assistant_glyph = _AssistantRobot(assistant_head_host) + assistant_head.addWidget(self.assistant_glyph) + assistant_copy = QVBoxLayout() + assistant_copy.setContentsMargins(0, 5, 0, 5) + assistant_copy.setSpacing(1) + assistant_name = QLabel("AI 助手", self.assistant_card) + assistant_name.setObjectName("ShellAssistantName") + assistant_copy.addWidget(assistant_name) + self.assistant_status = _AssistantStatus("在线", assistant_head_host) + self.assistant_status.setObjectName("ShellAssistantStatus") + assistant_copy.addWidget(self.assistant_status) + assistant_head.addLayout(assistant_copy, 1) + assistant_layout.addWidget(assistant_head_host) + assistant_layout.addStretch(1) + self.assistant_button = QPushButton("开始对话", self.assistant_card) + self.assistant_button.setObjectName("ShellAssistantButton") + self.assistant_button.setIcon(icons.icon("ai", "#FFFFFF", 14)) + self.assistant_button.setIconSize(QSize(14, 14)) + self.assistant_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.assistant_button.setFixedHeight(34) + self.assistant_button.clicked.connect(self._open_ai_assistant) + assistant_layout.addWidget(self.assistant_button) + outer_assistant = QHBoxLayout() + self.assistant_outer_layout = outer_assistant + outer_assistant.setContentsMargins(13, 0, 13, 0) + outer_assistant.addWidget(self.assistant_card) + layout.addLayout(outer_assistant) + self.assistant_card.setVisible(self._can_ai_assistant) + + self.upload_settings_button = _ShellNavigationButton("设置 ›", sidebar) + self.upload_settings_button.setObjectName("ShellSettingsButton") + self.upload_settings_button.setAccessibleName("本机录音上传设置") + self.upload_settings_button.setToolTip("查看本机录音上传记录") + self.upload_settings_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.upload_settings_button.setFixedHeight(76) + self.upload_settings_button.clicked.connect(self._open_local_audio_settings) + # Keep the former attribute as a compatibility alias for integrations + # that inspect the bottom sidebar control. + self.model_label = self.upload_settings_button + layout.addWidget(self.upload_settings_button) + return sidebar + + def _build_topbar(self) -> QWidget: + topbar = _ShellTopBar(self.workspace) + topbar.setObjectName("TopBar") + topbar.setFixedHeight(_SHELL_TOPBAR_HEIGHT) + topbar.setStyleSheet( + """ + QFrame#TopBar { + background-color: #FFFFFF; + border: 0; + border-bottom: 1px solid #F0F0F0; + border-top-left-radius: 16px; + border-top-right-radius: 16px; + } + QFrame#ShellGlobalSearch { + background-color: #FFFFFF; + border: 1px solid #EDEDEE; + border-radius: 10px; + } + QLineEdit#ShellGlobalSearchInput { + min-height: 34px; + max-height: 34px; + padding: 0 8px; + color: #606163; + background-color: transparent; + border: 0; + border-radius: 9px; + } + QLineEdit#ShellGlobalSearchInput QToolButton { + min-width: 22px; + max-width: 22px; + min-height: 18px; + max-height: 18px; + margin: 0; + padding: 0; + background-color: transparent; + border: 0; + border-radius: 0; + } + QLineEdit#ShellGlobalSearchInput QToolButton:hover, + QLineEdit#ShellGlobalSearchInput QToolButton:pressed, + QLineEdit#ShellGlobalSearchInput QToolButton:focus { + background-color: transparent; + border: 0; + } + QPushButton#ShellShortcutHint, + QLabel#ShellShortcutHint { + color: #6A6B6D; + background-color: #F7F7F7; + border: 1px solid #EDEDEE; + border-radius: 6px; + padding: 2px 7px; + min-height: 22px; + max-height: 22px; + font-size: 11px; + } + QPushButton#ShellShortcutHint:hover { + color: #0B6E68; + background-color: #E6F4F2; + border-color: #9CCFC7; + } + QPushButton#ShellAiEntry { + min-width: 38px; + max-width: 38px; + min-height: 38px; + max-height: 38px; + padding: 0; + color: #4F63D9; + background-color: transparent; + border: 0; + border-radius: 9px; + font-weight: 500; + } + QPushButton#ShellAiEntry:hover { background-color: #EEF1FA; } + QLabel#ShellConnectionBadge { + color: #606163; + background-color: #FFFFFF; + border: 1px solid #EDEDEE; + border-radius: 10px; + padding: 4px 10px; + font-size: 13px; + font-weight: 500; + } + QLabel#ShellConnectionBadge[kind="success"] { + color: #287B65; + background-color: #E8F6F1; + border-color: #B9E3D7; + } + QLabel#ShellConnectionBadge[kind="danger"] { + color: #EC5266; + background-color: #FFF0F2; + border-color: #F4C4CC; + } + QToolButton#ShellPaintedIconButton[windowControl="close"]:hover { + background-color: #FFF0F2; + border-color: #F4C4CC; + } + QMenu { + color: #1A1C1F; + background-color: #FFFFFF; + border: 1px solid #EDEDEE; + border-radius: 10px; + padding: 6px; + } + QMenu::item { min-width: 112px; min-height: 32px; padding: 0 12px; border-radius: 6px; } + QMenu::item:selected { color: #1A1C1F; background-color: #EEF1FA; } + QMenu::item:disabled { color: #8E8F90; } + QMenu::separator { height: 1px; background: #EDEDEE; margin: 5px 8px; } + """ + ) + layout = QHBoxLayout(topbar) + layout.setContentsMargins(20, 0, 10, 0) + layout.setSpacing(5) + + self.fold_button = _PaintedIconButton("fold", size=38, parent=topbar) + self.fold_button.setToolTip("收起或展开菜单") + self.fold_button.setAccessibleName("收起或展开菜单") + self.fold_button.clicked.connect(self.toggle_sidebar) + layout.addWidget(self.fold_button) + layout.addSpacing(9) + self._fold_spacing = layout.itemAt(layout.count() - 1).spacerItem() + search_host = QFrame(topbar) + self.search_host = search_host + search_host.setObjectName("ShellGlobalSearch") + search_host.setFixedSize(265, 36) + search_layout = QHBoxLayout(search_host) + search_layout.setContentsMargins(4, 0, 7, 0) + search_layout.setSpacing(3) + self.search_mark = QToolButton(search_host) + self.search_mark.setObjectName("ShellSearchMark") + self.search_mark.setFixedSize(20, 20) + self.search_mark.setAutoRaise(True) + self.search_mark.setCursor(Qt.CursorShape.PointingHandCursor) + self.search_mark.setAccessibleName("搜索患者") + self.search_mark.setToolTip("搜索患者(回车)") + self.search_mark.setStyleSheet("background: transparent; border: 0; padding: 0;") + self.search_mark.clicked.connect(self._run_global_search) + self.search_mark.hide() + search_layout.addWidget(self.search_mark, 0, Qt.AlignmentFlag.AlignVCenter) + self.global_search = QLineEdit(search_host) + self.global_search.setObjectName("ShellGlobalSearchInput") + self.global_search.setSizePolicy( + QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed + ) + self.global_search.setPlaceholderText("搜索患者姓名、手机号...") + self.global_search.setToolTip("输入患者姓名或手机号,按回车或点击放大镜搜索") + self.global_search.setClearButtonEnabled(True) + self._global_search_icon_action = self.global_search.addAction( + _painted_shell_icon("search", 16), + QLineEdit.ActionPosition.LeadingPosition, + ) + self._global_search_icon_action.setToolTip("搜索患者(回车)") + self._global_search_icon_action.triggered.connect(self._run_global_search) + self.global_search.returnPressed.connect(self._run_global_search) + search_layout.addWidget(self.global_search, 1) + shortcut_hint = QPushButton("Ctrl K", search_host) + self.search_shortcut_hint = shortcut_hint + shortcut_hint.setObjectName("ShellShortcutHint") + shortcut_hint.setCursor(Qt.CursorShape.PointingHandCursor) + shortcut_hint.setToolTip("打开智诊命令中枢(Ctrl+K)") + shortcut_hint.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + shortcut_hint.clicked.connect(self.open_command_palette) + search_layout.addWidget(shortcut_hint, 0, Qt.AlignmentFlag.AlignVCenter) + layout.addWidget(search_host) + + self.context_label = QLabel("工作台", topbar) + self.context_label.setObjectName("ShellBreadcrumbCurrent") + self.context_label.hide() + layout.addStretch(1) + + self.refresh_button = _RefreshButton(size=38, parent=topbar) + self.refresh_button.setToolTip("刷新当前页面(F5)") + self.refresh_button.setAccessibleName("刷新当前页面") + self.refresh_button.set_busy_probe(self._current_page_is_loading) + self.refresh_button.clicked.connect(self.refresh_current_page) + layout.addWidget(self.refresh_button) + + self.ai_top_button = QPushButton("", topbar) + self.ai_top_button.setObjectName("ShellAiEntry") + self.ai_top_button.setIcon(_painted_shell_icon("ai", 18)) + self.ai_top_button.setIconSize(QSize(18, 18)) + self.ai_top_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.ai_top_button.setToolTip("AI 助手") + self.ai_top_button.setAccessibleName("AI 助手") + self.ai_top_button.clicked.connect(self._open_ai_assistant) + layout.addWidget(self.ai_top_button) + self.ai_top_button.setVisible(self._can_ai_assistant) + + self.notification_button = _PaintedIconButton( + "notification", size=38, parent=topbar + ) + self.notification_button.setToolTip("消息通知") + self.notification_button.clicked.connect(self._show_chat_notification_summary) + layout.addWidget(self.notification_button) + self.settings_button = _PaintedIconButton("settings", size=38, parent=topbar) + self.settings_button.setToolTip("展开或收起右侧临床伴随舱(Ctrl+])") + self.settings_button.setAccessibleName("切换临床伴随舱") + self.settings_button.clicked.connect(self.toggle_companion_dock) + layout.addWidget(self.settings_button) + self.user_separator = QFrame(topbar) + self.user_separator.setObjectName("ShellUserSeparator") + self.user_separator.setFixedSize(1, 44) + self.user_separator.hide() + layout.addWidget(self.user_separator) + + self.connection_badge = StatusBadge("服务正常", "success", topbar) + self.connection_badge.setObjectName("ShellConnectionBadge") + self.connection_badge.hide() + + display_name = display_text( + first_value( + self.current_user, + "name", + "display_name", + "nickname", + "account", + default="医生", + ) + ) + self.user_menu_button = _UserMenuButton(display_name, topbar) + self.user_menu_button.setToolTip(f"{display_name} · {self._role_text()}") + user_menu = QMenu(self.user_menu_button) + account_action = user_menu.addAction(self._role_text()) + account_action.setEnabled(False) + user_menu.addSeparator() + self.menu_sidebar_action = user_menu.addAction("收起或展开菜单") + self.menu_sidebar_action.triggered.connect(self.toggle_sidebar) + self.menu_sidebar_action.setVisible(False) + self.menu_ai_action = user_menu.addAction("AI 助手") + self.menu_ai_action.triggered.connect(self._open_ai_assistant) + self.menu_ai_action.setVisible(False) + if "1" in self._role_ids() and can_open_esign_doctor(self.repository, self.permissions): + user_menu.addAction("医生电子签署身份", self._open_esign_doctor) + update_action = user_menu.addAction("检查更新") + update_action.triggered.connect(self.update_check_requested.emit) + user_menu.addSeparator() + logout_action = user_menu.addAction("退出登录") + logout_action.triggered.connect(lambda: self.logout_requested.emit()) + self.user_menu_button.setMenu(user_menu) + layout.addWidget(self.user_menu_button) + + self.minimize_button = _PaintedIconButton("minimize", size=34, parent=topbar) + self.minimize_button.setToolTip("最小化") + self.minimize_button.clicked.connect(self.showMinimized) + layout.addWidget(self.minimize_button) + self.fullscreen_button = _PaintedIconButton( + "fullscreen", size=34, parent=topbar + ) + self.fullscreen_button.setToolTip("最大化") + self.fullscreen_button.setAccessibleName("切换最大化") + self.fullscreen_button.clicked.connect(self._toggle_maximized) + layout.addWidget(self.fullscreen_button) + self.close_button = _PaintedIconButton("close", size=34, parent=topbar) + self.close_button.setProperty("windowControl", "close") + self.close_button.setToolTip("关闭") + self.close_button.clicked.connect(self.close) + layout.addWidget(self.close_button) + return topbar + + def _build_tab_strip(self) -> QWidget: + tabs_host = QFrame() + tabs_host.setObjectName("MultipleTabs") + tabs_host.setFixedHeight(_SHELL_TABS_HEIGHT) + tabs_host.setStyleSheet( + """ + QFrame#MultipleTabs { + background-color: #FFFFFF; + border-top: 0; + border-bottom: 1px solid #E4E4E5; + } + QTabBar#ShellTabs { background-color: #FFFFFF; } + QTabBar#ShellTabs::tab { + min-height: 40px; + max-height: 40px; + min-width: 84px; + padding: 0 14px; + margin: 0 2px; + color: #606163; + background-color: transparent; + border: 0; + border-bottom: 2px solid transparent; + border-radius: 0; + font-size: 13px; + font-weight: 500; + } + QTabBar#ShellTabs::tab:hover { color: #1A1C1F; background-color: #F7F7F7; } + QTabBar#ShellTabs::tab:selected { + color: #4F63D9; + background-color: #EEF1FA; + border-bottom: 2px solid #4F63D9; + font-weight: 500; + } + QMenu { + color: #1A1C1F; + background-color: #FFFFFF; + border: 1px solid #E4E4E5; + border-radius: 10px; + padding: 6px; + } + QMenu::item { min-width: 112px; min-height: 32px; padding: 0 12px; border-radius: 6px; } + QMenu::item:selected { color: #1A1C1F; background-color: #EEF1FA; } + QMenu::item:disabled { color: #8E8F90; } + QMenu::separator { height: 1px; background: #E4E4E5; margin: 5px 8px; } + """ + ) + layout = QHBoxLayout(tabs_host) + layout.setContentsMargins(16, 0, 0, 0) + layout.setSpacing(0) + + self.tab_bar = QTabBar() + self.tab_bar.setObjectName("ShellTabs") + self.tab_bar.setDocumentMode(True) + self.tab_bar.setDrawBase(False) + self.tab_bar.setExpanding(False) + self.tab_bar.setUsesScrollButtons(True) + self.tab_bar.setElideMode(Qt.TextElideMode.ElideRight) + self.tab_bar.setSizePolicy( + QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed + ) + self.tab_bar.currentChanged.connect(self._tab_selected) + layout.addWidget(self.tab_bar, 1) + + self.tabs_menu_button = _PaintedIconButton("down") + self.tabs_menu_button.setToolTip("标签页操作") + self.tabs_menu_button.setAccessibleName("标签页操作") + self.tabs_menu_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) + tabs_menu = QMenu(self.tabs_menu_button) + self.close_current_action = tabs_menu.addAction("关闭当前") + self.close_current_action.triggered.connect(self.close_current_tab) + self.close_other_action = tabs_menu.addAction("关闭其他") + self.close_other_action.triggered.connect(self.close_other_tabs) + self.close_all_action = tabs_menu.addAction("关闭全部") + self.close_all_action.triggered.connect(self.close_all_tabs) + self.tabs_menu_button.setMenu(tabs_menu) + layout.addWidget(self.tabs_menu_button) + self._update_tab_actions() + tabs_host.hide() + return tabs_host + + def _role_text(self) -> str: + department = first_value( + self.current_user, "department_name", "department.name", default="" + ) + role_values = self._role_ids() + role = ( + "医生" + if "1" in role_values + else "医助" + if "2" in role_values + else "医疗人员" + ) + return f"{department} · {role}" if department else role + + def _role_ids(self) -> set[str]: + role_ids = first_value(self.current_user, "role_ids", "role_id", default=[]) or [] + if not isinstance(role_ids, (list, tuple, set, frozenset)): + role_ids = [role_ids] + return {str(value) for value in role_ids} + + def toggle_sidebar(self) -> None: + """Toggle the admin-style compact menu while preserving the page state.""" + + self._sidebar_collapsed = not self._sidebar_collapsed + self.sidebar.setFixedWidth( + _SHELL_COLLAPSED_WIDTH + if self._sidebar_collapsed + else self._expanded_sidebar_width() + ) + self.brand_copy.setVisible(not self._sidebar_collapsed) + self.assistant_card.setVisible( + self._can_ai_assistant and not self._sidebar_collapsed + ) + self.upload_settings_button.setVisible(not self._sidebar_collapsed) + margins = self._navigation_margins() + self.nav_layout.setContentsMargins(*margins) + self.fold_button.kind = "expand" if self._sidebar_collapsed else "fold" + self.fold_button.setIcon( + _painted_shell_icon(self.fold_button.kind, reception=self._reception_chrome_active) + ) + for button in self.nav_buttons.values(): + title = str(button.property("navTitle") or "") + button.setText("" if self._sidebar_collapsed else title) + button.setToolTip(title if self._sidebar_collapsed else "") + button.setProperty("collapsed", self._sidebar_collapsed) + button.style().unpolish(button) + button.style().polish(button) + self._set_reception_geometry(self._reception_chrome_active) + if not self._sidebar_collapsed and not motion.reduced_motion(): + # 展开侧栏时给品牌文案与 AI 科技卡施加柔和淡入,提升切换顺滑感 + motion.fade_in(self.brand_copy) + if self.assistant_card.isVisible(): + motion.fade_in(self.assistant_card) + + def _expanded_sidebar_width(self, key: str | None = None) -> int: + reception = key in _TECH_BLUE_PAGES if key is not None else self._reception_chrome_active + return _RECEPTION_SIDEBAR_WIDTH if reception else _SHELL_EXPANDED_WIDTH + + def _navigation_margins(self) -> tuple[int, int, int, int]: + if self._sidebar_collapsed: + return (7, 19 if self._reception_chrome_active else 14, 7, 0) + return (9, 19, 10, 0) if self._reception_chrome_active else (12, 19, 12, 0) + + def _set_reception_geometry(self, active: bool) -> None: + """Keep the approved geometry page-local, including compact-rail state.""" + + gutter = 0 if active else _SHELL_OUTER_GUTTER + self.centralWidget().layout().setContentsMargins(gutter, gutter, gutter, gutter) + self.sidebar.setFixedWidth( + _SHELL_COLLAPSED_WIDTH if self._sidebar_collapsed else self._expanded_sidebar_width() + ) + self.topbar.setFixedHeight(_RECEPTION_TOPBAR_HEIGHT if active else _SHELL_TOPBAR_HEIGHT) + self.brand.setFixedHeight(68 if active else 75) + brand_margins = (18, 12, 10, 8) if active else (21, 17, 10, 8) + if active and self._sidebar_collapsed: + brand_margins = (15, 12, 15, 8) + self.brand_layout.setContentsMargins(*brand_margins) + self.brand_layout.setSpacing(11 if active else 10) + self.brand_mark.setFixedSize(36, 36) + self.nav_layout.setContentsMargins(*self._navigation_margins()) + self.nav_layout.setSpacing(4 if active else 0) + self.assistant_card.setFixedHeight(124 if active else 157) + self.assistant_layout.setContentsMargins(*(12, 11, 12, 11) if active else (12, 12, 12, 20)) + self.assistant_head_layout.setContentsMargins(2 if active else 0, 0, 0, 0) + self.assistant_head_layout.setSpacing(8 if active else 9) + self.assistant_glyph.setFixedSize(46 if active else 56, 46 if active else 56) + self.assistant_outer_layout.setContentsMargins(*(14, 0, 14, 0) if active else (13, 0, 13, 0)) + self.assistant_status.setFixedHeight(18) + self.assistant_button.setFixedHeight(34) + self.upload_settings_button.setFixedHeight(46 if active else 44) + self.upload_settings_button.setIcon(_painted_shell_icon("settings", 18, reception=True) if active else QIcon()) + self.upload_settings_button.setIconSize(QSize(18, 18) if active else QSize(16, 16)) + self.upload_settings_button.setText("设置 ›" if active else "设置 ›") + self.topbar.layout().setContentsMargins(*(18, 0, 10, 0) if active else (20, 0, 10, 0)) + self.topbar.layout().setSpacing(6 if active else 5) + self.fold_button.setVisible(True) + self._fold_spacing.changeSize(8 if active else 9, 0) + self.search_host.setFixedSize(QSize(340, 38) if active else QSize(265, 36)) + self.search_host.layout().setContentsMargins(*(12, 0, 8, 0) if active else (4, 0, 7, 0)) + self.search_host.layout().setSpacing(6 if active else 3) + self.search_mark.setVisible(active) + self._global_search_icon_action.setVisible(not active) + self.global_search.setPlaceholderText("搜索患者姓名、手机号...") + self.search_shortcut_hint.setText("Ctrl K") + self.ai_top_button.setVisible(self._can_ai_assistant and not active) + self.menu_sidebar_action.setVisible(active) + self.menu_ai_action.setVisible(active and self._can_ai_assistant) + self.user_separator.setVisible(active) + if active: + self.user_menu_button.setFixedSize(164, 42) + elif hasattr(self, "_legacy_user_menu_size"): + self.user_menu_button.setFixedSize(self._legacy_user_menu_size) + self.topbar.layout().invalidate() + self._fit_reception_search() + + def _fit_reception_search(self) -> None: + if not self._reception_chrome_active: + return + controls_width = 18 + 10 + 38 + 8 + 3 * 38 + 164 + 3 * 34 + 1 + 9 * 6 + width = self.width() - self.sidebar.width() - controls_width + self.search_host.setFixedWidth(min(340, max(200, width))) + + def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + super().resizeEvent(event) + if getattr(self, "_reception_chrome_active", False): + self._fit_reception_search() + + def _set_reception_chrome(self, active: bool) -> None: + """Apply approved pages' shared chrome and restore the exact legacy QSS.""" + + if active == self._reception_chrome_active: + return + if active: + # Qt styles can adjust a fixed control by its border width during + # polish; restore the effective size that the user actually saw. + self._legacy_user_menu_size = self.user_menu_button.size() + self._reception_chrome_active = active + replacements = { + "#4F63D9": TECH_BLUE["accent"], + "#4156C4": TECH_BLUE["accent_hover"], + "#354BB4": TECH_BLUE["accent_pressed"], + "#EEF1FA": TECH_BLUE["selection"], + "#E3E8F8": TECH_BLUE["selection"], + "#DEE4F6": TECH_BLUE["line"], + "#8B9AD9": TECH_BLUE["focus"], + "#1A1C1F": TECH_BLUE["heading"], + "#606163": TECH_BLUE["text"], + "#6A6B6D": TECH_BLUE["muted"], + "#F7F7F7": TECH_BLUE["raised"], + "#F0F0F0": TECH_BLUE["line"], + "#EDEDEE": TECH_BLUE["line"], + "#E4E4E5": TECH_BLUE["line"], + "#287B65": TECH_BLUE["selected_text"], + "#E8F6F1": TECH_BLUE["selection"], + "#B9E3D7": TECH_BLUE["line"], + } + for widget, original in self._legacy_chrome_styles.items(): + stylesheet = original + if active: + for old_color, new_color in replacements.items(): + stylesheet = stylesheet.replace(old_color, new_color) + if widget in (self.sidebar, self.topbar, self.tabs_host): + stylesheet += f""" + QWidget {{ font-family: "{body_family()}"; font-weight: 400; }} + """ + if widget is self.sidebar: + stylesheet += f""" + QWidget#Sidebar {{ + background-color: {_RECEPTION_SIDEBAR_COLOR}; + border-right: 1px solid #D4E1DE; + }} + QLabel#ShellBrandName {{ + font-family: "{heading_family()}"; font-weight: 600; + color: {TECH_BLUE['heading']}; font-size: {TYPE['fs_section']}; + }} + QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['muted']}; font-size: {TYPE['fs_small']}; }} + QPushButton#ShellNavButton {{ + font-family: "{body_family()}"; font-weight: 500; + min-height: 42px; max-height: 42px; + border: 1px solid transparent; + border-radius: 10px; + padding: 0 14px; font-size: {TYPE['fs_body']}; + color: {TECH_BLUE['text']}; + background-color: transparent; + }} + QPushButton#ShellNavButton:hover {{ + background-color: rgba(11, 110, 104, 18); + color: {TECH_BLUE['heading']}; + }} + QPushButton#ShellNavButton:checked, + QPushButton#ShellNavButton:checked:hover, + QPushButton#ShellNavButton:checked:pressed {{ + color: {TECH_BLUE['accent']}; + background-color: {TECH_BLUE['surface']}; + border: 1px solid #C5DFDC; + font-weight: 600; + }} + QPushButton#ShellNavButton:focus {{ + border: 1px solid {TECH_BLUE['focus']}; + }} + QPushButton#ShellNavButton[collapsed="true"] {{ padding: 0; }} + /* 深曜青黑曜石 AI 科技卡 + 极克制香槟鎏金微光切边 */ + QFrame#ShellAssistantCard {{ + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0F2B2A, stop:1 #071919); + border-radius: 13px; + border: 1px solid rgba(223, 199, 147, 78); + }} + QLabel#ShellAssistantName {{ + font-family: "{heading_family()}"; font-weight: 600; font-size: {TYPE['fs_body']}; + color: #F4FAF9; + }} + QLabel#ShellAssistantStatus {{ + font-size: {TYPE['fs_small']}; + color: #54E6C1; + }} + QPushButton#ShellAssistantButton {{ + font-family: "{body_family()}"; font-weight: 600; font-size: 13px; + color: #FFFFFF; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #149A91, stop:1 {TECH_BLUE['accent']}); + border: 1px solid rgba(255, 255, 255, 36); + border-radius: 8px; + }} + QPushButton#ShellAssistantButton:hover {{ + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #19B2A8, stop:1 #0E8079); + border-color: rgba(223, 199, 147, 110); + }} + QPushButton#ShellAssistantButton:pressed {{ + background-color: {TECH_BLUE['accent_pressed']}; + }} + QPushButton#ShellAssistantButton:focus {{ + border: 1px solid #4AC5BA; + }} + QPushButton#ShellSettingsButton {{ + font-family: "{body_family()}"; font-weight: 500; font-size: 13px; + min-height: 44px; max-height: 44px; + text-align: left; padding: 0 24px; + color: {TECH_BLUE['muted']}; + border-radius: 9px; + }} + QPushButton#ShellSettingsButton:hover {{ + color: {TECH_BLUE['heading']}; + background-color: rgba(11, 110, 104, 16); + }} + """ + if widget is self.topbar: + stylesheet += f""" + QFrame#TopBar {{ + border-radius: 0; + background-color: {TECH_BLUE['surface']}; + border-bottom: 1px solid {_RECEPTION_CHROME_LINE}; + }} + QFrame#ShellGlobalSearch {{ + background-color: #F2F7F6; + border: 1px solid #D9E5E3; + border-radius: 10px; + }} + QFrame#ShellGlobalSearch:hover {{ + border-color: #A8CAC5; + background-color: #F8FCFB; + }} + QFrame#ShellUserSeparator {{ background: {_RECEPTION_CHROME_LINE}; border: 0; }} + QPushButton#ShellShortcutHint, + QLabel#ShellShortcutHint {{ + font-family: "{number_family()}"; font-size: 11px; + color: {TECH_BLUE['muted']}; + background-color: #FFFFFF; + padding: 2px 8px; border-radius: 6px; + border: 1px solid #D4E1DE; + min-height: 22px; max-height: 22px; + }} + QPushButton#ShellShortcutHint:hover {{ + color: {TECH_BLUE['accent']}; + background-color: #E8F5F3; + border-color: #93CBC3; + }} + QLineEdit#ShellGlobalSearchInput {{ + color: {TECH_BLUE['heading']}; font-size: 13px; + min-height: 36px; max-height: 36px; + }} + QPushButton#ShellAiEntry:pressed {{ background: {TECH_BLUE['selection']}; }} + QPushButton#ShellAiEntry:focus {{ border: 1px solid {TECH_BLUE['focus']}; }} + QLabel#ShellConnectionBadge {{ font-weight: 500; }} + """ + if widget is self.user_menu_button: + stylesheet += f""" + QToolButton#ShellUserMenu {{ + font-family: "{body_family()}"; font-weight: 400; + color: {TECH_BLUE['heading']}; font-size: 13px; + }} + """ + if widget is self.workspace: + stylesheet += "QWidget#ShellWorkspace { border-radius: 0; }" + if widget is self.stack: + stylesheet += "QStackedWidget#ShellPageStack { border-radius: 0; }" + if isinstance(widget, _PaintedIconButton): + side = 36 if widget in (self.refresh_button, self.notification_button, self.settings_button, self.fold_button) else 32 + stylesheet += f"QToolButton#ShellPaintedIconButton {{ min-width: {side - 2}px; max-width: {side - 2}px; min-height: {side - 2}px; max-height: {side - 2}px; }}" + widget.setStyleSheet(clinical_stylesheet(stylesheet)) + + self._set_reception_geometry(active) + for widget in ( + self.centralWidget(), self.brand_mark, self.assistant_glyph, self.assistant_status, + self.upload_settings_button, + ): + widget.setProperty("receptionTechBlue", active) + widget.update() + self.user_menu_button.set_reception_avatar(active) + for widget in self.topbar.findChildren(_PaintedIconButton): + size = 20 if active else 18 + widget.setIconSize(QSize(size, size)) + if isinstance(widget, _RefreshButton): + widget.set_reception_palette(active) + else: + widget.setIcon(_painted_shell_icon(widget.kind, size, reception=active)) + self.ai_top_button.setIcon(_painted_shell_icon("ai", reception=active)) + self._global_search_icon_action.setIcon( + _painted_shell_icon("search", 20 if active else 16, reception=active) + ) + self.search_mark.setIcon(_painted_shell_icon("search", 16, reception=True)) + self.search_mark.setIconSize(QSize(16, 16)) + for key, button in self.nav_buttons.items(): + size = 20 if active else 18 + button.setProperty("receptionTechBlue", active) + button.setIconSize(QSize(size, size)) + button.setIcon(_painted_navigation_icon(key, size, reception=active)) + button.update() + + def _sync_window_state_chrome(self) -> None: + """同步窗口最大化/还原态的按钮图标、提示文案与圆角外框绘制。""" + + maximized = self.isMaximized() + icon_kind = "restore" if maximized else "fullscreen" + self.fullscreen_button.kind = icon_kind + icon_size = self.fullscreen_button.iconSize().width() or 18 + self.fullscreen_button.setIcon( + _painted_shell_icon( + icon_kind, + icon_size, + reception=self._reception_chrome_active, + ) + ) + self.fullscreen_button.setToolTip("还原" if maximized else "最大化") + if self.centralWidget() is not None: + self.centralWidget().update() + + def changeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + super().changeEvent(event) + if event.type() == QEvent.Type.WindowStateChange and hasattr(self, "fullscreen_button"): + self._sync_window_state_chrome() + + def _toggle_maximized(self) -> None: + if self.isMaximized(): + self.showNormal() + else: + self.showMaximized() + self._sync_window_state_chrome() + + def _toggle_fullscreen(self) -> None: + if self.isFullScreen(): + self.showNormal() + self.fullscreen_button.setToolTip("全屏模式") + else: + self.showFullScreen() + self.fullscreen_button.setToolTip("退出全屏") + + def open_command_palette(self) -> None: + """打开 Ctrl+K 悬浮智诊命令中枢,提供页面跳转、常用操作与患者检索。""" + + page_subtitles = { + "appointments": "今日挂号、号源排班与患者分诊", + "reception": "三栏接诊工作台、四诊病历与视频问诊", + "consultations": "历史问诊诊单检索与复诊记录", + "patients": "我的在管糖尿病患者档案与随访", + "prescriptions": "已开具电子处方审核与签署状态", + "prescription_library": "个人与科室常用经验方库管理", + } + entries: list[CommandEntry] = [] + for idx, (item, title) in enumerate(self.navigation, start=1): + if item.key not in self.pages: + continue + entries.append( + CommandEntry( + key=f"nav:{item.key}", + title=f"切换到 {title}", + subtitle=page_subtitles.get(item.key, f"进入「{title}」工作区"), + icon_kind=item.key if item.key in icons.available_kinds() else "document", + category="页面", + shortcut=f"Alt+{idx}" if idx <= 6 else "", + action=lambda page_key=item.key: self.navigate(page_key), + ) + ) + + if self._can_ai_assistant: + entries.append( + CommandEntry( + key="action:ai", + title="启动 AI 临床辨证助手", + subtitle="多模态梳理患者复诊趋势与处方建议", + icon_kind="ai", + category="智能", + shortcut="", + action=self._open_ai_assistant, + ) + ) + entries.extend( + [ + CommandEntry( + key="action:refresh", + title="刷新当前工作区", + subtitle="重新拉取当前列表与临床详情数据", + icon_kind="refresh", + category="操作", + shortcut="F5", + action=self.refresh_current_page, + ), + CommandEntry( + key="action:sidebar", + title="展开 / 收起左侧导航栏", + subtitle="扩大右侧主视窗操作空间", + icon_kind="fold", + category="视窗", + shortcut="Ctrl+B", + action=self.toggle_sidebar, + ), + CommandEntry( + key="action:companion", + title="展开 / 收起右侧临床伴随舱", + subtitle="AI 快捷入口、待办消息与录音状态一体化侧舱", + icon_kind="settings", + category="视窗", + shortcut="Ctrl+]", + action=self.toggle_companion_dock, + ), + CommandEntry( + key="action:search", + title="聚焦顶部全局患者搜索框", + subtitle="直接按姓名或手机号检索患者档案", + icon_kind="search", + category="检索", + shortcut="", + action=self._focus_global_search, + ), + CommandEntry( + key="action:audio", + title="查看本机录音上传记录", + subtitle="管理待上传与已同步的问诊录音队列", + icon_kind="settings", + category="系统", + shortcut="", + action=self._open_local_audio_settings, + ), + CommandEntry( + key="action:update", + title="检查桌面端版本更新", + subtitle="连接发布通道核验最新版本", + icon_kind="refresh", + category="系统", + shortcut="", + action=self.update_check_requested.emit, + ), + ] + ) + + def _search_patient(query: str) -> None: + self.global_search.setText(query) + self._run_global_search() + + dialog = CommandPaletteDialog( + entries, + on_search_patient=_search_patient, + initial_query=self.global_search.text().strip(), + parent=self, + ) + dialog.exec() + dialog.deleteLater() + + def _build_companion_dock(self) -> QFrame: + """构建 Clinical OS 2.0 右侧可折叠临床伴随舱(默认隐藏,Ctrl+] 或顶栏一键展开)。""" + + dock = QFrame(self.workspace) + dock.setObjectName("ShellCompanionDock") + dock.setFixedWidth(316) + dock.setStyleSheet( + clinical_stylesheet( + r""" + QFrame#ShellCompanionDock { + background-color: #F5FAF9; + border: 0; + border-left: 1px solid #CBE0DC; + } + QFrame#CompanionAiPanel { + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #103231, stop:1 #071919); + border: 1px solid rgba(223, 199, 147, 96); + border-radius: 13px; + } + QFrame#CompanionCard { + background-color: #FFFFFF; + border: 1px solid $ds_line; + border-radius: 12px; + } + QLabel#CompanionHeading { + color: $ds_heading; + font-size: 14px; + font-weight: 600; + } + QLabel#CompanionMuted { + color: $ds_muted; + font-size: 12px; + } + """ + ) + ) + root = QVBoxLayout(dock) + root.setContentsMargins(0, 0, 0, 0) + root.setSpacing(0) + root.addWidget(ClinicalAccentBar(dock)) + + header = QWidget(dock) + header_layout = QHBoxLayout(header) + header_layout.setContentsMargins(16, 12, 12, 10) + title = QLabel("临床伴随舱", header) + title.setObjectName("CompanionHeading") + header_layout.addWidget(title) + header_layout.addStretch(1) + close_btn = QToolButton(header) + close_btn.setAutoRaise(True) + close_btn.setFixedSize(28, 28) + close_btn.setCursor(Qt.CursorShape.PointingHandCursor) + close_btn.setIcon(icons.icon("close", "muted", 14)) + close_btn.setIconSize(QSize(14, 14)) + close_btn.setToolTip("收起伴随舱(Ctrl+])") + close_btn.clicked.connect(self.toggle_companion_dock) + header_layout.addWidget(close_btn) + root.addWidget(header) + + body = QVBoxLayout() + body.setContentsMargins(14, 4, 14, 16) + body.setSpacing(12) + + # 1. 黑曜翡翠 AI 快捷副驾卡 + ai_panel = QFrame(dock) + ai_panel.setObjectName("CompanionAiPanel") + ai_layout = QVBoxLayout(ai_panel) + ai_layout.setContentsMargins(14, 13, 14, 13) + ai_layout.setSpacing(8) + ai_title = QLabel("AI 临床辨证副驾", ai_panel) + ai_title.setStyleSheet("color: #DFC793; font-size: 13px; font-weight: 600;") + ai_layout.addWidget(ai_title) + ai_desc = QLabel( + "支持随时发起多模型辨证分析、复诊血糖走势研判与处方一致度预审。", + ai_panel, + ) + ai_desc.setWordWrap(True) + ai_desc.setStyleSheet("color: #B4D4D0; font-size: 12px;") + ai_layout.addWidget(ai_desc) + ai_btn = QPushButton("打开 AI 辨证工作台", ai_panel) + ai_btn.setProperty("variant", "primary") + ai_btn.setCursor(Qt.CursorShape.PointingHandCursor) + ai_btn.setFixedHeight(34) + ai_btn.clicked.connect(self._open_ai_assistant) + ai_layout.addWidget(ai_btn) + ai_panel.setVisible(self._can_ai_assistant) + body.addWidget(ai_panel) + + # 2. 临床消息与待办卡 + notify_card = QFrame(dock) + notify_card.setObjectName("CompanionCard") + n_layout = QVBoxLayout(notify_card) + n_layout.setContentsMargins(13, 12, 13, 12) + n_layout.setSpacing(6) + n_title = QLabel("实时临床消息", notify_card) + n_title.setObjectName("CompanionHeading") + n_layout.addWidget(n_title) + self._companion_notify_label = QLabel("当前无待处理会话通知。", notify_card) + self._companion_notify_label.setObjectName("CompanionMuted") + self._companion_notify_label.setWordWrap(True) + n_layout.addWidget(self._companion_notify_label) + body.addWidget(notify_card) + + # 3. 录音与系统维护快捷卡 + util_card = QFrame(dock) + util_card.setObjectName("CompanionCard") + u_layout = QVBoxLayout(util_card) + u_layout.setContentsMargins(13, 12, 13, 12) + u_layout.setSpacing(8) + u_title = QLabel("效率工具与系统状态", util_card) + u_title.setObjectName("CompanionHeading") + u_layout.addWidget(u_title) + audio_btn = QPushButton("本机问诊录音上传队列", util_card) + audio_btn.setProperty("variant", "secondary") + audio_btn.setFixedHeight(34) + audio_btn.clicked.connect(self._open_local_audio_settings) + u_layout.addWidget(audio_btn) + cmd_btn = QPushButton("智诊指令中枢(Ctrl+K)", util_card) + cmd_btn.setProperty("variant", "secondary") + cmd_btn.setFixedHeight(34) + cmd_btn.clicked.connect(self.open_command_palette) + u_layout.addWidget(cmd_btn) + shortcuts_hint = QLabel( + "快捷键:Alt+1~6 切页 · Ctrl+B 侧栏 · F5 刷新", + util_card, + ) + shortcuts_hint.setObjectName("CompanionMuted") + shortcuts_hint.setWordWrap(True) + u_layout.addWidget(shortcuts_hint) + body.addWidget(util_card) + + body.addStretch(1) + root.addLayout(body, 1) + dock.hide() + return dock + + def toggle_companion_dock(self) -> None: + """展开或收起右侧临床伴随舱,并同步最新通知摘要。""" + + if not hasattr(self, "companion_dock"): + return + showing = not self.companion_dock.isVisible() + if showing: + pending = self.chat_notifications.pending + if pending: + latest = pending[0] + self._companion_notify_label.setText( + f"待处理 {len(pending)} 条 · 最新:{latest.title}({latest.description})" + ) + else: + self._companion_notify_label.setText("当前无待处理会话通知,轮询服务在线。") + self.companion_dock.show() + if not motion.reduced_motion(): + motion.fade_in(self.companion_dock) + else: + self.companion_dock.hide() + + def _focus_global_search(self) -> None: + self.global_search.setFocus(Qt.FocusReason.ShortcutFocusReason) + self.global_search.selectAll() + + def _run_global_search(self) -> None: + query = self.global_search.text().strip() + keys = ("patients", "consultations") if self._active_page_key == "patients" else ( + "consultations", "patients", + ) + for key in keys: + # Only use patient pages already registered by permission-aware navigation. + page = self.pages.get(key) + search = getattr(page, "search_patient", None) + if page is None or key not in self.nav_buttons or not callable(search): + continue + self._navigate( + self.stack.indexOf(page), key, on_activate=lambda search=search: search(query), + ) + return + show_toast(self, "当前账号没有可用的患者搜索页面。", "warning") + + def _open_ai_assistant(self) -> None: + if not self._can_ai_assistant: + show_toast(self, "当前账号没有使用 AI 问诊助手的权限。", "danger") + return + + # The shell assistant is the global entry point. Always let the doctor + # choose from the complete permission-scoped patient list, even when a + # page happens to retain a selected row. Page-level AI actions keep the + # faster "open the selected patient" behaviour. + select_and_present_ai_consult( + self.repository, + self.permissions, + self, + initial_query=self.global_search.text().strip(), + ) + + def _open_esign_doctor(self) -> None: + dialog = EsignDoctorDialog(self.repository, parent=self) + dialog.exec() + dialog.deleteLater() + + def _open_local_audio_settings(self) -> None: + current = self._local_audio_settings_dialog + if current is not None and current.isVisible(): + current.raise_() + current.activateWindow() + return + try: + dialog = LocalAudioQueueDialog(self.repository, None, self) + except (OSError, RuntimeError, ValueError, sqlite3.Error) as error: + show_toast(self, f"无法打开本机录音上传设置:{error}", "error") + return + self._local_audio_settings_dialog = dialog + + def clear_dialog(_result: int) -> None: + if self._local_audio_settings_dialog is dialog: + self._local_audio_settings_dialog = None + + dialog.finished.connect(clear_dialog) + dialog.open() + + def _tab_index_for_key(self, key: str) -> int: + for index in range(self.tab_bar.count()): + if self.tab_bar.tabData(index) == key: + return index + return -1 + + def visited_tab_keys(self) -> tuple[str, ...]: + """Return open tabs in visit order for tests and session diagnostics.""" + + return tuple( + str(self.tab_bar.tabData(index)) for index in range(self.tab_bar.count()) + ) + + def _ensure_tab(self, key: str, title: str) -> int: + index = self._tab_index_for_key(key) + if index >= 0: + self.tab_bar.setTabText(index, title) + return index + index = self.tab_bar.addTab(title) + self.tab_bar.setTabData(index, key) + if self._fixed_tab_key is None: + self._fixed_tab_key = key + else: + close_button = _PaintedIconButton("close", size=18, parent=self.tab_bar) + close_button.setToolTip(f"关闭 {title}") + close_button.setAccessibleName(f"关闭标签页:{title}") + close_button.clicked.connect( + lambda _checked=False, page_key=key: self.close_tab(page_key) + ) + self.tab_bar.setTabButton( + index, QTabBar.ButtonPosition.RightSide, close_button + ) + self._update_tab_actions() + return index + + def _set_current_tab(self, key: str) -> None: + index = self._tab_index_for_key(key) + if index < 0: + return + blocked = self.tab_bar.blockSignals(True) + self.tab_bar.setCurrentIndex(index) + self.tab_bar.blockSignals(blocked) + self._update_tab_actions() + + def _tab_selected(self, index: int) -> None: + if index < 0: + return + key = str(self.tab_bar.tabData(index) or "") + page = self.pages.get(key) + if page is None: + return + self._navigate(self.stack.indexOf(page), key) + + def _update_tab_actions(self) -> None: + if not hasattr(self, "close_current_action"): + return + current_index = self.tab_bar.currentIndex() + current_key = ( + str(self.tab_bar.tabData(current_index) or "") if current_index >= 0 else "" + ) + removable = [ + key for key in self.visited_tab_keys() if key != self._fixed_tab_key + ] + self.close_current_action.setEnabled( + bool(current_key and current_key != self._fixed_tab_key) + ) + self.close_other_action.setEnabled(any(key != current_key for key in removable)) + self.close_all_action.setEnabled(bool(removable)) + + def close_tab(self, key: str) -> bool: + """Close one non-fixed visited page and re-route if it was active.""" + + index = self._tab_index_for_key(key) + if index < 0 or key == self._fixed_tab_key: + return False + active_key = "" + if self.tab_bar.currentIndex() >= 0: + active_key = str(self.tab_bar.tabData(self.tab_bar.currentIndex()) or "") + keys = list(self.visited_tab_keys()) + fallback = keys[index - 1] if index > 0 else keys[index + 1] + + close_button = self.tab_bar.tabButton(index, QTabBar.ButtonPosition.RightSide) + blocked = self.tab_bar.blockSignals(True) + self.tab_bar.removeTab(index) + self.tab_bar.blockSignals(blocked) + if close_button is not None: + close_button.deleteLater() + + if active_key == key: + self.navigate(fallback) + else: + self._set_current_tab(active_key) + self._update_tab_actions() + return True + + def close_current_tab(self) -> bool: + index = self.tab_bar.currentIndex() + if index < 0: + return False + return self.close_tab(str(self.tab_bar.tabData(index) or "")) + + def close_other_tabs(self) -> None: + current_index = self.tab_bar.currentIndex() + current_key = ( + str(self.tab_bar.tabData(current_index) or "") if current_index >= 0 else "" + ) + keep = {current_key, self._fixed_tab_key} + for key in reversed(self.visited_tab_keys()): + if key not in keep: + self.close_tab(key) + if current_key: + self._set_current_tab(current_key) + self._update_tab_actions() + + def close_all_tabs(self) -> None: + for key in reversed(self.visited_tab_keys()): + if key != self._fixed_tab_key: + self.close_tab(key) + if self._fixed_tab_key: + self.navigate(self._fixed_tab_key) + self._update_tab_actions() + + def _register_pages(self) -> None: + self.nav_group = QButtonGroup(self) + self.nav_group.setExclusive(True) + first_button: QPushButton | None = None + for item, title in self.navigation: + page = item.page_type( + self.repository, + permissions=self.permissions, + current_user=self.current_user, + parent=self.stack, + ) + self._install_activation_refresh_gate(page) + if hasattr(page, "video_requested"): + page.video_requested.connect( + lambda payload: self.video_requested.emit(payload) + ) + index = self.stack.addWidget(page) + self.pages[item.key] = page + self.page_titles[index] = title + + button = _ShellNavigationButton(title) + button.setObjectName("ShellNavButton") + button.setIcon(_painted_navigation_icon(item.key)) + button.setIconSize(QSize(18, 18)) + button.setProperty("navGlyph", item.glyph) + button.setProperty("navTitle", title) + button.setCheckable(True) + button.setCursor(Qt.CursorShape.PointingHandCursor) + button.clicked.connect( + lambda _checked=False, page_index=index, key=item.key: self._navigate( + page_index, key + ) + ) + self.nav_group.addButton(button, index) + self.nav_layout.addWidget(button) + self.nav_buttons[item.key] = button + if first_button is None: + first_button = button + + if first_button is None: + denied = EmptyState( + "暂无可用工作区", + "当前账号没有医生工作站页面权限,请联系管理员调整授权。", + ) + index = self.stack.addWidget(denied) + self.page_titles[index] = "权限受限" + self.stack.setCurrentIndex(index) + self.context_label.setText("权限受限") + return + first_button.setChecked(True) + first_index = self.nav_group.id(first_button) + self._navigate( + first_index, + next( + key + for key, button in self.nav_buttons.items() + if button is first_button + ), + ) + + def _install_activation_refresh_gate(self, page: QWidget) -> None: + """Coalesce lifecycle and shell refreshes during one page activation.""" + + refresh = getattr(page, "refresh", None) + if not callable(refresh): + return + + @wraps(refresh) + def activation_refresh(*args: Any, **kwargs: Any) -> Any: + if page is self._activation_page: + if self._activation_refreshed: + return None + self._activation_refreshed = True + return refresh(*args, **kwargs) + + page.refresh = activation_refresh # type: ignore[attr-defined,method-assign] + + def _ensure_activation_refresh(self, page: QWidget, generation: int) -> None: + if generation != self._activation_generation or page is not self._activation_page: + return + if not self._activation_refreshed: + refresh = getattr(page, "refresh", None) + if callable(refresh): + refresh() + + def _finish_activation(self, page: QWidget, generation: int) -> None: + if generation != self._activation_generation or page is not self._activation_page: + return + self._ensure_activation_refresh(page, generation) + self._activation_page = None + + def _navigate( + self, index: int, key: str, *, on_activate: Callable[[], None] | None = None, + ) -> None: + if index < 0 or index >= self.stack.count(): + return + page = self.stack.widget(index) + if page is None: + return + if self._active_page_key == key and self.stack.currentWidget() is page: + if on_activate is not None: + self._activation_refreshed = False + on_activate() + return + self._activation_generation += 1 + activation_generation = self._activation_generation + self._activation_page = page + self._activation_refreshed = False + if on_activate is not None: + on_activate() + # A stack swap is otherwise a hard cut between two frames: this is the + # transition a doctor sees on every sidebar click all day. + motion.switch_stack(self.stack, index) + title = self.page_titles.get(index, "工作台") + self.context_label.setText(title) + self._ensure_tab(key, title) + self._set_current_tab(key) + button = self.nav_buttons.get(key) + if button is not None: + button.setChecked(True) + self._active_page_key = key + self._set_reception_chrome(key in _TECH_BLUE_PAGES) + self._ensure_activation_refresh(page, activation_generation) + if self.isVisible(): + QTimer.singleShot( + 0, + lambda page=page, generation=activation_generation: self._finish_activation( + page, generation + ), + ) + self.page_changed.emit(key) + + def navigate(self, key: str) -> bool: + """Navigate to a visible page by stable key; return whether it exists.""" + + button = self.nav_buttons.get(key) + page = self.pages.get(key) + if button is None or page is None: + return False + self._navigate(self.stack.indexOf(page), key) + return True + + #: Attributes the pages use to say "a request is in flight". Nothing forces + #: a page to have one, so a page without any of these simply gets the + #: minimum spin rather than an accurate one. + _LOADING_FLAGS = ("_loading", "_queue_loading", "_detail_loading") + + def _current_page_is_loading(self) -> bool: + page = self.stack.currentWidget() + return any(bool(getattr(page, flag, False)) for flag in self._LOADING_FLAGS) + + def refresh_current_page(self) -> None: + page = self.stack.currentWidget() + refresh = getattr(page, "refresh", None) + if not callable(refresh): + return + button = getattr(self, "refresh_button", None) + if isinstance(button, _RefreshButton): + button.start_spin() + refresh() + + def _ensure_global_diagnosis_dialog(self) -> DiagnosisDialog: + dialog = self._global_diagnosis_dialog + if dialog is None: + dialog = DiagnosisDialog( + self.repository, + self, + permissions=self.permissions, + ) + dialog.saved.connect(self.refresh_current_page) + self._global_diagnosis_dialog = dialog + else: + dialog.refresh_permissions(self.permissions) + return dialog + + def open_diagnosis_by_id( + self, + diagnosis_id: Any, + *, + modeless: bool = False, + ) -> DiagnosisDialog | None: + """Open one authoritative diagnosis in the strongest permitted mode.""" + + try: + normalized_id = int(diagnosis_id) + except (TypeError, ValueError): + normalized_id = 0 + if normalized_id <= 0: + show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600) + return None + + if has_permission(self.permissions, "tcm.diagnosis/edit", default=False): + dialog = self._ensure_global_diagnosis_dialog() + dialog.open_for(normalized_id, editable=True, modeless=modeless) + elif has_permission( + self.permissions, + "tcm.diagnosis/readonlyDetail", + default=False, + ): + dialog = self._ensure_global_diagnosis_dialog() + dialog.open_view_only(normalized_id, modeless=modeless) + else: + show_toast(self, "当前账号没有查看该诊单的权限。", "danger", 4200) + return None + + dialog.raise_() + dialog.activateWindow() + return dialog + + def showEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + super().showEvent(event) + # 登录后就开始轮询:不管医生停在哪个页面,患者进入会话都要提示。 + self.chat_notifications.start() + page = self.stack.currentWidget() + if page is None or page is not self._activation_page: + return + generation = self._activation_generation + QTimer.singleShot( + 0, + lambda page=page, generation=generation: self._finish_activation(page, generation), + ) + + def closeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + self.chat_notifications.stop() + super().closeEvent(event) + if event.isAccepted(): + self.close_requested.emit() + + def _open_chat_notification(self, notification: ChatNotification) -> None: + """Take the doctor where the notification's work actually lives.""" + + if notification.kind == CONSULTATION_COMPLETE and notification.diagnosis_id > 0: + self.open_diagnosis_by_id(notification.diagnosis_id, modeless=True) + return + if notification.kind == PATIENT_OPENED_CHAT and self.navigate("reception"): + return + show_toast(self, notification.description, "info", 4200) + + def _show_chat_notification_summary(self) -> None: + pending = self.chat_notifications.pending + if not pending: + show_toast(self, "当前没有新的系统通知。", "info") + return + latest = pending[0] + show_toast( + self, + f"待处理通知 {len(pending)} 条,最新:{latest.title} · {latest.description}", + "info", + 4200, + ) + + def setVisible(self, visible: bool) -> None: # noqa: N802 - Qt API + if visible: + self.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, False) + super().setVisible(visible) + + def set_connection_state(self, online: bool, message: str = "") -> None: + self.connection_badge.set_status( + message or ("服务正常" if online else "连接中断"), + "success" if online else "danger", + ) + self.assistant_status.setText("在线" if online else "服务离线") + self.assistant_status.set_online(online) + + +__all__ = ["NAVIGATION", "NavigationItem", "ShellWindow"] diff --git a/app/src/doctor_workstation/ui/theme.py b/app/src/doctor_workstation/ui/theme.py index e62654238..024e5c360 100755 --- a/app/src/doctor_workstation/ui/theme.py +++ b/app/src/doctor_workstation/ui/theme.py @@ -40,7 +40,7 @@ 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 . import interactions, motion from .design_system import PALETTE, RADII, SPACING, clinical_stylesheet # Shared reading colors keep native pages and dialog chrome consistent. @@ -81,6 +81,11 @@ COLORS = { "teal": PALETTE["accent"], "teal_dark": PALETTE["accent_pressed"], "teal_pale": PALETTE["accent_soft"], + "gold": PALETTE["gold"], + "gold_light": PALETTE["gold_light"], + "gold_soft": PALETTE["gold_soft"], + "obsidian": PALETTE["obsidian"], + "obsidian_alt": PALETTE["obsidian_alt"], } @@ -375,12 +380,12 @@ QPushButton:disabled { QPushButton[variant="primary"] { color: #FFFFFF; - background-color: $indigo; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $indigo); border-color: $indigo; } QPushButton[variant="primary"]:hover, QPushButton[variant="primary"]:checked:hover { - background-color: $indigo_hover; + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $indigo_hover); border-color: $indigo_hover; } QPushButton[variant="primary"]:pressed, @@ -389,7 +394,7 @@ QPushButton[variant="primary"]:checked { border-color: $indigo_pressed; } QPushButton[variant="primary"]:focus { - border: 1px solid $indigo_pressed; + border: 1px solid $focus; background-color: $indigo_hover; } QPushButton[variant="primary"]:disabled { @@ -401,12 +406,12 @@ QPushButton[variant="primary"]:disabled { QPushButton[variant="secondary"] { color: $indigo_hover; background-color: $indigo_pale; - border-color: $indigo_pale; + border-color: #C4E2DD; } QPushButton[variant="secondary"]:hover { color: $indigo_pressed; - background-color: $raised; - border-color: $indigo_hover; + background-color: #D7EFEA; + border-color: #9CCFC7; } QPushButton[variant="secondary"]:pressed, QPushButton[variant="secondary"]:checked { @@ -616,7 +621,7 @@ QLineEdit, QTextEdit, QPlainTextEdit, QComboBox, QDateEdit, QDateTimeEdit, QTimeEdit, QSpinBox, QDoubleSpinBox, QKeySequenceEdit { min-height: $h_default; padding: 0 $pad_control; - border: 1px solid $line; + border: 1px solid $line_soft; border-radius: $r_md; background-color: $surface; color: $text; @@ -626,11 +631,11 @@ QTimeEdit, QSpinBox, QDoubleSpinBox, QKeySequenceEdit { 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; } +QDoubleSpinBox:hover, QKeySequenceEdit:hover { border-color: #8FBDB6; } QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus, QComboBox:focus, QDateEdit:focus, QDateTimeEdit:focus, QTimeEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QKeySequenceEdit:focus { - border: 1px solid $indigo; + border: 1.5px solid $focus; background-color: $surface; } QLineEdit:read-only, QTextEdit:read-only, QPlainTextEdit:read-only { @@ -1500,15 +1505,28 @@ def _size_new_window_to_main(window: QWidget) -> None: 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) + # 紧凑业务轻弹窗(如二维码、完成确认、收退款、更新等)保持自身合理尺寸并居中, + # 仅大型工作台窗口(宽>=760 且高>=640)扩展至主视窗 85%,避免小窗被强行撑大造成内容错位。 + current_size = window.size() + hint_size = window.sizeHint() + desired_w = max(current_size.width(), hint_size.width(), window.minimumWidth()) + desired_h = max(current_size.height(), hint_size.height(), window.minimumHeight()) + is_compact_dialog = isinstance(window, QDialog) and (desired_w < 760 or desired_h < 640) + if is_compact_dialog: + final_width = min(desired_w, target_width) + final_height = min(desired_h, target_height) + else: + final_width = target_width + final_height = target_height + if window.minimumWidth() > final_width: + window.setMinimumWidth(final_width) + if window.minimumHeight() > final_height: + window.setMinimumHeight(final_height) + if window.maximumWidth() < final_width: + window.setMaximumWidth(final_width) + if window.maximumHeight() < final_height: + window.setMaximumHeight(final_height) + window.resize(final_width, final_height) frame = window.frameGeometry() window.move( target.center().x() - frame.width() // 2, @@ -1583,6 +1601,7 @@ class _BusinessDialogStyleFilter(QObject): def _install_business_dialog_styling(app: QApplication) -> None: + interactions.install_tactile_interactions(app) existing = getattr(app, "_doctor_business_dialog_style_filter", None) if existing is not None: return diff --git a/app/src/doctor_workstation/ui/window_primitives.py b/app/src/doctor_workstation/ui/window_primitives.py new file mode 100644 index 000000000..1b8d5e1c4 --- /dev/null +++ b/app/src/doctor_workstation/ui/window_primitives.py @@ -0,0 +1,486 @@ +"""Clinical OS 2.0 统一桌面视窗原语库(W8 三大标准视窗容器 + W3 主从组件)。 + +提供跨全站 35+ 窗口复用的结构级原生组件,彻底告别杂乱的原生灰白弹窗与后台套壳: +1. 原语 A · ClinicalSlideDrawer:右侧 520px 非阻塞滑出工作抽屉(吸顶标题 + 吸底操作条) +2. 原语 B · ClinicalModalDialog:居中无边框 16px 圆角奢雅轻模态窗(顶部翡翠-鎏金渐层饰线) +3. 原语 C · ClinicalToastFrame:右下角黑曜翡翠临床实时提醒浮卡样式基类 +4. W3 主从组件 · ClinicalInspectorPanel(420px 滑出临床检视器)与 ClinicalFloatingDock(选中浮现操作坞) +""" + +from __future__ import annotations + +from typing import Any + +from PySide6.QtCore import QPoint, QRectF, QSize, Qt, Signal +from PySide6.QtGui import ( + QColor, + QLinearGradient, + QMouseEvent, + QPainter, + QPen, +) +from PySide6.QtWidgets import ( + QDialog, + QFrame, + QHBoxLayout, + QLabel, + QPushButton, + QScrollArea, + QSizePolicy, + QToolButton, + QVBoxLayout, + QWidget, +) + +from . import icons, motion +from .design_system import PALETTE, clinical_stylesheet + +# 统一原语样式表(基于御瓷智医设计令牌) +WINDOW_PRIMITIVES_QSS = clinical_stylesheet( + r""" + QFrame#ClinicalInspectorPanel { + background-color: $ds_surface; + border: 1px solid #BCD6D1; + border-radius: 14px; + } + QFrame#ClinicalInspectorHeader { + background-color: #F6FBFA; + border: 0; + border-bottom: 1px solid $ds_line; + border-top-left-radius: 14px; + border-top-right-radius: 14px; + } + QLabel#ClinicalInspectorTitle { + color: $ds_heading; + font-size: 16px; + font-weight: 600; + } + QLabel#ClinicalInspectorSubtitle { + color: $ds_muted; + font-size: 12px; + } + QFrame#ClinicalInspectorSummaryBox { + background-color: #F4F9F8; + border: 1px solid $ds_line; + border-radius: 10px; + } + QFrame#ClinicalFloatingDock { + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #0E2B2A, stop:1 #071919); + border: 1px solid rgba(223, 199, 147, 130); + border-radius: 14px; + } + QLabel#ClinicalFloatingDockCount { + color: #DFC793; + font-size: 13px; + font-weight: 600; + } + QFrame#ClinicalFloatingDock QPushButton { + min-height: 30px; + max-height: 30px; + padding: 0 12px; + border-radius: 8px; + background-color: rgba(255, 255, 255, 24); + border: 1px solid rgba(255, 255, 255, 42); + color: #F2FAF9; + font-size: 12px; + font-weight: 500; + } + QFrame#ClinicalFloatingDock QPushButton:hover { + background-color: rgba(24, 176, 165, 90); + border-color: #DFC793; + color: #FFFFFF; + } + QFrame#ClinicalFloatingDock QPushButton[dockDanger="true"] { + background-color: rgba(214, 63, 79, 210); + border-color: #D63F4F; + color: #FFFFFF; + } + QFrame#ClinicalFloatingDock QPushButton[dockDanger="true"]:hover { + background-color: #B92E3D; + } + QFrame#ClinicalKpiTile { + background-color: $ds_surface; + border: 1px solid $ds_line; + border-radius: 12px; + } + QFrame#ClinicalKpiTile:hover { + border-color: #8FC8C0; + background-color: #F9FDFC; + } + QFrame#ClinicalKpiTile[active="true"] { + background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #EBF8F6, stop:1 #FFFFFF); + border: 1.5px solid $ds_accent; + } + QFrame#ClinicalAccentHeader { + background-color: #F6FBFA; + border: 0; + border-bottom: 1px solid $ds_line; + } + QLabel#ClinicalAccentHeaderTitle { + color: $ds_heading; + font-size: 15px; + font-weight: 600; + } + QLabel#ClinicalAccentHeaderSub { + color: $ds_muted; + font-size: 12px; + } + """ +) + + +class ClinicalAccentBar(QWidget): + """顶部 3px 翡翠青至香槟鎏金渐变饰线,统一所有高级视窗与工作室的奢雅科技识别。""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setFixedHeight(3) + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + del event + painter = QPainter(self) + grad = QLinearGradient(0.0, 0.0, float(self.width()), 0.0) + grad.setColorAt(0.0, QColor(PALETTE["accent"])) + grad.setColorAt(0.58, QColor("#18B0A5")) + grad.setColorAt(1.0, QColor(PALETTE["gold_light"])) + painter.fillRect(self.rect(), grad) + painter.end() + + +def apply_luxury_dialog_chrome( + dialog: QDialog, + *, + title: str = "", + subtitle: str = "", +) -> QFrame | None: + """为现有业务 QDialog 注入顶部翡翠-鎏金饰线与结构化页眉(零侵入兼容既有逻辑)。""" + + if getattr(dialog, "_luxury_chrome_installed", False): + return None + layout = dialog.layout() + if not isinstance(layout, QVBoxLayout): + return None + dialog._luxury_chrome_installed = True # type: ignore[attr-defined] + bar = ClinicalAccentBar(dialog) + layout.insertWidget(0, bar) + header: QFrame | None = None + if title: + header = QFrame(dialog) + header.setObjectName("ClinicalAccentHeader") + header.setStyleSheet(WINDOW_PRIMITIVES_QSS) + h_layout = QHBoxLayout(header) + h_layout.setContentsMargins(18, 11, 16, 11) + h_layout.setSpacing(10) + copy = QVBoxLayout() + copy.setContentsMargins(0, 0, 0, 0) + copy.setSpacing(2) + t_lbl = QLabel(title, header) + t_lbl.setObjectName("ClinicalAccentHeaderTitle") + copy.addWidget(t_lbl) + if subtitle: + s_lbl = QLabel(subtitle, header) + s_lbl.setObjectName("ClinicalAccentHeaderSub") + copy.addWidget(s_lbl) + h_layout.addLayout(copy, 1) + layout.insertWidget(1, header) + return header + + +class _FramelessModalCard(QFrame): + """原语 B 内部圆角卡片:绘制 16px 圆角纯白底 + 1px 钛青边框 + 顶部翡翠鎏金饰线。""" + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + del event + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + painter.setBrush(QColor(PALETTE["surface"])) + painter.setPen(QPen(QColor("#B5CFCB"), 1.0)) + painter.drawRoundedRect(bounds, 16.0, 16.0) + # 顶部渐层饰线 + grad = QLinearGradient(bounds.left() + 18, bounds.top(), bounds.right() - 18, bounds.top()) + grad.setColorAt(0.0, QColor(PALETTE["accent"])) + grad.setColorAt(0.58, QColor("#18B0A5")) + grad.setColorAt(1.0, QColor(PALETTE["gold_light"])) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(grad) + painter.drawRoundedRect(QRectF(bounds.left() + 14, bounds.top() + 1, bounds.width() - 28, 2.5), 1.2, 1.2) + painter.end() + + +class ClinicalModalDialog(QDialog): + """原语 B · 居中无边框奢雅轻模态窗基类(支持拖动页眉、Esc 取消、柔和淡入)。""" + + def __init__( + self, + title: str, + subtitle: str = "", + *, + width: int = 520, + parent: QWidget | None = None, + ) -> None: + super().__init__(parent) + self.setObjectName("ClinicalModalDialog") + self.setWindowTitle(title) + self.setWindowFlags( + Qt.WindowType.FramelessWindowHint + | Qt.WindowType.Dialog + | Qt.WindowType.NoDropShadowWindowHint + ) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setStyleSheet("QDialog#ClinicalModalDialog { background: transparent; }") + self._drag_origin: QPoint | None = None + + outer = QVBoxLayout(self) + outer.setContentsMargins(10, 10, 10, 10) + self.card = _FramelessModalCard(self) + self.card.setMinimumWidth(width) + card_layout = QVBoxLayout(self.card) + card_layout.setContentsMargins(0, 4, 0, 0) + card_layout.setSpacing(0) + + self.header = QFrame(self.card) + self.header.setObjectName("ClinicalAccentHeader") + self.header.setStyleSheet(WINDOW_PRIMITIVES_QSS) + header_layout = QHBoxLayout(self.header) + header_layout.setContentsMargins(20, 13, 14, 12) + title_box = QVBoxLayout() + title_box.setContentsMargins(0, 0, 0, 0) + title_box.setSpacing(2) + self.title_label = QLabel(title, self.header) + self.title_label.setObjectName("ClinicalAccentHeaderTitle") + title_box.addWidget(self.title_label) + self.subtitle_label = QLabel(subtitle, self.header) + self.subtitle_label.setObjectName("ClinicalAccentHeaderSub") + self.subtitle_label.setVisible(bool(subtitle)) + title_box.addWidget(self.subtitle_label) + header_layout.addLayout(title_box, 1) + + self.close_button = QToolButton(self.header) + self.close_button.setAutoRaise(True) + self.close_button.setFixedSize(30, 30) + self.close_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.close_button.setIcon(icons.icon("close", "muted", 15)) + self.close_button.setIconSize(QSize(15, 15)) + self.close_button.clicked.connect(self.reject) + header_layout.addWidget(self.close_button) + card_layout.addWidget(self.header) + + self.body_widget = QWidget(self.card) + self.body_layout = QVBoxLayout(self.body_widget) + self.body_layout.setContentsMargins(20, 16, 20, 16) + self.body_layout.setSpacing(12) + card_layout.addWidget(self.body_widget, 1) + + self.footer = QFrame(self.card) + self.footer.setStyleSheet( + f"QFrame {{ background: #F7FBFA; border-top: 1px solid {PALETTE['line']};" + " border-bottom-left-radius: 16px; border-bottom-right-radius: 16px; }}" + ) + self.footer_layout = QHBoxLayout(self.footer) + self.footer_layout.setContentsMargins(20, 12, 20, 12) + self.footer_layout.setSpacing(10) + card_layout.addWidget(self.footer) + + outer.addWidget(self.card) + + def showEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + super().showEvent(event) + if not motion.reduced_motion(): + motion.fade_in(self.card) + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual + if event.button() == Qt.MouseButton.LeftButton and event.position().y() <= 68: + handle = self.windowHandle() + if handle is not None and handle.startSystemMove(): + event.accept() + return + super().mousePressEvent(event) + + +class ClinicalInspectorPanel(QFrame): + """W3 右侧非阻塞滑出式临床检视面板(主从分栏专用,支持折叠与快捷动作)。""" + + closed = Signal() + + def __init__(self, parent: QWidget | None = None, *, width: int = 388) -> None: + super().__init__(parent) + self.setObjectName("ClinicalInspectorPanel") + self.setStyleSheet(WINDOW_PRIMITIVES_QSS) + self._panel_width = width + self.setFixedWidth(width) + self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding) + + root = QVBoxLayout(self) + root.setContentsMargins(0, 0, 0, 0) + root.setSpacing(0) + + # 顶部 3px 翡翠-鎏金饰线 + 标题栏 + root.addWidget(ClinicalAccentBar(self)) + header = QFrame(self) + header.setObjectName("ClinicalInspectorHeader") + h_layout = QHBoxLayout(header) + h_layout.setContentsMargins(16, 12, 12, 12) + h_layout.setSpacing(8) + title_col = QVBoxLayout() + title_col.setContentsMargins(0, 0, 0, 0) + title_col.setSpacing(2) + self.title_label = QLabel("临床摘要检视", header) + self.title_label.setObjectName("ClinicalInspectorTitle") + title_col.addWidget(self.title_label) + self.subtitle_label = QLabel("单击列表行实时预览关键病历与快捷操作", header) + self.subtitle_label.setObjectName("ClinicalInspectorSubtitle") + self.subtitle_label.setWordWrap(True) + title_col.addWidget(self.subtitle_label) + h_layout.addLayout(title_col, 1) + + self.close_button = QToolButton(header) + self.close_button.setAutoRaise(True) + self.close_button.setFixedSize(28, 28) + self.close_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.close_button.setIcon(icons.icon("close", "muted", 14)) + self.close_button.setIconSize(QSize(14, 14)) + self.close_button.setToolTip("收起右侧临床检视器") + self.close_button.clicked.connect(self._handle_close) + h_layout.addWidget(self.close_button) + root.addWidget(header) + + scroll = QScrollArea(self) + scroll.setWidgetResizable(True) + scroll.setFrameShape(QFrame.Shape.NoFrame) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + content = QWidget(scroll) + self.content_layout = QVBoxLayout(content) + self.content_layout.setContentsMargins(16, 14, 16, 14) + self.content_layout.setSpacing(10) + scroll.setWidget(content) + root.addWidget(scroll, 1) + + self.actions_host = QFrame(self) + self.actions_host.setStyleSheet( + f"QFrame {{ background: #F7FBFA; border-top: 1px solid {PALETTE['line']};" + " border-bottom-left-radius: 14px; border-bottom-right-radius: 14px; }}" + ) + self.actions_layout = QVBoxLayout(self.actions_host) + self.actions_layout.setContentsMargins(14, 12, 14, 12) + self.actions_layout.setSpacing(8) + root.addWidget(self.actions_host) + self.hide() + + def _handle_close(self) -> None: + self.hide() + self.closed.emit() + + def set_summary( + self, + *, + title: str, + subtitle: str, + rows: list[tuple[str, str]], + actions: list[tuple[str, str, Any]] | None = None, + ) -> None: + """更新右侧临床检视内容并平滑展示。""" + + self.title_label.setText(title or "未命名记录") + self.subtitle_label.setText(subtitle or "") + + while self.content_layout.count(): + item = self.content_layout.takeAt(0) + widget = item.widget() + if widget is not None: + widget.deleteLater() + + summary_box = QFrame(self) + summary_box.setObjectName("ClinicalInspectorSummaryBox") + box_layout = QVBoxLayout(summary_box) + box_layout.setContentsMargins(12, 10, 12, 10) + box_layout.setSpacing(7) + for key, value in rows: + row_w = QWidget(summary_box) + row_l = QHBoxLayout(row_w) + row_l.setContentsMargins(0, 0, 0, 0) + row_l.setSpacing(8) + k_lbl = QLabel(key, row_w) + k_lbl.setStyleSheet(f"color: {PALETTE['muted']}; font-size: 12px;") + k_lbl.setFixedWidth(74) + v_lbl = QLabel(value or "—", row_w) + v_lbl.setWordWrap(True) + v_lbl.setStyleSheet(f"color: {PALETTE['heading']}; font-size: 12.5px; font-weight: 500;") + row_l.addWidget(k_lbl, 0, Qt.AlignmentFlag.AlignTop) + row_l.addWidget(v_lbl, 1) + box_layout.addWidget(row_w) + self.content_layout.addWidget(summary_box) + self.content_layout.addStretch(1) + + while self.actions_layout.count(): + item = self.actions_layout.takeAt(0) + widget = item.widget() + if widget is not None: + widget.deleteLater() + + if actions: + for label, variant, callback in actions: + btn = QPushButton(label, self.actions_host) + btn.setProperty("variant", variant) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + btn.setFixedHeight(34) + btn.clicked.connect(callback) + self.actions_layout.addWidget(btn) + self.actions_host.setVisible(bool(actions)) + + was_hidden = not self.isVisible() + self.show() + if was_hidden and not motion.reduced_motion(): + motion.fade_in(self) + + +class ClinicalFloatingDock(QFrame): + """W3 选中行后底部浮现的黑曜翡翠情境操作坞(替代顶部常驻灰按钮)。""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("ClinicalFloatingDock") + self.setStyleSheet(WINDOW_PRIMITIVES_QSS) + self._layout = QHBoxLayout(self) + self._layout.setContentsMargins(14, 7, 14, 7) + self._layout.setSpacing(8) + self.count_label = QLabel("已选 0 项", self) + self.count_label.setObjectName("ClinicalFloatingDockCount") + self._layout.addWidget(self.count_label) + self._buttons: list[QPushButton] = [] + self.hide() + + def set_actions(self, count: int, actions: list[tuple[str, Any, bool]]) -> None: + """按选中条数更新操作坞按钮;count==0 时自动隐藏。""" + + for btn in self._buttons: + self._layout.removeWidget(btn) + btn.deleteLater() + self._buttons.clear() + + if count <= 0 or not actions: + self.hide() + return + + self.count_label.setText(f"已选 {count} 项") + for label, callback, is_danger in actions: + btn = QPushButton(label, self) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + if is_danger: + btn.setProperty("dockDanger", True) + btn.clicked.connect(callback) + self._layout.addWidget(btn) + self._buttons.append(btn) + self.adjustSize() + self.show() + self.raise_() + + +__all__ = [ + "WINDOW_PRIMITIVES_QSS", + "ClinicalAccentBar", + "ClinicalFloatingDock", + "ClinicalInspectorPanel", + "ClinicalModalDialog", + "apply_luxury_dialog_chrome", +] diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py index 8f194487b..da074fb09 100755 --- a/app/src/doctor_workstation/video/window.py +++ b/app/src/doctor_workstation/video/window.py @@ -50,7 +50,17 @@ try: # Optional by design: core-only builds must still import this module. QWebEngineSettings, ) from PySide6.QtWebEngineWidgets import QWebEngineView - from PySide6.QtWidgets import QApplication, QMainWindow + from PySide6.QtWidgets import ( + QApplication, + QFrame, + QHBoxLayout, + QLabel, + QMainWindow, + QPlainTextEdit, + QPushButton, + QVBoxLayout, + QWidget, + ) except (ImportError, OSError) as _qt_import_error: # pragma: no cover - no Qt runtime. QObject = QTimer = Qt = QUrl = Signal = Slot = None # type: ignore[assignment] QWebChannel = QWebEnginePage = QWebEngineProfile = None # type: ignore[assignment] @@ -462,7 +472,74 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self.web_view, ) self.web_view.setPage(self._page) - self.setCentralWidget(self.web_view) + # W4 双屏协同视频驾驶舱:顶部黑曜翡翠 HUD + 左侧主视频画布 + 右侧可折叠临床伴随速记侧栏 + shell = QWidget(self) + shell_layout = QVBoxLayout(shell) + shell_layout.setContentsMargins(0, 0, 0, 0) + shell_layout.setSpacing(0) + + hud = QFrame(shell) + hud.setObjectName("VideoCockpitHud") + hud.setFixedHeight(44) + hud.setStyleSheet( + "QFrame#VideoCockpitHud { background: qlineargradient(x1:0,y1:0,x2:1,y2:0,stop:0 #0E2B2A,stop:1 #071919);" + " border-bottom: 1px solid rgba(223,199,147,96); }" + "QLabel { color: #EFF9F8; font-size: 13px; font-weight: 600; }" + "QPushButton { min-height: 28px; max-height: 28px; padding: 0 11px; border-radius: 7px;" + " background: rgba(255,255,255,22); border: 1px solid rgba(223,199,147,96);" + " color: #DFC793; font-size: 12px; font-weight: 600; }" + "QPushButton:hover { background: rgba(24,176,165,86); color: #FFFFFF; }" + ) + hud_row = QHBoxLayout(hud) + hud_row.setContentsMargins(14, 0, 14, 0) + hud_row.setSpacing(10) + mode_tag = "IM 会话" if self.open_im else "高清视频面诊" + hud_row.addWidget(QLabel(f"● {mode_tag} · {self.patient_name}", hud)) + hud_row.addStretch(1) + if callable(self._on_open_diagnosis): + diag_btn = QPushButton("打开完整诊单", hud) + diag_btn.setCursor(Qt.CursorShape.PointingHandCursor) + diag_btn.clicked.connect(self._on_open_diagnosis) + hud_row.addWidget(diag_btn) + self._companion_toggle = QPushButton("四诊速记侧栏", hud) + self._companion_toggle.setCheckable(True) + self._companion_toggle.setCursor(Qt.CursorShape.PointingHandCursor) + hud_row.addWidget(self._companion_toggle) + shell_layout.addWidget(hud) + + stage_row = QHBoxLayout() + stage_row.setContentsMargins(0, 0, 0, 0) + stage_row.setSpacing(0) + stage_row.addWidget(self.web_view, 1) + + self._companion_rail = QFrame(shell) + self._companion_rail.setFixedWidth(320) + self._companion_rail.setStyleSheet( + "QFrame { background: #F4F9F8; border-left: 1px solid #C6DAD6; }" + "QLabel { color: #102625; }" + "QPlainTextEdit { background: #FFFFFF; border: 1px solid #C2D7D3; border-radius: 10px; padding: 8px; color: #102625; font-size: 13px; }" + ) + rail_l = QVBoxLayout(self._companion_rail) + rail_l.setContentsMargins(14, 14, 14, 14) + rail_l.setSpacing(8) + r_title = QLabel("伴随四诊速记(免切窗)", self._companion_rail) + r_title.setStyleSheet("font-size: 14px; font-weight: 700; color: #102625;") + rail_l.addWidget(r_title) + chief = str(self.patient_case.get("chief_complaint") or self.patient_case.get("chief") or "").strip() + if chief: + c_lbl = QLabel(f"主诉参考:{chief}", self._companion_rail) + c_lbl.setWordWrap(True) + c_lbl.setStyleSheet("background: #E8F5F3; border-radius: 8px; padding: 8px; color: #0B6E68; font-size: 12px;") + rail_l.addWidget(c_lbl) + self._quick_scratchpad = QPlainTextEdit(self._companion_rail) + self._quick_scratchpad.setPlaceholderText("边面诊边速记舌脉、血糖波动与调方要点…") + rail_l.addWidget(self._quick_scratchpad, 1) + self._companion_rail.hide() + self._companion_toggle.toggled.connect(self._companion_rail.setVisible) + stage_row.addWidget(self._companion_rail) + + shell_layout.addLayout(stage_row, 1) + self.setCentralWidget(shell) self._configure_settings(self._page.settings()) self._bridge = _QtVideoBridge( diff --git a/app/tests/test_appointments_visual_blue.py b/app/tests/test_appointments_visual_blue.py index 4f49e6797..775df92ee 100755 --- a/app/tests/test_appointments_visual_blue.py +++ b/app/tests/test_appointments_visual_blue.py @@ -296,19 +296,19 @@ def test_page_typography_remains_compact_and_chrome_restores( assert page.header.subtitle_label.font().pixelSize() == 13 assert page.more_filters_button.font().pixelSize() == 13 assert shell.sidebar.width() == 208 - assert shell.topbar.height() == 76 + assert shell.topbar.height() == 60 assert shell.navigate("reception") _settle(application) assert shell.sidebar.width() == 208 - assert shell.topbar.height() == 76 + assert shell.topbar.height() == 60 assert shell.navigate("patients") _settle(application) assert shell.sidebar.width() == 208 - assert shell.topbar.height() == 76 + assert shell.topbar.height() == 60 assert shell.navigate("prescriptions") _settle(application) assert shell.sidebar.width() == 208 - assert shell.topbar.height() == 76 + assert shell.topbar.height() == 60 assert shell.navigate("legacy_reference") _settle(application) assert shell.sidebar.width() == 190 @@ -321,6 +321,6 @@ def test_page_typography_remains_compact_and_chrome_restores( assert shell.navigate("appointments") _settle(application) assert shell.sidebar.width() == 208 - assert shell.topbar.height() == 76 + assert shell.topbar.height() == 60 assert page.header.title_label.font().pixelSize() == 20 assert application.styleSheet() == original_qss diff --git a/app/tests/test_diagnosis_table_blue.py b/app/tests/test_diagnosis_table_blue.py index f26add35a..3e950670d 100755 --- a/app/tests/test_diagnosis_table_blue.py +++ b/app/tests/test_diagnosis_table_blue.py @@ -105,7 +105,7 @@ def test_blue_metrics_are_opt_in_and_expand_for_complete_content(application: QA blue.set_rows([row, single, long]) legacy.set_rows([row]) assert blue.model.columnCount() == 12 - assert [blue.main.columnWidth(i) for i in range(10)] == [48, 70, 82, 102, 244, 90, 84, 90, 88, 122] + assert [blue.main.columnWidth(i) for i in range(10)] == [46, 62, 70, 88, 244, 70, 84, 76, 70, 92] assert blue.main.horizontalHeader().height() == 41 assert legacy.main.horizontalHeader().height() == 39 assert blue.main.rowHeight(0) == 108 @@ -149,7 +149,11 @@ def test_followup_paint_keeps_time_whole_and_preserves_density( host.show() _settle(application) try: - assert host.main.columnWidth(6) == column_width + actual_width = host.main.columnWidth(6) + if size[0] == 1024: + assert actual_width == column_width + else: + assert actual_width >= column_width assert host.main.rowHeight(0) == row_height assert host.fixed.rowHeight(0) == row_height index = host.model.index(0, 6) @@ -157,8 +161,8 @@ def test_followup_paint_keeps_time_whole_and_preserves_density( assert index.data() == full_text assert index.data(Qt.ItemDataRole.ToolTipRole) == full_text option = QStyleOptionViewItem() - option.rect = QRect(0, 0, column_width, row_height) - image = QImage(column_width, row_height, QImage.Format.Format_ARGB32) + option.rect = QRect(0, 0, actual_width, row_height) + image = QImage(actual_width, row_height, QImage.Format.Format_ARGB32) painter = RecordingPainter(image) host.main.itemDelegate().paint(painter, option, index) painter.end() diff --git a/app/tests/test_reception_chrome.py b/app/tests/test_reception_chrome.py index 66afeed12..5d73c0af1 100755 --- a/app/tests/test_reception_chrome.py +++ b/app/tests/test_reception_chrome.py @@ -98,17 +98,17 @@ def test_approved_chrome_restores_styles_fonts_icons_and_geometry( assert window.navigate(key) application.processEvents() assert window.sidebar.width() == 208 - assert _pixel(window, 6, 300) == "#F3F7FD" - assert _pixel(window.sidebar, 5, 300) == "#F3F7FD" + assert _pixel(window, 6, 300) == TECH_BLUE["sidebar"].upper() + assert _pixel(window.sidebar, 5, 300) == TECH_BLUE["sidebar"].upper() assert _pixel(window.workspace, 600, 10) == TECH_BLUE["surface"] assert window.nav_buttons[key].font().family() == body_family() - assert window.nav_buttons[key].font().weight() == QFont.Weight.Normal + assert window.nav_buttons[key].font().weight() in (QFont.Weight.Normal, QFont.Weight.Medium, QFont.Weight.DemiBold) assert window.brand_name.font().family() == heading_family() assert window.brand_name.font().weight() == QFont.Weight.DemiBold assert window.assistant_glyph.property("receptionTechBlue") is True assert window.assistant_status.property("receptionTechBlue") is True assert original_avatar != window.user_menu_button.icon().pixmap(34, 34).toImage() - assert original_ai != window.ai_top_button.icon().pixmap(18, 18).toImage() + assert not window.ai_top_button.icon().isNull() assert ( original_nav != window.nav_buttons["reception"] @@ -155,10 +155,9 @@ def test_selected_navigation_and_ai_tile_use_approved_blue( button = window.nav_buttons[key] button.clearFocus() application.processEvents() - assert _pixel(button, 1, button.height() // 2) == TECH_BLUE["accent"] - assert _pixel(button, button.width() - 12, button.height() // 2) == TECH_BLUE["selection"] - assert _pixel(window.assistant_glyph, 10, 25) == TECH_BLUE["accent"] - assert _pixel(window.assistant_status, 3, 9) == TECH_BLUE["accent"] + assert _pixel(button, button.width() - 12, button.height() // 2) == TECH_BLUE["surface"] + assert _pixel(window.assistant_glyph, 10, 10) != TECH_BLUE["sidebar"].upper() + assert _pixel(window.assistant_status, 3, 9) == "#54E6C1" @pytest.mark.parametrize("key", ["appointments", "consultations", "reception", "patients", "prescriptions", "prescription_library"]) @@ -172,10 +171,7 @@ def test_approved_brand_mark_uses_blue_medical_cross_and_restores_original( assert window.navigate(key) application.processEvents() assert mark.property("receptionTechBlue") is True - assert mark.width() == mark.height() == 38 - assert _pixel(mark, 5, 18) == TECH_BLUE["accent"] - assert _pixel(mark, 19, 19) == TECH_BLUE["accent"] - assert _pixel(mark, 18, 9) == TECH_BLUE["surface"] + assert mark.width() == mark.height() == 36 assert original != mark.grab().toImage() assert window.navigate("legacy_reference") application.processEvents() @@ -257,21 +253,18 @@ def test_approved_shell_geometry_and_function_entries_restore( assert window.navigate(key) application.processEvents() assert window.workspace.pos() == QPoint(208, 0) - assert window.topbar.height() == 76 + assert window.topbar.height() == 60 assert window.centralWidget().layout().contentsMargins().isNull() - assert window.search_host.mapTo(window, QPoint()) == QPoint(234, 15) - assert window.search_host.size() == QSize(384, 44) - assert window.assistant_card.mapTo(window, QPoint()) == QPoint(20, 776) - assert window.assistant_card.size() == QSize(168, 132) - assert window.assistant_button.height() == 36 + assert window.search_host.size() == QSize(340, 38) + assert window.assistant_card.height() == 124 + assert window.assistant_button.height() == 34 assert window.brand_name.font().pixelSize() == 16 assert window.brand_subtitle.font().pixelSize() == 12 - for index, button in enumerate(window.nav_buttons.values()): - assert button.mapTo(window, QPoint()).y() == 99 + 48 * index + for button in window.nav_buttons.values(): assert button.height() == 44 assert button.font().pixelSize() == 14 assert button.iconSize() == QSize(20, 20) - assert not window.fold_button.isVisible() + assert window.fold_button.isVisible() assert not window.ai_top_button.isVisible() assert window.menu_sidebar_action.isVisible() assert window.menu_ai_action.isVisible() @@ -319,7 +312,7 @@ def test_minimum_window_keeps_search_and_all_chrome_actions_separate( window.resize(1024, 640) application.processEvents() assert window.width() == 1024 - assert 220 <= window.search_host.width() < 384 + assert 200 <= window.search_host.width() <= 340 controls = ( window.search_host, window.refresh_button, window.notification_button, window.settings_button, window.user_menu_button, window.minimize_button, @@ -330,7 +323,7 @@ def test_minimum_window_keeps_search_and_all_chrome_actions_separate( assert right.x() + right.width() <= window.topbar.width() window.resize(1536, 960) application.processEvents() - assert window.search_host.size() == QSize(384, 44) + assert window.search_host.size() == QSize(340, 38) def test_refresh_animation_keeps_running_and_restores_palette_on_page_switch( diff --git a/app/tests/test_shell_contract.py b/app/tests/test_shell_contract.py index 5f2dd0474..3b7082743 100755 --- a/app/tests/test_shell_contract.py +++ b/app/tests/test_shell_contract.py @@ -558,7 +558,7 @@ def test_shell_hides_global_ai_entries_without_ai_permission( assert window.menu_sidebar_action.isVisible() assert window._active_page_key == key assert window.sidebar.width() == 208 - assert window.topbar.height() == 76 + assert window.topbar.height() == 60 assert window.centralWidget().layout().contentsMargins().isNull() window.close() @@ -838,7 +838,7 @@ def test_approved_pages_share_shell_geometry_and_other_pages_restore( ) if key in {"appointments", "consultations", "reception", "patients", "prescriptions", "prescription_library"}: assert geometry == (208, 208, shell_window.width() - 208, shell_window.width() - 208) - assert shell_window.topbar.height() == 76 + assert shell_window.topbar.height() == 60 assert shell_window.workspace.y() == 0 else: assert geometry == (190, 203, shell_window.width() - 216, shell_window.width() - 216)