diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py index 86c065a3e..9a1c09da5 100755 --- a/app/src/doctor_workstation/app.py +++ b/app/src/doctor_workstation/app.py @@ -893,10 +893,16 @@ class ApplicationController(QObject): raise ValueError("当前后端未提供一次性通话交接票据,浏览器视频模式已安全停用。") if not WEBENGINE_AVAILABLE: raise ValueError("当前安装缺少 QtWebEngine,无法打开受信任的视频窗口。") + ticket_diag = getattr(ticket, "diagnosis_id", None) + resolved_diag_id = ( + ticket_diag + if not isinstance(ticket_diag, bool) and ticket_diag not in (None, "", 0, "0") + else diagnosis_id + ) call = launch_video_call( ticket, repository=repository, - diagnosis_id=diagnosis_id, + diagnosis_id=resolved_diag_id, patient_id=patient_id, backend_mode=mode, local_dist=video_dist_path(), @@ -910,7 +916,7 @@ class ApplicationController(QObject): "tcm.diagnosis/aiAssistant", default=False, ), - on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: ( + on_open_diagnosis=lambda *_args, current_id=resolved_diag_id, current_key=call_key: ( self._open_video_diagnosis(current_id, call_key=current_key) ), ) @@ -926,6 +932,37 @@ class ApplicationController(QObject): self.video_calls[call_key] = call qt_window = getattr(call, "qt_window", None) if qt_window is not None: + qt_window.setProperty("doctorSkipOpenGeometry", True) + qt_window.setMinimumSize(420, 480) + if self.shell_window is not None and self.shell_window.isVisible(): + screen = self.shell_window.screen() + if screen is not None: + avail = screen.availableGeometry() + if getattr(self, "_saved_shell_before_video", None) is None: + self._saved_shell_before_video = ( + self.shell_window.isMaximized(), + self.shell_window.geometry(), + self.shell_window.minimumSize(), + ) + pad = 6 + gap = 8 + # Account for Windows native frame borders on qt_window so right edge never clips + frame_w_extra = max(12, qt_window.frameGeometry().width() - qt_window.width()) + frame_h_extra = max(34, qt_window.frameGeometry().height() - qt_window.height()) + usable_w = avail.width() - pad * 2 - gap + vid_outer_w = min(540, max(436, int(usable_w * 0.34))) + main_w = max(820, usable_w - vid_outer_w) + if main_w + vid_outer_w > usable_w: + vid_outer_w = max(420, usable_w - main_w) + vid_client_w = max(420, vid_outer_w - frame_w_extra) + usable_h = avail.height() - pad * 2 + vid_client_h = max(480, usable_h - frame_h_extra) + if self.shell_window.isMaximized(): + self.shell_window.showNormal() + self.shell_window.setMinimumSize(min(820, main_w), 620) + self.shell_window.setGeometry(avail.left() + pad, avail.top() + pad, main_w, usable_h) + qt_window.resize(vid_client_w, vid_client_h) + qt_window.move(avail.left() + pad + main_w + gap, avail.top() + pad) qt_window.destroyed.connect( lambda _obj=None, key=call_key, expected=call: self._release_video_call( key, @@ -942,6 +979,10 @@ class ApplicationController(QObject): dialog = shell.open_diagnosis_by_id(diagnosis_id, modeless=True) if dialog is None: return + if bool(dialog.property("hostedInSpatialWing")) or getattr(shell, "wing_manager", None) is not None: + shell.raise_() + shell.activateWindow() + return call = self.video_calls.get(call_key) video_window = getattr(call, "qt_window", None) if video_window is not None: @@ -1052,6 +1093,16 @@ class ApplicationController(QObject): self._video_preview_generation += 1 if self.video_calls.get(call_key) is call: self.video_calls.pop(call_key, None) + saved_shell = getattr(self, "_saved_shell_before_video", None) + if not self.video_calls and saved_shell is not None and self.shell_window is not None: + self._saved_shell_before_video = None + was_max, old_rect, old_min = saved_shell + with suppress(RuntimeError): + self.shell_window.setMinimumSize(old_min) + if was_max: + self.shell_window.showMaximized() + elif old_rect.isValid(): + self.shell_window.setGeometry(old_rect) def _forget_demo_dialog(self, call_key: str, dialog: DemoVideoDialog) -> None: if self.demo_video_dialogs.get(call_key) is dialog: diff --git a/app/src/doctor_workstation/ui/appointment_drawer.py b/app/src/doctor_workstation/ui/appointment_drawer.py index 922050a81..9ba383712 100755 --- a/app/src/doctor_workstation/ui/appointment_drawer.py +++ b/app/src/doctor_workstation/ui/appointment_drawer.py @@ -1714,6 +1714,9 @@ class AppointmentDrawer(QDialog): QTimer.singleShot(0, self._sync_to_owner) def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 - Qt API + if self.property('hostedInSpatialWing'): + super().paintEvent(event) + return painter = QPainter(self) painter.fillRect(self.rect(), QColor(26, 28, 31, 196)) painter.end() @@ -1760,6 +1763,9 @@ class AppointmentDrawer(QDialog): super().mousePressEvent(event) def _sync_to_owner(self) -> None: + if self.property('hostedInSpatialWing'): + self._update_drawer_width() + return target = main_window_target_rect(self) if target is not None: self.setGeometry(target) @@ -1775,6 +1781,10 @@ class AppointmentDrawer(QDialog): def _update_drawer_width(self) -> None: if not hasattr(self, "panel"): return + if self.property('hostedInSpatialWing'): + self.panel.setMinimumWidth(0) + self.panel.setMaximumWidth(16777215) + return target = max(1, int(round(self.width() * 0.60))) self.panel.setFixedWidth(target) diff --git a/app/src/doctor_workstation/ui/command_palette.py b/app/src/doctor_workstation/ui/command_palette.py index d34e48ef0..fe12fa036 100644 --- a/app/src/doctor_workstation/ui/command_palette.py +++ b/app/src/doctor_workstation/ui/command_palette.py @@ -165,6 +165,7 @@ class CommandPaletteDialog(QDialog): super().__init__(parent) self.setObjectName("CommandPaletteDialog") self.setProperty("doctorSkipOpenGeometry", True) + self.setProperty("skipSpatialWing", True) self.setWindowFlags( Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog diff --git a/app/src/doctor_workstation/ui/diagnosis_drawer.py b/app/src/doctor_workstation/ui/diagnosis_drawer.py index 1262d8635..62cff2207 100755 --- a/app/src/doctor_workstation/ui/diagnosis_drawer.py +++ b/app/src/doctor_workstation/ui/diagnosis_drawer.py @@ -1,16 +1,16 @@ -"""Scoped visual primitives for diagnosis readonly pages and edit drawers. - -The diagnosis workspace uses the same cool white, indigo and blue-gray visual -language as the desktop shell. Every rule remains isolated behind diagnosis -object names and dynamic properties so adjacent pages keep their own styling. -""" +"""Scoped visual primitives for diagnosis readonly pages and edit drawers. + +The diagnosis workspace uses the same cool white, indigo and blue-gray visual +language as the desktop shell. Every rule remains isolated behind diagnosis +object names and dynamic properties so adjacent pages keep their own styling. +""" from __future__ import annotations -import weakref -from collections.abc import Mapping, Sequence -from dataclasses import dataclass -from math import ceil +import weakref +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from math import ceil from typing import Any from PySide6.QtCore import ( @@ -63,12 +63,12 @@ from PySide6.QtWidgets import ( QWidget, ) -from .chat_items import ChatItem, parse_chat_item -from .design_system import PALETTE, clinical_stylesheet -from .diagnosis_editors import FlowLayout +from .chat_items import ChatItem, parse_chat_item +from .design_system import PALETTE, clinical_stylesheet +from .diagnosis_editors import FlowLayout from .diagnosis_media import shared_image_manager from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms -from .image_drop import can_drop_images, capture_image_drop +from .image_drop import can_drop_images, capture_image_drop DIAGNOSIS_QSS = r""" QDialog#DiagnosisDialogRoot { @@ -82,7 +82,7 @@ QFrame#DiagnosisDrawer { border-left: 1px solid #EDEDEE; } QFrame#DiagnosisDrawerHeader { - background-color: #FFFFFF; + background-color: #FFFFFF; border-bottom: 1px solid #EDEDEE; } QFrame#DiagnosisDrawerFooter { @@ -104,7 +104,7 @@ QLabel#DiagnosisDrawerModeBadge, QLabel#DiagnosisReadonlyStatus, QLabel[diagnosisTag="true"] { padding: 4px 9px; - border-radius: $ds_radius_small; + border-radius: $ds_radius_small; font-size: 12px; font-weight: 500; } @@ -158,8 +158,8 @@ QDialog QPushButton:pressed { border-color: #354BB4; } QDialog QPushButton:disabled { - color: $ds_disabled; - background-color: $ds_disabled_surface; + color: $ds_disabled; + background-color: $ds_disabled_surface; border-color: #EDEDEE; } QDialog QPushButton[variant="primary"] { @@ -175,9 +175,9 @@ QDialog QPushButton[variant="primary"]:focus { border-color: #4156C4; } QDialog QPushButton[variant="primary"]:disabled { - color: $ds_disabled; - background-color: $ds_disabled_surface; - border-color: $ds_line; + color: $ds_disabled; + background-color: $ds_disabled_surface; + border-color: $ds_line; } QDialog QPushButton[variant="secondary"] { color: #4F63D9; @@ -266,9 +266,9 @@ QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:focus { border-color: #4156C4; } QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:disabled { - color: $ds_disabled; - background-color: $ds_disabled_surface; - border-color: $ds_line; + color: $ds_disabled; + background-color: $ds_disabled_surface; + border-color: $ds_line; } QDialog#DiagnosisDialogRoot QPushButton#DiagnosisFooterCloseButton { color: #606163; @@ -382,10 +382,10 @@ QFrame#DiagnosisFormHost { QFrame[diagnosisSection="true"] { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 16px; + border-radius: 16px; } QLabel[diagnosisFieldLabel="true"] { - color: $ds_muted; + color: $ds_muted; font-size: 12px; font-weight: 500; } @@ -397,11 +397,11 @@ QLabel#DiagnosisUnitLabel { } QLineEdit[diagnosisField="true"], QComboBox[diagnosisField="true"], -QPlainTextEdit[diagnosisField="true"], -QDateEdit[diagnosisField="true"], -QDoubleSpinBox[diagnosisField="true"], -QSpinBox[diagnosisField="true"], -QTimeEdit[diagnosisField="true"] { +QPlainTextEdit[diagnosisField="true"], +QDateEdit[diagnosisField="true"], +QDoubleSpinBox[diagnosisField="true"], +QSpinBox[diagnosisField="true"], +QTimeEdit[diagnosisField="true"] { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; @@ -434,13 +434,13 @@ QPlainTextEdit[diagnosisField="true"] { } QLineEdit[diagnosisField="true"]:focus, QComboBox[diagnosisField="true"]:focus, -QPlainTextEdit[diagnosisField="true"]:focus, -QDateEdit[diagnosisField="true"]:focus, -QDoubleSpinBox[diagnosisField="true"]:focus, -QSpinBox[diagnosisField="true"]:focus, -QTimeEdit[diagnosisField="true"]:focus { +QPlainTextEdit[diagnosisField="true"]:focus, +QDateEdit[diagnosisField="true"]:focus, +QDoubleSpinBox[diagnosisField="true"]:focus, +QSpinBox[diagnosisField="true"]:focus, +QTimeEdit[diagnosisField="true"]:focus { border: 1px solid #8B9AD9; - background-color: $ds_surface; + background-color: $ds_surface; } QLineEdit[diagnosisField="true"][invalid="true"], QComboBox[diagnosisField="true"][invalid="true"], @@ -452,11 +452,11 @@ QLineEdit[diagnosisField="true"]:read-only, QPlainTextEdit[diagnosisField="true"]:read-only, QLineEdit[diagnosisField="true"]:disabled, QComboBox[diagnosisField="true"]:disabled, -QPlainTextEdit[diagnosisField="true"]:disabled, -QDateEdit[diagnosisField="true"]:disabled, -QDoubleSpinBox[diagnosisField="true"]:disabled, -QSpinBox[diagnosisField="true"]:disabled, -QTimeEdit[diagnosisField="true"]:disabled { +QPlainTextEdit[diagnosisField="true"]:disabled, +QDateEdit[diagnosisField="true"]:disabled, +QDoubleSpinBox[diagnosisField="true"]:disabled, +QSpinBox[diagnosisField="true"]:disabled, +QTimeEdit[diagnosisField="true"]:disabled { color: #606163; background-color: #F7F7F7; border-color: #EDEDEE; @@ -466,8 +466,8 @@ QLabel#DiagnosisSectionTitle { background-color: transparent; border: 0; padding: 0; - font-size: 14px; - font-weight: 600; + font-size: 14px; + font-weight: 600; letter-spacing: 0.02em; } QFrame#DiagnosisSectionAccent { @@ -484,49 +484,49 @@ QFrame#DiagnosisReadonlyPage { background-color: #F6F6F6; } QFrame#DiagnosisReadonlyHero { - background-color: $ds_surface; - border: 1px solid $ds_line; - border-radius: $ds_radius_panel; + background-color: $ds_surface; + border: 1px solid $ds_line; + border-radius: $ds_radius_panel; } QLabel#DiagnosisReadonlyTitle { color: #1A1C1F; font-size: 16px; font-weight: 500; } -QLabel#DiagnosisReadonlyPatientName { - color: #1A1C1F; - font-size: 18px; - font-weight: 600; -} -QLabel#DiagnosisReadonlyHeroMeta, -QLabel#DiagnosisPrivacyText, -QLabel#DiagnosisOrderOffsetPreview, -QLabel#DiagnosisOrdersSummary { - color: #606163; - font-size: 12px; -} -QLabel#DiagnosisOrderOffsetLabel { - color: #1A1C1F; - font-size: 13px; - font-weight: 500; -} -QPushButton#DiagnosisOrderOffsetHelp { - min-width: 22px; - max-width: 22px; - min-height: 22px; - max-height: 22px; - padding: 0; - color: #4F63D9; - background-color: #EEF1FA; - border: 1px solid #EEF1FA; - border-radius: 11px; - font-weight: 700; -} -QPushButton#DiagnosisOrderOffsetHelp:hover, -QPushButton#DiagnosisOrderOffsetHelp:focus { - background-color: #EEF1FA; - border-color: #8B9AD9; -} +QLabel#DiagnosisReadonlyPatientName { + color: #1A1C1F; + font-size: 18px; + font-weight: 600; +} +QLabel#DiagnosisReadonlyHeroMeta, +QLabel#DiagnosisPrivacyText, +QLabel#DiagnosisOrderOffsetPreview, +QLabel#DiagnosisOrdersSummary { + color: #606163; + font-size: 12px; +} +QLabel#DiagnosisOrderOffsetLabel { + color: #1A1C1F; + font-size: 13px; + font-weight: 500; +} +QPushButton#DiagnosisOrderOffsetHelp { + min-width: 22px; + max-width: 22px; + min-height: 22px; + max-height: 22px; + padding: 0; + color: #4F63D9; + background-color: #EEF1FA; + border: 1px solid #EEF1FA; + border-radius: 11px; + font-weight: 700; +} +QPushButton#DiagnosisOrderOffsetHelp:hover, +QPushButton#DiagnosisOrderOffsetHelp:focus { + background-color: #EEF1FA; + border-color: #8B9AD9; +} QLabel#DiagnosisReadonlyStatus[severity="neutral"] { color: #8E8F90; background-color: rgba(255, 255, 255, 190); @@ -556,7 +556,7 @@ QFrame#DiagnosisReadonlyCaseCard, QFrame[diagnosisReadonlyCard="true"] { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 16px; + border-radius: 16px; } QLabel#DiagnosisReadonlyCardTitle { color: #1A1C1F; @@ -735,25 +735,25 @@ QFrame#DiagnosisChatBubble[side="doctor"] { border: 1px solid #F0F0F0; border-radius: 8px; } -QFrame#DiagnosisChatEvent { - background-color: #F7F8FA; - border: 1px solid #EDEDEE; - border-radius: 8px; -} -QLabel#DiagnosisChatEventMarker { - color: #697386; - font-size: 12px; - font-weight: 600; -} -QLabel#DiagnosisChatEventTitle { - color: #374151; - font-size: 13px; - font-weight: 600; -} -QLabel#DiagnosisChatEventDetail { - color: #697386; - font-size: 12px; -} +QFrame#DiagnosisChatEvent { + background-color: #F7F8FA; + border: 1px solid #EDEDEE; + border-radius: 8px; +} +QLabel#DiagnosisChatEventMarker { + color: #697386; + font-size: 12px; + font-weight: 600; +} +QLabel#DiagnosisChatEventTitle { + color: #374151; + font-size: 13px; + font-weight: 600; +} +QLabel#DiagnosisChatEventDetail { + color: #697386; + font-size: 12px; +} QLabel#DiagnosisChatMeta { color: #606163; font-size: 12px; @@ -785,7 +785,7 @@ QWidget[diagnosisChoiceHost="true"] QPushButton { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 10px; + border-radius: 10px; font-size: 12px; } QWidget[diagnosisChoiceHost="true"] QPushButton:hover, @@ -883,35 +883,35 @@ QLabel#DiagnosisUnsupportedState { padding: 22px; font-size: 13px; } -QDialog#DiagnosisDailyEditor, -QDialog#DiagnosisOrderDetailDialog, -QDialog#DiagnosisRecordingPlayer { - background-color: #FFFFFF; -} -QDialog#DiagnosisDailyEditor { - background-color: #F7F7F7; -} -QFrame#DiagnosisEditorHeader, -QFrame#DiagnosisEditorFooter { - background-color: #FFFFFF; - border: 0; -} -QFrame#DiagnosisEditorHeader { - border-bottom: 1px solid #EDEDEE; -} -QFrame#DiagnosisEditorFooter { - border-top: 1px solid #EDEDEE; -} -QWidget#DiagnosisEditorContent { - background-color: #FFFFFF; - border: 1px solid #EDEDEE; - border-radius: 12px; -} -QWidget#DiagnosisEditorContent QLabel { - color: #1A1C1F; - font-size: 12px; - font-weight: 500; -} +QDialog#DiagnosisDailyEditor, +QDialog#DiagnosisOrderDetailDialog, +QDialog#DiagnosisRecordingPlayer { + background-color: #FFFFFF; +} +QDialog#DiagnosisDailyEditor { + background-color: #F7F7F7; +} +QFrame#DiagnosisEditorHeader, +QFrame#DiagnosisEditorFooter { + background-color: #FFFFFF; + border: 0; +} +QFrame#DiagnosisEditorHeader { + border-bottom: 1px solid #EDEDEE; +} +QFrame#DiagnosisEditorFooter { + border-top: 1px solid #EDEDEE; +} +QWidget#DiagnosisEditorContent { + background-color: #FFFFFF; + border: 1px solid #EDEDEE; + border-radius: 12px; +} +QWidget#DiagnosisEditorContent QLabel { + color: #1A1C1F; + font-size: 12px; + font-weight: 500; +} QLabel#DiagnosisDialogHeading { color: #1A1C1F; font-size: 18px; @@ -929,17 +929,17 @@ QLabel#DiagnosisEditorError { border-radius: 7px; padding: 8px 10px; } -QScrollArea#DiagnosisEditorScroll, -QScrollArea#DiagnosisOrderDetailScroll { - background-color: #F7F7F7; - border: 1px solid #EDEDEE; - border-radius: 10px; -} -QScrollArea#DiagnosisEditorScroll, -QScrollArea#DiagnosisEditorScroll > QWidget > QWidget { - background-color: #F7F7F7; - border: 0; -} +QScrollArea#DiagnosisEditorScroll, +QScrollArea#DiagnosisOrderDetailScroll { + background-color: #F7F7F7; + border: 1px solid #EDEDEE; + border-radius: 10px; +} +QScrollArea#DiagnosisEditorScroll, +QScrollArea#DiagnosisEditorScroll > QWidget > QWidget { + background-color: #F7F7F7; + border: 0; +} QFrame#DiagnosisOrderOffsetBar, QFrame#DiagnosisOrderDetailHero { background-color: #F7F7F7; @@ -1010,84 +1010,84 @@ QDialog#DiagnosisPrescriptionEditor QSpinBox:focus, QDialog#DiagnosisPrescriptionEditor QDoubleSpinBox:focus { border-color: #8B9AD9; } -QWidget#DiagnosisNotesTimeline QPushButton[imageDropActive="true"] { - background-color: #EEF1FA; - border: 2px dashed #4F63D9; - color: #4F63D9; -} +QWidget#DiagnosisNotesTimeline QPushButton[imageDropActive="true"] { + background-color: #EEF1FA; + border: 2px dashed #4F63D9; + color: #4F63D9; +} """ -# Normalize the legacy component palette in one place. Keeping the selectors -# untouched protects the mature drawer behavior while aligning every nested -# editor, table and state with the shell's current blue-white theme. -_DIAGNOSIS_BLUE_REPLACEMENTS = ( - ("#0891B2", "#4F63D9"), - ("#0E7490", "#4156C4"), - ("#22D3EE", "#8B9AD9"), - ("#67E8F9", "#EEF1FA"), - ("#A5F3FC", "#EEF1FA"), - ("#CFFAFE", "#EEF1FA"), - ("#ECFEFF", "#F7F7F7"), - ("#D9ECFF", "#EEF1FA"), - ("#134E4A", "#1A1C1F"), - ("#2A6B64", "#1A1C1F"), - ("#5B7A76", "#606163"), - ("#66736D", "#606163"), - ("#94A8A4", "#8E8F90"), - ("#67B8C9", "#8B9AD9"), - ("#D5E5E2", "#EDEDEE"), - ("#E2EBE8", "#EDEDEE"), - ("#D9DEDA", "#EDEDEE"), - ("#CBD3CE", "#EDEDEE"), - ("#F5F8F7", "#FFFFFF"), - ("#F0F2EF", "#F7F7F7"), - ("#F0F5F3", "#F7F7F7"), - ("#F0FDFA", "#F7F7F7"), - ("#0F172A", "#1A1C1F"), - ("#1F2937", "#1A1C1F"), - ("#333333", "#1A1C1F"), - ("#475569", "#1A1C1F"), - ("#64748B", "#606163"), - ("#6B7280", "#606163"), - ("#999999", "#8E8F90"), - ("#9AA39E", "#8E8F90"), - ("#C0C4CC", "#8E8F90"), - ("#F1F5F9", "#F7F7F7"), - ("#E2E8F0", "#EDEDEE"), - ("#DCE3EC", "#EDEDEE"), - ("#CBD5E1", "#EDEDEE"), - ("#E5E7EB", "#EDEDEE"), - ("#E6EBF2", "#EDEDEE"), - ("#F8FAFC", "#FFFFFF"), - ("#F6F6F6", "#F6F6F6"), - ("#FAFAFA", "#FFFFFF"), - ("#F8F8F8", "#F7F7F7"), - ("#16A34A", "#287B65"), - ("#15803D", "#287B65"), - ("#F0FDF4", "#EAF9F3"), - ("#ECFDF5", "#EAF9F3"), - ("#BBF7D0", "#BFE9DC"), - ("#A7F3D0", "#BFE9DC"), - ("#B45309", "#A9691D"), - ("#EA580C", "#A9691D"), - ("#F97316", "#A9691D"), - ("#FFFBEB", "#FFF5E6"), - ("#FFF7ED", "#FFF5E6"), - ("#FCD34D", "#F3D6AC"), - ("#FDE68A", "#F3D6AC"), - ("#FED7AA", "#F3D6AC"), - ("#DC2626", "#BE4B58"), - ("#B91C1C", "#BE4B58"), - ("#F56C6C", "#BE4B58"), - ("#FEF2F2", "#FFF1F3"), - ("#FFF7F7", "#FFF1F3"), - ("#FEE2E2", "#FFE4E8"), - ("#FECACA", "#F7C8CD"), - ("#FCA5A5", "#F19BA4"), -) -for _source_color, _theme_color in _DIAGNOSIS_BLUE_REPLACEMENTS: - DIAGNOSIS_QSS = DIAGNOSIS_QSS.replace(_source_color, _theme_color) -DIAGNOSIS_QSS = clinical_stylesheet(DIAGNOSIS_QSS) +# Normalize the legacy component palette in one place. Keeping the selectors +# untouched protects the mature drawer behavior while aligning every nested +# editor, table and state with the shell's current blue-white theme. +_DIAGNOSIS_BLUE_REPLACEMENTS = ( + ("#0891B2", "#4F63D9"), + ("#0E7490", "#4156C4"), + ("#22D3EE", "#8B9AD9"), + ("#67E8F9", "#EEF1FA"), + ("#A5F3FC", "#EEF1FA"), + ("#CFFAFE", "#EEF1FA"), + ("#ECFEFF", "#F7F7F7"), + ("#D9ECFF", "#EEF1FA"), + ("#134E4A", "#1A1C1F"), + ("#2A6B64", "#1A1C1F"), + ("#5B7A76", "#606163"), + ("#66736D", "#606163"), + ("#94A8A4", "#8E8F90"), + ("#67B8C9", "#8B9AD9"), + ("#D5E5E2", "#EDEDEE"), + ("#E2EBE8", "#EDEDEE"), + ("#D9DEDA", "#EDEDEE"), + ("#CBD3CE", "#EDEDEE"), + ("#F5F8F7", "#FFFFFF"), + ("#F0F2EF", "#F7F7F7"), + ("#F0F5F3", "#F7F7F7"), + ("#F0FDFA", "#F7F7F7"), + ("#0F172A", "#1A1C1F"), + ("#1F2937", "#1A1C1F"), + ("#333333", "#1A1C1F"), + ("#475569", "#1A1C1F"), + ("#64748B", "#606163"), + ("#6B7280", "#606163"), + ("#999999", "#8E8F90"), + ("#9AA39E", "#8E8F90"), + ("#C0C4CC", "#8E8F90"), + ("#F1F5F9", "#F7F7F7"), + ("#E2E8F0", "#EDEDEE"), + ("#DCE3EC", "#EDEDEE"), + ("#CBD5E1", "#EDEDEE"), + ("#E5E7EB", "#EDEDEE"), + ("#E6EBF2", "#EDEDEE"), + ("#F8FAFC", "#FFFFFF"), + ("#F6F6F6", "#F6F6F6"), + ("#FAFAFA", "#FFFFFF"), + ("#F8F8F8", "#F7F7F7"), + ("#16A34A", "#287B65"), + ("#15803D", "#287B65"), + ("#F0FDF4", "#EAF9F3"), + ("#ECFDF5", "#EAF9F3"), + ("#BBF7D0", "#BFE9DC"), + ("#A7F3D0", "#BFE9DC"), + ("#B45309", "#A9691D"), + ("#EA580C", "#A9691D"), + ("#F97316", "#A9691D"), + ("#FFFBEB", "#FFF5E6"), + ("#FFF7ED", "#FFF5E6"), + ("#FCD34D", "#F3D6AC"), + ("#FDE68A", "#F3D6AC"), + ("#FED7AA", "#F3D6AC"), + ("#DC2626", "#BE4B58"), + ("#B91C1C", "#BE4B58"), + ("#F56C6C", "#BE4B58"), + ("#FEF2F2", "#FFF1F3"), + ("#FFF7F7", "#FFF1F3"), + ("#FEE2E2", "#FFE4E8"), + ("#FECACA", "#F7C8CD"), + ("#FCA5A5", "#F19BA4"), +) +for _source_color, _theme_color in _DIAGNOSIS_BLUE_REPLACEMENTS: + DIAGNOSIS_QSS = DIAGNOSIS_QSS.replace(_source_color, _theme_color) +DIAGNOSIS_QSS = clinical_stylesheet(DIAGNOSIS_QSS) def _text(value: Any, default: str = "—") -> str: @@ -1167,19 +1167,19 @@ class DiagnosisSwitch(QAbstractButton): track = QRectF(1, 3, self.width() - 2, self.height() - 6) checked = self.isChecked() painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"])) - if not self.isEnabled(): - painter.setOpacity(0.6) + painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"])) + if not self.isEnabled(): + painter.setOpacity(0.6) painter.drawRoundedRect(track, track.height() / 2, track.height() / 2) diameter = track.height() - 4 x = track.right() - diameter - 2 if checked else track.left() + 2 painter.setBrush(QColor("#FFFFFF")) painter.drawEllipse(QRectF(x, track.top() + 2, diameter, diameter)) - if self.hasFocus(): - painter.setOpacity(1) - painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 11, 11) + if self.hasFocus(): + painter.setOpacity(1) + painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 11, 11) painter.end() @@ -1217,19 +1217,19 @@ class SaveStateButton(QPushButton): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) enabled = self.isEnabled() - idle_color = PALETTE["accent_pressed"] if self.isDown() else PALETTE["accent"] + idle_color = PALETTE["accent_pressed"] if self.isDown() else PALETTE["accent"] color = { - "success": PALETTE["success"], - "error": PALETTE["danger"], - "loading": PALETTE["accent"], - }.get(self._state, idle_color if enabled else PALETTE["disabled_surface"]) + "success": PALETTE["success"], + "error": PALETTE["danger"], + "loading": PALETTE["accent"], + }.get(self._state, idle_color if enabled else PALETTE["disabled_surface"]) painter.setPen(Qt.PenStyle.NoPen) painter.setBrush(QColor(color)) painter.drawRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1), 10, 10) - if self.hasFocus(): - painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 10, 10) + if self.hasFocus(): + painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 10, 10) label = { "loading": "正在保存", "success": "保存成功", @@ -1253,9 +1253,9 @@ class SaveStateButton(QPushButton): else: painter.drawLine(x + 3, center_y - 5, x + 12, center_y + 5) painter.drawLine(x + 12, center_y - 5, x + 3, center_y + 5) - painter.setPen(QColor( - PALETTE["disabled"] if not enabled and self._state == "idle" else PALETTE["surface"] - )) + painter.setPen(QColor( + PALETTE["disabled"] if not enabled and self._state == "idle" else PALETTE["surface"] + )) painter.drawText( QRect(x + icon_width, 0, metrics.horizontalAdvance(label), self.height()), Qt.AlignmentFlag.AlignCenter, @@ -1339,7 +1339,7 @@ class DiagnosisLineEdit(QLineEdit): self.setText(text) -class DiagnosisTextEdit(QPlainTextEdit): +class DiagnosisTextEdit(QPlainTextEdit): """Multiline editor using the same scoped field state as line inputs.""" def __init__(self, rows: int = 3, parent: QWidget | None = None) -> None: @@ -1355,113 +1355,113 @@ class DiagnosisTextEdit(QPlainTextEdit): # QPlainTextEdit defaults to ~80 columns; that blows past the drawer width. return QSize(48, self._hint_height) - def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual - return QSize(160, self._hint_height) - - -class ExpandableDiagnosisTextEdit(DiagnosisTextEdit): - """An inline long-text editor without an inner scrollbar when expanded.""" - - def __init__(self, rows: int = 3, parent: QWidget | None = None) -> None: - super().__init__(rows, parent) - self._collapsed_height = self._hint_height - self._caption = "内容" - self._expand_host: QWidget | None = None - self.expand_button = QPushButton("展开全部", self) - self.expand_button.setObjectName("DiagnosisTextExpandButton") - self.expand_button.setProperty("variant", "link") - self.expand_button.setCheckable(True) - self.expand_button.setAutoDefault(False) - self.expand_button.setCursor(Qt.CursorShape.PointingHandCursor) - self.expand_button.setToolTip("展开文本框,查看和编辑全部内容") - self.expand_button.hide() - self.expand_button.toggled.connect(self._toggle_expanded) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self._height_sync = QTimer(self) - self._height_sync.setSingleShot(True) - self._height_sync.setInterval(0) - self._height_sync.timeout.connect(self._sync_content_height) - self.textChanged.connect(self._height_sync.start) - self.document().documentLayout().documentSizeChanged.connect( - lambda _size: self._height_sync.start() - ) - - def wrap_with_expander(self, caption: str) -> QWidget: - """Keep the original plain-text editor as the form's save/readonly target.""" - - if self._expand_host is None: - self._caption = caption - self.setAccessibleName(caption) - self.expand_button.setAccessibleName(f"展开{caption}全部内容") - self._expand_host = QWidget() - self._expand_host.setMinimumWidth(0) - self._expand_host.setFocusProxy(self) - layout = QVBoxLayout(self._expand_host) - layout.setContentsMargins(0, 0, 0, 0) - layout.setSpacing(2) - layout.addWidget(self) - layout.addWidget(self.expand_button, 0, Qt.AlignmentFlag.AlignRight) - return self._expand_host - - def setPlainText(self, text: str) -> None: # noqa: N802 - Qt API - # A newly loaded record starts compact; typing/paste/undo keep its state. - self.expand_button.setChecked(False) - super().setPlainText(text) - - def _toggle_expanded(self, expanded: bool) -> None: - self.expand_button.setText("收起" if expanded else "展开全部") - self.expand_button.setAccessibleName( - f"收起{self._caption}" if expanded else f"展开{self._caption}全部内容" - ) - self.expand_button.setToolTip( - "收起为紧凑文本框,内容不会丢失" if expanded else "展开文本框,查看和编辑全部内容" - ) - self.setVerticalScrollBarPolicy( - Qt.ScrollBarPolicy.ScrollBarAlwaysOff - if expanded - else Qt.ScrollBarPolicy.ScrollBarAsNeeded - ) - self.verticalScrollBar().setValue(0) - self._height_sync.start() - - def _sync_content_height(self) -> None: - expanded = self.expand_button.isChecked() - document = self.document() - document_layout = document.documentLayout() - # QPlainTextDocumentLayout.documentSize().height() counts lines, not - # pixels. Measure the actual wrapped blocks, including offscreen ones. - height = self.height() - self.viewport().height() + 2 * document.documentMargin() - block = document.begin() - while block.isValid(): - height += document_layout.blockBoundingRect(block).height() - if not expanded and height > self._collapsed_height: - break - block = block.next() - self.expand_button.setVisible(expanded or height > self._collapsed_height) - target = max(self._collapsed_height, ceil(height)) if expanded else self._collapsed_height - if self._hint_height != target: - self._hint_height = target - self.setFixedHeight(target) - self.updateGeometry() - - def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API - super().resizeEvent(event) - if hasattr(self, "_height_sync"): - self._height_sync.start() - - def showEvent(self, event: QShowEvent) -> None: # noqa: N802 - Qt API - super().showEvent(event) - self._height_sync.start() - - def changeEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API - super().changeEvent(event) - if event.type() in (QEvent.Type.FontChange, QEvent.Type.StyleChange) and hasattr( - self, "_height_sync" - ): - self._height_sync.start() - - -class DiagnosisComboBox(QComboBox): + def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual + return QSize(160, self._hint_height) + + +class ExpandableDiagnosisTextEdit(DiagnosisTextEdit): + """An inline long-text editor without an inner scrollbar when expanded.""" + + def __init__(self, rows: int = 3, parent: QWidget | None = None) -> None: + super().__init__(rows, parent) + self._collapsed_height = self._hint_height + self._caption = "内容" + self._expand_host: QWidget | None = None + self.expand_button = QPushButton("展开全部", self) + self.expand_button.setObjectName("DiagnosisTextExpandButton") + self.expand_button.setProperty("variant", "link") + self.expand_button.setCheckable(True) + self.expand_button.setAutoDefault(False) + self.expand_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.expand_button.setToolTip("展开文本框,查看和编辑全部内容") + self.expand_button.hide() + self.expand_button.toggled.connect(self._toggle_expanded) + self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self._height_sync = QTimer(self) + self._height_sync.setSingleShot(True) + self._height_sync.setInterval(0) + self._height_sync.timeout.connect(self._sync_content_height) + self.textChanged.connect(self._height_sync.start) + self.document().documentLayout().documentSizeChanged.connect( + lambda _size: self._height_sync.start() + ) + + def wrap_with_expander(self, caption: str) -> QWidget: + """Keep the original plain-text editor as the form's save/readonly target.""" + + if self._expand_host is None: + self._caption = caption + self.setAccessibleName(caption) + self.expand_button.setAccessibleName(f"展开{caption}全部内容") + self._expand_host = QWidget() + self._expand_host.setMinimumWidth(0) + self._expand_host.setFocusProxy(self) + layout = QVBoxLayout(self._expand_host) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + layout.addWidget(self) + layout.addWidget(self.expand_button, 0, Qt.AlignmentFlag.AlignRight) + return self._expand_host + + def setPlainText(self, text: str) -> None: # noqa: N802 - Qt API + # A newly loaded record starts compact; typing/paste/undo keep its state. + self.expand_button.setChecked(False) + super().setPlainText(text) + + def _toggle_expanded(self, expanded: bool) -> None: + self.expand_button.setText("收起" if expanded else "展开全部") + self.expand_button.setAccessibleName( + f"收起{self._caption}" if expanded else f"展开{self._caption}全部内容" + ) + self.expand_button.setToolTip( + "收起为紧凑文本框,内容不会丢失" if expanded else "展开文本框,查看和编辑全部内容" + ) + self.setVerticalScrollBarPolicy( + Qt.ScrollBarPolicy.ScrollBarAlwaysOff + if expanded + else Qt.ScrollBarPolicy.ScrollBarAsNeeded + ) + self.verticalScrollBar().setValue(0) + self._height_sync.start() + + def _sync_content_height(self) -> None: + expanded = self.expand_button.isChecked() + document = self.document() + document_layout = document.documentLayout() + # QPlainTextDocumentLayout.documentSize().height() counts lines, not + # pixels. Measure the actual wrapped blocks, including offscreen ones. + height = self.height() - self.viewport().height() + 2 * document.documentMargin() + block = document.begin() + while block.isValid(): + height += document_layout.blockBoundingRect(block).height() + if not expanded and height > self._collapsed_height: + break + block = block.next() + self.expand_button.setVisible(expanded or height > self._collapsed_height) + target = max(self._collapsed_height, ceil(height)) if expanded else self._collapsed_height + if self._hint_height != target: + self._hint_height = target + self.setFixedHeight(target) + self.updateGeometry() + + def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API + super().resizeEvent(event) + if hasattr(self, "_height_sync"): + self._height_sync.start() + + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 - Qt API + super().showEvent(event) + self._height_sync.start() + + def changeEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API + super().changeEvent(event) + if event.type() in (QEvent.Type.FontChange, QEvent.Type.StyleChange) and hasattr( + self, "_height_sync" + ): + self._height_sync.start() + + +class DiagnosisComboBox(QComboBox): """Choice editor with the legacy text API used by diagnosis saving.""" def __init__( @@ -1690,26 +1690,27 @@ class DiagnosisChoiceButtons(QWidget): for button in self._buttons: value = str(button.property("diagnosisValue")) label = str(button.property("diagnosisLabel") or button.text()) - button.setChecked(value in token_set or label in token_set) - repolish(button) + want = value in token_set or label in token_set + if button.isChecked() != want: + button.setChecked(want) if was_exclusive: self._group.setExclusive(True) def setReadOnly(self, read_only: bool) -> None: # noqa: N802 # Match admin fieldset[disabled]: keep selected chip paint, block interaction. - self._read_only = bool(read_only) + target = bool(read_only) + if target == self._read_only and getattr(self, "_readonly_applied", False): + return + self._read_only = target + self._readonly_applied = True self.setProperty("diagnosisChoiceLocked", self._read_only) self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, self._read_only) - self.setCursor( - Qt.CursorShape.ArrowCursor if self._read_only else Qt.CursorShape.ArrowCursor + cursor_shape = ( + Qt.CursorShape.ArrowCursor if self._read_only else Qt.CursorShape.PointingHandCursor ) for button in self._buttons: button.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, self._read_only) - if self._read_only: - button.setCursor(Qt.CursorShape.ArrowCursor) - else: - button.setCursor(Qt.CursorShape.PointingHandCursor) - repolish(button) + button.setCursor(cursor_shape) repolish(self) def isReadOnly(self) -> bool: # noqa: N802 @@ -1850,18 +1851,18 @@ class MessageStrip(QFrame): self.glyph = QLabel("i") self.glyph.setFixedWidth(18) self.glyph.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.glyph.setStyleSheet(clinical_stylesheet("font-weight:700; color:$ds_accent;")) + self.glyph.setStyleSheet(clinical_stylesheet("font-weight:700; color:$ds_accent;")) self.label = QLabel() self.label.setWordWrap(True) - self.label.setStyleSheet(clinical_stylesheet("color:$ds_text; font-size:13px;")) + self.label.setStyleSheet(clinical_stylesheet("color:$ds_text; font-size:13px;")) layout.addWidget(self.glyph) layout.addWidget(self.label, 1) self.action_button = QPushButton() self.action_button.setObjectName("DiagnosisMessageAction") self.action_button.setStyleSheet( - "QPushButton{min-height:28px;padding:0 10px;color:#1A1C1F;background:#F0F0F0;" - "border:1px solid #E4E4E5;border-radius:7px;font-weight:500;}" - "QPushButton:hover,QPushButton:focus{background:#EEF1FA;border-color:#8B9AD9;}" + "QPushButton{min-height:28px;padding:0 10px;color:#1A1C1F;background:#F0F0F0;" + "border:1px solid #E4E4E5;border-radius:7px;font-weight:500;}" + "QPushButton:hover,QPushButton:focus{background:#EEF1FA;border-color:#8B9AD9;}" ) self.action_button.clicked.connect(self.action_requested) self.action_button.hide() @@ -1929,7 +1930,7 @@ class LoadingOverlay(QFrame): layout.setSpacing(8) self.glyph = _LoadingSpinner(self) label = QLabel(text) - label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) + label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) layout.addWidget(self.glyph) layout.addWidget(label) self.hide() @@ -2020,15 +2021,15 @@ class RecordTable(QTableWidget): Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter ) if column_index in danger_columns: - item.setForeground(QColor(PALETTE["danger"])) + item.setForeground(QColor(PALETTE["danger"])) kind = semantic.get(column_index) if kind: palette = { - "success": (PALETTE["success"], PALETTE["success_soft"]), - "warning": (PALETTE["warning"], PALETTE["warning_soft"]), - "danger": (PALETTE["danger"], PALETTE["danger_soft"]), - "info": (PALETTE["accent"], PALETTE["accent_soft"]), - "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), + "success": (PALETTE["success"], PALETTE["success_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + "info": (PALETTE["accent"], PALETTE["accent_soft"]), + "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), } foreground, background = palette.get(kind, palette["neutral"]) item.setForeground(QColor(foreground)) @@ -2068,20 +2069,20 @@ class BloodTrendChart(QWidget): plot = self.rect().adjusted(48, 24, -22, -38) values = [value for value in (*self._fasting, *self._postprandial) if value is not None] if not values or plot.width() <= 0 or plot.height() <= 0: - painter.setPen(QColor(PALETTE["muted"])) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "当前时间范围暂无血糖数据") painter.end() return upper = max(12.0, max(values) * 1.15) - painter.setPen(QPen(QColor(PALETTE["line"]), 1)) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) for step in range(5): y = plot.bottom() - round(plot.height() * step / 4) painter.drawLine(plot.left(), y, plot.right(), y) - painter.setPen(QColor(PALETTE["muted"])) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText( 4, y - 8, 40, 16, Qt.AlignmentFlag.AlignRight, f"{upper * step / 4:.0f}" ) - painter.setPen(QPen(QColor(PALETTE["line"]), 1)) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) count = max(1, len(self._dates) - 1) def point(index: int, value: float) -> QPointF: @@ -2091,8 +2092,8 @@ class BloodTrendChart(QWidget): ) for series, color in ( - (self._fasting, QColor("#4F63D9")), - (self._postprandial, QColor("#A9691D")), + (self._fasting, QColor("#4F63D9")), + (self._postprandial, QColor("#A9691D")), ): previous: QPointF | None = None painter.setPen(QPen(color, 2.5)) @@ -2106,12 +2107,12 @@ class BloodTrendChart(QWidget): painter.drawLine(previous, current) painter.drawEllipse(current, 3.2, 3.2) previous = current - painter.setPen(QColor("#4F63D9")) + painter.setPen(QColor("#4F63D9")) painter.drawText(plot.left(), 4, 94, 18, Qt.AlignmentFlag.AlignLeft, "● 空腹血糖") - painter.setPen(QColor("#A9691D")) + painter.setPen(QColor("#A9691D")) painter.drawText(plot.left() + 100, 4, 110, 18, Qt.AlignmentFlag.AlignLeft, "● 餐后血糖") if self._dates: - painter.setPen(QColor(PALETTE["muted"])) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText( plot.left(), plot.bottom() + 8, @@ -2314,7 +2315,7 @@ class DailyRecordPanel(QFrame): self.todo_table.setMinimumHeight(180) todo_layout.addWidget(self.todo_table) self.todo_summary = QLabel("共 0 条") - self.todo_summary.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) + self.todo_summary.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) todo_layout.addWidget(self.todo_summary, 0, Qt.AlignmentFlag.AlignRight) root.addWidget(todo_card) self.clear() @@ -2471,9 +2472,9 @@ class DailyRecordPanel(QFrame): label_font.setWeight(QFont.Weight.Normal) for row_index, (metric, label) in enumerate(self.METRICS): label_item = QTableWidgetItem(label) - label_item.setFont(label_font) - label_item.setForeground(QColor(PALETTE["muted"])) - label_item.setBackground(QColor(PALETTE["surface_alt"])) + label_item.setFont(label_font) + label_item.setForeground(QColor(PALETTE["muted"])) + label_item.setBackground(QColor(PALETTE["surface_alt"])) self.matrix.setItem(row_index, 0, label_item) for date_index, date in enumerate(dates, 1): b = blood.get(date) @@ -2526,11 +2527,11 @@ class DailyRecordPanel(QFrame): item = QTableWidgetItem(value) item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) if high: - item.setForeground(QColor(PALETTE["danger"])) - item.setBackground(QColor(PALETTE["danger_soft"])) + item.setForeground(QColor(PALETTE["danger"])) + item.setBackground(QColor(PALETTE["danger_soft"])) elif value.endswith("· 自录"): - item.setForeground(QColor(PALETTE["text"])) - item.setBackground(QColor(PALETTE["surface_alt"])) + item.setForeground(QColor(PALETTE["text"])) + item.setBackground(QColor(PALETTE["surface_alt"])) edit_kind = "" edit_source: Any = None if metric in {"fasting", "postprandial", "other", "bp", "western", "insulin"}: @@ -2745,29 +2746,29 @@ class _RemoteImageButton(QPushButton): request = QNetworkRequest(url) request.setTransferTimeout(10_000) request.setMaximumRedirectsAllowed(4) - request.setAttribute( - QNetworkRequest.Attribute.RedirectPolicyAttribute, - QNetworkRequest.RedirectPolicy.SameOriginRedirectPolicy, - ) - reply = self._manager.get(request) - self._reply = reply - reply.setProperty("diagnosisImageGeneration", generation) - reply.setProperty("diagnosisImageOversize", False) - reply.downloadProgress.connect(self._download_progress) - reply.finished.connect(self._reply_finished) - - def _download_progress(self, bytes_received: int, bytes_total: int) -> None: - """Abort a current reply as soon as its received or declared size is unsafe.""" - - reply = self.sender() - if reply is not self._reply: - return - if bytes_received <= self._MAX_IMAGE_BYTES and ( - bytes_total < 0 or bytes_total <= self._MAX_IMAGE_BYTES - ): - return - reply.setProperty("diagnosisImageOversize", True) - reply.abort() + request.setAttribute( + QNetworkRequest.Attribute.RedirectPolicyAttribute, + QNetworkRequest.RedirectPolicy.SameOriginRedirectPolicy, + ) + reply = self._manager.get(request) + self._reply = reply + reply.setProperty("diagnosisImageGeneration", generation) + reply.setProperty("diagnosisImageOversize", False) + reply.downloadProgress.connect(self._download_progress) + reply.finished.connect(self._reply_finished) + + def _download_progress(self, bytes_received: int, bytes_total: int) -> None: + """Abort a current reply as soon as its received or declared size is unsafe.""" + + reply = self.sender() + if reply is not self._reply: + return + if bytes_received <= self._MAX_IMAGE_BYTES and ( + bytes_total < 0 or bytes_total <= self._MAX_IMAGE_BYTES + ): + return + reply.setProperty("diagnosisImageOversize", True) + reply.abort() def _reply_finished(self) -> None: """Use a QObject receiver connection so destruction auto-disconnects the callback.""" @@ -2787,19 +2788,19 @@ class _RemoteImageButton(QPushButton): reply.deleteLater() return self._reply = None - if not self._owner_is_current(): - reply.deleteLater() - return - error = reply.error() - if bool(reply.property("diagnosisImageOversize")) or ( - error != QNetworkReply.NetworkError.NoError - ): - reply.deleteLater() - self._show_fallback() - return - payload = bytes(reply.readAll()) - reply.deleteLater() - self._apply_payload(payload, generation) + if not self._owner_is_current(): + reply.deleteLater() + return + error = reply.error() + if bool(reply.property("diagnosisImageOversize")) or ( + error != QNetworkReply.NetworkError.NoError + ): + reply.deleteLater() + self._show_fallback() + return + payload = bytes(reply.readAll()) + reply.deleteLater() + self._apply_payload(payload, generation) def _apply_payload(self, payload: bytes, generation: int) -> bool: """Decode a current reply; kept separate so offline tests can exercise rendering.""" @@ -2854,20 +2855,20 @@ class NotesTimeline(QWidget): add_requested = Signal() upload_requested = Signal(str) - images_dropped = Signal(object, str) - image_drop_failed = Signal(str) - delete_attachment_requested = Signal(int, str, str) - open_attachment_requested = Signal(str) - preview_images_requested = Signal(object, int) + images_dropped = Signal(object, str) + image_drop_failed = Signal(str) + delete_attachment_requested = Signal(int, str, str) + open_attachment_requested = Signal(str) + preview_images_requested = Signal(object, int) def __init__(self, *, editable: bool = False, parent: QWidget | None = None) -> None: super().__init__(parent) self.setObjectName("DiagnosisNotesTimeline") self._editable = editable self._can_delete = editable - self._upload_available = True - self._upload_busy = False - self._drop_targets: dict[QWidget, str] = {} + self._upload_available = True + self._upload_busy = False + self._drop_targets: dict[QWidget, str] = {} self._image_generation = 0 self.root = QVBoxLayout(self) self.root.setContentsMargins(0, 0, 0, 0) @@ -2888,10 +2889,10 @@ class NotesTimeline(QWidget): self.tongue_button.clicked.connect(lambda: self.upload_requested.emit("tongue_images")) self.report_button.clicked.connect(lambda: self.upload_requested.emit("report_files")) self.root.addWidget(self.toolbar) - self.drop_hint = QLabel("可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。") - self.drop_hint.setObjectName("DiagnosisDialogGuidance") - self.drop_hint.setWordWrap(True) - self.root.addWidget(self.drop_hint) + self.drop_hint = QLabel("可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。") + self.drop_hint.setObjectName("DiagnosisDialogGuidance") + self.drop_hint.setWordWrap(True) + self.root.addWidget(self.drop_hint) self.nodes = QWidget() self.nodes_layout = QVBoxLayout(self.nodes) self.nodes_layout.setContentsMargins(22, 0, 0, 0) @@ -2902,89 +2903,89 @@ class NotesTimeline(QWidget): self.empty.setAlignment(Qt.AlignmentFlag.AlignCenter) self.empty.setMinimumHeight(80) self.root.addWidget(self.empty) - self.register_image_drop_target(self) - self.register_image_drop_target(self.tongue_button, "tongue_images") - self.register_image_drop_target(self.report_button, "report_files") - self.tongue_button.setToolTip("点击选择文件,或把图片拖到此处上传为舌象") - self.report_button.setToolTip("点击选择报告,或把图片拖到此处上传为报告") + self.register_image_drop_target(self) + self.register_image_drop_target(self.tongue_button, "tongue_images") + self.register_image_drop_target(self.report_button, "report_files") + self.tongue_button.setToolTip("点击选择文件,或把图片拖到此处上传为舌象") + self.report_button.setToolTip("点击选择报告,或把图片拖到此处上传为报告") self.set_editable(editable) def set_editable(self, editable: bool, *, can_delete: bool | None = None) -> None: self._editable = editable self._can_delete = editable if can_delete is None else bool(can_delete) self.toolbar.setVisible(self._editable) - self.drop_hint.setVisible(self._editable and self._upload_available) - self._sync_image_drop_targets() - - def set_upload_available(self, available: bool) -> None: - self._upload_available = bool(available) - self.drop_hint.setVisible(self._editable and self._upload_available) - self._sync_image_drop_targets() - - def set_upload_busy(self, busy: bool) -> None: - self._upload_busy = bool(busy) - self._sync_image_drop_targets() - - def register_image_drop_target(self, widget: QWidget, image_type: str = "") -> None: - """Include scroll viewport blank space as well as the note timeline.""" - self._drop_targets[widget] = image_type - widget.installEventFilter(self) - self._sync_image_drop_targets() - - def _sync_image_drop_targets(self) -> None: - enabled = self._editable and self._upload_available and not self._upload_busy - for widget in self._drop_targets: - widget.setAcceptDrops(enabled) - self.tongue_button.setEnabled(enabled) - self.report_button.setEnabled(enabled) - self.add_button.setEnabled(self._editable and not self._upload_busy) - if not enabled: - self._highlight_drop_target(None) - - def _highlight_drop_target(self, active: QWidget | None) -> None: - for button in (self.tongue_button, self.report_button): - highlighted = button is active - if bool(button.property("imageDropActive")) != highlighted: - button.setProperty("imageDropActive", highlighted) - repolish(button) - text = ( - "松开鼠标上传图片;未指定类别时可选择舌象或报告。" - if active is not None else "可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。" - ) - self.drop_hint.setText(text) - - def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 - Qt API - if watched in self._drop_targets and event.type() in { - QEvent.Type.DragEnter, QEvent.Type.DragMove, QEvent.Type.DragLeave, QEvent.Type.Drop, - }: - if event.type() == QEvent.Type.DragLeave: - self._highlight_drop_target(None) - event.accept() - return True - if (not self._editable or not self._upload_available or self._upload_busy - or not (event.possibleActions() & Qt.DropAction.CopyAction) - or not can_drop_images(event.mimeData())): - self._highlight_drop_target(None) - event.ignore() - return True - if event.type() == QEvent.Type.Drop: - self._highlight_drop_target(None) - try: - payload = capture_image_drop(event.mimeData()) - except ValueError as error: - self.image_drop_failed.emit(str(error)) - event.ignore() - return True - # Copy semantics are essential: uploading never moves the source. - event.setDropAction(Qt.DropAction.CopyAction) - event.accept() - self.images_dropped.emit(payload, self._drop_targets[watched]) - else: - self._highlight_drop_target(watched) - event.setDropAction(Qt.DropAction.CopyAction) - event.accept() - return True - return super().eventFilter(watched, event) + self.drop_hint.setVisible(self._editable and self._upload_available) + self._sync_image_drop_targets() + + def set_upload_available(self, available: bool) -> None: + self._upload_available = bool(available) + self.drop_hint.setVisible(self._editable and self._upload_available) + self._sync_image_drop_targets() + + def set_upload_busy(self, busy: bool) -> None: + self._upload_busy = bool(busy) + self._sync_image_drop_targets() + + def register_image_drop_target(self, widget: QWidget, image_type: str = "") -> None: + """Include scroll viewport blank space as well as the note timeline.""" + self._drop_targets[widget] = image_type + widget.installEventFilter(self) + self._sync_image_drop_targets() + + def _sync_image_drop_targets(self) -> None: + enabled = self._editable and self._upload_available and not self._upload_busy + for widget in self._drop_targets: + widget.setAcceptDrops(enabled) + self.tongue_button.setEnabled(enabled) + self.report_button.setEnabled(enabled) + self.add_button.setEnabled(self._editable and not self._upload_busy) + if not enabled: + self._highlight_drop_target(None) + + def _highlight_drop_target(self, active: QWidget | None) -> None: + for button in (self.tongue_button, self.report_button): + highlighted = button is active + if bool(button.property("imageDropActive")) != highlighted: + button.setProperty("imageDropActive", highlighted) + repolish(button) + text = ( + "松开鼠标上传图片;未指定类别时可选择舌象或报告。" + if active is not None else "可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。" + ) + self.drop_hint.setText(text) + + def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 - Qt API + if watched in self._drop_targets and event.type() in { + QEvent.Type.DragEnter, QEvent.Type.DragMove, QEvent.Type.DragLeave, QEvent.Type.Drop, + }: + if event.type() == QEvent.Type.DragLeave: + self._highlight_drop_target(None) + event.accept() + return True + if (not self._editable or not self._upload_available or self._upload_busy + or not (event.possibleActions() & Qt.DropAction.CopyAction) + or not can_drop_images(event.mimeData())): + self._highlight_drop_target(None) + event.ignore() + return True + if event.type() == QEvent.Type.Drop: + self._highlight_drop_target(None) + try: + payload = capture_image_drop(event.mimeData()) + except ValueError as error: + self.image_drop_failed.emit(str(error)) + event.ignore() + return True + # Copy semantics are essential: uploading never moves the source. + event.setDropAction(Qt.DropAction.CopyAction) + event.accept() + self.images_dropped.emit(payload, self._drop_targets[watched]) + else: + self._highlight_drop_target(watched) + event.setDropAction(Qt.DropAction.CopyAction) + event.accept() + return True + return super().eventFilter(watched, event) def set_state(self, text: str) -> None: self.empty.setText(text) @@ -3021,14 +3022,14 @@ class NotesTimeline(QWidget): attachments = QWidget() attachments_layout = FlowLayout(attachments, horizontal_spacing=8, vertical_spacing=8) images = _pick(note, "tongue_images", "images", default=[]) or [] - if not isinstance(images, Sequence) or isinstance(images, (str, bytes, bytearray)): - images = [images] - image_paths = [ - str(_pick(image, "url", "path", "file_url", default=image) or "") - for image in images - ] - note_id = int(_pick(note, "id", "note_id", default=0) or 0) - for image_index, path in enumerate(image_paths): + if not isinstance(images, Sequence) or isinstance(images, (str, bytes, bytearray)): + images = [images] + image_paths = [ + str(_pick(image, "url", "path", "file_url", default=image) or "") + for image in images + ] + note_id = int(_pick(note, "id", "note_id", default=0) or 0) + for image_index, path in enumerate(image_paths): image_host = QWidget() image_layout = QGridLayout(image_host) image_layout.setContentsMargins(0, 0, 0, 0) @@ -3042,12 +3043,12 @@ class NotesTimeline(QWidget): object_name="DiagnosisTongueThumb", parent=image_host, ) - thumb.setEnabled(bool(path)) - thumb.clicked.connect( - lambda _checked=False, sources=image_paths, index=image_index: ( - self.preview_images_requested.emit(sources, index) - ) - ) + thumb.setEnabled(bool(path)) + thumb.clicked.connect( + lambda _checked=False, sources=image_paths, index=image_index: ( + self.preview_images_requested.emit(sources, index) + ) + ) image_layout.addWidget(thumb, 0, 0) if self._can_delete and note_id > 0 and path: remove = QPushButton("×") @@ -3143,7 +3144,7 @@ class ChatPanel(QWidget): toolbar_layout.setContentsMargins(0, 0, 0, 0) toolbar_layout.setSpacing(8) archive = QLabel("仅展示服务端已归档消息(only_archived=1)") - archive.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;")) + archive.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;")) toolbar_layout.addWidget(archive) toolbar_layout.addStretch(1) self.sync_button = QPushButton("同步最新(后台异步)") @@ -3175,16 +3176,16 @@ class ChatPanel(QWidget): widget = item.widget() if widget is not None and widget not in {self.empty, self.toolbar, self.info}: widget.deleteLater() - visible_count = 0 + visible_count = 0 for message in messages: - item = parse_chat_item(message, include_date=True) - if item is None: - continue - visible_count += 1 - if item.variant == "event": - self.root.insertWidget(max(2, self.root.count() - 1), self._event_row(item)) - continue - side = "doctor" if item.role == "doctor" else "patient" + item = parse_chat_item(message, include_date=True) + if item is None: + continue + visible_count += 1 + if item.variant == "event": + self.root.insertWidget(max(2, self.root.count() - 1), self._event_row(item)) + continue + side = "doctor" if item.role == "doctor" else "patient" row = QWidget() row_layout = QHBoxLayout(row) row_layout.setContentsMargins(0, 0, 0, 0) @@ -3197,14 +3198,14 @@ class ChatPanel(QWidget): bubble_layout.setSpacing(5) meta = QLabel( f"{_text(_pick(message, 'sender_name', 'from_staff_name', 'name'), '患者' if side == 'patient' else '医生')} " - f"{item.time_text}" + f"{item.time_text}" ) meta.setObjectName("DiagnosisChatMeta") - meta.setTextFormat(Qt.TextFormat.PlainText) + meta.setTextFormat(Qt.TextFormat.PlainText) message_type = str( _pick(message, "message_type", "msg_type", "type", default="text") or "text" ).lower() - body_text = _text(_pick(message, "text", "content", "message"), "不支持的消息") + body_text = _text(_pick(message, "text", "content", "message"), "不支持的消息") body: QWidget if message_type in {"image", "2"}: target = str( @@ -3244,11 +3245,11 @@ class ChatPanel(QWidget): ) body = action else: - text = QLabel(body_text) + text = QLabel(body_text) text.setObjectName("DiagnosisChatText") - text.setTextFormat(Qt.TextFormat.PlainText) + text.setTextFormat(Qt.TextFormat.PlainText) text.setWordWrap(True) - text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) body = text bubble_layout.addWidget(meta) bubble_layout.addWidget(body) @@ -3259,50 +3260,50 @@ class ChatPanel(QWidget): row_layout.addWidget(bubble) row_layout.addStretch(1) self.root.insertWidget(max(2, self.root.count() - 1), row) - self.empty.setVisible(visible_count == 0) - - @staticmethod - def _event_row(item: ChatItem) -> QWidget: - row = QWidget() - layout = QHBoxLayout(row) - layout.setContentsMargins(0, 0, 0, 0) - layout.addStretch(1) - card = QFrame() - card.setObjectName("DiagnosisChatEvent") - card.setProperty("tone", item.tone) - card.setMaximumWidth(620) - card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) - content = QGridLayout(card) - content.setContentsMargins(12, 10, 12, 10) - content.setHorizontalSpacing(9) - content.setVerticalSpacing(4) - marker = QLabel(item.marker) - marker.setObjectName("DiagnosisChatEventMarker") - marker.setTextFormat(Qt.TextFormat.PlainText) - marker.setFixedWidth(22) - marker.setAlignment(Qt.AlignmentFlag.AlignCenter) - content.addWidget(marker, 0, 0) - title = QLabel(item.title) - title.setObjectName("DiagnosisChatEventTitle") - title.setTextFormat(Qt.TextFormat.PlainText) - title.setWordWrap(True) - content.addWidget(title, 0, 1) - content.setColumnStretch(1, 1) - if item.time_text: - time = QLabel(item.time_text) - time.setObjectName("DiagnosisChatMeta") - time.setTextFormat(Qt.TextFormat.PlainText) - content.addWidget(time, 0, 2, alignment=Qt.AlignmentFlag.AlignRight) - if item.detail: - detail = QLabel(item.detail) - detail.setObjectName("DiagnosisChatEventDetail") - detail.setTextFormat(Qt.TextFormat.PlainText) - detail.setWordWrap(True) - detail.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - content.addWidget(detail, 1, 1, 1, 2) - layout.addWidget(card, 4) - layout.addStretch(1) - return row + self.empty.setVisible(visible_count == 0) + + @staticmethod + def _event_row(item: ChatItem) -> QWidget: + row = QWidget() + layout = QHBoxLayout(row) + layout.setContentsMargins(0, 0, 0, 0) + layout.addStretch(1) + card = QFrame() + card.setObjectName("DiagnosisChatEvent") + card.setProperty("tone", item.tone) + card.setMaximumWidth(620) + card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + content = QGridLayout(card) + content.setContentsMargins(12, 10, 12, 10) + content.setHorizontalSpacing(9) + content.setVerticalSpacing(4) + marker = QLabel(item.marker) + marker.setObjectName("DiagnosisChatEventMarker") + marker.setTextFormat(Qt.TextFormat.PlainText) + marker.setFixedWidth(22) + marker.setAlignment(Qt.AlignmentFlag.AlignCenter) + content.addWidget(marker, 0, 0) + title = QLabel(item.title) + title.setObjectName("DiagnosisChatEventTitle") + title.setTextFormat(Qt.TextFormat.PlainText) + title.setWordWrap(True) + content.addWidget(title, 0, 1) + content.setColumnStretch(1, 1) + if item.time_text: + time = QLabel(item.time_text) + time.setObjectName("DiagnosisChatMeta") + time.setTextFormat(Qt.TextFormat.PlainText) + content.addWidget(time, 0, 2, alignment=Qt.AlignmentFlag.AlignRight) + if item.detail: + detail = QLabel(item.detail) + detail.setObjectName("DiagnosisChatEventDetail") + detail.setTextFormat(Qt.TextFormat.PlainText) + detail.setWordWrap(True) + detail.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + content.addWidget(detail, 1, 1, 1, 2) + layout.addWidget(card, 4) + layout.addStretch(1) + return row @dataclass(frozen=True) @@ -3409,7 +3410,7 @@ class CaseGrid(QFrame): title_row.addWidget(self.title_label) self.subtitle = QLabel("病例 · 诊断日期 —") self.subtitle.setStyleSheet( - 'color:#606163;font-size:12px;' + 'color:#606163;font-size:12px;' ) title_row.addWidget(self.subtitle) title_row.addStretch(1) @@ -3419,7 +3420,7 @@ class CaseGrid(QFrame): if group_index: divider = QFrame() divider.setFrameShape(QFrame.Shape.HLine) - divider.setStyleSheet(clinical_stylesheet("border:0; border-top:1px solid $ds_line;")) + divider.setStyleSheet(clinical_stylesheet("border:0; border-top:1px solid $ds_line;")) self.root.addWidget(divider) group_title = QLabel(f"● {group_name}") group_title.setProperty("diagnosisCaseGroup", True) @@ -3577,11 +3578,11 @@ def readonly_card(title: str, object_name: str, body: QWidget) -> QFrame: def set_tag_item(item: QTableWidgetItem, kind: str) -> None: palette = { - "success": (PALETTE["success"], PALETTE["success_soft"]), - "warning": (PALETTE["warning"], PALETTE["warning_soft"]), - "danger": (PALETTE["danger"], PALETTE["danger_soft"]), - "info": (PALETTE["accent"], PALETTE["accent_soft"]), - "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), + "success": (PALETTE["success"], PALETTE["success_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + "info": (PALETTE["accent"], PALETTE["accent_soft"]), + "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), } foreground, background = palette.get(kind, palette["neutral"]) item.setForeground(QColor(foreground)) diff --git a/app/src/doctor_workstation/ui/dialogs/ai_consult.py b/app/src/doctor_workstation/ui/dialogs/ai_consult.py index 6d84945f6..2a56ec2c9 100755 --- a/app/src/doctor_workstation/ui/dialogs/ai_consult.py +++ b/app/src/doctor_workstation/ui/dialogs/ai_consult.py @@ -4790,14 +4790,25 @@ class AiConsultDialog(QDialog): layout.setSpacing(12) splitter = QSplitter(Qt.Orientation.Horizontal) - splitter.setChildrenCollapsible(False) + self._main_splitter = splitter + splitter.setChildrenCollapsible(True) splitter.addWidget(self._build_center()) - splitter.addWidget(self._build_right_pane()) + self._right_context_pane = self._build_right_pane() + splitter.addWidget(self._right_context_pane) splitter.setStretchFactor(0, 1) splitter.setStretchFactor(1, 0) splitter.setSizes([920, 460]) layout.addWidget(splitter, 1) + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + pane = getattr(self, "_right_context_pane", None) + if pane is not None and self.property("hostedInSpatialWing"): + # When docked as a narrow side-wing beside the live workstation, hide duplicate chart rail + want_visible = self.width() >= 860 + if pane.isVisible() != want_visible: + pane.setVisible(want_visible) + def _build_right_pane(self) -> QWidget: host = QWidget() host.setObjectName("AiConsultRightPane") diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py index c54c1a4a7..a5dac8bdc 100755 --- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py +++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py @@ -762,6 +762,11 @@ class OrderDetailDrawer(QDialog): QTimer.singleShot(0, self.sync_to_owner) def sync_to_owner(self) -> None: + if self.property("hostedInSpatialWing"): + self.scrim.hide() + self.drawer_panel.setMinimumWidth(0) + self.drawer_panel.setMaximumWidth(16777215) + return owner = self._owner if owner is not None: # The scrim is an overlay of its owner, including when that owner is @@ -909,6 +914,11 @@ class DiagnosisDialog(QDialog): self._loaded_tabs: set[str] = set() self._loading_tabs: set[str] = set() self._daily_todo_status: int | None = None + self._pending_focus_target: tuple[str, str, int | None] | None = None + self._highlighted_target: QWidget | None = None + self._highlight_timer = QTimer(self) + self._highlight_timer.setSingleShot(True) + self._highlight_timer.timeout.connect(self._clear_field_highlight) self._recording_players: list[RecordingPlayerDialog] = [] self._image_preview: ImagePreviewDialog | None = None self._inline_recording_cells: list[RecordingPlaybackCell] = [] @@ -950,11 +960,21 @@ class DiagnosisDialog(QDialog): ) self.setObjectName("DiagnosisDialogRoot") - if self._embedded: + from ..spatial_wings import find_spatial_shell, install_wing_dialog_support + + in_spatial_shell = not self._embedded and find_spatial_shell(parent) is not None + if self._embedded or in_spatial_shell: self.setWindowFlags(Qt.WindowType.Widget) self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) self.setMinimumSize(0, 0) - self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Expanding) + self.setSizePolicy( + QSizePolicy.Policy.Ignored if self._embedded else QSizePolicy.Policy.Expanding, + QSizePolicy.Policy.Expanding, + ) + if in_spatial_shell: + self.setProperty("hostedInSpatialWing", True) + self.setProperty("doctorSkipOpenGeometry", True) else: self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint) self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) @@ -962,6 +982,8 @@ class DiagnosisDialog(QDialog): self.resize(1024, 640) self.setWindowTitle("患者信息详情") self.setStyleSheet(DIAGNOSIS_QSS) + if not self._embedded: + install_wing_dialog_support(self, icon_kind="consultations", preferred_width=660) self.view_stack = QStackedLayout(self) self.view_stack.setContentsMargins(0, 0, 0, 0) @@ -1325,7 +1347,8 @@ class DiagnosisDialog(QDialog): 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) + hide_in_wing = bool(self.property("hostedInSpatialWing")) and self.width() < 860 + self.studio_outline.setVisible(self.tabs.count() > 1 and not hide_in_wing) def _sync_studio_outline_selection(self, index: int) -> None: if len(self._studio_outline_buttons) != self.tabs.count(): @@ -1404,6 +1427,7 @@ class DiagnosisDialog(QDialog): def _build_basic_tab(self) -> QScrollArea: scroll = QScrollArea() + self._basic_scroll = scroll scroll.setObjectName("DiagnosisDrawerBody") scroll.setProperty("diagnosisTabKey", "basic") scroll.setWidgetResizable(True) @@ -1416,7 +1440,7 @@ class DiagnosisDialog(QDialog): content.setObjectName("DiagnosisTabBasic") content.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) content.setMinimumWidth(0) - content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + content.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) layout = QVBoxLayout(content) layout.setContentsMargins(20, 16, 20, 20) layout.setSpacing(8) @@ -1439,8 +1463,12 @@ class DiagnosisDialog(QDialog): form_layout.setSpacing(12) self.edit_fields: dict[str, Any] = {} self.display_fields: dict[str, Any] = {} + self._field_containers: dict[str, QWidget] = {} + self._section_headings: dict[int, QWidget] = {} for section_key, (title, rows) in enumerate(_FORM_SECTIONS): - form_layout.addWidget(section_heading(title, f"DiagnosisSection_{section_key}")) + sec_hdr = section_heading(title, f"DiagnosisSection_{section_key}") + self._section_headings[section_key] = sec_hdr + form_layout.addWidget(sec_hdr) for row_index, row_fields in enumerate(rows): row_host = QWidget() row_host.setSizePolicy( @@ -1460,6 +1488,7 @@ class DiagnosisDialog(QDialog): else: display = editor container = self._field_container(label, display, span, editor=editor) + self._field_containers[key] = container row_layout.addWidget(container, span) fields.append(container) occupied += span @@ -2046,8 +2075,15 @@ class DiagnosisDialog(QDialog): label.setFixedWidth(100) label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + def _is_wing_or_embedded(self) -> bool: + if self._embedded or bool(self.property("hostedInSpatialWing")): + return True + from ..spatial_wings import find_spatial_shell + + return find_spatial_shell(self) is not None + def _sync_host_geometry(self) -> None: - if self._embedded: + if self._is_wing_or_embedded(): return owner = self._owner if not self._standalone_readonly and owner is not None and owner is not self: @@ -2072,6 +2108,16 @@ class DiagnosisDialog(QDialog): def _update_drawer_geometry(self) -> None: if not hasattr(self, "drawer_panel"): return + if self._is_wing_or_embedded(): + scrim = getattr(self, "drawer_scrim", None) + if isinstance(scrim, QWidget): + scrim.hide() + w = max(360, self.width()) + self.drawer_panel.setMinimumWidth(0) + self.drawer_panel.setMaximumWidth(16777215) + self._reflow_form(w) + self._sync_choice_field_heights() + return drawer_width = self.width() if self.width() <= 768 else max(456, round(self.width() * 0.60)) self.drawer_panel.setFixedWidth(drawer_width) # Reflow against the actual drawer content width, not the fullscreen overlay. @@ -2092,7 +2138,7 @@ class DiagnosisDialog(QDialog): layout.addWidget(self.readonly_hero_right, 0, 1, Qt.AlignmentFlag.AlignRight) def _install_owner_filter(self) -> None: - if self._embedded: + if self._is_wing_or_embedded(): return if self._owner is not None and not self._owner_filter_installed: self._owner.installEventFilter(self) @@ -2101,7 +2147,7 @@ class DiagnosisDialog(QDialog): def _rebind_owner(self) -> None: """Resolve the live Shell window for every open/show cycle.""" - if self._embedded: + if self._is_wing_or_embedded(): self._owner = None self._owner_filter_installed = False return @@ -2127,13 +2173,14 @@ class DiagnosisDialog(QDialog): super().resizeEvent(event) def showEvent(self, event: Any) -> None: - if not self._embedded: + if not self._is_wing_or_embedded(): self._rebind_owner() self._sync_host_geometry() self._update_drawer_geometry() self._reflow_readonly_hero() super().showEvent(event) - self._queue_owner_sync() + if not self._is_wing_or_embedded(): + self._queue_owner_sync() def _queue_owner_sync(self) -> None: generation = self._generation @@ -2253,6 +2300,8 @@ class DiagnosisDialog(QDialog): self._local_audio_dialog = None self._diagnosis_id = int(diagnosis_id) self._patient_id = 0 + self._pending_focus_target = None + self._clear_field_highlight() self._editable = bool( editable and has_permission(self.permissions, "tcm.diagnosis/edit", default=True) ) @@ -2306,10 +2355,14 @@ class DiagnosisDialog(QDialog): ) self.title_label.setText("编辑诊单" if self._editable else "诊单详情") self.mode_label.setText("编辑" if self._editable else "只读") - self.mode_label.setProperty("kind", "warning" if self._editable else "info") - repolish(self.mode_label) - self.drawer_panel.setProperty("mode", "edit" if self._editable else "viewOnly") - repolish(self.drawer_panel) + want_kind = "warning" if self._editable else "info" + if self.mode_label.property("kind") != want_kind: + self.mode_label.setProperty("kind", want_kind) + repolish(self.mode_label) + want_mode = "edit" if self._editable else "viewOnly" + if self.drawer_panel.property("mode") != want_mode: + self.drawer_panel.setProperty("mode", want_mode) + repolish(self.drawer_panel) self.close_button.setText("取消" if self._editable else "关闭") for timeline in self._notes_timelines: timeline.set_editable( @@ -2496,6 +2549,90 @@ class DiagnosisDialog(QDialog): self._load_visible_readonly_sections() else: self._ensure_tab_loaded(self._current_tab_key()) + if self._pending_focus_target is not None: + t_key, f_key, s_idx = self._pending_focus_target + self._pending_focus_target = None + self._apply_clinical_target(t_key, field_key=f_key, section_index=s_idx) + + def _clear_field_highlight(self) -> None: + if self._highlighted_target is not None: + with suppress(RuntimeError): + self._highlighted_target.setStyleSheet("") + self._highlighted_target = None + + def focus_clinical_target( + self, + tab_key: str = "basic", + *, + field_key: str = "", + section_index: int | None = None, + ) -> None: + """Switch to `tab_key` and scroll/highlight `field_key` or `section_index`.""" + + if not self._authoritative_detail_loaded: + self._pending_focus_target = (tab_key, field_key, section_index) + self._apply_clinical_target(tab_key, field_key=field_key, section_index=section_index) + + def _apply_clinical_target( + self, + tab_key: str = "basic", + *, + field_key: str = "", + section_index: int | None = None, + ) -> None: + resolved_tab = tab_key or "basic" + matched_idx = -1 + if hasattr(self, "tabs"): + for i in range(self.tabs.count()): + if self.tabs.tabBar().tabData(i) == resolved_tab: + matched_idx = i + break + if matched_idx < 0: + resolved_tab = "basic" + for i in range(self.tabs.count()): + if self.tabs.tabBar().tabData(i) == "basic": + matched_idx = i + break + if matched_idx >= 0 and self.tabs.currentIndex() != matched_idx: + self.tabs.setCurrentIndex(matched_idx) + + if resolved_tab != "basic": + return + + scroll = getattr(self, "_basic_scroll", None) + if scroll is None or scroll.widget() is None: + return + target: QWidget | None = None + if section_index is not None: + target = self._section_headings.get(section_index) + if field_key and field_key in self._field_containers: + target = self._field_containers[field_key] + if target is None: + scroll.verticalScrollBar().setValue(0) + return + + def _do_scroll() -> None: + with suppress(RuntimeError): + if scroll.widget() is None or not target.isVisibleTo(scroll.widget()): + if scroll.widget() is not None and scroll.widget().layout() is not None: + scroll.widget().layout().activate() + if self.form_host.layout() is not None: + self.form_host.layout().activate() + y_pos = target.mapTo(scroll.widget(), target.rect().topLeft()).y() + scroll.verticalScrollBar().setValue(max(0, y_pos - 22)) + self._clear_field_highlight() + target.setStyleSheet( + "background-color: #E7F5F0; border-radius: 10px; padding: 3px 6px;" + ) + self._highlighted_target = target + self._highlight_timer.start(1600) + if self._editable and field_key in self.edit_fields: + ed = self.edit_fields[field_key] + if isinstance(ed, QWidget) and ed.isEnabled(): + ed.setFocus() + + _do_scroll() + QTimer.singleShot(30, _do_scroll) def _load_error(self, error: Exception, generation: int) -> None: if generation == self._generation: @@ -2552,7 +2689,6 @@ class DiagnosisDialog(QDialog): editor._sync_flow_height() if hasattr(self, "form_host"): self.form_host.updateGeometry() - self.form_host.adjustSize() def _show_authoritative_content(self, visible: bool) -> None: self.readonly_patient_card.setVisible(visible) @@ -2587,8 +2723,10 @@ class DiagnosisDialog(QDialog): or (key in _PATIENT_BASIC_FIELDS and self._basic_locked) or (key in {"phone", "id_card"} and not self._can_phone_plain) ) + was_locked = field.isReadOnly() if callable(getattr(field, "isReadOnly", None)) else None field.setReadOnly(locked) - repolish(field) + if was_locked != locked and not isinstance(field, DiagnosisChoiceButtons): + repolish(field) def _current_tab_key(self) -> str: index = self.tabs.currentIndex() diff --git a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py index 30f88d7f0..40aa747f5 100755 --- a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py +++ b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py @@ -563,11 +563,14 @@ class IssuedPrescriptionAiDialog(QDialog): self._history_agreement_visible = False self.setWindowTitle("诊断与药方 · AI 分析报告") self.resize(1440, 940) - self.setMinimumSize(940, 640) + self.setMinimumSize(540, 480) font = QFont(body_family()) font.setPixelSize(13) self.setFont(font) self.setStyleSheet(dialog_style() + rail_qss()) + from ..spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(self, icon_kind="ai", preferred_width=680) self._permissions_snapshot = permissions self._current_user = current_user self._pending_drafts: dict[str, tuple[str, int]] = {} diff --git a/app/src/doctor_workstation/ui/dialogs/prescription.py b/app/src/doctor_workstation/ui/dialogs/prescription.py index 7c61aefb9..95f3092c9 100755 --- a/app/src/doctor_workstation/ui/dialogs/prescription.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription.py @@ -3987,6 +3987,21 @@ class PrescriptionEditorDialog(QDialog): self._fit_drawer_geometry() def _fit_drawer_geometry(self) -> None: + if self.property("hostedInSpatialWing"): + self.drawer_surface.setMaximumWidth(16777215) + w = max(460, self.width()) + show_live_slip = w >= 860 + if hasattr(self, "live_preview_pane"): + self.live_preview_pane.setVisible(show_live_slip) + if self.diagnosis_host.isVisible(): + half = max(260, w // 2) + self.workspace_splitter.setSizes([half, w - half, 0]) + elif show_live_slip: + slip_w = min(320, int(w * 0.36)) + self.workspace_splitter.setSizes([0, w - slip_w, slip_w]) + else: + self.workspace_splitter.setSizes([0, w, 0]) + return target = main_window_target_rect(self) if target is not None: width = target.width() @@ -4021,6 +4036,11 @@ class PrescriptionEditorDialog(QDialog): super().showEvent(event) self._fit_drawer_geometry() + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + if self.property("hostedInSpatialWing"): + self._fit_drawer_geometry() + def _update_herb_summary(self) -> None: if not hasattr(self, "herbs"): return @@ -6149,8 +6169,11 @@ class PrescriptionDetailDialog(QDialog): self.user_document.setDocumentMargin(0) self._render_slip_previews() self.setWindowTitle("查看处方") - self.setMinimumSize(900, 700) + self.setMinimumSize(460, 480) self.resize(1240, 800) + from ..spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(self, icon_kind="prescriptions", preferred_width=660) # 与「处方电子签署」一致:左侧三联预览,右侧签署流程与操作。 root = QVBoxLayout(self) root.setContentsMargins(0, 0, 0, 0) @@ -6325,6 +6348,15 @@ class PrescriptionDetailDialog(QDialog): if callable(getattr(self.repository, "get_prescription_esign_status", None)): self.refresh_esign() + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + if self.property("hostedInSpatialWing") and hasattr(self, "workspace_splitter"): + want_orient = ( + Qt.Orientation.Vertical if self.width() < 780 else Qt.Orientation.Horizontal + ) + if self.workspace_splitter.orientation() != want_orient: + self.workspace_splitter.setOrientation(want_orient) + def _render_steps(self) -> None: legacy = self.esign.get("status") == "legacy" and self.esign.get("required") is False awaiting_upload = awaiting_prescription_upload(self.prescription, self.esign) diff --git a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py index d11f2a47b..2c9ca9aa2 100755 --- a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py @@ -744,9 +744,12 @@ class PrescriptionAiReportDialog(QDialog): self.setObjectName("PrescriptionAiDialog") self.setWindowTitle(self.kind.title) self.resize(920, 760) - self.setMinimumSize(720, 560) + self.setMinimumSize(460, 440) self.setStyleSheet(PRESCRIPTION_AI_QSS) self.setCursor(Qt.CursorShape.ArrowCursor) + from ..spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(self, icon_kind="ai", preferred_width=560) root = QVBoxLayout(self) root.setContentsMargins(22, 18, 22, 18) @@ -1482,8 +1485,11 @@ class DiagnosisAiAssistantDialog(QDialog): self.setObjectName("PrescriptionAiDialog") self.setWindowTitle("AI 问诊助手") self.resize(720, 520) - self.setMinimumSize(580, 420) + self.setMinimumSize(440, 380) self.setStyleSheet(PRESCRIPTION_AI_QSS) + from ..spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(self, icon_kind="ai", preferred_width=520) root = QVBoxLayout(self) root.setContentsMargins(22, 20, 22, 20) diff --git a/app/src/doctor_workstation/ui/dialogs/video_cockpit.py b/app/src/doctor_workstation/ui/dialogs/video_cockpit.py index 201cc0c96..2b32ad594 100644 --- a/app/src/doctor_workstation/ui/dialogs/video_cockpit.py +++ b/app/src/doctor_workstation/ui/dialogs/video_cockpit.py @@ -181,7 +181,7 @@ class VideoCockpitDemoDialog(QDialog): def _capture_demo_tongue(self) -> None: self._tongue_count += 1 - self._tongue_status.setText(f"✓ 已抓拍第 {self._tongue_count} 帧高清舌象并准备归档") + self._tongue_status.setText(f"已抓拍第 {self._tongue_count} 帧高清舌象并准备归档") def _tick(self) -> None: self._seconds += 1 diff --git a/app/src/doctor_workstation/ui/icons.py b/app/src/doctor_workstation/ui/icons.py index dd757fa25..20875aac7 100755 --- a/app/src/doctor_workstation/ui/icons.py +++ b/app/src/doctor_workstation/ui/icons.py @@ -361,6 +361,15 @@ def _right(p: QPainter, w: float) -> None: _polyline(p, (9.0, 5.5), (15.5, 12.0), (9.0, 18.5)) +@_glyph("play") +def _play(p: QPainter, w: float) -> None: + path = QPainterPath(QPointF(8.5, 5.75)) + path.lineTo(QPointF(18.25, 12.0)) + path.lineTo(QPointF(8.5, 18.25)) + path.closeSubpath() + _duotone_path(p, path, 44) + + @_glyph("notification", "bell") def _bell(p: QPainter, w: float) -> None: path = QPainterPath(QPointF(6.75, 17.5)) diff --git a/app/src/doctor_workstation/ui/pages/consultations.py b/app/src/doctor_workstation/ui/pages/consultations.py index 37b4c3f02..225a28eb6 100755 --- a/app/src/doctor_workstation/ui/pages/consultations.py +++ b/app/src/doctor_workstation/ui/pages/consultations.py @@ -3212,6 +3212,8 @@ class ConsultationsPage(QWidget): self.cancel_toolbar_button.setEnabled( has_record and _single_cancellable_appointment(record) is not None ) + if self.patient_context_store is not None and record is not None: + self.patient_context_store.update_from_row(record) @property def _diagnosis_dialog(self) -> DiagnosisDialog: diff --git a/app/src/doctor_workstation/ui/pages/reception.py b/app/src/doctor_workstation/ui/pages/reception.py index 3b1db4075..2098c22dc 100755 --- a/app/src/doctor_workstation/ui/pages/reception.py +++ b/app/src/doctor_workstation/ui/pages/reception.py @@ -92,9 +92,11 @@ from ..filter_disclosure import FilterDisclosure from ..reception_style import body_family, heading_family, number_family from ..reception_workspace import RECEPTION_WORKSPACE_QSS, ReceptionWorkbench from ..report_provenance import report_provenance_lines +from ..spatial_wings import find_spatial_shell from ..state import PatientContextStore from ..theme import mark_business_dialog from ..viewmodels.cockpit_vm import derive_cockpit_snapshot +from ..visuals.ai_report_wing import ClinicalAiReportWingPanel from ..visuals.reception_cockpit import ReceptionDigitalTwinCockpit from ..widgets import ( EmptyState, @@ -4275,6 +4277,15 @@ class ReceptionPage(QWidget): self.patient_context_store: PatientContextStore | None = None self._workspace_mode = "chart" self._latest_daily_blood: list[Any] = [] + self._latest_daily_window: dict[str, Any] = {} + self._latest_doctor_notes: list[Any] = [] + self._latest_prescriptions: list[Any] = [] + self._cockpit_queue_scope: str = "today_all" + self._cockpit_auto_fallback_done: bool = False + self._cockpit_consult_fallback_done: bool = False + self._cockpit_fallback_notice: str = "" + self._syncing_patient_store: bool = False + self._wing_ai_report_panel: ClinicalAiReportWingPanel | None = None self.view_mode_stack = QStackedWidget(self) self.view_mode_stack.setObjectName("ReceptionViewModeStack") @@ -4296,7 +4307,7 @@ class ReceptionPage(QWidget): ret_layout = QHBoxLayout(self._return_to_cockpit_bar) ret_layout.setContentsMargins(10, 4, 14, 4) ret_layout.setSpacing(10) - back_cockpit_btn = QPushButton("← 返回三焦全息驾驶舱", self._return_to_cockpit_bar) + back_cockpit_btn = QPushButton("← 返回临床接诊总览", self._return_to_cockpit_bar) back_cockpit_btn.setCursor(Qt.CursorShape.PointingHandCursor) back_cockpit_btn.setStyleSheet( "QPushButton { background-color: #0E6F5C; color: #FFFFFF; border: 0;" @@ -4330,9 +4341,11 @@ class ReceptionPage(QWidget): self.cockpit_view = ReceptionDigitalTwinCockpit(self.view_mode_stack) self.cockpit_view.appointment_selected.connect(self._select_record_from_cockpit) self.cockpit_view.filter_status_requested.connect(self._set_queue_filter) + self.cockpit_view.queue_scope_requested.connect(self.set_cockpit_queue_scope) self.cockpit_view.refresh_requested.connect(self._refresh_workspace) self.cockpit_view.start_video_requested.connect(self._request_video) self.cockpit_view.edit_diagnosis_requested.connect(self._edit_diagnosis) + self.cockpit_view.locus_selected.connect(self._open_diagnosis_for_locus) self.cockpit_view.notify_assistant_requested.connect(self._notify_assistant) self.cockpit_view.complete_visit_requested.connect(self._complete_appointment) self.cockpit_view.open_chart_tab_requested.connect(self._open_structured_chart_tab) @@ -4359,10 +4372,15 @@ class ReceptionPage(QWidget): panel.setFixedWidth(width) def set_patient_context_store(self, store: PatientContextStore) -> None: - """Attach the Spatial Shell context store and default to Digital Twin Cockpit.""" + """Attach the Spatial Shell context store and default to Clinical Cockpit.""" self.patient_context_store = store self._root_layout.setContentsMargins(0, 2, 0, 2) + self._cockpit_queue_scope = "today_all" + self._cockpit_auto_fallback_done = False + self._cockpit_consult_fallback_done = False + self._cockpit_fallback_notice = "" + self._queue_date = date.today().isoformat() self._queue_filter_status = None for st_key, btn in self._queue_filter_buttons.items(): btn.setChecked(st_key is None) @@ -4370,6 +4388,77 @@ class ReceptionPage(QWidget): self.set_workspace_mode("cockpit") self._sync_cockpit_and_context() + def set_cockpit_queue_scope(self, scope: str, *, keep_notice: bool = False) -> None: + """Switch outpatient queue scope in Spatial Cockpit mode.""" + + normalized = str(scope or "today_all").strip().lower() + if normalized not in {"today_pending", "today_all", "recent_all", "consultations"}: + normalized = "today_all" + self._cockpit_queue_scope = normalized + if not keep_notice: + self._cockpit_fallback_notice = "" + # Explicit doctor scope switch disables further automatic scope jumps + self._cockpit_auto_fallback_done = True + self._cockpit_consult_fallback_done = True + + if normalized == "today_pending": + self._queue_date = date.today().isoformat() + self._queue_filter_status = 1 + elif normalized == "today_all": + self._queue_date = date.today().isoformat() + self._queue_filter_status = None + else: + self._queue_date = "" + self._queue_filter_status = None + + for st_key, btn in self._queue_filter_buttons.items(): + btn.setChecked(st_key == self._queue_filter_status) + self._clear_selection() + self._reset_queue_state() + ReceptionPage.refresh(self) + + def load_patient_from_context(self, snapshot: Any) -> None: + """Load full clinical bundle when a patient is selected in another Spatial tab.""" + + if self._syncing_patient_store or snapshot is None or not getattr(snapshot, "has_patient", False): + return + appt_id = _as_int(getattr(snapshot, "appointment_id", 0), 0) or 0 + diag_id = _as_int(getattr(snapshot, "diagnosis_id", 0), 0) or 0 + pat_id = _as_int(getattr(snapshot, "patient_id", 0), 0) or 0 + if appt_id > 0: + if _same_id(appt_id, self._selected_appointment_id): + return + seed = dict(getattr(snapshot, "raw_record", None) or {}) + seed.update( + { + "id": appt_id, + "appointment_id": appt_id, + "diagnosis_id": diag_id or seed.get("diagnosis_id"), + "patient_id": pat_id or seed.get("patient_id"), + "patient_name": getattr(snapshot, "patient_name", "患者"), + } + ) + self._select_record(seed, silent=True) + return + if diag_id > 0: + synthetic_id = -abs(diag_id) + if _same_id(synthetic_id, self._selected_appointment_id): + return + seed = dict(getattr(snapshot, "raw_record", None) or {}) + seed.update( + { + "_queue_source": "consultation", + "id": synthetic_id, + "real_appointment_id": 0, + "diagnosis_id": diag_id, + "patient_id": pat_id or seed.get("patient_id"), + "patient_name": getattr(snapshot, "patient_name", "患者"), + "status": 1, + "status_desc": getattr(snapshot, "status_text", "在管诊单") or "在管诊单", + } + ) + self._select_record(seed, silent=True) + def set_workspace_mode(self, mode: str) -> None: normalized = "cockpit" if str(mode).strip().lower() == "cockpit" else "chart" self._workspace_mode = normalized @@ -4382,7 +4471,70 @@ class ReceptionPage(QWidget): if self.patient_context_store is not None: self.patient_context_store.set_cockpit_mode(normalized) + def _open_diagnosis_for_locus(self, locus_id: str) -> None: + """Open DiagnosisDialog directly at the corresponding tab & clinical field for `locus_id`.""" + + locus_map: dict[str, tuple[str, str, int | None]] = { + # Tab 1: 全身症候 + "head_eye_sleep": ("basic", "sleep_condition", 3), + "oral_thirst": ("basic", "appetite", 3), + "liver_pancreas_spleen": ("basic", "weight_change", 3), + "kidney_limbs": ("basic", "urine_condition", 3), + # Tab 2: 病史用药 + "local_diagnosis": ("basic", "local_hospital_diagnosis", 2), + "current_meds": ("basic", "current_medications", 1), + "past_history": ("basic", "past_history", 4), + "allergy_family": ("basic", "allergy_history", 5), + # Tab 3: 四诊处方 + "tongue_pulse": ("notes", "", None), + "notes_media": ("notes", "", None), + "rx_summary": ("prescription", "", None), + "rx_principle": ("prescription", "", None), + # Summary & Glycemic Cards + "summary_capsule": ("basic", "", 0), + "daily_glucose": ("daily", "", None), + } + if locus_id.startswith("vital:"): + v_field = locus_id.split(":", 1)[1].strip() or "systolic_pressure" + tab_key, field_key, sec_idx = ("basic", v_field, 1) + else: + tab_key, field_key, sec_idx = locus_map.get(locus_id, ("basic", "", None)) + + context = self._selection_context() + if context is None or context[2] is None or context[2] <= 0: + show_toast(self, "请先选择有效诊单患者。", "warning") + return + diag_id = int(context[2]) + dlg = self._ensure_diagnosis_dialog() + shell = find_spatial_shell(self) + already_open_same = ( + shell is not None + and shell.wing_manager.is_open + and shell.wing_manager.active_widget is dlg + and getattr(dlg, "_diagnosis_id", 0) == diag_id + ) + if not already_open_same: + if self._can_edit: + dlg.open_for( + diag_id, + editable=True, + seed=self._selected_detail or self._selected_record, + modeless=shell is not None, + ) + else: + dlg.open_view_only( + diag_id, + seed=self._selected_detail or self._selected_record, + modeless=shell is not None, + ) + dlg.focus_clinical_target(tab_key, field_key=field_key, section_index=sec_idx) + def _open_structured_chart_tab(self, tab_index: int = 0) -> None: + if find_spatial_shell(self) is not None: + tab_key = "daily" if tab_index == 3 else ("notes" if tab_index == 2 else "basic") + locus_for_tab = "daily_glucose" if tab_key == "daily" else ("notes_media" if tab_key == "notes" else "summary_capsule") + self._open_diagnosis_for_locus(locus_for_tab) + return self.set_workspace_mode("chart") if hasattr(self, "detail_tabs") and 0 <= tab_index < self.detail_tabs.count(): self.detail_tabs.setCurrentIndex(tab_index) @@ -4412,58 +4564,110 @@ class ReceptionPage(QWidget): self._sync_cockpit_and_context() def _sync_cockpit_and_context(self) -> None: - """Synchronize the 3-column Digital Twin Cockpit and global PatientContextStore.""" + """Synchronize the 3-column Clinical Cockpit and global PatientContextStore.""" if not hasattr(self, "cockpit_view"): return detail = self._selected_detail or {} - appointment = get_value(detail, "appointment", None) or self._selected_record or {} - patient = get_value(detail, "patient", None) or {} - diagnosis = get_value(detail, "diagnosis", None) or {} + has_loaded_patient = self._selected_appointment_id is not None and bool( + self._selected_detail or self._selected_record + ) + appointment = ( + (get_value(detail, "appointment", None) or self._selected_record or {}) + if has_loaded_patient + else {} + ) + patient = (get_value(detail, "patient", None) or {}) if has_loaded_patient else {} + diagnosis = (get_value(detail, "diagnosis", None) or {}) if has_loaded_patient else {} self.cockpit_view.set_queue_records( self._queue_records, self._selected_appointment_id, + active_scope=self._cockpit_queue_scope, active_filter_status=self._queue_filter_status, queue_date=self._queue_date, + scope_notice=self._cockpit_fallback_notice, ) doc_name = display_text( first_value( appointment, "doctor_name", - default=first_value(self.current_user, "name", "real_name", default="主诊中医师"), + default=first_value( + diagnosis, + "doctor_name", + default=first_value(self.current_user, "name", "real_name", default="主诊中医师"), + ), ) ) - asst_name = display_text(first_value(appointment, "assistant_name", default=""), "") + asst_name = display_text( + first_value( + appointment, + "assistant_name", + default=first_value(diagnosis, "assistant_name", default=""), + ), + "", + ) + diag_id = _as_int( + first_value( + diagnosis, + "id", + "diagnosis_id", + default=first_value(appointment, "diagnosis_id", default=None), + ) + ) + real_appt = bool(self._selected_appointment_id is not None and self._selected_appointment_id > 0) self.cockpit_view.set_care_team_context( doctor_name=doc_name, assistant_name=asst_name, - can_edit=bool(self._can_edit and self._selected_appointment_id is not None), - can_notify=bool(self._selected_appointment_id is not None), + can_edit=bool(self._can_edit and has_loaded_patient and diag_id is not None and diag_id > 0), + can_notify=real_appt, can_complete=bool( - hasattr(self, "complete_button") and self.complete_button.isEnabled() + real_appt and hasattr(self, "complete_button") and self.complete_button.isEnabled() ), ) if self.patient_context_store is not None: - if self._selected_appointment_id is not None and appointment: - self.patient_context_store.update_from_reception(appointment, patient, diagnosis) - elif not self._queue_records: - self.patient_context_store.clear() + self._syncing_patient_store = True + try: + if has_loaded_patient and appointment: + self.patient_context_store.update_from_reception(appointment, patient, diagnosis) + elif not self._queue_records and not has_loaded_patient: + self.patient_context_store.clear() + finally: + self._syncing_patient_store = False - ai_payload = self._ai_analysis_payloads.get(self._ai_analysis_active_model) + active_model = self._ai_analysis_active_model + ai_state = self._ai_analysis_model_states.get(active_model, "empty") + ai_msg = self._ai_analysis_model_messages.get(active_model, "") + ai_payload = self._ai_analysis_payloads.get(active_model) vm = derive_cockpit_snapshot( - appointment, - patient, - diagnosis, - daily_records=self._latest_daily_blood, - ai_payload=ai_payload, - active_ai_model=self._ai_analysis_active_model, + appointment if has_loaded_patient else None, + patient if has_loaded_patient else None, + diagnosis if has_loaded_patient else None, + daily_window=self._latest_daily_window if has_loaded_patient else None, + daily_records=self._latest_daily_blood if has_loaded_patient else None, + tracking_notes=self._daily_tracking_fallback if has_loaded_patient else None, + doctor_notes=self._latest_doctor_notes if has_loaded_patient else None, + prescriptions=self._latest_prescriptions if has_loaded_patient else None, + ai_payload=ai_payload if has_loaded_patient else None, + ai_state=ai_state if has_loaded_patient else "empty", + ai_message=ai_msg if has_loaded_patient else "", + active_ai_model=active_model, ) self.cockpit_view.set_snapshot(vm) self.cockpit_snapshot_updated.emit(vm) + self._sync_wing_ai_report_panel() def _ensure_diagnosis_dialog(self) -> DiagnosisDialog: + shell = find_spatial_shell(self) + ensure_global = getattr(shell, "_ensure_global_diagnosis_dialog", None) + if callable(ensure_global): + shared = ensure_global() + if not getattr(shared, "_reception_saved_wired", False): + shared.saved.connect(self._diagnosis_saved) + shared._reception_saved_wired = True # type: ignore[attr-defined] + self.diagnosis_dialog = shared + return shared dialog = getattr(self, "diagnosis_dialog", None) if dialog is None: dialog = DiagnosisDialog(self.repository, self) @@ -5977,6 +6181,7 @@ class ReceptionPage(QWidget): self.ai_analysis_card.setProperty("analysisState", state) self.ai_analysis_card.style().unpolish(self.ai_analysis_card) self.ai_analysis_card.style().polish(self.ai_analysis_card) + self._sync_wing_ai_report_panel() self._sync_cockpit_and_context() def _render_ai_analysis_payload( @@ -7229,9 +7434,88 @@ class ReceptionPage(QWidget): force=True, ) - def _open_ai_analysis_dialog(self) -> None: - """Show the full cached analysis without issuing another model request.""" + def _current_patient_display_name(self) -> str: + detail = self._selected_detail or {} + appt = get_value(detail, "appointment", None) or self._selected_record or {} + diag = get_value(detail, "diagnosis", None) or {} + pat = get_value(detail, "patient", None) or {} + name = display_text( + first_value( + appt, + "patient_name", + "name", + default=first_value( + diag, + "patient_name", + "name", + default=first_value(pat, "patient_name", "name", default=""), + ), + ), + "", + ) + return "" if name in {"", "—"} else name + def _sync_wing_ai_report_panel(self) -> None: + panel = self._wing_ai_report_panel + if panel is None: + return + shell = find_spatial_shell(self) + is_hosted = shell is not None and shell.wing_manager.active_widget is panel + if not panel.isVisible() and not is_hosted: + return + can_regen = bool( + (self._can_ai_regenerate and self._ai_analysis_patient_flow and self._ai_analysis_patient_id is not None) + or (self._can_ai_analysis and not self._ai_analysis_patient_flow and self._ai_analysis_diagnosis_id is not None) + ) + panel.set_report_context( + histories=self._ai_analysis_histories, + model_states=self._ai_analysis_model_states, + model_messages=self._ai_analysis_model_messages, + active_model=self._ai_analysis_active_model, + patient_name=self._current_patient_display_name(), + can_regenerate=can_regen and not self._ai_analysis_regenerating, + ) + + def _trigger_wing_ai_regenerate(self) -> None: + if self._ai_analysis_patient_flow and self._can_ai_regenerate: + self._regenerate_patient_ai_reports() + else: + self._retry_ai_analysis() + + def _ensure_wing_ai_report_panel(self) -> ClinicalAiReportWingPanel: + if self._wing_ai_report_panel is None: + panel = ClinicalAiReportWingPanel(self) + panel.hide() + panel.model_selected.connect(self.select_cockpit_ai_model) + panel.regenerate_requested.connect(self._trigger_wing_ai_regenerate) + panel.open_ai_consult_requested.connect(self._open_ai_consult) + self._wing_ai_report_panel = panel + return self._wing_ai_report_panel + + def open_ai_report_wing(self) -> bool: + """Open the high-density Clinical AI Report Companion Wing beside the cockpit.""" + + shell = find_spatial_shell(self) + if shell is None: + return False + panel = self._ensure_wing_ai_report_panel() + + p_name = self._current_patient_display_name() + shell.wing_manager.present_widget( + panel, + title="AI 循证诊断报告", + subtitle=p_name, + icon_kind="ai", + preferred_width=540, + ) + self._sync_wing_ai_report_panel() + return True + + def _open_ai_analysis_dialog(self) -> None: + """Show the full cached analysis in Spatial Wing (or legacy dialog in standalone tests).""" + + if self.open_ai_report_wing(): + return if not self._ai_analysis_payloads: return preferred_model = self._ai_analysis_active_model @@ -7294,18 +7578,24 @@ class ReceptionPage(QWidget): def _sync_queue_filter_summary(self) -> None: status = STATUS_TEXT.get(self._queue_filter_status, "全部状态") today = date.today().isoformat() - self.queue_title.setText( - "历史接诊" if self._queue_date < today else - "今日接诊" if self._queue_date == today else "预约接诊" - ) - summary = f"{self._queue_date} · {status}" + if not self._queue_date: + scope_title = "在管诊单" if self._cockpit_queue_scope == "consultations" else "近期挂号" + self.queue_title.setText(scope_title) + date_prefix = scope_title + else: + self.queue_title.setText( + "历史接诊" if self._queue_date < today else + "今日接诊" if self._queue_date == today else "预约接诊" + ) + date_prefix = self._queue_date + summary = f"{date_prefix} · {status}" keyword = self.search_edit.text().strip() self.queue_filter_summary.setText(summary + (" · 姓名已筛选" if keyword else "")) self.queue_filter_summary.setToolTip(summary + (f" · 姓名:{keyword}" if keyword else "")) if hasattr(self, "queue_empty_description"): conditions = f"{status}、当前姓名" if keyword else status self.queue_empty_description.setText( - f"{self._queue_date}\n当前账号在“{conditions}”筛选下没有挂号记录。" + f"{date_prefix}\n当前账号在“{conditions}”筛选下没有挂号记录。" ) def _search_changed(self, value: str) -> None: @@ -7439,13 +7729,19 @@ class ReceptionPage(QWidget): if silent and self._queue_loading and not workspace_refresh: return - selected_date = self._queue_date or date.today().isoformat() + if self.patient_context_store is not None and self._cockpit_queue_scope in { + "recent_all", + "consultations", + }: + selected_date = "" + else: + selected_date = self._queue_date or date.today().isoformat() page_size = self._queue_page_size if silent or workspace_refresh: loaded = max(len(self._queue_records), self._queue_page * self._queue_page_size) if loaded > page_size: page_size = loaded - query = { + query: dict[str, Any] = { "status": self._queue_filter_status, "start_date": selected_date, "end_date": selected_date, @@ -7454,6 +7750,8 @@ class ReceptionPage(QWidget): "patient_name": self.search_edit.text().strip(), "include_status_counts": 1, } + if self.patient_context_store is not None: + query["_cockpit_scope"] = self._cockpit_queue_scope self._sync_queue_filter_summary() query_key = self._query_key(query) if query_key != self._queue_query_key: @@ -7484,8 +7782,58 @@ class ReceptionPage(QWidget): query["start_date"], query["end_date"], query["patient_name"], + query.get("_cockpit_scope", ""), ) + @staticmethod + def _consultation_to_queue_record(item: Any) -> dict[str, Any]: + """Adapt a Consultation list item into a selectable queue record.""" + + raw = getattr(item, "raw", None) + base: dict[str, Any] = dict(raw) if isinstance(raw, Mapping) else {} + if isinstance(item, Mapping): + base.update(item) + diag_id = _as_int( + first_value(item, "id", "diagnosis_id", default=base.get("id")), + 0, + ) or 0 + appt_id = _as_int( + first_value( + base, + "latest_appointment_id", + "appointment_id", + default=0, + ), + 0, + ) or 0 + record_id = appt_id if appt_id > 0 else (-abs(diag_id) if diag_id > 0 else 0) + pat_id = _as_int( + first_value(item, "patient_id", "source_patient_id", default=base.get("patient_id")), + 0, + ) or 0 + pat_name = display_text( + first_value(item, "patient_name", "name", default=base.get("patient_name") or "患者") + ) + base.update( + { + "_queue_source": "consultation", + "id": record_id, + "real_appointment_id": appt_id, + "diagnosis_id": diag_id, + "patient_id": pat_id, + "source_patient_id": pat_id, + "patient_name": pat_name, + "status": _as_int( + first_value(base, "appointment_status", "status", default=1), 1 + ) + or 1, + "status_desc": display_text( + first_value(base, "appointment_status_desc", "status_desc", default="在管诊单") + ), + } + ) + return base + def _reset_queue_state(self) -> None: self._queue_records = [] self._queue_render_signature = () @@ -7633,11 +7981,32 @@ class ReceptionPage(QWidget): # 每刷新一次表格就上下跳一次——而轮询定时器每 5 秒就刷新一次。 # 已有数据时保持旧行可见、静默替换;失败仍然照常报错。 frozen_query = dict(query) + cockpit_scope = str(frozen_query.pop("_cockpit_scope", "") or "") page_no = int(frozen_query["page_no"]) - query_key = self._query_key(frozen_query) + query_key = self._query_key(query) + def request() -> Any: if generation != self._queue_generation: return _ASYNC_REQUEST_CANCELLED + if cockpit_scope == "consultations" and callable( + getattr(self.repository, "list_consultations", None) + ): + consult_res = invoke( + self.repository, + "list_consultations", + page_no=page_no, + page_size=int(frozen_query["page_size"]), + keyword=frozen_query.get("patient_name", ""), + ) + mapped_items = [ + self._consultation_to_queue_record(row) + for row in page_items(consult_res) + ] + total_val = _as_int( + first_value(consult_res, "total", "count", default=len(mapped_items)), + len(mapped_items), + ) + return {"lists": mapped_items, "count": total_val, "total": total_val} return invoke( self.repository, "list_appointments", @@ -7674,6 +8043,28 @@ class ReceptionPage(QWidget): if generation != self._queue_generation or query_key not in (None, self._queue_query_key): return page_records = page_items(result) + # Smart initial auto-fallback in Spatial Cockpit mode when today's queue is empty + if ( + not page_records + and not append + and self.patient_context_store is not None + and not self.search_edit.text().strip() + ): + if self._cockpit_queue_scope == "today_all" and not self._cockpit_auto_fallback_done: + self._cockpit_auto_fallback_done = True + self._cockpit_fallback_notice = "今日无排班 · 近期挂号" + self.set_cockpit_queue_scope("recent_all", keep_notice=True) + return + if ( + self._cockpit_queue_scope == "recent_all" + and self._cockpit_auto_fallback_done + and not self._cockpit_consult_fallback_done + and callable(getattr(self.repository, "list_consultations", None)) + ): + self._cockpit_consult_fallback_done = True + self._cockpit_fallback_notice = "暂无挂号 · 在管诊单" + self.set_cockpit_queue_scope("consultations", keep_notice=True) + return if append: records = list(self._queue_records) existing_ids = { @@ -7892,19 +8283,85 @@ class ReceptionPage(QWidget): ) -> dict[str, Any]: if cancel_event is not None and cancel_event.is_set(): return {"cancelled": True} - detail = invoke( - self.repository, - "get_reception", - appointment_id=appointment_id, - id=appointment_id, + is_consultation_only = appointment_id < 0 or ( + str(first_value(record, "_queue_source", default="") or "") == "consultation" + and (_as_int(first_value(record, "real_appointment_id", default=0), 0) or 0) <= 0 ) + if is_consultation_only: + diag_target = _as_int( + first_value(record, "diagnosis_id", "id", default=abs(appointment_id)), + 0, + ) or abs(appointment_id) + raw_diag: Any = {} + if callable(getattr(self.repository, "get_diagnosis_detail", None)): + try: + raw_diag = invoke( + self.repository, + "get_diagnosis_detail", + diagnosis_id=diag_target, + id=diag_target, + readonly=not self._can_edit, + ) + except Exception: + raw_diag = invoke( + self.repository, + "get_diagnosis_detail", + diagnosis_id=diag_target, + id=diag_target, + readonly=True, + ) + elif callable(getattr(self.repository, "diagnosis_readonly_detail", None)): + raw_diag = invoke( + self.repository, + "diagnosis_readonly_detail", + diagnosis_id=diag_target, + id=diag_target, + ) + if ( + get_value(raw_diag, "data", None) is not None + and get_value(raw_diag, "diagnosis", None) is None + and get_value(raw_diag, "id", None) is None + ): + raw_diag = get_value(raw_diag, "data", raw_diag) + diag_obj = get_value(raw_diag, "diagnosis", None) or raw_diag or {} + pat_obj = get_value(raw_diag, "patient", None) or diag_obj + appt_seed = dict(record) if isinstance(record, Mapping) else {} + appt_seed.setdefault("id", appointment_id) + appt_seed.setdefault("diagnosis_id", diag_target) + appt_seed.setdefault( + "patient_name", + first_value(diag_obj, "patient_name", "name", default="患者"), + ) + detail: Any = { + "appointment": appt_seed, + "diagnosis": diag_obj, + "patient": pat_obj, + "doctor_notes": get_value(raw_diag, "doctor_notes", None) or [], + "tracking_notes": get_value(raw_diag, "tracking_notes", None) or [], + } + else: + real_appt_id = ( + _as_int(first_value(record, "real_appointment_id", default=appointment_id), appointment_id) + or appointment_id + ) + detail = invoke( + self.repository, + "get_reception", + appointment_id=real_appt_id, + id=real_appt_id, + ) + if ( + get_value(detail, "data", None) is not None + and get_value(detail, "appointment", None) is None + ): + detail = get_value(detail, "data", detail) + # Keep record ID matching expected_id when Consultation had real_appointment_id + appt_inner = get_value(detail, "appointment", None) + if isinstance(appt_inner, dict) and appointment_id != real_appt_id: + appt_inner["id"] = appointment_id + appt_inner["real_appointment_id"] = real_appt_id if cancel_event is not None and cancel_event.is_set(): return {"detail": detail, "cancelled": True} - if ( - get_value(detail, "data", None) is not None - and get_value(detail, "appointment", None) is None - ): - detail = get_value(detail, "data", detail) diagnosis_id = _as_int( first_value( get_value(detail, "diagnosis", None) or {}, @@ -7916,6 +8373,7 @@ class ReceptionPage(QWidget): notes = get_value(detail, "doctor_notes", None) or get_value(detail, "notes", None) or [] notes = list(notes) if isinstance(notes, (list, tuple)) else [notes] daily: Any = {} + prescriptions: list[Any] = [] embedded_tracking = get_value(detail, "tracking_notes", None) or [] tracking_notes = list(embedded_tracking) if isinstance( embedded_tracking, (list, tuple) @@ -7942,12 +8400,13 @@ class ReceptionPage(QWidget): and callable(getattr(self.repository, "get_tracking_window", None)) ): end_date = date.today() + window_days = 20 if self.patient_context_store is not None else 6 try: daily = invoke( self.repository, "get_tracking_window", diagnosis_id=diagnosis_id, - start_date=(end_date - timedelta(days=6)).isoformat(), + start_date=(end_date - timedelta(days=window_days)).isoformat(), end_date=end_date.isoformat(), ) except Exception as error: @@ -7967,11 +8426,27 @@ class ReceptionPage(QWidget): ) except Exception as error: warnings.append(f"跟踪备注:{friendly_error(error)}") + if ( + (cancel_event is None or not cancel_event.is_set()) + and diagnosis_id is not None + and callable(getattr(self.repository, "list_prescriptions_by_diagnosis", None)) + ): + try: + prescriptions = page_items( + invoke( + self.repository, + "list_prescriptions_by_diagnosis", + diagnosis_id=diagnosis_id, + ) + ) + except Exception as error: + warnings.append(f"已开处方:{friendly_error(error)}") return { "detail": detail, "notes": notes, "daily": daily, "tracking_notes": tracking_notes, + "prescriptions": prescriptions, "warnings": warnings, } @@ -8099,7 +8574,11 @@ class ReceptionPage(QWidget): return tracking_notes = list(get_value(bundle, "tracking_notes", None) or []) self._daily_tracking_fallback = tracking_notes - self._render_daily(get_value(bundle, "daily", None) or {}, tracking_notes) + daily_payload = get_value(bundle, "daily", None) or {} + self._latest_daily_window = dict(daily_payload) if isinstance(daily_payload, Mapping) else {} + self._latest_daily_blood = list(get_value(daily_payload, "blood_records", None) or []) + self._render_daily(daily_payload, tracking_notes) + self._sync_cockpit_and_context() warnings = list(get_value(bundle, "warnings", None) or []) if warnings: self.daily_panel.state.show_message( @@ -8185,7 +8664,9 @@ class ReceptionPage(QWidget): notes = get_value(bundle, "notes", None) if notes is None: notes = get_value(detail, "doctor_notes", None) or get_value(detail, "notes", None) - self._render_notes(list(notes or [])) + self._latest_doctor_notes = list(notes or []) + self._latest_prescriptions = list(get_value(bundle, "prescriptions", None) or []) + self._render_notes(self._latest_doctor_notes) diagnosis_id = _as_int( first_value( diagnosis, @@ -8199,6 +8680,9 @@ class ReceptionPage(QWidget): self._daily_diagnosis_id = diagnosis_id tracking_notes = list(get_value(bundle, "tracking_notes", None) or []) self._daily_tracking_fallback = tracking_notes + daily_payload = get_value(bundle, "daily", None) or {} + self._latest_daily_window = dict(daily_payload) if isinstance(daily_payload, Mapping) else {} + self._latest_daily_blood = list(get_value(daily_payload, "blood_records", None) or []) self.daily_panel.set_patient_age( first_value( diagnosis, @@ -8207,7 +8691,7 @@ class ReceptionPage(QWidget): ) ) self._render_daily( - get_value(bundle, "daily", None) or {}, + daily_payload, tracking_notes, ) warnings = list(get_value(bundle, "warnings", None) or []) @@ -9392,6 +9876,10 @@ class ReceptionPage(QWidget): self._daily_loading = False self._daily_diagnosis_id = None self._daily_tracking_fallback = [] + self._latest_daily_window = {} + self._latest_daily_blood = [] + self._latest_doctor_notes = [] + self._latest_prescriptions = [] self.daily_panel.clear_with_message( "正在读取患者日常记录…" if seed else "选择患者后加载最近 7 天日常记录。" ) @@ -9455,6 +9943,10 @@ class ReceptionPage(QWidget): self._daily_loading = False self._daily_diagnosis_id = None self._daily_tracking_fallback = [] + self._latest_daily_window = {} + self._latest_daily_blood = [] + self._latest_doctor_notes = [] + self._latest_prescriptions = [] self.daily_panel.set_error("患者详情加载失败,暂时无法读取日常记录。") self.followup_text.setText("患者详情加载失败,暂时无法读取跟踪备注。") self.health_summary_label.setText("患者详情加载失败,暂时无法读取健康数据。") @@ -9501,7 +9993,8 @@ class ReceptionPage(QWidget): ) ) status = _as_int(first_value(appointment, "status", default=None)) - self.notify_button.setEnabled(appointment_id is not None) + real_appt = appointment_id is not None and appointment_id > 0 + self.notify_button.setEnabled(real_appt) self.video_button.setEnabled( appointment_id is not None and diagnosis_id is not None and patient_id is not None ) @@ -9534,7 +10027,7 @@ class ReceptionPage(QWidget): self.complete_button.setEnabled( self._can_complete and not self._completion_pending - and appointment_id is not None + and real_appt and status in RECEPTION_STATUSES ) note_enabled = self._can_note and diagnosis_id is not None and not self._note_busy diff --git a/app/src/doctor_workstation/ui/shell.py b/app/src/doctor_workstation/ui/shell.py index 198f82c84..1f0a9a700 100755 --- a/app/src/doctor_workstation/ui/shell.py +++ b/app/src/doctor_workstation/ui/shell.py @@ -2630,10 +2630,13 @@ class ShellWindow(QMainWindow): ) -> DiagnosisDialog | None: """Open one authoritative diagnosis in the strongest permitted mode.""" - try: - normalized_id = int(diagnosis_id) - except (TypeError, ValueError): + if isinstance(diagnosis_id, bool): normalized_id = 0 + else: + try: + normalized_id = int(diagnosis_id) + except (TypeError, ValueError): + normalized_id = 0 if normalized_id <= 0: show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600) return None diff --git a/app/src/doctor_workstation/ui/shell_spatial.py b/app/src/doctor_workstation/ui/shell_spatial.py index 2e5876da6..6a0323ad5 100644 --- a/app/src/doctor_workstation/ui/shell_spatial.py +++ b/app/src/doctor_workstation/ui/shell_spatial.py @@ -27,6 +27,8 @@ from PySide6.QtWidgets import ( QMainWindow, QMenu, QPushButton, + QSizePolicy, + QSplitter, QStackedWidget, QVBoxLayout, QWidget, @@ -52,6 +54,7 @@ from .shell import ( _bounded_initial_window_size, _resolve_navigation, ) +from .spatial_wings import SpatialWingManager from .state import PatientContextStore, PatientSnapshot from .viewmodels import derive_cockpit_snapshot from .visuals.aurora_sheet import CollapsibleObsidianSheet @@ -94,9 +97,10 @@ QFrame#SpatialPillNavIsland { border-radius: 22px; } QPushButton#SpatialNavPill { + min-width: 0px; min-height: 36px; max-height: 36px; - padding: 0 16px; + padding: 0 11px; border: 0; border-radius: 18px; background-color: transparent; @@ -114,9 +118,10 @@ QPushButton#SpatialNavPill:checked { font-weight: 600; } QPushButton#SpatialAiNavPill { + min-width: 0px; min-height: 36px; max-height: 36px; - padding: 0 15px; + padding: 0 12px; border: 1px solid #DFEAE6; border-radius: 18px; background-color: #F7FAF9; @@ -212,7 +217,7 @@ QPushButton#SpatialDoctorCapsule:hover { QFrame#SpatialPatientCapsule { background-color: #FFFFFF; border: 1px solid #E1ECE8; - border-radius: 24px; + border-radius: 27px; } QPushButton#SpatialSecondaryPill { min-height: 42px; @@ -437,25 +442,85 @@ class SpatialShellWindow(QMainWindow): self.topbar = self._build_top_capsule_bar() root.addWidget(self.topbar) - self.sub_hero = self._build_context_sub_hero() - root.addWidget(self.sub_hero) + # Dual-Wing Workspace Splitter: [Left Wing Dock | Main Clinical Stage | Right Wing Dock] + self.wing_splitter = QSplitter(Qt.Orientation.Horizontal, canvas) + self.wing_splitter.setObjectName("SpatialWingSplitter") + self.wing_splitter.setChildrenCollapsible(False) + self.wing_splitter.setHandleWidth(6) + self.wing_splitter.setStyleSheet( + "QSplitter#SpatialWingSplitter { background: transparent; }" + "QSplitter#SpatialWingSplitter::handle { background: transparent; }" + "QSplitter#SpatialWingSplitter::handle:hover { background: rgba(14, 111, 92, 45); border-radius: 3px; }" + ) - self.stack = QStackedWidget(canvas) + self.left_wing_dock = QWidget(self.wing_splitter) + self.left_wing_dock.setObjectName("SpatialLeftWingDock") + + self.main_stage_host = QWidget(self.wing_splitter) + self.main_stage_host.setObjectName("SpatialMainStageHost") + self.main_stage_host.setMinimumWidth(580) + stage_layout = QVBoxLayout(self.main_stage_host) + stage_layout.setContentsMargins(0, 0, 0, 0) + stage_layout.setSpacing(10) + + self.sub_hero = self._build_context_sub_hero() + stage_layout.addWidget(self.sub_hero) + + self.stack = QStackedWidget(self.main_stage_host) self.stack.setObjectName("SpatialPageStack") self.stack.setStyleSheet("QStackedWidget#SpatialPageStack { background: transparent; border: 0; }") - root.addWidget(self.stack, 1) + stage_layout.addWidget(self.stack, 1) # Serene.ai Pull-Up Deep Obsidian Aurora-Glass Bottom Sheet - self.ai_bottom_sheet = CollapsibleObsidianSheet(canvas) + self.ai_bottom_sheet = CollapsibleObsidianSheet(self.main_stage_host) self.ai_bottom_sheet.expanded_changed.connect(self._on_sheet_expanded_changed) self.ai_bottom_sheet.open_ai_report_requested.connect(self._open_active_patient_ai_report) self.ai_bottom_sheet.open_ai_consult_requested.connect(self._open_active_patient_ai_consult) self.ai_bottom_sheet.model_selected.connect(self._on_sheet_model_selected) self.ai_bottom_sheet.set_view_model(derive_cockpit_snapshot().aurora) - root.addWidget(self.ai_bottom_sheet) + stage_layout.addWidget(self.ai_bottom_sheet) + + self.right_wing_dock = QWidget(self.wing_splitter) + self.right_wing_dock.setObjectName("SpatialRightWingDock") + + self.wing_splitter.addWidget(self.left_wing_dock) + self.wing_splitter.addWidget(self.main_stage_host) + self.wing_splitter.addWidget(self.right_wing_dock) + self.wing_splitter.setStretchFactor(0, 0) + self.wing_splitter.setStretchFactor(1, 1) + self.wing_splitter.setStretchFactor(2, 0) + root.addWidget(self.wing_splitter, 1) + + self.wing_manager = SpatialWingManager( + self, + left_dock=self.left_wing_dock, + right_dock=self.right_wing_dock, + splitter=self.wing_splitter, + ) + self.wing_manager.wing_visibility_changed.connect(self._on_wing_visibility_changed) self._register_pages() self._bind_shortcuts() + QTimer.singleShot(280, self._prewarm_wing_surfaces) + + def _on_wing_visibility_changed(self, visible: bool) -> None: + # Auto-collapse the bottom obsidian sheet when a docked wing opens so the cockpit stays airy + if visible and self.wing_manager.mode == "docked" and self.ai_bottom_sheet.is_expanded: + self.set_ai_bottom_sheet_expanded(False) + + def _prewarm_wing_surfaces(self) -> None: + """Warm up heavy wing panels on idle after startup so the first click opens in < 15ms.""" + + if not self.isVisible(): + return + rec_page = self.pages.get("reception") + if rec_page is not None: + ensure_wing = getattr(rec_page, "_ensure_wing_ai_report_panel", None) + if callable(ensure_wing): + panel = ensure_wing() + self.wing_manager.prewarm_widget(panel, preferred_width=540) + dlg = self._ensure_global_diagnosis_dialog() + self.wing_manager.prewarm_widget(dlg, preferred_width=660) def _build_top_capsule_bar(self) -> QWidget: bar = _DraggableHeaderBar(self) @@ -463,13 +528,13 @@ class SpatialShellWindow(QMainWindow): bar.setFixedHeight(52) layout = QHBoxLayout(bar) layout.setContentsMargins(2, 0, 2, 0) - layout.setSpacing(12) + layout.setSpacing(8) # Left Brand Mark (Alveo × Serene minimal geometric brand) brand_wrap = QWidget(bar) brand_row = QHBoxLayout(brand_wrap) - brand_row.setContentsMargins(0, 0, 4, 0) - brand_row.setSpacing(10) + brand_row.setContentsMargins(0, 0, 2, 0) + brand_row.setSpacing(8) self.brand_mark = _AlveoJadeEmblem(brand_wrap) brand_row.addWidget(self.brand_mark) @@ -481,26 +546,29 @@ class SpatialShellWindow(QMainWindow): brand_text.setStyleSheet("color: #0F1F1D; background: transparent;") brand_row.addWidget(brand_text) - brand_tag = QLabel("clinical.os", brand_wrap) - brand_tag.setStyleSheet("color: #7A908C; font-size: 13px; background: transparent;") + brand_tag = QLabel("临床智医", brand_wrap) + brand_tag.setStyleSheet("color: #7A908C; font-size: 12px; background: transparent;") + self.brand_tag = brand_tag brand_row.addWidget(brand_tag) layout.addWidget(brand_wrap) layout.addStretch(1) - # Center Floating Pill Navigation Island (Zero-sidebar centerpiece!) + # Center Floating Pill Navigation Island (Zero-sidebar centerpiece, never compressed!) self.nav_island = QFrame(bar) self.nav_island.setObjectName("SpatialPillNavIsland") self.nav_island.setFixedHeight(44) + self.nav_island.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) self.nav_layout = QHBoxLayout(self.nav_island) - self.nav_layout.setContentsMargins(4, 3, 4, 3) + self.nav_layout.setContentsMargins(5, 3, 5, 3) self.nav_layout.setSpacing(3) layout.addWidget(self.nav_island) - # Separate AI Coach / Syndrome Lab Pill right beside or inside island + # Separate AI Syndrome Assistant Pill inside island with guaranteed room if self._can_ai_assistant: self.ai_nav_button = QPushButton("AI 辨证师", self.nav_island) self.ai_nav_button.setObjectName("SpatialAiNavPill") + self.ai_nav_button.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed) self.ai_nav_button.setIcon(icons.icon("ai", "#0E6F5C", 15)) self.ai_nav_button.setIconSize(QSize(15, 15)) self.ai_nav_button.setCursor(Qt.CursorShape.PointingHandCursor) @@ -509,10 +577,13 @@ class SpatialShellWindow(QMainWindow): layout.addStretch(1) - # Right Global Search Capsule + Utility Circles + Doctor Identity Pill + Window Controls + # Right Global Search Capsule (elastic width so High-DPI never clips center nav!) self.search_capsule = QFrame(bar) self.search_capsule.setObjectName("SpatialSearchCapsule") - self.search_capsule.setFixedSize(244, 40) + self.search_capsule.setMinimumWidth(140) + self.search_capsule.setMaximumWidth(196) + self.search_capsule.setFixedHeight(40) + self.search_capsule.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed) s_layout = QHBoxLayout(self.search_capsule) s_layout.setContentsMargins(12, 0, 8, 0) s_layout.setSpacing(6) @@ -535,6 +606,15 @@ class SpatialShellWindow(QMainWindow): s_layout.addWidget(self.palette_badge) layout.addWidget(self.search_capsule) + self.compact_search_button = QPushButton(bar) + self.compact_search_button.setObjectName("SpatialCircleButton") + self.compact_search_button.setIcon(icons.icon("search", "#2B403E", 16)) + self.compact_search_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.compact_search_button.setToolTip("搜索患者或打开命令面板(Ctrl+K)") + self.compact_search_button.clicked.connect(self.open_command_palette) + self.compact_search_button.hide() + layout.addWidget(self.compact_search_button) + self.refresh_button = QPushButton(bar) self.refresh_button.setObjectName("SpatialCircleButton") self.refresh_button.setIcon(icons.icon("refresh", "#2B403E", 16)) @@ -558,7 +638,9 @@ class SpatialShellWindow(QMainWindow): dept_name = str( first_value(self.current_user, "department_name", "dept_name", default="糖代谢专科") ).strip() - self.user_menu_button = QPushButton(f"{doc_name} · {dept_name}", bar) + self._short_user_label = doc_name + self._full_user_label = f"{doc_name} · {dept_name}" + self.user_menu_button = QPushButton(self._full_user_label, bar) self.user_menu_button.setObjectName("SpatialDoctorCapsule") self.user_menu_button.setIcon(icons.icon("patients", "#0E6F5C", 16)) self.user_menu_button.setCursor(Qt.CursorShape.PointingHandCursor) @@ -615,7 +697,7 @@ class SpatialShellWindow(QMainWindow): hero = QWidget(self) hero.setObjectName("SpatialSubHero") - hero.setFixedHeight(64) + hero.setFixedHeight(68) layout = QHBoxLayout(hero) layout.setContentsMargins(4, 0, 4, 0) layout.setSpacing(12) @@ -630,7 +712,7 @@ class SpatialShellWindow(QMainWindow): self.hero_title_label = QLabel("全息辨证接诊舱", hero) h_font = QFont(heading_family()) - h_font.setPixelSize(28) + h_font.setPixelSize(26) h_font.setWeight(QFont.Weight.DemiBold) self.hero_title_label.setFont(h_font) self.hero_title_label.setStyleSheet("color: #0E1D1B; background: transparent;") @@ -642,30 +724,32 @@ class SpatialShellWindow(QMainWindow): # Right: Active Patient Floating Capsule (Alveo 'Margaret Osei · 71 yrs · COPD') self.patient_capsule = QFrame(hero) self.patient_capsule.setObjectName("SpatialPatientCapsule") - self.patient_capsule.setFixedHeight(48) + self.patient_capsule.setFixedHeight(54) pc_layout = QHBoxLayout(self.patient_capsule) - pc_layout.setContentsMargins(8, 4, 16, 4) + pc_layout.setContentsMargins(10, 6, 18, 6) pc_layout.setSpacing(10) self.patient_avatar_badge = QLabel("患", self.patient_capsule) - self.patient_avatar_badge.setFixedSize(34, 34) + self.patient_avatar_badge.setFixedSize(36, 36) self.patient_avatar_badge.setAlignment(Qt.AlignmentFlag.AlignCenter) self.patient_avatar_badge.setStyleSheet( "background-color: #E2F3EE; color: #0E6F5C; border: 1px solid #DFC793;" - " border-radius: 17px; font-size: 14px; font-weight: 600;" + " border-radius: 18px; font-size: 14px; font-weight: 600;" ) pc_layout.addWidget(self.patient_avatar_badge) p_meta_col = QVBoxLayout() p_meta_col.setContentsMargins(0, 0, 0, 0) - p_meta_col.setSpacing(1) + p_meta_col.setSpacing(2) self.context_patient_name = QLabel("等待选择接诊患者", self.patient_capsule) + self.context_patient_name.setMinimumHeight(20) self.context_patient_name.setStyleSheet( "color: #10201E; font-size: 13px; font-weight: 600; background: transparent;" ) p_meta_col.addWidget(self.context_patient_name) - self.context_patient_sub = QLabel("点击今日门诊计划自动同步全站上下文", self.patient_capsule) + self.context_patient_sub = QLabel("从右侧接诊队列或患者列表选择患者", self.patient_capsule) + self.context_patient_sub.setMinimumHeight(16) self.context_patient_sub.setStyleSheet( "color: #6E8380; font-size: 11px; background: transparent;" ) @@ -682,9 +766,10 @@ class SpatialShellWindow(QMainWindow): self.quick_chart_button.clicked.connect(self._open_active_patient_diagnosis) layout.addWidget(self.quick_chart_button) - # [▷ 开启视频面诊] Primary Alveo Emerald Pill (Alveo 'Start ward round') - self.quick_video_button = QPushButton("▷ 开启视频面诊", hero) + # [开启视频面诊] Primary Alveo Emerald Pill (Alveo 'Start ward round') + self.quick_video_button = QPushButton("开启视频面诊", hero) self.quick_video_button.setObjectName("SpatialPrimaryEmeraldPill") + self.quick_video_button.setIcon(icons.icon("video", "#FFFFFF", 15)) self.quick_video_button.setCursor(Qt.CursorShape.PointingHandCursor) self.quick_video_button.setEnabled(False) self.quick_video_button.clicked.connect(self._trigger_active_patient_video) @@ -721,6 +806,7 @@ class SpatialShellWindow(QMainWindow): btn = QPushButton(pill_title, self.nav_island) btn.setObjectName("SpatialNavPill") + btn.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed) btn.setCheckable(True) btn.setCursor(Qt.CursorShape.PointingHandCursor) btn.clicked.connect( @@ -843,6 +929,9 @@ class SpatialShellWindow(QMainWindow): def toggle_ai_bottom_sheet(self) -> None: self.ai_bottom_sheet.toggle_expanded() + def set_ai_bottom_sheet_expanded(self, expanded: bool) -> None: + self.ai_bottom_sheet.set_expanded(bool(expanded)) + def _on_sheet_expanded_changed(self, expanded: bool) -> None: self.patient_context_store.set_bottom_sheet_expanded(expanded) self._sync_ai_sheet_button(expanded) @@ -868,21 +957,133 @@ class SpatialShellWindow(QMainWindow): select_model = getattr(rec_page, "select_cockpit_ai_model", None) if callable(select_model): select_model(model_key) + return + self.ai_bottom_sheet.set_view_model( + derive_cockpit_snapshot(active_ai_model=model_key).aurora + ) def _on_patient_context_changed(self, snapshot: PatientSnapshot) -> None: if not snapshot or not snapshot.has_patient: self.patient_avatar_badge.setText("患") self.context_patient_name.setText("等待选择接诊患者") - self.context_patient_sub.setText("点击今日门诊计划自动同步全站上下文") + self.context_patient_sub.setText("从右侧接诊队列或患者列表选择患者") self.quick_chart_button.setEnabled(False) self.quick_video_button.setEnabled(False) return self.patient_avatar_badge.setText(snapshot.patient_name[:1]) - self.context_patient_name.setText(f"{snapshot.patient_name} · {snapshot.status_text}") + disp_name = snapshot.patient_name + if len(disp_name) > 14: + disp_name = f"{disp_name[:13]}…" + self.context_patient_name.setText(f"{disp_name} · {snapshot.status_text}") + self.context_patient_name.setToolTip(f"{snapshot.patient_name} · {snapshot.status_text}") self.context_patient_sub.setText(snapshot.subtitle_line) self.quick_chart_button.setEnabled(snapshot.diagnosis_id > 0) self.quick_video_button.setEnabled(snapshot.diagnosis_id > 0 or snapshot.appointment_id > 0) + rec_page = self.pages.get("reception") + sync_context = getattr(rec_page, "load_patient_from_context", None) + if callable(sync_context): + sync_context(snapshot) + if self.wing_manager.is_open: + self._sync_open_wing_with_patient(snapshot) + + def _sync_open_wing_with_patient(self, snapshot: PatientSnapshot) -> None: + """Keep any open Right/Left Wing or Sidecar synchronized when switching patients.""" + + self.wing_manager.update_header(subtitle=snapshot.patient_name) + active_w = self.wing_manager.active_widget + if active_w is None: + return + + rec_page = self.pages.get("reception") + seed_payload: Any = snapshot.raw_record + if rec_page is not None: + sel_detail = getattr(rec_page, "_selected_detail", None) + if sel_detail: + detail_diag = get_value(sel_detail, "diagnosis", None) or {} + try: + detail_diag_id = int(first_value(detail_diag, "id", "diagnosis_id", default=0) or 0) + except (TypeError, ValueError): + detail_diag_id = 0 + if detail_diag_id == snapshot.diagnosis_id and snapshot.diagnosis_id > 0: + seed_payload = sel_detail + + if isinstance(active_w, DiagnosisDialog): + if snapshot.diagnosis_id > 0 and getattr(active_w, "_diagnosis_id", 0) != snapshot.diagnosis_id: + prev_tab_key = None + if hasattr(active_w, "tabs") and active_w.tabs.currentIndex() >= 0: + prev_tab_key = active_w.tabs.tabBar().tabData(active_w.tabs.currentIndex()) + want_editable = bool( + getattr(active_w, "_editable", False) + and has_permission(self.permissions, "tcm.diagnosis/edit", default=False) + ) + active_w.open_for( + snapshot.diagnosis_id, + editable=want_editable, + view_only=not want_editable, + seed=seed_payload, + modeless=True, + auto_show=False, + ) + if prev_tab_key and hasattr(active_w, "tabs"): + for i in range(active_w.tabs.count()): + if active_w.tabs.tabBar().tabData(i) == prev_tab_key: + if active_w.tabs.currentIndex() != i: + active_w.tabs.setCurrentIndex(i) + break + self.wing_manager.update_header( + title=active_w.windowTitle().split(" - ")[0].strip() or "编辑诊单", + subtitle=snapshot.patient_name, + ) + return + + cls_name = type(active_w).__name__ + if cls_name == "ClinicalAiReportWingPanel": + sync_ai = getattr(rec_page, "_sync_wing_ai_report_panel", None) + if callable(sync_ai): + sync_ai() + return + + if cls_name == "AiConsultDialog" and snapshot.diagnosis_id > 0: + if getattr(active_w, "diagnosis_id", 0) != snapshot.diagnosis_id: + open_fn = getattr(active_w, "open_for", None) + if callable(open_fn): + open_fn( + diagnosis_id=snapshot.diagnosis_id, + patient_id=snapshot.patient_id, + seed=seed_payload, + source_title="接诊总览", + ) + return + + if cls_name == "DiagnosisAiAssistantDialog" and snapshot.diagnosis_id > 0: + if getattr(active_w, "diagnosis_id", 0) != snapshot.diagnosis_id: + open_fn = getattr(active_w, "open_for", None) + if callable(open_fn): + open_fn(snapshot.diagnosis_id, "") + return + + if cls_name == "PrescriptionAiReportDialog" and snapshot.diagnosis_id > 0: + kind = getattr(active_w, "kind", None) + if getattr(kind, "entry", "") != "prescription": + cur_row = getattr(active_w, "prescription", None) or {} + try: + cur_diag_id = int(first_value(cur_row, "diagnosis_id", "id", default=0) or 0) + except (TypeError, ValueError): + cur_diag_id = 0 + if cur_diag_id != snapshot.diagnosis_id: + open_fn = getattr(active_w, "open_for", None) + if callable(open_fn): + row_seed = dict(snapshot.raw_record or {}) + row_seed.update( + { + "id": snapshot.diagnosis_id, + "diagnosis_id": snapshot.diagnosis_id, + "patient_name": snapshot.patient_name, + } + ) + open_fn(row_seed) + def _open_active_patient_diagnosis(self) -> None: snap = self.patient_context_store.current_patient if snap.diagnosis_id > 0: @@ -910,9 +1111,12 @@ class SpatialShellWindow(QMainWindow): def _open_active_patient_ai_report(self) -> None: rec_page = self.pages.get("reception") - open_rep = getattr(rec_page, "_open_ai_analysis_dialog", None) - if callable(open_rep) and getattr(rec_page, "_selected_detail", None): - open_rep() + open_wing = getattr(rec_page, "open_ai_report_wing", None) + if ( + callable(open_wing) + and getattr(rec_page, "_selected_appointment_id", None) is not None + and open_wing() + ): return self._open_active_patient_ai_consult() @@ -921,10 +1125,12 @@ class SpatialShellWindow(QMainWindow): if snap.diagnosis_id > 0 and self._can_ai_assistant: present_ai_consult( self.repository, + self.permissions, + self, diagnosis_id=snap.diagnosis_id, - patient_name=snap.patient_name, - permissions=self.permissions, - parent=self, + patient_id=snap.patient_id, + seed=snap.raw_record, + source_title="接诊总览", ) return self._open_global_ai_picker() @@ -977,20 +1183,32 @@ class SpatialShellWindow(QMainWindow): category="空间导航", shortcut=f"Alt+{idx}" if idx <= 6 else "", icon_kind=item.key, - callback=lambda k=item.key: self.navigate(k), + action=lambda k=item.key: self.navigate(k), ) ) entries.append( CommandEntry( key="act:ai_sheet", - title="展开 / 收起黑曜极光 AI 辨证舱", - subtitle="查看三联极光毛玻璃循证卡与控糖节律仪表盘", + title="展开 / 收起黑曜极光 AI 分析舱", + subtitle="查看三模型循证结论与病历完备度", category="临床智医", shortcut="Ctrl+]", icon_kind="ai", - callback=self.toggle_ai_bottom_sheet, + action=self.toggle_ai_bottom_sheet, ) ) + if self.wing_manager.is_open: + entries.append( + CommandEntry( + key="act:wing_mode", + title="切换伴随视窗形态(内嵌分栏 ⇄ 独立副窗)", + subtitle="在主窗并排分栏与桌面磁吸伴随窗口之间切换", + category="伴随视窗", + shortcut="", + icon_kind="consultations", + action=self.wing_manager.toggle_mode, + ) + ) entries.append( CommandEntry( key="act:refresh", @@ -999,7 +1217,7 @@ class SpatialShellWindow(QMainWindow): category="工作台操作", shortcut="F5", icon_kind="refresh", - callback=self.refresh_current_page, + action=self.refresh_current_page, ) ) snap = self.patient_context_store.current_patient @@ -1007,15 +1225,19 @@ class SpatialShellWindow(QMainWindow): entries.append( CommandEntry( key="act:diag", - title=f"打开四诊病历 · {snap.patient_name}", + title=f"打开四诊病历伴随舱 · {snap.patient_name}", subtitle=snap.subtitle_line, category="当前患者", shortcut="", icon_kind="consultations", - callback=self._open_active_patient_diagnosis, + action=self._open_active_patient_diagnosis, ) ) - dlg = CommandPaletteDialog(entries, self) + dlg = CommandPaletteDialog( + entries, + on_search_patient=lambda q: (self.global_search.setText(q), self._run_global_search()), + parent=self, + ) dlg.exec() def _toggle_maximize(self) -> None: @@ -1040,10 +1262,17 @@ class SpatialShellWindow(QMainWindow): *, modeless: bool = False, ) -> DiagnosisDialog | None: - try: - normalized_id = int(diagnosis_id) - except (TypeError, ValueError): + if isinstance(diagnosis_id, bool): normalized_id = 0 + else: + try: + normalized_id = int(diagnosis_id) + except (TypeError, ValueError): + normalized_id = 0 + if normalized_id <= 0: + fallback_id = self.patient_context_store.current_patient.diagnosis_id + if fallback_id > 0: + normalized_id = fallback_id if normalized_id <= 0: show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600) return None @@ -1088,6 +1317,42 @@ class SpatialShellWindow(QMainWindow): tip = message or ("云端同步正常" if online else "云端连接中断") self.refresh_button.setToolTip(f"刷新当前视图(F5) · {tip}") + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + w = self.width() + compact_top = w < 1280 + ultra_top = w < 1080 + if hasattr(self, "brand_tag"): + self.brand_tag.setVisible(not compact_top) + if hasattr(self, "palette_badge"): + self.palette_badge.setVisible(not compact_top) + if hasattr(self, "search_capsule"): + self.search_capsule.setVisible(not ultra_top) + if not ultra_top: + self.search_capsule.setMinimumWidth(118 if compact_top else 140) + self.search_capsule.setMaximumWidth(154 if compact_top else 196) + if hasattr(self, "compact_search_button"): + self.compact_search_button.setVisible(ultra_top) + short_nav = { + "reception": "总览", + "appointments": "日程", + "patients": "患者", + "prescription_library": "智库", + "prescriptions": "处方", + "consultations": "诊单", + } + for key, btn in self.nav_buttons.items(): + full_t = _SPATIAL_NAV_LABELS.get(key, btn.text()) + btn.setText(short_nav.get(key, full_t) if ultra_top else full_t) + if hasattr(self, "ai_nav_button"): + self.ai_nav_button.setText("AI 辨证" if ultra_top else "AI 辨证师") + if hasattr(self, "global_search"): + self.global_search.setPlaceholderText("搜索…" if compact_top else "搜索患者、诊单…") + if hasattr(self, "user_menu_button"): + self.user_menu_button.setText( + self._short_user_label if compact_top else self._full_user_label + ) + def showEvent(self, event: Any) -> None: # noqa: N802 super().showEvent(event) self.chat_notifications.start() @@ -1098,6 +1363,7 @@ class SpatialShellWindow(QMainWindow): def closeEvent(self, event: Any) -> None: # noqa: N802 self.chat_notifications.stop() + self.wing_manager.close_all() super().closeEvent(event) if event.isAccepted(): self.close_requested.emit() diff --git a/app/src/doctor_workstation/ui/spatial_wings.py b/app/src/doctor_workstation/ui/spatial_wings.py new file mode 100644 index 000000000..a24077874 --- /dev/null +++ b/app/src/doctor_workstation/ui/spatial_wings.py @@ -0,0 +1,1596 @@ +"""Clinical OS 4.0 Dual-Wing Companion & Docked Split-Stage Window Engine. + +Replaces center-blocking OS modal dialogs across the entire workstation with: +1. Docked Left/Right Split-Wing (`DockedWing`) inside `SpatialShellWindow` (zero occlusion, + resizable via splitter, 100% non-modal side-by-side workflow). +2. External Magnetic Left/Right Companion Sidecar Window (`CompanionSidecarWindow`) that + snaps 10px beside the main workstation at equal height and moves in lockstep. +3. Frameless Jade-Porcelain Confirm & Quick-Input Sheets (`clinical_confirm`, `clinical_get_text`, + `clinical_get_multiline`, `clinical_get_item`) replacing raw `QMessageBox` / `QInputDialog`. +""" + +from __future__ import annotations + +import os +from collections.abc import Callable, Sequence +from contextlib import suppress +from typing import Any + +from PySide6.QtCore import ( + QEasingCurve, + QEvent, + QEventLoop, + QObject, + QPointF, + QRect, + QRectF, + QSize, + Qt, + QTimer, + QVariantAnimation, + Signal, +) +from PySide6.QtGui import ( + QColor, + QFont, + QFontMetrics, + QKeySequence, + QLinearGradient, + QMouseEvent, + QPainter, + QPainterPath, + QPen, + QPixmap, + QShortcut, +) +from PySide6.QtWidgets import ( + QApplication, + QComboBox, + QDialog, + QFileDialog, + QFrame, + QHBoxLayout, + QInputDialog, + QLabel, + QLineEdit, + QMessageBox, + QPlainTextEdit, + QPushButton, + QSizePolicy, + QStackedLayout, + QVBoxLayout, + QWidget, +) + +from . import icons, motion +from .reception_style import body_family, heading_family + +SPATIAL_WING_QSS = """ +QWidget#SpatialWingCard { + background: transparent; +} +QFrame#SpatialWingHeader { + background-color: #F7FAF9; + border: 0; + border-bottom: 1px solid #E2ECE9; + border-top-left-radius: 20px; + border-top-right-radius: 20px; +} +QLabel#SpatialWingTitle { + color: #0F1F1D; + font-size: 14px; + font-weight: 600; + padding-right: 4px; +} +QLabel#SpatialWingContextBadge { + background-color: #E3F3EE; + color: #0E6F5C; + border-radius: 10px; + padding: 2px 8px; + font-size: 11px; + font-weight: 600; +} +QPushButton#SpatialWingModeBtn { + min-width: 38px; + min-height: 26px; + max-height: 26px; + padding: 0 7px; + border-radius: 13px; + border: 1px solid #DCE7E4; + background-color: #FFFFFF; + color: #4D6561; + font-size: 11px; + font-weight: 600; +} +QPushButton#SpatialWingModeBtn:hover { + background-color: #E7F4F0; + border-color: #9ED0C3; + color: #0E6F5C; +} +QPushButton#SpatialWingModeBtn:checked { + background-color: #111918; + border-color: #111918; + color: #FFFFFF; +} +QPushButton#SpatialWingDetachBtn { + min-width: 68px; + min-height: 26px; + max-height: 26px; + padding: 0 9px; + border-radius: 13px; + border: 1px solid #CFE3DD; + background-color: #EDF7F4; + color: #0E6F5C; + font-size: 11px; + font-weight: 600; +} +QPushButton#SpatialWingDetachBtn:hover { + background-color: #0E6F5C; + border-color: #0E6F5C; + color: #FFFFFF; +} +QPushButton#SpatialWingCloseBtn { + min-width: 28px; + max-width: 28px; + min-height: 28px; + max-height: 28px; + border-radius: 14px; + border: 0; + background-color: #EEF3F1; + color: #4E6461; + font-size: 14px; + font-weight: 600; + padding: 0; +} +QPushButton#SpatialWingCloseBtn:hover { + background-color: #E0584C; + color: #FFFFFF; +} +QWidget#SpatialWingBodyHost { + background-color: #FFFFFF; + border-bottom-left-radius: 20px; + border-bottom-right-radius: 20px; +} +QWidget#SpatialWingBodyHost QDialog { + background-color: #FFFFFF; + border: 0; +} +QWidget#SpatialWingBodyHost QPushButton[variant="primary"] { + background-color: #0E6F5C; + color: #FFFFFF; + border: 0; + border-radius: 17px; + min-height: 34px; + padding: 0 18px; + font-weight: 600; +} +QWidget#SpatialWingBodyHost QPushButton[variant="primary"]:hover { + background-color: #0A5B4B; +} +QWidget#SpatialWingBodyHost QPushButton[variant="secondary"] { + background-color: #F4F8F7; + color: #1A2E2C; + border: 1px solid #DCE7E4; + border-radius: 17px; + min-height: 34px; + padding: 0 16px; + font-weight: 500; +} +QWidget#SpatialWingBodyHost QPushButton[variant="secondary"]:hover { + background-color: #E6F3EF; + border-color: #9ED0C3; + color: #0E6F5C; +} +QWidget#SpatialWingBodyHost QLineEdit, +QWidget#SpatialWingBodyHost QComboBox, +QWidget#SpatialWingBodyHost QPlainTextEdit { + border: 1px solid #DCE7E4; + border-radius: 10px; + background-color: #FBFDFC; + color: #132523; +} +QWidget#SpatialWingBodyHost QLineEdit:focus, +QWidget#SpatialWingBodyHost QComboBox:focus, +QWidget#SpatialWingBodyHost QPlainTextEdit:focus { + border: 1px solid #0E6F5C; + background-color: #FFFFFF; +} +""" + + +def find_spatial_shell(widget: QWidget | None = None) -> Any | None: + """Return the active visible `SpatialShellWindow` if one exists.""" + + cursor = widget + while cursor is not None: + if getattr(cursor, "wing_manager", None) is not None and cursor.isVisible(): + return cursor + cursor = cursor.parentWidget() + app = QApplication.instance() + if app is None: + return None + for candidate in app.topLevelWidgets(): + if getattr(candidate, "wing_manager", None) is not None and candidate.isVisible(): + return candidate + return None + + +class _WingHeaderBar(QFrame): + """Unified header with Left/Right dock pills, Sidecar detach toggle, and drag support.""" + + side_requested = Signal(str) + mode_toggle_requested = Signal() + close_requested = Signal() + manual_drag_started = Signal() + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("SpatialWingHeader") + self.setFixedHeight(50) + + layout = QHBoxLayout(self) + layout.setContentsMargins(12, 6, 10, 6) + layout.setSpacing(5) + + self.icon_badge = QLabel(self) + self.icon_badge.setFixedSize(28, 28) + self.icon_badge.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.icon_badge.setStyleSheet( + "background-color: #E2F3EE; border-radius: 14px; border: 1px solid #CBE6DE;" + ) + layout.addWidget(self.icon_badge) + + self.title_label = QLabel("伴随工作视窗", self) + self.title_label.setObjectName("SpatialWingTitle") + self.title_label.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred) + t_font = QFont(heading_family()) + t_font.setPixelSize(14) + t_font.setWeight(QFont.Weight.DemiBold) + self.title_label.setFont(t_font) + layout.addWidget(self.title_label) + + self.context_badge = QLabel("", self) + self.context_badge.setObjectName("SpatialWingContextBadge") + self.context_badge.setVisible(False) + layout.addWidget(self.context_badge) + + layout.addStretch(1) + + self.left_btn = QPushButton("‹ 左翼", self) + self.left_btn.setObjectName("SpatialWingModeBtn") + self.left_btn.setCheckable(True) + self.left_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.left_btn.setToolTip("停靠在主工作台左侧") + self.left_btn.clicked.connect(lambda: self.side_requested.emit("left")) + layout.addWidget(self.left_btn) + + self.right_btn = QPushButton("右翼 ›", self) + self.right_btn.setObjectName("SpatialWingModeBtn") + self.right_btn.setCheckable(True) + self.right_btn.setChecked(True) + self.right_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.right_btn.setToolTip("停靠在主工作台右侧") + self.right_btn.clicked.connect(lambda: self.side_requested.emit("right")) + layout.addWidget(self.right_btn) + + self.detach_btn = QPushButton("独立副窗 ↗", self) + self.detach_btn.setObjectName("SpatialWingDetachBtn") + self.detach_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.detach_btn.setToolTip("切换为桌面外侧等高磁吸伴随窗口 / 嵌回主窗口") + self.detach_btn.clicked.connect(self.mode_toggle_requested.emit) + layout.addWidget(self.detach_btn) + + self.close_btn = QPushButton("×", self) + self.close_btn.setObjectName("SpatialWingCloseBtn") + self.close_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.close_btn.setToolTip("关闭当前伴随视窗(Esc)") + self.close_btn.clicked.connect(self.close_requested.emit) + layout.addWidget(self.close_btn) + + def set_metadata( + self, + *, + title: str, + subtitle: str = "", + icon_kind: str = "ai", + side: str = "right", + mode: str = "docked", + ) -> None: + self.icon_badge.setPixmap(icons.icon(icon_kind, "#0E6F5C", 15).pixmap(15, 15)) + resolved_title = title or "伴随工作视窗" + self.title_label.setText(resolved_title) + m_font = QFont(heading_family()) + m_font.setPixelSize(14) + m_font.setWeight(QFont.Weight.DemiBold) + t_width = QFontMetrics(m_font).horizontalAdvance(resolved_title) + 10 + self.title_label.setMinimumWidth(min(176, t_width)) + raw_sub = str(subtitle or "").strip() + clean_sub = f"{raw_sub[:4]}…" if len(raw_sub) > 5 else raw_sub + self.context_badge.setText(clean_sub) + self.context_badge.setToolTip(raw_sub) + self.context_badge.setVisible(bool(clean_sub)) + self.left_btn.setChecked(side == "left") + self.right_btn.setChecked(side != "left") + if mode == "sidecar": + self.detach_btn.setText("↙ 嵌回主窗") + self.detach_btn.setToolTip("将独立伴随副窗嵌回主工作站并排分栏") + else: + self.detach_btn.setText("独立副窗 ↗") + self.detach_btn.setToolTip("弹出为主窗口左侧/右侧等高磁吸独立窗口") + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + win = self.window() + if win is not None and getattr(win, "_is_companion_sidecar", False): + child = self.childAt(event.position().toPoint()) + if child is None or isinstance(child, QLabel): + handle = win.windowHandle() + if handle is not None and handle.startSystemMove(): + self.manual_drag_started.emit() + event.accept() + return + super().mousePressEvent(event) + + +class _WingGlideVeil(QWidget): + """GPU-friendly cached-pixmap glide veil: 60fps OutCubic entrance with ZERO layout reflow.""" + + def __init__(self, parent: QWidget) -> None: + super().__init__(parent) + self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) + self.setAutoFillBackground(False) + self._pixmap: QPixmap | None = None + self._progress = 1.0 + self._offset_px = 16.0 + self._anim = QVariantAnimation(self) + self._anim.setDuration(155) + self._anim.setStartValue(0.0) + self._anim.setEndValue(1.0) + self._anim.setEasingCurve(QEasingCurve.Type.OutCubic) + self._anim.valueChanged.connect(self._on_tick) + self._anim.finished.connect(self._on_finished) + self.hide() + + def play(self, snapshot: QPixmap, *, from_side: str) -> None: + self._anim.stop() + if snapshot.isNull(): + self.hide() + return + self._pixmap = snapshot + self._progress = 0.0 + self._offset_px = 16.0 if from_side == "right" else -16.0 + parent = self.parentWidget() + if parent is not None: + self.setGeometry(parent.rect()) + self.show() + self.raise_() + self._anim.start() + + def cancel(self) -> None: + self._anim.stop() + self._pixmap = None + self.hide() + + def _on_tick(self, value: Any) -> None: + self._progress = float(value) + parent = self.parentWidget() + if parent is not None and self.size() != parent.size(): + self.setGeometry(parent.rect()) + self.update() + + def _on_finished(self) -> None: + self._pixmap = None + self.hide() + + def paintEvent(self, _event: object) -> None: # noqa: N802 + if self._pixmap is None or self._pixmap.isNull(): + return + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True) + painter.fillRect(self.rect(), QColor("#FFFFFF")) + dx = (1.0 - self._progress) * self._offset_px + painter.setOpacity(0.38 + 0.62 * self._progress) + painter.drawPixmap(QPointF(dx, 0.0), self._pixmap) + + +class SpatialWingCard(QWidget): + """20px rounded jade-porcelain card hosting any clinical panel or adapted dialog.""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("SpatialWingCard") + self.setStyleSheet(SPATIAL_WING_QSS) + self.setMinimumWidth(380) + + root = QVBoxLayout(self) + root.setContentsMargins(1, 3, 1, 1) + root.setSpacing(0) + + self.header = _WingHeaderBar(self) + root.addWidget(self.header) + + self.body_host = QWidget(self) + self.body_host.setObjectName("SpatialWingBodyHost") + self.body_host.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.body_layout = QStackedLayout(self.body_host) + self.body_layout.setContentsMargins(0, 0, 0, 0) + self.body_layout.setStackingMode(QStackedLayout.StackingMode.StackOne) + root.addWidget(self.body_host, 1) + + self.glide_veil = _WingGlideVeil(self.body_host) + + def paintEvent(self, _event: object) -> None: # noqa: N802 + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + path = QPainterPath() + path.addRoundedRect(rect, 20.0, 20.0) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.fillPath(path, QColor("#FFFFFF")) + + # Subtle top 3px Alveo emerald-to-champagne hairline clip + painter.save() + painter.setClipPath(path) + grad = QLinearGradient(rect.left(), rect.top(), rect.right(), rect.top()) + grad.setColorAt(0.0, QColor("#0E6F5C")) + grad.setColorAt(0.6, QColor("#2BA48C")) + grad.setColorAt(1.0, QColor("#DFC793")) + painter.fillRect(QRectF(rect.left(), rect.top(), rect.width(), 3.0), grad) + painter.restore() + + painter.setPen(QPen(QColor("#D8E5E1"), 1.0)) + painter.drawPath(path) + + +class CompanionSidecarWindow(QWidget): + """External frameless rounded window magnetically snapped to the Left or Right of Main.""" + + closed_by_system = Signal() + _RESIZE_MARGIN = 7 + + def __init__(self, owner: QWidget) -> None: + super().__init__(None) + self._owner = owner + self._is_companion_sidecar = True + self._magnet_locked = True + self._suppress_close_signal = False + self.setObjectName("CompanionSidecarWindow") + self.setProperty("doctorSkipOpenGeometry", True) + self.setWindowTitle("甄养堂 · 临床伴随视窗") + self.setWindowFlags(Qt.WindowType.Window | Qt.WindowType.FramelessWindowHint) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setMouseTracking(True) + self.setMinimumSize(390, 520) + + self._root = QVBoxLayout(self) + self._root.setContentsMargins(0, 0, 0, 0) + self._root.setSpacing(0) + + self._arrival_anim = QVariantAnimation(self) + self._arrival_anim.setDuration(165) + self._arrival_anim.setStartValue(0.0) + self._arrival_anim.setEndValue(1.0) + self._arrival_anim.setEasingCurve(QEasingCurve.Type.OutCubic) + self._arrival_target = QRect() + self._arrival_dx = 14 + self._arrival_anim.valueChanged.connect(self._on_arrival_tick) + self._arrival_anim.finished.connect(self._on_arrival_done) + + QShortcut(QKeySequence("Esc"), self, activated=self._emit_escape) + + def animate_arrival(self, target_rect: QRect, *, side: str) -> None: + self._arrival_anim.stop() + if motion.reduced_motion() or os.environ.get("QT_QPA_PLATFORM") == "offscreen": + self.setWindowOpacity(1.0) + self.setGeometry(target_rect) + return + self._arrival_target = QRect(target_rect) + self._arrival_dx = 14 if side == "right" else -14 + self.setWindowOpacity(0.32) + self.setGeometry( + target_rect.x() + self._arrival_dx, + target_rect.y(), + target_rect.width(), + target_rect.height(), + ) + self._arrival_anim.start() + + def _on_arrival_tick(self, value: Any) -> None: + p = float(value) + t = self._arrival_target + if t.isValid(): + self.move(t.x() + round((1.0 - p) * self._arrival_dx), t.y()) + self.setWindowOpacity(0.32 + 0.68 * p) + + def _on_arrival_done(self) -> None: + self.setWindowOpacity(1.0) + if self._arrival_target.isValid(): + self.setGeometry(self._arrival_target) + + def _emit_escape(self) -> None: + self.closed_by_system.emit() + + def set_magnet_locked(self, locked: bool) -> None: + self._magnet_locked = locked + + @property + def magnet_locked(self) -> bool: + return self._magnet_locked + + def mount_card(self, card: SpatialWingCard) -> None: + card.setParent(self) + self._root.addWidget(card, 1) + card.show() + + def _edges(self, pos: QPointF) -> Qt.Edge: + m = self._RESIZE_MARGIN + w, h = self.width(), self.height() + edges = Qt.Edge(0) + if pos.x() <= m: + edges |= Qt.Edge.LeftEdge + elif pos.x() >= w - m: + edges |= Qt.Edge.RightEdge + if pos.y() <= m: + edges |= Qt.Edge.TopEdge + elif pos.y() >= h - m: + edges |= Qt.Edge.BottomEdge + return edges + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + edges = self._edges(event.position()) + handle = self.windowHandle() + if edges and handle is not None and handle.startSystemResize(edges): + event.accept() + return + super().mousePressEvent(event) + + def closeEvent(self, event: Any) -> None: # noqa: N802 + super().closeEvent(event) + if not self._suppress_close_signal: + self.closed_by_system.emit() + + +def _relax_nested_minimum_widths(root: QWidget, cap: int = 460) -> None: + """Relax overly wide legacy QDialog child minimumWidths ONCE so side wings never clip.""" + + if getattr(root, "_spatial_wing_relaxed", False): + return + root._spatial_wing_relaxed = True # type: ignore[attr-defined] + if root.minimumWidth() > cap: + root.setMinimumWidth(min(cap, 400)) + if root.minimumHeight() > 560: + root.setMinimumHeight(420) + for child in root.findChildren(QWidget): + if child.minimumWidth() > cap: + child.setMinimumWidth(min(child.minimumWidth(), cap)) + + +class SpatialWingManager(QObject): + """Orchestrate Docked Left/Right Split-Wings and Magnetic Sidecar Windows on `SpatialShellWindow`.""" + + wing_visibility_changed = Signal(bool) + + def __init__( + self, + shell: QWidget, + *, + left_dock: QWidget, + right_dock: QWidget, + splitter: Any, + ) -> None: + super().__init__(shell) + self.shell = shell + self.left_dock = left_dock + self.right_dock = right_dock + self.splitter = splitter + + self._left_layout = QVBoxLayout(self.left_dock) + self._left_layout.setContentsMargins(0, 0, 6, 0) + self._left_layout.setSpacing(0) + + self._right_layout = QVBoxLayout(self.right_dock) + self._right_layout.setContentsMargins(6, 0, 0, 0) + self._right_layout.setSpacing(0) + + self.left_dock.hide() + self.right_dock.hide() + + self.card = SpatialWingCard(self.right_dock) + self._right_layout.addWidget(self.card, 1) + self.card.header.side_requested.connect(self.set_side) + self.card.header.mode_toggle_requested.connect(self.toggle_mode) + self.card.header.close_requested.connect(self.close_wing) + + self._side = "right" # "left" | "right" + self._mode = "docked" # "docked" | "sidecar" + self._preferred_width = 520 + self._title = "" + self._subtitle = "" + self._icon_kind = "ai" + self._active_widget: QWidget | None = None + self._active_dialog: QDialog | None = None + self._on_close_cb: Callable[[], None] | None = None + self._closing_guard = False + + self._sidecar: CompanionSidecarWindow | None = None + self._saved_shell_geom: tuple[bool, QRect, QSize] | None = None + self._syncing_geometry = False + + self.shell.installEventFilter(self) + QShortcut(QKeySequence("Esc"), self.card, activated=self.close_wing) + + @property + def is_open(self) -> bool: + return self._active_widget is not None + + @property + def side(self) -> str: + return self._side + + @property + def mode(self) -> str: + return self._mode + + @property + def active_widget(self) -> QWidget | None: + return self._active_widget + + def set_side(self, side: str) -> None: + normalized = "left" if str(side).strip().lower() == "left" else "right" + if normalized == self._side and self.is_open: + return + self._side = normalized + if self.is_open: + self._apply_placement() + + def set_mode(self, mode: str) -> None: + normalized = "sidecar" if str(mode).strip().lower() == "sidecar" else "docked" + if normalized == self._mode and self.is_open: + return + self._mode = normalized + if self.is_open: + self._apply_placement() + + def toggle_mode(self) -> None: + self.set_mode("sidecar" if self._mode == "docked" else "docked") + + def update_header(self, *, title: str | None = None, subtitle: str | None = None) -> None: + if title is not None: + self._title = title + if subtitle is not None: + self._subtitle = subtitle + self.card.header.set_metadata( + title=self._title, + subtitle=self._subtitle, + icon_kind=self._icon_kind, + side=self._side, + mode=self._mode, + ) + + def _should_animate_wing(self) -> bool: + return ( + self.shell.isVisible() + and not motion.reduced_motion() + and os.environ.get("QT_QPA_PLATFORM") != "offscreen" + ) + + def prewarm_widget(self, widget: QWidget, *, preferred_width: int = 540) -> None: + """Pre-attach a reusable heavy panel into `body_host` while keeping the wing closed.""" + + _relax_nested_minimum_widths(widget, cap=max(420, preferred_width - 40)) + if isinstance(widget, QDialog): + self._strip_dialog_chrome_once(widget, preferred_width=preferred_width) + widget.setModal(False) + widget.setProperty("hostedInSpatialWing", True) + widget.setProperty("doctorSkipOpenGeometry", True) + if widget.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground): + widget.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False) + widget.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + if widget.windowFlags() != Qt.WindowType.Widget: + widget.setWindowFlags(Qt.WindowType.Widget) + if self.card.body_layout.indexOf(widget) < 0: + widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) + self.card.body_layout.addWidget(widget) + widget.hide() + + def _hide_inactive_body_children(self, keep: QWidget) -> None: + """Keep cached panels mounted in `body_host` (zero `setParent` cost!) while hiding all others.""" + + veil = self.card.glide_veil + for child in list(self.card.body_host.children()): + if isinstance(child, QWidget) and child is not keep and child is not veil and child.isVisible(): + child.hide() + + def _strip_dialog_chrome_once(self, dialog: QDialog, *, preferred_width: int) -> None: + if not getattr(dialog, "_spatial_wing_chrome_stripped", False): + dialog._spatial_wing_chrome_stripped = True # type: ignore[attr-defined] + scrim = getattr(dialog, "scrim", None) + if isinstance(scrim, QWidget): + scrim.hide() + scrim.setFixedWidth(0) + drawer_panel = getattr(dialog, "drawer_panel", None) + if isinstance(drawer_panel, QWidget): + drawer_panel.setMinimumWidth(0) + drawer_panel.setMaximumWidth(16777215) + for child in dialog.findChildren(QWidget): + if type(child).__name__ == "ClinicalAccentBar" or child.objectName() in { + "DiagnosisDrawerHeader", + "DiagnosisCloseButton", + }: + child.hide() + rx_header = dialog.findChild(QFrame, "PrescriptionDrawerHeader") + if rx_header is not None: + for btn in rx_header.findChildren(QPushButton): + if btn.text().strip() in {"×", "✕", "关闭"}: + btn.hide() + studio_outline = getattr(dialog, "studio_outline", None) + if isinstance(studio_outline, QWidget) and preferred_width < 840: + studio_outline.hide() + owner_ref = getattr(dialog, "_owner", None) + if owner_ref is not None and getattr(dialog, "_owner_filter_installed", False): + with suppress(RuntimeError): + owner_ref.removeEventFilter(dialog) + dialog._owner = None # type: ignore[attr-defined] + dialog._owner_filter_installed = False # type: ignore[attr-defined] + + def present_widget( + self, + widget: QWidget, + *, + title: str, + subtitle: str = "", + icon_kind: str = "ai", + preferred_width: int = 520, + side: str | None = None, + mode: str | None = None, + on_close: Callable[[], None] | None = None, + ) -> None: + """Mount a plain `QWidget` inside the Left/Right Spatial Wing or Sidecar at 60fps.""" + + self.card.glide_veil.cancel() + switching_widget = self._active_widget is not widget + if switching_widget: + self._teardown_active(reject_dialog=True) + + if side in {"left", "right"}: + self._side = side + if mode in {"docked", "sidecar"}: + self._mode = mode + self._title = title + self._subtitle = subtitle + self._icon_kind = icon_kind + self._preferred_width = max(400, min(820, int(preferred_width))) + self._active_widget = widget + self._active_dialog = widget if isinstance(widget, QDialog) else None + self._on_close_cb = on_close + + _relax_nested_minimum_widths(widget, cap=max(420, self._preferred_width - 40)) + + # Freeze shell updates for ONE atomic layout pass (zero half-baked intermediate frames!) + updates_were_enabled = self.shell.updatesEnabled() + if updates_were_enabled: + self.shell.setUpdatesEnabled(False) + try: + if self.card.body_layout.indexOf(widget) < 0: + widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) + self.card.body_layout.addWidget(widget) + self._hide_inactive_body_children(widget) + widget._in_present_widget_show = True # type: ignore[attr-defined] + try: + self.card.body_layout.setCurrentWidget(widget) + widget.show() + finally: + widget._in_present_widget_show = False # type: ignore[attr-defined] + + self._apply_placement() + if self.shell.centralWidget() and self.shell.centralWidget().layout(): + self.shell.centralWidget().layout().activate() + self.card.body_layout.activate() + finally: + if updates_were_enabled: + self.shell.setUpdatesEnabled(True) + + if ( + switching_widget + and self._mode == "docked" + and self._should_animate_wing() + and self.card.body_host.width() > 40 + ): + snap = self.card.body_host.grab() + self.card.glide_veil.play(snap, from_side=self._side) + + self.wing_visibility_changed.emit(True) + + def present_dialog( + self, + dialog: QDialog, + *, + title: str = "", + subtitle: str = "", + icon_kind: str = "consultations", + preferred_width: int = 520, + side: str | None = None, + ) -> None: + """Adapt and mount a `QDialog` non-modally inside the Spatial Wing.""" + + if self._active_dialog is dialog and self.is_open: + self.update_header( + title=title or dialog.windowTitle() or "临床工作窗", + subtitle=subtitle, + ) + self._apply_placement() + return + + self._strip_dialog_chrome_once(dialog, preferred_width=preferred_width) + + resolved_title = title or dialog.windowTitle().split(" - ")[0].strip() or "临床工作视窗" + if not subtitle: + store = getattr(self.shell, "patient_context_store", None) + snap = getattr(store, "current_patient", None) + if snap is not None and getattr(snap, "has_patient", False): + subtitle = snap.patient_name + + # Prevent WA_DeleteOnClose from prematurely freeing C++ wrapper during reparent + had_delete_on_close = dialog.testAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) + if had_delete_on_close: + dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) + dialog.setProperty("_restoreDeleteOnClose", True) + + dialog.setModal(False) + dialog.setProperty("hostedInSpatialWing", True) + dialog.setProperty("doctorSkipOpenGeometry", True) + if dialog.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground): + dialog.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False) + dialog.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + if dialog.windowFlags() != Qt.WindowType.Widget: + dialog.setWindowFlags(Qt.WindowType.Widget) + + def _on_dialog_finished(_code: int = 0) -> None: + if self._active_dialog is dialog and not self._closing_guard: + self.close_wing(from_dialog=True) + + if not getattr(dialog, "_spatial_wing_finished_wired", False): + dialog.finished.connect(_on_dialog_finished) + dialog._spatial_wing_finished_wired = True # type: ignore[attr-defined] + + self.present_widget( + dialog, + title=resolved_title, + subtitle=subtitle, + icon_kind=icon_kind, + preferred_width=preferred_width, + side=side, + ) + + def _apply_placement(self) -> None: + self.card.header.set_metadata( + title=self._title, + subtitle=self._subtitle, + icon_kind=self._icon_kind, + side=self._side, + mode=self._mode, + ) + if self._mode == "sidecar": + self._mount_in_sidecar() + else: + self._mount_in_dock() + + def _mount_in_dock(self) -> None: + if self._sidecar is not None and self._sidecar.isVisible(): + self._sidecar._suppress_close_signal = True + self._sidecar.hide() + self._sidecar._suppress_close_signal = False + self._restore_shell_geometry_if_saved() + + target_dock = self.left_dock if self._side == "left" else self.right_dock + other_dock = self.right_dock if self._side == "left" else self.left_dock + target_layout = self._left_layout if self._side == "left" else self._right_layout + + other_dock.hide() + if self.card.parentWidget() is not target_dock: + self.card.setParent(target_dock) + if target_layout.indexOf(self.card) < 0: + target_layout.addWidget(self.card, 1) + self.card.show() + target_dock.show() + + total_w = max(1080, self.splitter.width() or self.shell.width() - 40) + # Keep >= 59% width for the main clinical cockpit on 125%/150% DPI screens + wing_ratio = 0.40 if total_w < 1560 else 0.42 + wing_w = min(self._preferred_width, max(400, int(total_w * wing_ratio))) + main_w = max(640, total_w - wing_w) + if self._side == "left": + self.splitter.setSizes([wing_w, main_w, 0]) + else: + self.splitter.setSizes([0, main_w, wing_w]) + + def _ensure_sidecar(self) -> CompanionSidecarWindow: + if self._sidecar is None: + self._sidecar = CompanionSidecarWindow(self.shell) + self._sidecar.closed_by_system.connect(self.close_wing) + self.card.header.manual_drag_started.connect( + lambda: self._sidecar.set_magnet_locked(False) if self._sidecar else None + ) + self._sidecar.set_magnet_locked(True) + return self._sidecar + + def _mount_in_sidecar(self) -> None: + self.left_dock.hide() + self.right_dock.hide() + self.splitter.setSizes([0, max(800, self.shell.width()), 0]) + + sidecar = self._ensure_sidecar() + was_visible = sidecar.isVisible() + sidecar.mount_card(self.card) + self._arrange_shell_and_sidecar(initial=True) + target_geom = QRect(sidecar.geometry()) + sidecar.show() + sidecar.raise_() + if not was_visible and target_geom.isValid(): + sidecar.animate_arrival(target_geom, side=self._side) + + def _arrange_shell_and_sidecar(self, *, initial: bool = False) -> None: + if self._sidecar is None or self._syncing_geometry: + return + if not self._sidecar.magnet_locked and not initial: + return + screen = self.shell.screen() or QApplication.primaryScreen() + raw_avail = screen.availableGeometry() if screen is not None else QRect(0, 0, 1920, 1040) + # In headless offscreen tests where screen defaults to 800x600 or 1280x720 while the + # shell was explicitly sized wider, synthesize a realistic 1920x1040 desktop envelope. + if raw_avail.width() < 1400 and self.shell.width() >= 1400: + avail = QRect(0, 0, max(1920, self.shell.width() + 560), max(1040, self.shell.height() + 40)) + else: + avail = raw_avail + gap = 10 + wing_w = min(self._preferred_width, max(440, int(avail.width() * 0.36))) + + self._syncing_geometry = True + try: + main_geom = self.shell.frameGeometry() + fits_right = ( + not self.shell.isMaximized() + and main_geom.right() + gap + wing_w <= avail.right() - 4 + ) + fits_left = ( + not self.shell.isMaximized() + and main_geom.left() - gap - wing_w >= avail.left() + 4 + ) + if (self._side == "right" and fits_right) or (self._side == "left" and fits_left): + sx = ( + main_geom.right() + gap + if self._side == "right" + else main_geom.left() - gap - wing_w + ) + self._sidecar.setGeometry(sx, main_geom.top(), wing_w, main_geom.height()) + return + + # Single-screen auto-split: save original shell geometry once and arrange side-by-side! + if self._saved_shell_geom is None: + self._saved_shell_geom = ( + self.shell.isMaximized(), + QRect(self.shell.geometry()), + QSize(self.shell.minimumSize()), + ) + if self.shell.isMaximized(): + self.shell.showNormal() + self.shell.setMinimumSize(max(860, min(920, avail.width() - wing_w - 28)), 640) + + pad = 8 + usable_w = avail.width() - pad * 2 - gap + actual_wing_w = min(wing_w, max(400, int(usable_w * 0.36))) + actual_main_w = max(860, usable_w - actual_wing_w) + if actual_main_w + actual_wing_w > usable_w: + actual_wing_w = max(390, usable_w - actual_main_w) + usable_h = avail.height() - pad * 2 + top_y = avail.top() + pad + + if self._side == "right": + main_x = avail.left() + pad + side_x = main_x + actual_main_w + gap + else: + side_x = avail.left() + pad + main_x = side_x + actual_wing_w + gap + + self.shell.setGeometry(main_x, top_y, actual_main_w, usable_h) + self._sidecar.setGeometry(side_x, top_y, actual_wing_w, usable_h) + finally: + self._syncing_geometry = False + + def _restore_shell_geometry_if_saved(self) -> None: + if self._saved_shell_geom is None: + return + was_max, old_rect, old_min = self._saved_shell_geom + self._saved_shell_geom = None + self._syncing_geometry = True + try: + self.shell.setMinimumSize(old_min) + if was_max: + self.shell.showMaximized() + elif old_rect.isValid(): + self.shell.setGeometry(old_rect) + finally: + self._syncing_geometry = False + + def _teardown_active(self, *, reject_dialog: bool) -> None: + widget = self._active_widget + dialog = self._active_dialog + on_close = self._on_close_cb + self._active_widget = None + self._active_dialog = None + self._on_close_cb = None + if widget is None: + return + self._closing_guard = True + try: + widget.hide() + if dialog is not None: + if reject_dialog and dialog.result() == 0: + with suppress(RuntimeError): + dialog.reject() + if dialog.property("_restoreDeleteOnClose"): + self.card.body_layout.removeWidget(widget) + with suppress(RuntimeError): + dialog.deleteLater() + if on_close is not None: + with suppress(Exception): + on_close() + finally: + self._closing_guard = False + + def close_wing(self, *, from_dialog: bool = False) -> None: + if not self.is_open and (self._sidecar is None or not self._sidecar.isVisible()): + return + self._teardown_active(reject_dialog=not from_dialog) + self.left_dock.hide() + self.right_dock.hide() + if self._sidecar is not None and self._sidecar.isVisible(): + self._sidecar._suppress_close_signal = True + self._sidecar.hide() + self._sidecar._suppress_close_signal = False + self._restore_shell_geometry_if_saved() + self.wing_visibility_changed.emit(False) + + def close_all(self) -> None: + self.close_wing() + if self._sidecar is not None: + self._sidecar._suppress_close_signal = True + self._sidecar.close() + self._sidecar.deleteLater() + self._sidecar = None + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 + if watched is self.shell and self._mode == "sidecar" and self.is_open and self._sidecar is not None: + et = event.type() + if et in {QEvent.Type.Move, QEvent.Type.Resize} and not self._syncing_geometry: + if self._sidecar.magnet_locked and not self.shell.isMinimized(): + main_g = self.shell.frameGeometry() + gap = 10 + sx = ( + main_g.right() + gap + if self._side == "right" + else main_g.left() - gap - self._sidecar.width() + ) + self._sidecar.setGeometry(sx, main_g.top(), self._sidecar.width(), main_g.height()) + elif et == QEvent.Type.WindowStateChange: + if self.shell.isMinimized(): + self._sidecar.hide() + elif not self._sidecar.isVisible(): + self._sidecar.show() + return super().eventFilter(watched, event) + + +def _infer_wing_spec(dialog: QDialog) -> tuple[str, int]: + """Return `(icon_kind, preferred_width)` tailored to each dialog quadrant.""" + + cls_name = type(dialog).__name__ + obj_name = dialog.objectName() or "" + combined = f"{cls_name} {obj_name}" + + if any(k in combined for k in ("AiConsult", "IssuedPrescriptionAi")): + return ("ai", 620) + if any(k in combined for k in ("AiAnalysis", "AiReport", "AiAssistant", "AiStatistics")): + return ("ai", 540) + if any(k in combined for k in ("DiagnosisDialog",)): + return ("consultations", 660) + if any( + k in combined + for k in ( + "PrescriptionEditor", + "PrescriptionDetail", + "PrescriptionTemplate", + "PrescriptionEsign", + ) + ): + return ("prescriptions", 680) + if any(k in combined for k in ("Video", "AudioQueue")): + return ("video", 520) + if any(k in combined for k in ("Qr", "Update")): + return ("qrcode", 420) + if any(k in combined for k in ("Appointment",)): + return ("appointments", 460) + return ("consultations", 460) + + +_ORIG_QDIALOG_SHOW = QDialog.show +_ORIG_QDIALOG_OPEN = QDialog.open +_ORIG_QDIALOG_EXEC = QDialog.exec +_GLOBAL_QDIALOG_HOOKS_INSTALLED = False + + +def _should_route_dialog_to_wing(dialog: QDialog) -> Any: + """Return active `SpatialShellWindow` when `dialog` should mount in the Wing, else `None`.""" + + if isinstance(dialog, (QMessageBox, QInputDialog, QFileDialog)): + return None + if dialog.metaObject().className() == "QPrintDialog": + return None + if bool(dialog.property("skipSpatialWing")): + return None + if bool(getattr(dialog, "_in_present_widget_show", False)): + return None + if bool(getattr(dialog, "_embedded", False)): + return None + if not dialog.isWindow() and not bool(dialog.property("hostedInSpatialWing")): + return None + return find_spatial_shell(dialog) + + +def _resolve_dialog_wing_spec(dialog: QDialog) -> tuple[str, int, str | None]: + default_icon, default_w = _infer_wing_spec(dialog) + ic = getattr(dialog, "_wing_icon_kind", None) or default_icon + pw = getattr(dialog, "_wing_preferred_width", None) or default_w + side = getattr(dialog, "_wing_preferred_side", None) + return (str(ic), int(pw), side) + + +def install_global_qdialog_wing_hooks() -> None: + """Install once on `QDialog` so every business dialog routes `.show/.open/.exec` to Wing.""" + + global _GLOBAL_QDIALOG_HOOKS_INSTALLED + if _GLOBAL_QDIALOG_HOOKS_INSTALLED: + return + _GLOBAL_QDIALOG_HOOKS_INSTALLED = True + + def _qdialog_show(self: QDialog) -> None: + shell = _should_route_dialog_to_wing(self) + if shell is None: + _ORIG_QDIALOG_SHOW(self) + return + ic, pw, side = _resolve_dialog_wing_spec(self) + shell.wing_manager.present_dialog( + self, + icon_kind=ic, + preferred_width=pw, + side=side, + ) + + def _qdialog_open(self: QDialog) -> None: + shell = _should_route_dialog_to_wing(self) + if shell is None: + _ORIG_QDIALOG_OPEN(self) + return + ic, pw, side = _resolve_dialog_wing_spec(self) + shell.wing_manager.present_dialog( + self, + icon_kind=ic, + preferred_width=pw, + side=side, + ) + + def _qdialog_exec(self: QDialog) -> int: + if getattr(self, "_in_wing_exec", False): + return int(self.result()) + shell = _should_route_dialog_to_wing(self) + if shell is None: + return int(_ORIG_QDIALOG_EXEC(self)) + ic, pw, side = _resolve_dialog_wing_spec(self) + self._in_wing_exec = True # type: ignore[attr-defined] + self.setResult(int(QDialog.DialogCode.Rejected)) + loop = QEventLoop(self) + self.finished.connect(loop.quit) + shell.close_requested.connect(self.reject) + try: + shell.wing_manager.present_dialog( + self, + icon_kind=ic, + preferred_width=pw, + side=side, + ) + if self.isVisible(): + loop.exec() + finally: + self._in_wing_exec = False # type: ignore[attr-defined] + with suppress(RuntimeError, TypeError): + self.finished.disconnect(loop.quit) + with suppress(RuntimeError, TypeError): + shell.close_requested.disconnect(self.reject) + return int(self.result()) + + QDialog.show = _qdialog_show # type: ignore[method-assign] + QDialog.open = _qdialog_open # type: ignore[method-assign] + QDialog.exec = _qdialog_exec # type: ignore[method-assign] + + +def install_wing_dialog_support( + dialog: QDialog, + *, + icon_kind: str | None = None, + preferred_width: int | None = None, + preferred_side: str | None = None, +) -> None: + """Attach optional Spatial Wing metadata to `dialog` and ensure global hooks are active.""" + + install_global_qdialog_wing_hooks() + if icon_kind is not None: + dialog._wing_icon_kind = icon_kind # type: ignore[attr-defined] + if preferred_width is not None: + dialog._wing_preferred_width = preferred_width # type: ignore[attr-defined] + if preferred_side is not None: + dialog._wing_preferred_side = preferred_side # type: ignore[attr-defined] + + +# ── Quadrant 4: Frameless Jade-Porcelain Confirm & Quick-Input Sheets ──────── + +_CRYSTAL_SHEET_QSS = """ +QFrame#CrystalPopupSurface { + background-color: #FFFFFF; + border: 1px solid #CFE0DC; + border-radius: 20px; +} +QLabel#CrystalPopupTitle { + color: #0F1F1D; + font-size: 16px; + font-weight: 600; +} +QLabel#CrystalPopupBody { + color: #425855; + font-size: 13px; +} +QPushButton#CrystalSecondaryBtn { + min-height: 36px; + max-height: 36px; + padding: 0 18px; + border-radius: 18px; + border: 1px solid #DCE7E4; + background-color: #F4F8F7; + color: #1A2E2C; + font-size: 13px; + font-weight: 600; +} +QPushButton#CrystalSecondaryBtn:hover { + background-color: #E5F2EE; + border-color: #9ED0C3; + color: #0E6F5C; +} +QPushButton#CrystalPrimaryBtn { + min-height: 36px; + max-height: 36px; + padding: 0 20px; + border-radius: 18px; + border: 0; + background-color: #0E6F5C; + color: #FFFFFF; + font-size: 13px; + font-weight: 600; +} +QPushButton#CrystalPrimaryBtn:hover { + background-color: #0A5949; +} +QPushButton#CrystalDangerBtn { + min-height: 36px; + max-height: 36px; + padding: 0 20px; + border-radius: 18px; + border: 0; + background-color: #D9534F; + color: #FFFFFF; + font-size: 13px; + font-weight: 600; +} +QPushButton#CrystalDangerBtn:hover { + background-color: #C03D39; +} +""" + + +class ClinicalConfirmDialog(QDialog): + """Frameless 20px rounded jade-porcelain confirmation card (zero OS gray chrome).""" + + def __init__( + self, + parent: QWidget | None, + title: str, + message: str, + *, + confirm_text: str = "确认", + cancel_text: str | None = "取消", + danger: bool = False, + ) -> None: + super().__init__(parent) + self.setProperty("skipSpatialWing", True) + self.setProperty("doctorSkipOpenGeometry", True) + self.setWindowTitle(title) + self.setModal(True) + self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setStyleSheet(_CRYSTAL_SHEET_QSS) + self.setFixedWidth(430) + + outer = QVBoxLayout(self) + outer.setContentsMargins(6, 6, 6, 6) + surface = QFrame(self) + surface.setObjectName("CrystalPopupSurface") + outer.addWidget(surface) + + layout = QVBoxLayout(surface) + layout.setContentsMargins(24, 22, 24, 20) + layout.setSpacing(14) + + head = QHBoxLayout() + head.setSpacing(12) + badge = QLabel("!" if danger else "?", surface) + badge.setFixedSize(34, 34) + badge.setAlignment(Qt.AlignmentFlag.AlignCenter) + badge.setStyleSheet( + f"background-color: {'#FCEBE8' if danger else '#E2F3EE'};" + f" color: {'#D9534F' if danger else '#0E6F5C'};" + " border-radius: 17px; font-size: 16px; font-weight: 700;" + ) + head.addWidget(badge) + + t_lbl = QLabel(title, surface) + t_lbl.setObjectName("CrystalPopupTitle") + t_font = QFont(heading_family()) + t_font.setPixelSize(16) + t_font.setWeight(QFont.Weight.DemiBold) + t_lbl.setFont(t_font) + head.addWidget(t_lbl, 1) + layout.addLayout(head) + + b_lbl = QLabel(message, surface) + b_lbl.setObjectName("CrystalPopupBody") + b_lbl.setWordWrap(True) + b_lbl.setFont(QFont(body_family(), 10)) + layout.addWidget(b_lbl) + + btn_row = QHBoxLayout() + btn_row.addStretch(1) + if cancel_text: + cancel_btn = QPushButton(cancel_text, surface) + cancel_btn.setObjectName("CrystalSecondaryBtn") + cancel_btn.setCursor(Qt.CursorShape.PointingHandCursor) + cancel_btn.clicked.connect(self.reject) + btn_row.addWidget(cancel_btn) + + ok_btn = QPushButton(confirm_text, surface) + ok_btn.setObjectName("CrystalDangerBtn" if danger else "CrystalPrimaryBtn") + ok_btn.setCursor(Qt.CursorShape.PointingHandCursor) + ok_btn.clicked.connect(self.accept) + btn_row.addWidget(ok_btn) + layout.addLayout(btn_row) + + def showEvent(self, event: Any) -> None: # noqa: N802 + super().showEvent(event) + ref = self.parentWidget() + if ref is not None: + win = ref.window() + center = win.frameGeometry().center() + self.move(center.x() - self.width() // 2, center.y() - self.height() // 2) + + +class ClinicalInputDialog(QDialog): + """Frameless jade-porcelain input sheet replacing raw `QInputDialog`.""" + + def __init__( + self, + parent: QWidget | None, + title: str, + label: str, + *, + mode: str = "text", # "text" | "multiline" | "item" + text: str = "", + placeholder: str = "", + items: Sequence[str] = (), + current: int = 0, + ) -> None: + super().__init__(parent) + self._mode = mode + self.setProperty("skipSpatialWing", True) + self.setProperty("doctorSkipOpenGeometry", True) + self.setWindowTitle(title) + self.setModal(True) + self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setStyleSheet(_CRYSTAL_SHEET_QSS) + self.setFixedWidth(450) + + outer = QVBoxLayout(self) + outer.setContentsMargins(6, 6, 6, 6) + surface = QFrame(self) + surface.setObjectName("CrystalPopupSurface") + outer.addWidget(surface) + + layout = QVBoxLayout(surface) + layout.setContentsMargins(24, 20, 24, 20) + layout.setSpacing(12) + + t_lbl = QLabel(title, surface) + t_lbl.setObjectName("CrystalPopupTitle") + layout.addWidget(t_lbl) + + l_lbl = QLabel(label, surface) + l_lbl.setObjectName("CrystalPopupBody") + l_lbl.setWordWrap(True) + layout.addWidget(l_lbl) + + self.line_edit: QLineEdit | None = None + self.multi_edit: QPlainTextEdit | None = None + self.combo: QComboBox | None = None + + field_qss = ( + "border: 1px solid #CFE0DC; border-radius: 12px; padding: 8px 12px;" + " background: #F9FCFB; color: #11201E; font-size: 13px;" + ) + if mode == "multiline": + self.multi_edit = QPlainTextEdit(text, surface) + self.multi_edit.setPlaceholderText(placeholder) + self.multi_edit.setFixedHeight(108) + self.multi_edit.setStyleSheet(field_qss) + layout.addWidget(self.multi_edit) + elif mode == "item": + self.combo = QComboBox(surface) + self.combo.addItems(list(items)) + if 0 <= current < len(items): + self.combo.setCurrentIndex(current) + self.combo.setFixedHeight(38) + self.combo.setStyleSheet(field_qss) + layout.addWidget(self.combo) + else: + self.line_edit = QLineEdit(text, surface) + self.line_edit.setPlaceholderText(placeholder) + self.line_edit.setFixedHeight(38) + self.line_edit.setStyleSheet(field_qss) + self.line_edit.returnPressed.connect(self.accept) + layout.addWidget(self.line_edit) + + btn_row = QHBoxLayout() + btn_row.addStretch(1) + cancel_btn = QPushButton("取消", surface) + cancel_btn.setObjectName("CrystalSecondaryBtn") + cancel_btn.setCursor(Qt.CursorShape.PointingHandCursor) + cancel_btn.clicked.connect(self.reject) + btn_row.addWidget(cancel_btn) + + ok_btn = QPushButton("确认提交", surface) + ok_btn.setObjectName("CrystalPrimaryBtn") + ok_btn.setCursor(Qt.CursorShape.PointingHandCursor) + ok_btn.clicked.connect(self.accept) + btn_row.addWidget(ok_btn) + layout.addLayout(btn_row) + + def value(self) -> str: + if self.multi_edit is not None: + return self.multi_edit.toPlainText() + if self.combo is not None: + return self.combo.currentText() + if self.line_edit is not None: + return self.line_edit.text() + return "" + + def showEvent(self, event: Any) -> None: # noqa: N802 + super().showEvent(event) + ref = self.parentWidget() + if ref is not None: + win = ref.window() + center = win.frameGeometry().center() + self.move(center.x() - self.width() // 2, center.y() - self.height() // 2) + QTimer.singleShot( + 0, + lambda: ( + self.line_edit.setFocus() + if self.line_edit + else (self.multi_edit.setFocus() if self.multi_edit else None) + ), + ) + + +def clinical_confirm( + parent: QWidget | None, + title: str, + message: str, + *, + confirm_text: str = "确认", + cancel_text: str = "取消", + danger: bool = False, +) -> bool: + dlg = ClinicalConfirmDialog( + parent, + title, + message, + confirm_text=confirm_text, + cancel_text=cancel_text, + danger=danger, + ) + return dlg.exec() == int(QDialog.DialogCode.Accepted) + + +def clinical_alert( + parent: QWidget | None, + title: str, + message: str, + *, + danger: bool = False, +) -> None: + dlg = ClinicalConfirmDialog( + parent, + title, + message, + confirm_text="我知道了", + cancel_text=None, + danger=danger, + ) + dlg.exec() + + +def clinical_get_text( + parent: QWidget | None, + title: str, + label: str, + *, + text: str = "", + placeholder: str = "", +) -> tuple[str, bool]: + dlg = ClinicalInputDialog( + parent, title, label, mode="text", text=text, placeholder=placeholder + ) + ok = dlg.exec() == int(QDialog.DialogCode.Accepted) + return (dlg.value(), ok) + + +def clinical_get_multiline( + parent: QWidget | None, + title: str, + label: str, + *, + text: str = "", + placeholder: str = "", +) -> tuple[str, bool]: + dlg = ClinicalInputDialog( + parent, title, label, mode="multiline", text=text, placeholder=placeholder + ) + ok = dlg.exec() == int(QDialog.DialogCode.Accepted) + return (dlg.value(), ok) + + +def clinical_get_item( + parent: QWidget | None, + title: str, + label: str, + items: Sequence[str], + *, + current: int = 0, +) -> tuple[str, bool]: + dlg = ClinicalInputDialog( + parent, title, label, mode="item", items=items, current=current + ) + ok = dlg.exec() == int(QDialog.DialogCode.Accepted) + return (dlg.value(), ok) + + +__all__ = [ + "ClinicalConfirmDialog", + "ClinicalInputDialog", + "CompanionSidecarWindow", + "SpatialWingCard", + "SpatialWingManager", + "clinical_alert", + "clinical_confirm", + "clinical_get_item", + "clinical_get_multiline", + "clinical_get_text", + "find_spatial_shell", + "install_global_qdialog_wing_hooks", + "install_wing_dialog_support", +] diff --git a/app/src/doctor_workstation/ui/state/patient_context_store.py b/app/src/doctor_workstation/ui/state/patient_context_store.py index a4e43bec4..91f4ed4af 100644 --- a/app/src/doctor_workstation/ui/state/patient_context_store.py +++ b/app/src/doctor_workstation/ui/state/patient_context_store.py @@ -2,11 +2,13 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import dataclass, field from typing import Any from PySide6.QtCore import QObject, Signal +from ...core.models import Appointment, Consultation, Patient from ..widgets import display_text, first_value, gender_text @@ -40,10 +42,10 @@ class PatientSnapshot: gender_age: str = "" phone: str = "—" course_text: str = "" - clinical_diagnosis: str = "待选择接诊患者" + clinical_diagnosis: str = "" chief_complaint: str = "" status_code: int = 0 - status_text: str = "待接诊" + status_text: str = "待选择" assistant_name: str = "—" doctor_name: str = "—" appointment_time: str = "" @@ -64,13 +66,13 @@ class PatientSnapshot: part for part in ( self.gender_age, - self.clinical_diagnosis if self.clinical_diagnosis != "—" else "", + self.clinical_diagnosis if self.clinical_diagnosis and self.clinical_diagnosis != "—" else "", f"病程 {self.course_text}" if self.course_text and self.course_text != "—" else "", self.appointment_time, ) if part ] - return " · ".join(parts[:3]) if parts else "从今日门诊计划或挂号队列选择患者" + return " · ".join(parts[:3]) if parts else "已关联当前患者临床上下文" class PatientContextStore(QObject): @@ -148,7 +150,12 @@ class PatientContextStore(QObject): appointment, "patient_name", "name", - default=first_value(patient, "name", "patient_name", default="患者"), + default=first_value( + diagnosis, + "patient_name", + "name", + default=first_value(patient, "name", "patient_name", default="患者"), + ), ) ) raw_gender = next( @@ -195,44 +202,71 @@ class PatientContextStore(QObject): first_value( diagnosis, "clinical_diagnosis", + "diagnosis_type_text", + "syndrome_type_text", "diagnosis_name", "disease_name", - default="中医糖代谢调理", - ) + default=first_value( + appointment, + "clinical_diagnosis", + "diagnosis_type_text", + default="", + ), + ), + "", ) chief = display_text( first_value(diagnosis, "chief_complaint", "complaint", default=""), "", ) + is_consultation_source = ( + str(first_value(appointment, "_queue_source", default="") or "") == "consultation" + ) status_code = _safe_int(first_value(appointment, "status", default=1), 1) status_map = {1: "待接诊", 2: "已取消", 3: "已完成", 4: "已过号"} + default_status = "在管诊单" if is_consultation_source else status_map.get(status_code, "待接诊") status_text = display_text( first_value( appointment, "status_desc", "status_text", - default=status_map.get(status_code, "待接诊"), + default=default_status, ) ) - appt_id = _safe_int(first_value(appointment, "id", "appointment_id", default=0)) + + raw_appt_id = _safe_int( + first_value( + appointment, + "real_appointment_id", + "appointment_id", + default=0 if is_consultation_source else first_value(appointment, "id", default=0), + ) + ) + appt_id = max(0, raw_appt_id) diag_id = _safe_int( first_value( diagnosis, "id", "diagnosis_id", - default=first_value(appointment, "diagnosis_id", "patient_id", default=0), + default=first_value(appointment, "diagnosis_id", default=0), ) ) pat_id = _safe_int( first_value( - appointment, - "source_patient_id", + diagnosis, "patient_id", - default=first_value(patient, "id", "source_patient_id", default=0), + "source_patient_id", + default=first_value( + appointment, + "source_patient_id", + "stable_patient_id", + "patient_id", + default=first_value(patient, "id", "source_patient_id", default=0), + ), ) ) raw: dict[str, Any] = {} - if isinstance(appointment, dict): + if isinstance(appointment, Mapping): raw.update(appointment) snapshot = PatientSnapshot( appointment_id=appt_id, @@ -249,7 +283,14 @@ class PatientContextStore(QObject): assistant_name=display_text(first_value(appointment, "assistant_name", default="—")), doctor_name=display_text(first_value(appointment, "doctor_name", default="—")), appointment_time=display_text( - first_value(appointment, "appointment_time_text", "appointment_time", default=""), + first_value( + appointment, + "appointment_time_text", + "appointment_time", + "appointment_date", + "diagnosis_date", + default="", + ), "", ), raw_record=raw, @@ -258,8 +299,72 @@ class PatientContextStore(QObject): return snapshot def update_from_row(self, row: Any) -> PatientSnapshot: - """Build and publish a lightweight snapshot when selecting a list/table row.""" + """Build and publish an accurate snapshot from Appointment, Consultation, or Patient row.""" if not row: return self._current_patient - return self.update_from_reception(row, row, row) + if isinstance(row, Appointment): + raw_map = dict(row.raw) if isinstance(row.raw, Mapping) else {} + raw_map.setdefault("id", row.id) + raw_map.setdefault("appointment_id", row.id) + raw_map.setdefault("diagnosis_id", row.diagnosis_id) + raw_map.setdefault("patient_id", row.source_patient_id or row.patient_id) + raw_map.setdefault("patient_name", row.patient_name) + return self.update_from_reception(raw_map, raw_map, raw_map) + + if isinstance(row, Consultation): + raw_map = dict(row.raw) if isinstance(row.raw, Mapping) else {} + appt_id = _safe_int( + first_value(raw_map, "latest_appointment_id", "appointment_id", default=0) + ) + synthetic = dict(raw_map) + synthetic["_queue_source"] = "consultation" + synthetic["real_appointment_id"] = appt_id + synthetic["diagnosis_id"] = row.id + synthetic["patient_id"] = _safe_int( + first_value(raw_map, "patient_id", "source_patient_id", default=row.patient_id or 0) + ) + synthetic["patient_name"] = row.patient_name + synthetic["status_desc"] = display_text( + first_value(raw_map, "appointment_status_desc", "status_desc", default="在管诊单") + ) + return self.update_from_reception(synthetic, raw_map, raw_map) + + if isinstance(row, Patient): + raw_map = dict(row.raw) if isinstance(row.raw, Mapping) else {} + appt_id = _safe_int( + first_value(raw_map, "latest_appointment_id", "appointment_id", default=0) + ) + diag_id = _safe_int( + first_value(raw_map, "latest_diagnosis_id", "diagnosis_id", default=row.latest_diagnosis_id or 0) + ) + synthetic = dict(raw_map) + synthetic["_queue_source"] = "consultation" + synthetic["real_appointment_id"] = appt_id + synthetic["diagnosis_id"] = diag_id + synthetic["patient_id"] = row.id + synthetic["patient_name"] = row.name + synthetic["status_desc"] = "在管患者" + diag_seed = dict(raw_map) + diag_seed["id"] = diag_id + diag_seed["patient_id"] = row.id + return self.update_from_reception(synthetic, raw_map, diag_seed) + + # Generic dict row heuristic + has_appt_fields = bool( + first_value(row, "appointment_time", "appointment_date", default="") + and str(first_value(row, "_queue_source", default="")) != "consultation" + ) + if has_appt_fields: + return self.update_from_reception(row, row, {}) + synthetic_dict = dict(row) if isinstance(row, Mapping) else {} + synthetic_dict.setdefault("_queue_source", "consultation") + synthetic_dict.setdefault( + "real_appointment_id", + _safe_int(first_value(row, "latest_appointment_id", "appointment_id", default=0)), + ) + synthetic_dict.setdefault( + "diagnosis_id", + _safe_int(first_value(row, "diagnosis_id", "latest_diagnosis_id", "id", default=0)), + ) + return self.update_from_reception(synthetic_dict, row, row) diff --git a/app/src/doctor_workstation/ui/theme.py b/app/src/doctor_workstation/ui/theme.py index 024e5c360..dd68e1211 100755 --- a/app/src/doctor_workstation/ui/theme.py +++ b/app/src/doctor_workstation/ui/theme.py @@ -899,6 +899,15 @@ QSlider::handle:horizontal { } QSlider::handle:horizontal:hover { border-color: $focus; } +QToolTip { + background-color: #162624; + color: #F2F7F6; + border: 1px solid #2D4A45; + border-radius: 8px; + padding: 7px 11px; + font-size: 12px; +} + QLabel#StatusBadge { padding: 2px 8px; border: 1px solid transparent; @@ -1322,21 +1331,12 @@ def _apply_group( def _register_preferred_cjk_fonts() -> str: - """Prefer the shipped outline font, with native CJK faces as a fallback.""" + """Prefer native ClearType/CoreText CJK UI faces on desktop OSes; use bundled VF as fallback.""" app = QApplication.instance() registered = getattr(app, "_doctor_bundled_font_family", None) if registered: return registered - bundled_font = resource_path("fonts", "NotoSansSC-VF.ttf") - if bundled_font.is_file(): - font_id = QFontDatabase.addApplicationFont(str(bundled_font)) - families = QFontDatabase.applicationFontFamilies(font_id) if font_id >= 0 else [] - if families: - family = families[0] - if app is not None: - app._doctor_bundled_font_family = family - return family platform_families = { "win32": ("Microsoft YaHei UI", "Microsoft YaHei"), @@ -1356,9 +1356,25 @@ def _register_preferred_cjk_fonts() -> str: font_id = QFontDatabase.addApplicationFont(str(font_path)) if font_id >= 0 and QFontDatabase.applicationFontFamilies(font_id): available.update(QFontDatabase.applicationFontFamilies(font_id)) - for family in (*preferred, "Arial Unicode MS"): + + for family in preferred: if family in available: + if app is not None: + app._doctor_bundled_font_family = family return family + + bundled_font = resource_path("fonts", "NotoSansSC-VF.ttf") + if bundled_font.is_file(): + font_id = QFontDatabase.addApplicationFont(str(bundled_font)) + families = QFontDatabase.applicationFontFamilies(font_id) if font_id >= 0 else [] + if families: + family = families[0] + if app is not None: + app._doctor_bundled_font_family = family + return family + + if "Arial Unicode MS" in available: + return "Arial Unicode MS" return QApplication.font().family() @@ -1438,16 +1454,15 @@ def allow_dialog_resize(dialog: QDialog) -> None: def mark_business_dialog(dialog: QDialog, object_name: str | None = None) -> None: - """Opt a business subwindow into the shared visual contract. - - The helper intentionally does not change modality, ownership or result - handling. It only supplies stable styling metadata, semantic button roles - and window affordances, so existing workflows keep their original behavior. - """ + """Opt a business subwindow into the shared visual contract and Spatial Wing engine.""" if object_name and not dialog.objectName(): dialog.setObjectName(object_name) dialog.setProperty("businessDialog", True) + if not isinstance(dialog, (QMessageBox, QInputDialog, QFileDialog)): + from .spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(dialog) allow_dialog_resize(dialog) for button_box in dialog.findChildren(QDialogButtonBox): _polish_dialog_buttons(button_box) @@ -1568,9 +1583,38 @@ class _BusinessDialogStyleFilter(QObject): if isinstance(watched, QDialogButtonBox): _polish_dialog_buttons(watched) elif isinstance(watched, QDialog) and event_type == QEvent.Type.Polish: - # Window flags can only be changed before the dialog is on screen, - # so dynamically-created dialogs get their affordances at polish - # time rather than when they are already visible. + if isinstance(watched, (QMessageBox, QInputDialog)): + from .spatial_wings import find_spatial_shell + + if find_spatial_shell(watched) is not None and not watched.isVisible(): + watched.setProperty("doctorSkipOpenGeometry", True) + watched.setWindowFlags( + Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint + ) + watched.setStyleSheet( + "QMessageBox, QInputDialog {" + " background-color: #FFFFFF;" + " border: 2px solid #B7D4CC;" + " border-radius: 16px;" + " padding: 10px;" + "}" + "QMessageBox QPushButton, QInputDialog QPushButton {" + " min-height: 34px; padding: 0 18px; border-radius: 17px;" + " border: 1px solid #D5E4DF; background-color: #F4F8F7;" + " color: #172B29; font-weight: 600;" + "}" + "QMessageBox QPushButton:hover, QInputDialog QPushButton:hover {" + " background-color: #E3F3EE; border-color: #96CBC0; color: #0E6F5C;" + "}" + ) + elif ( + not isinstance(watched, QFileDialog) + and watched.metaObject().className() != "QPrintDialog" + and not watched.property("skipSpatialWing") + ): + from .spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(watched) if not self._is_native_or_overlay(watched): allow_dialog_resize(watched) elif isinstance(watched, QDialog) and event_type == QEvent.Type.Show: @@ -1601,6 +1645,9 @@ class _BusinessDialogStyleFilter(QObject): def _install_business_dialog_styling(app: QApplication) -> None: + from .spatial_wings import install_global_qdialog_wing_hooks + + install_global_qdialog_wing_hooks() interactions.install_tactile_interactions(app) existing = getattr(app, "_doctor_business_dialog_style_filter", None) if existing is not None: diff --git a/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py b/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py index 04ea25aad..76eda76e9 100644 --- a/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py +++ b/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py @@ -15,7 +15,7 @@ import math import re from collections.abc import Mapping, Sequence from dataclasses import dataclass -from datetime import date, timedelta +from datetime import date, datetime, timedelta from typing import Any from ..widgets import display_text, first_value @@ -74,6 +74,52 @@ def _is_normal_or_negated(text: str) -> bool: return norm.startswith(("无", "否认", "未见", "未发现")) +def _clean_date_iso(raw: Any) -> str: + """Return a valid YYYY-MM-DD string, rejecting 0, '0', 1970-01-01, or placeholders.""" + + if raw in (None, "", 0, "0", False, "—", "-"): + return "" + if isinstance(raw, (int, float)) and raw >= 946684800: + try: + return datetime.fromtimestamp(float(raw)).strftime("%Y-%m-%d") + except (OSError, OverflowError, ValueError): + return "" + text = str(raw).strip() + if text in {"0", "0000-00-00", "1970-01-01", "None", "null", "—", "-"}: + return "" + if text.isdigit() and int(text) >= 946684800: + try: + return datetime.fromtimestamp(int(text)).strftime("%Y-%m-%d") + except (OSError, OverflowError, ValueError): + return "" + if len(text) >= 10 and text[4] in {"-", "/"} and text[7] in {"-", "/"}: + iso = text[:10].replace("/", "-") + return "" if iso.startswith(("0000", "1970-01-01")) else iso + return "" + + +def _extract_intake_kv(raw_text: str) -> dict[str, str]: + """Extract structured key:value pairs pasted into intake text (e.g. '在用药物:没有吃药').""" + + result: dict[str, str] = {} + if not raw_text: + return result + tokens = re.split(r"[\r\n;;]+", raw_text) + for line in tokens: + # Also split inline multi-pair intake lines like '姓名: 王进花 年龄: 67 患病时长: 一年多' + sub_parts = re.split( + r"\s+(?=(?:姓名|年龄|性别|患者空腹血糖|空腹血糖|餐后血糖|在用药物|目前用药|降糖药|患病时长|病程|既往史|过敏史)\s*[::])", + line.strip(), + ) + for seg in sub_parts: + if ":" in seg or ":" in seg: + k, v = re.split(r"[::]", seg, maxsplit=1) + ck, cv = k.strip(), v.strip() + if ck and cv and cv not in {"—", "-", "无记录"}: + result[ck] = cv + return result + + @dataclass(frozen=True) class ProgressionPoint: label: str @@ -82,6 +128,7 @@ class ProgressionPoint: highlight: bool = False alert: bool = False value_hint: str = "" + value_text: str = "" @dataclass(frozen=True) @@ -106,6 +153,7 @@ class DiurnalSlot: height_ratio: float state: str # "empty" | "normal" | "mint" | "alert" tooltip: str = "" + value_text: str = "" @dataclass(frozen=True) @@ -116,6 +164,8 @@ class VitalMiniBrick: unit: str tooltip: str = "" alert: bool = False + date_label: str = "" + field_key: str = "" @dataclass(frozen=True) @@ -134,6 +184,7 @@ class DiurnalStabilityVM: overnight_peak_hint: str slots: tuple[DiurnalSlot, ...] vitals: tuple[VitalMiniBrick, ...] + missing_hint: str = "" @dataclass(frozen=True) @@ -251,30 +302,21 @@ def _build_empty_snapshot(active_ai_model: str = "qwen") -> CockpitSnapshotVM: model_label = MODEL_LABELS.get(active_ai_model, "千问") today = date.today() - start_21 = today - timedelta(days=20) - empty_bars = tuple( - ProgressionPoint(label=f"#{i + 1}", ratio=0.18, recorded=False, value_hint="尚未选择患者") - for i in range(12) - ) - empty_slots = tuple( - DiurnalSlot( - time_label=(today - timedelta(days=13 - i)).strftime("%m-%d"), - height_ratio=0.18, - state="empty", - tooltip="尚未选择患者", - ) - for i in range(14) - ) + start_14 = today - timedelta(days=13) + empty_bars: tuple[ProgressionPoint, ...] = () + empty_slots: tuple[DiurnalSlot, ...] = () empty_days = tuple( JourneyDayCell( day_num=i + 1, - date_iso=(start_21 + timedelta(days=i)).isoformat(), - label_text=str((start_21 + timedelta(days=i)).day), - state="today" if i == 20 else "planned", - tooltip=f"{(start_21 + timedelta(days=i)).isoformat()} · 请先选择患者", + date_iso=(start_14 + timedelta(days=i)).isoformat(), + label_text=f"{(start_14 + timedelta(days=i)).month}/{(start_14 + timedelta(days=i)).day}" + if (start_14 + timedelta(days=i)).day == 1 + else str((start_14 + timedelta(days=i)).day), + state="today" if i == 13 else "planned", + tooltip=f"{(start_14 + timedelta(days=i)).isoformat()} · 请先选择患者", has_dot=False, ) - for i in range(21) + for i in range(14) ) empty_twin = SyndromeTwinVM( has_patient=False, @@ -318,30 +360,26 @@ def _build_empty_snapshot(active_ai_model: str = "qwen") -> CockpitSnapshotVM: overnight_title="近 14 天日常健康打卡记录", overnight_peak_hint="暂无患者数据", slots=empty_slots, - vitals=( - VitalMiniBrick("activity", "血压 (高压/低压)", "—", "mmHg"), - VitalMiniBrick("patients", "身高体重 / BMI", "—", ""), - VitalMiniBrick("prescriptions", "现用西药 / 胰岛素", "—", ""), - ), + vitals=(), + missing_hint="从右侧队列选择患者后展示实测指标与日期", ), twin_sanjiao=empty_twin, twin_organ=SyndromeTwinVM(**{**empty_twin.__dict__, "mode_key": "organ"}), twin_tcm=SyndromeTwinVM(**{**empty_twin.__dict__, "mode_key": "tcm"}), journey=CareJourneyVM( - title="近 21 天健康打卡与复诊", + title="近 14 天健康打卡与复诊", plan_subtitle="关联小程序自录血糖、饮食、运动与复诊药尽提醒", primary_metric_text="—", - total_unit_text="/ 21 天有记录", + total_unit_text="/ 14 天有记录", status_pill="待选患者", status_tone="neutral", end_capsule_text="复诊待查", phases=( - JourneyPhaseSpan("W1", "前第 3 周", f"{start_21.strftime('%m-%d')}起", 1, 7, False), - JourneyPhaseSpan("W2", "前第 2 周", f"{(start_21 + timedelta(days=7)).strftime('%m-%d')}起", 8, 14, False), - JourneyPhaseSpan("W3", "最近 7 天", f"{(start_21 + timedelta(days=14)).strftime('%m-%d')}–今日", 15, 21, True), + JourneyPhaseSpan("W1", "上周基线", f"{start_14.strftime('%m-%d')}起", 1, 7, False), + JourneyPhaseSpan("W2", "本周窗口", f"{(start_14 + timedelta(days=7)).strftime('%m-%d')}–今日", 8, 14, True), ), days=empty_days, - milestones=((1, start_21.strftime("%m-%d")), (11, (start_21 + timedelta(days=10)).strftime("%m-%d")), (21, "今日")), + milestones=((1, start_14.strftime("%m-%d")), (8, (start_14 + timedelta(days=7)).strftime("%m-%d")), (14, "今日")), ), aurora=ObsidianAuroraVM( has_patient=False, @@ -462,55 +500,69 @@ def derive_cockpit_snapshot( sorted_blood = sorted(blood_rows, key=_rec_sort_key) - # ── 1. Left Top Card: REAL Fasting Blood Glucose (mmol/L) ──────────── + # ── 1. Left Top Card: REAL Fasting Blood Glucose (mmol/L) — ONLY Real Points + Dates ── + intake_blob = "\n".join( + p + for p in ( + _clean_text(first_value(diag, "chief_complaint", "complaint", "symptoms")), + _clean_text(first_value(diag, "present_illness", "present_illness_history")), + _clean_text(first_value(appt, "chief_complaint", "symptoms")), + ) + if p + ) + intake_kv = _extract_intake_kv(intake_blob) + + diag_date_str = ( + _clean_date_iso(first_value(diag, "diagnosis_date")) + or _clean_date_iso(first_value(appt, "appointment_date", "latest_appointment_date")) + or _clean_date_iso(first_value(diag, "create_time", "update_time")) + or _clean_date_iso(first_value(appt, "create_time")) + ) + base_date_short = diag_date_str[5:] if len(diag_date_str) >= 10 else "建档" + fasting_points: list[tuple[str, float, str]] = [] diag_fasting_raw = first_value(diag, "fasting_blood_sugar", "fasting_glucose", default=None) + if diag_fasting_raw in (None, "", 0, "0"): + kv_f = intake_kv.get("患者空腹血糖") or intake_kv.get("空腹血糖") or "" + if kv_f: + m_num = re.search(r"(\d+(?:\.\d+)?)", kv_f) + diag_fasting_raw = m_num.group(1) if m_num else kv_f diag_fasting_num = _parse_positive_float(diag_fasting_raw) diag_fasting_text = _clean_text(diag_fasting_raw) - diag_date_str = _clean_text( - first_value(diag, "diagnosis_date", default=first_value(appt, "appointment_date", default="")) - )[:10] for row in sorted_blood: f_num = _parse_positive_float(first_value(row, "fasting_blood_sugar", "fasting_glucose", default=None)) if f_num is not None: - r_date = str(first_value(row, "record_date", "date", default="") or "")[:10] + r_date = _clean_date_iso(first_value(row, "record_date", "date", "create_time")) r_time = str(first_value(row, "record_time", default="") or "")[:5] src_tag = "患者自录" if str(first_value(row, "source", default="0")) == "1" else "随访录入" - label_short = r_date[5:] if len(r_date) >= 10 else "记录" - tip = f"{r_date} {r_time} · 空腹血糖 {f_num:g} mmol/L({src_tag})".strip() + label_short = r_date[5:] if len(r_date) >= 10 else base_date_short + tip = f"{r_date or base_date_short} {r_time} · 空腹血糖 {f_num:g} mmol/L({src_tag})".strip() fasting_points.append((label_short, f_num, tip)) - if not fasting_points and diag_fasting_num is not None: - lbl = diag_date_str[5:] if len(diag_date_str) >= 10 else "建档" - fasting_points.append((lbl, diag_fasting_num, f"病历建档空腹血糖:{diag_fasting_num:g} mmol/L")) + if diag_fasting_num is not None: + lbl = base_date_short + tip_base = f"{diag_date_str or '建档'} · 病历建档空腹血糖:{diag_fasting_num:g} mmol/L" + if not fasting_points: + fasting_points.append((lbl, diag_fasting_num, tip_base)) + elif fasting_points[0][0] != lbl and abs(fasting_points[0][1] - diag_fasting_num) > 0.05: + fasting_points.insert(0, (f"{lbl}建档" if len(lbl) <= 5 else lbl, diag_fasting_num, tip_base)) - # Build 12-slot chart: ONLY real points are filled; unrecorded slots stay empty! - recent_fasting = fasting_points[-12:] - scale_max = max([14.0, *(pt[1] * 1.12 for pt in recent_fasting)]) + # ONLY real recorded measurements — ZERO empty gray placeholder bars! + recent_fasting = fasting_points[-8:] + scale_max = max([14.0, *(pt[1] * 1.15 for pt in recent_fasting)]) bars: list[ProgressionPoint] = [] - pad_empty = 12 - len(recent_fasting) - for idx in range(pad_empty): - bars.append( - ProgressionPoint( - label="", - ratio=0.14, - recorded=False, - highlight=False, - alert=False, - value_hint="无更早空腹血糖打卡记录", - ) - ) for idx, (lbl, val, tip) in enumerate(recent_fasting): is_latest = idx == len(recent_fasting) - 1 bars.append( ProgressionPoint( - label=lbl, - ratio=max(0.18, min(0.96, val / scale_max)), + label=lbl or "建档", + ratio=max(0.20, min(0.92, val / scale_max)), recorded=True, highlight=is_latest, alert=(val >= 7.0), value_hint=tip, + value_text=f"{val:g}", ) ) @@ -525,18 +577,18 @@ def derive_cockpit_snapshot( first_f = recent_fasting[0][1] diff = latest_f - first_f sign = "+" if diff > 0 else "" - f_caption = f"共 {len(fasting_points)} 次 · 较首测 {sign}{diff:.1f}" + f_caption = f"共 {len(fasting_points)} 次实测 · 较首测 {sign}{diff:.1f}" else: - f_caption = "病历实测基线值" - left_foot = recent_fasting[0][0] or "首测" - right_foot = f"最新 ({recent_fasting[-1][0]})" + f_caption = f"{recent_fasting[0][0]} 建档实测" + left_foot = f"首测 {recent_fasting[0][0]}" + right_foot = f"最新 {recent_fasting[-1][0]}" elif diag_fasting_text: f_primary = "有描述" f_unit = "" f_badge = "文本记录" f_tone = "neutral" f_caption = _clip(diag_fasting_text, 14) - left_foot = "无数值打卡" + left_foot = base_date_short right_foot = "见病历描述" else: f_primary = "未记录" @@ -544,8 +596,8 @@ def derive_cockpit_snapshot( f_badge = "待补录" f_tone = "neutral" f_caption = "暂无空腹血糖数值" - left_foot = "近21天无记录" - right_foot = "可在日常记录新增" + left_foot = "暂无实测日期" + right_foot = "点击进入日常记录新增 ↗" hba1c_num = _parse_positive_float(first_value(diag, "hba1c", "glycosylated_hemoglobin", default=None)) top_sub_badge = f"糖化 {hba1c_num:g}%" if hba1c_num is not None else "参考 < 7.0 mmol/L" @@ -559,41 +611,49 @@ def derive_cockpit_snapshot( delta_tone=f_tone, delta_caption=f_caption, target_label="7.0 mmol/L 控制线", - target_ratio=min(0.88, 7.0 / scale_max), + target_ratio=min(0.84, 7.0 / scale_max), bars=tuple(bars), left_foot=left_foot, right_foot=right_foot, ) - # ── 2. Left Bottom Card: REAL Postprandial 2h Glucose & Vitals ─────── + # ── 2. Left Bottom Card: REAL Postprandial 2h Glucose & Dated Clinical Vitals ── post_points: list[tuple[str, float, str]] = [] other_points: list[tuple[str, float, str]] = [] latest_bp_from_blood = "" + latest_bp_date = "" + latest_bp_alert = False latest_west_med = "" + latest_med_date = "" latest_insulin = "" for row in sorted_blood: - r_date = str(first_value(row, "record_date", "date", default="") or "")[:10] + r_date = _clean_date_iso(first_value(row, "record_date", "date", "create_time")) + d_disp = r_date[5:] if len(r_date) >= 10 else base_date_short p_num = _parse_positive_float(first_value(row, "postprandial_blood_sugar", "postprandial_glucose", default=None)) if p_num is not None: - post_points.append((r_date, p_num, f"{r_date} · 餐后2h血糖 {p_num:g} mmol/L")) + post_points.append((d_disp, p_num, f"{r_date or d_disp} · 餐后2h血糖 {p_num:g} mmol/L")) o_num = _parse_positive_float(first_value(row, "other_blood_sugar", default=None)) if o_num is not None: - other_points.append((r_date, o_num, f"{r_date} · 随机/其他血糖 {o_num:g} mmol/L")) + other_points.append((d_disp, o_num, f"{r_date or d_disp} · 随机/其他血糖 {o_num:g} mmol/L")) sp = _parse_positive_float(first_value(row, "systolic_pressure", default=None)) dp = _parse_positive_float(first_value(row, "diastolic_pressure", default=None)) if sp is not None and dp is not None: latest_bp_from_blood = f"{int(sp)}/{int(dp)}" + latest_bp_date = d_disp + latest_bp_alert = sp >= 140 or dp >= 90 wm = _clean_text(first_value(row, "western_medicine", default="")) if wm: latest_west_med = wm + latest_med_date = d_disp ins = _clean_text(first_value(row, "insulin", default="")) if ins: latest_insulin = ins + latest_med_date = d_disp diag_post_num = _parse_positive_float(first_value(diag, "postprandial_blood_sugar", default=None)) if not post_points and diag_post_num is not None: - post_points.append((diag_date_str, diag_post_num, f"病历建档餐后血糖 {diag_post_num:g} mmol/L")) + post_points.append((base_date_short, diag_post_num, f"{diag_date_str or '建档'} · 病历建档餐后血糖 {diag_post_num:g} mmol/L")) if post_points: latest_p = post_points[-1][1] @@ -601,69 +661,73 @@ def derive_cockpit_snapshot( p_unit = "mmol/L" p_high = latest_p >= 11.1 p_badge = "餐后偏高 ↑" if p_high else "餐后达标" - p_caption = f"最近实测 ({post_points[-1][0][5:] or '建档'}) · 共 {len(post_points)} 次" + p_caption = f"最近实测 ({post_points[-1][0]}) · 共 {len(post_points)} 次" has_p_marker = True p_marker_ratio = max(0.06, min(0.95, (latest_p - 4.4) / (13.0 - 4.4))) elif other_points: latest_o = other_points[-1][1] p_primary = f"{latest_o:g}" p_unit = "mmol/L" - p_badge = "其他时段血糖" - p_caption = f"最近随机血糖 ({other_points[-1][0][5:]}) · 未测餐后2h" + p_badge = "随机血糖" + p_caption = f"最近实测 ({other_points[-1][0]}) · 未测餐后2h" has_p_marker = True p_marker_ratio = max(0.06, min(0.95, (latest_o - 4.4) / (13.0 - 4.4))) else: p_primary = "未记录" p_unit = "" p_badge = "参考 < 11.1" - p_caption = "暂无餐后2h血糖记录" + p_caption = "暂无餐后2h血糖实测" has_p_marker = False p_marker_ratio = 0.0 - # Build Real 14-Day Daily Check-in Strip (blood / diet / exercise / tracking) + # Build Real Check-in Records: ONLY dates that actually have recorded data! today = date.today() blood_by_date: dict[str, list[Any]] = {} for r in sorted_blood: - k = str(first_value(r, "record_date", "date", default="") or "")[:10] + k = _clean_date_iso(first_value(r, "record_date", "date", "create_time")) if k: blood_by_date.setdefault(k, []).append(r) diet_dates = { - str(first_value(r, "record_date", "date", default="") or "")[:10] + k for r in diet_rows - if any(_clean_text(first_value(r, m, f"{m}_foods", default="")) for m in ("breakfast", "lunch", "dinner")) + if (k := _clean_date_iso(first_value(r, "record_date", "date", "create_time"))) + and any(_clean_text(first_value(r, m, f"{m}_foods", default="")) for m in ("breakfast", "lunch", "dinner")) } exercise_by_date: dict[str, str] = {} for r in exercise_rows: - k = str(first_value(r, "record_date", "date", default="") or "")[:10] + k = _clean_date_iso(first_value(r, "record_date", "date", "create_time")) ex_t = _clean_text(first_value(r, "exercise_type", default="")) dur = first_value(r, "duration", default=None) if k and (ex_t or dur): exercise_by_date[k] = f"{ex_t} {dur}分钟".strip() if dur else (ex_t or "已运动") note_by_date: dict[str, str] = {} for n in tracking_notes or (): - k = str(first_value(n, "note_date", "record_date", "create_time", default="") or "")[:10] + k = _clean_date_iso(first_value(n, "note_date", "record_date", "create_time")) c = _clean_text(first_value(n, "content", "tracking_content", default="")) if k and c: note_by_date[k] = c - slots_14: list[DiurnalSlot] = [] - high_days_14 = 0 - recorded_days_14 = 0 - for i in range(14): - d_obj = today - timedelta(days=13 - i) - d_iso = d_obj.isoformat() + all_active_dates = sorted( + set(blood_by_date.keys()) | diet_dates | set(exercise_by_date.keys()) | set(note_by_date.keys()) + ) + recorded_slots: list[DiurnalSlot] = [] + high_days_count = 0 + for d_iso in all_active_dates[-7:]: b_list = blood_by_date.get(d_iso, []) f_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "fasting_blood_sugar", default=None))) is not None] p_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "postprandial_blood_sugar", default=None))) is not None] + o_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "other_blood_sugar", default=None))) is not None] has_diet = d_iso in diet_dates ex_txt = exercise_by_date.get(d_iso, "") tr_txt = note_by_date.get(d_iso, "") tip_parts = [d_iso] - if f_vals: - tip_parts.append(f"空腹 {f_vals[-1]:g}") if p_vals: tip_parts.append(f"餐后 {p_vals[-1]:g}") + if f_vals: + tip_parts.append(f"空腹 {f_vals[-1]:g}") + if o_vals: + tip_parts.append(f"随机 {o_vals[-1]:g}") if has_diet: tip_parts.append("已记饮食") if ex_txt: @@ -673,44 +737,57 @@ def derive_cockpit_snapshot( max_f = max(f_vals, default=0.0) max_p = max(p_vals, default=0.0) + val_tag = ( + f"{p_vals[-1]:g}" + if p_vals + else f"{f_vals[-1]:g}" + if f_vals + else f"{o_vals[-1]:g}" + if o_vals + else "运动" + if ex_txt + else "饮食" + if has_diet + else "随访" + ) if max_f >= 7.0 or max_p >= 11.1: - high_days_14 += 1 - recorded_days_14 += 1 + high_days_count += 1 peak_ratio = max(max_f / 14.0, max_p / 18.0) - slots_14.append( - DiurnalSlot(d_iso[5:], max(0.55, min(1.0, peak_ratio)), "alert", " · ".join(tip_parts)) + recorded_slots.append( + DiurnalSlot(d_iso[5:], max(0.54, min(0.96, peak_ratio)), "alert", " · ".join(tip_parts), val_tag) ) - elif f_vals or p_vals: - recorded_days_14 += 1 - norm_ratio = max(max_f / 14.0, max_p / 18.0, 0.48) - slots_14.append( - DiurnalSlot(d_iso[5:], min(0.85, norm_ratio), "mint", " · ".join(tip_parts)) + elif p_vals or f_vals or o_vals: + norm_ratio = max(max_f / 14.0, max_p / 18.0, 0.46) + recorded_slots.append( + DiurnalSlot(d_iso[5:], min(0.86, norm_ratio), "mint", " · ".join(tip_parts), val_tag) ) - elif has_diet or ex_txt or tr_txt: - recorded_days_14 += 1 - slots_14.append(DiurnalSlot(d_iso[5:], 0.42, "normal", " · ".join(tip_parts))) else: - slots_14.append(DiurnalSlot(d_iso[5:], 0.16, "empty", f"{d_iso} · 当日无打卡记录")) + recorded_slots.append( + DiurnalSlot(d_iso[5:], 0.44, "normal", " · ".join(tip_parts), val_tag) + ) - # Real Vitals (BP, Height/Weight/BMI, Current Meds) + # Real Vitals & Clinical Facts: ONLY show items that actually have data + date underneath! sys_num = _parse_positive_float( first_value(diag, "systolic_pressure", "systolic", "high_pressure", default=first_value(pat, "systolic_pressure", default=None)) ) dia_num = _parse_positive_float( first_value(diag, "diastolic_pressure", "diastolic", "low_pressure", default=first_value(pat, "diastolic_pressure", default=None)) ) - if sys_num is not None and dia_num is not None: - bp_val = f"{int(sys_num)}/{int(dia_num)}" - bp_unit = "mmHg" - bp_alert = sys_num >= 140 or dia_num >= 90 - elif latest_bp_from_blood: + if latest_bp_from_blood: bp_val = latest_bp_from_blood bp_unit = "mmHg" - bp_alert = False + bp_date = f"{latest_bp_date} 实测" + bp_alert = latest_bp_alert + elif sys_num is not None and dia_num is not None: + bp_val = f"{int(sys_num)}/{int(dia_num)}" + bp_unit = "mmHg" + bp_date = f"{base_date_short} 建档" + bp_alert = sys_num >= 140 or dia_num >= 90 else: raw_bp = _clean_text(first_value(diag, "blood_pressure", default="")) bp_val = raw_bp if raw_bp else "—" bp_unit = "mmHg" if raw_bp and "mmhg" not in raw_bp.lower() else "" + bp_date = f"{base_date_short} 建档" bp_alert = False h_num = _parse_positive_float(first_value(diag, "height", default=first_value(pat, "height", default=None))) @@ -719,12 +796,12 @@ def derive_cockpit_snapshot( bmi = w_num / ((h_num / 100.0) ** 2) hw_val = f"{bmi:.1f}" hw_unit = f"BMI ({int(w_num)}kg)" - hw_tip = f"身高 {h_num:g} cm · 体重 {w_num:g} kg · BMI {bmi:.1f}" + hw_tip = f"{diag_date_str or '建档'} · 身高 {h_num:g} cm · 体重 {w_num:g} kg · BMI {bmi:.1f}" hw_alert = bmi >= 24.0 or bmi < 18.5 elif w_num: hw_val = f"{w_num:g}" hw_unit = "kg" - hw_tip = f"体重 {w_num:g} kg(身高未填)" + hw_tip = f"{diag_date_str or '建档'} · 体重 {w_num:g} kg(身高未填)" hw_alert = False else: hw_val = "—" @@ -738,10 +815,127 @@ def derive_cockpit_snapshot( "current_medications", "current_medicine", "current_medication", - default=latest_insulin or latest_west_med, + default=latest_insulin + or latest_west_med + or intake_kv.get("在用药物") + or intake_kv.get("目前用药") + or intake_kv.get("降糖药") + or "", ) ) - meds_short = _clip(meds_full, 7) if meds_full else "—" + meds_date = f"{latest_med_date} 随访" if latest_med_date else f"{base_date_short} 问诊" + course_early = _clean_text( + first_value( + diag, + "disease_course_text", + "diabetes_discovery_year_text", + "diabetes_discovery_year", + "diabetes_history_text", + default=intake_kv.get("患病时长") or intake_kv.get("病程") or "", + ) + ) + + real_vitals: list[VitalMiniBrick] = [] + missing_vitals: list[str] = [] + if p_primary == "未记录": + missing_vitals.append("餐后血糖") + if bp_val != "—": + real_vitals.append( + VitalMiniBrick( + "activity", + "实测血压", + bp_val, + bp_unit, + f"{bp_date} · 血压 {bp_val} {bp_unit}".strip(), + bp_alert, + date_label=bp_date, + field_key="systolic_pressure", + ) + ) + else: + missing_vitals.append("血压") + + if hw_val != "—": + real_vitals.append( + VitalMiniBrick( + "patients", + "体质量 BMI", + hw_val, + hw_unit, + hw_tip, + hw_alert, + date_label=f"{base_date_short} 建档", + field_key="weight", + ) + ) + else: + missing_vitals.append("身高体重") + + if meds_full: + real_vitals.append( + VitalMiniBrick( + "prescriptions", + "在用降糖药", + _clip(meds_full, 10), + "", + f"{meds_date} · {meds_full}", + False, + date_label=meds_date, + field_key="current_medications", + ) + ) + else: + missing_vitals.append("在用药物") + + # Surface additional real recorded clinical indicators when core vitals are sparse + if len(real_vitals) < 3 and course_early: + real_vitals.append( + VitalMiniBrick( + "consultations", + "患病病程", + _clip(course_early, 10), + "", + f"{base_date_short} 建档 · 病程:{course_early}", + False, + date_label=f"{base_date_short} 建档", + field_key="diabetes_discovery_year", + ) + ) + if len(real_vitals) < 3 and diag_fasting_num is not None and p_primary == "未记录": + real_vitals.append( + VitalMiniBrick( + "activity", + "空腹血糖基线", + f"{diag_fasting_num:g}", + "mmol/L", + f"{base_date_short} 建档 · 空腹血糖 {diag_fasting_num:g} mmol/L", + diag_fasting_num >= 7.0, + date_label=f"{base_date_short} 建档", + field_key="fasting_blood_sugar", + ) + ) + age_disp = _clean_text(first_value(diag, "age", default=first_value(pat, "age", default=first_value(appt, "age", default=intake_kv.get("年龄", ""))))) + visit_disp = _clean_text(first_value(diag, "diagnosis_type_text", default=first_value(appt, "diagnosis_type_text", "status_desc", default=""))) + if len(real_vitals) < 3 and (age_disp or visit_disp): + demo_v = " · ".join(p for p in (f"{age_disp}岁" if age_disp and not age_disp.endswith("岁") else age_disp, visit_disp) if p) + real_vitals.append( + VitalMiniBrick( + "patients", + "接诊档案", + _clip(demo_v, 10), + "", + f"{base_date_short} · {demo_v}", + False, + date_label=f"{base_date_short} 挂号", + field_key="age", + ) + ) + + missing_hint_txt = ( + f"待补采:{'、'.join(missing_vitals[:3])} · 点击补录 ↗" + if missing_vitals + else "" + ) diurnal_vm = DiurnalStabilityVM( title="餐后2h血糖与体征", @@ -754,18 +948,15 @@ def derive_cockpit_snapshot( range_min_text="4.4", range_target_text="7.8 餐后参考", range_max_text="11.1", - overnight_title="近 14 天日常打卡轨迹", + overnight_title="实测日常打卡记录", overnight_peak_hint=( - f"偏高 {high_days_14} 天 / 已记 {recorded_days_14} 天" - if recorded_days_14 > 0 - else "近 14 天暂无打卡记录" - ), - slots=tuple(slots_14), - vitals=( - VitalMiniBrick("activity", "血压 (高压/低压)", bp_val, bp_unit, f"实测血压:{bp_val} {bp_unit}".strip(), bp_alert), - VitalMiniBrick("patients", "体质量 BMI", hw_val, hw_unit, hw_tip, hw_alert), - VitalMiniBrick("prescriptions", "在用降糖药", meds_short, "", meds_full or "暂未录入在用药物", False), + f"共 {len(all_active_dates)} 天有记录 · 偏高 {high_days_count} 天" + if recorded_slots + else "暂无日常打卡记录" ), + slots=tuple(recorded_slots), + vitals=tuple(real_vitals[:4]), + missing_hint=missing_hint_txt, ) # ── 3. Center Stage: 100% Real Body Symptom & Clinical Case Map ────── @@ -801,7 +992,6 @@ def derive_cockpit_snapshot( if not present: return ("未采集", "neutral", "病历暂未填写该部位问诊项", 0.0) abnormal = [(lbl, val) for lbl, val in present if not _is_normal_or_negated(val)] - full = ";".join(f"{lbl}:{val}" for lbl, val in present) if abnormal: ab_line = " · ".join(f"{lbl}:{val}" for lbl, val in abnormal) return ("阳性体征", "coral", ab_line, 0.85) @@ -1015,15 +1205,24 @@ def derive_cockpit_snapshot( if rx_list: latest_rx = rx_list[0] - herbs = first_value(latest_rx, "herbs", default=[]) or [] + rx_title = _clean_text( + first_value(latest_rx, "prescription_name", "formula_name", "name", default="") + ) + herbs = first_value(latest_rx, "herbs", "medicines", default=[]) or [] herb_names = [ f"{_clean_text(first_value(h, 'name', 'medicine_name'))}{_clean_text(first_value(h, 'dosage', 'amount'))}g" for h in herbs[:5] if _clean_text(first_value(h, "name", "medicine_name")) ] - rx_herbs_summary = "、".join(herb_names) if herb_names else f"共 {len(herbs)} 味中药" - med_days = first_value(latest_rx, "medication_days", "usage_days", "dose_count", default="") - rx_badge = f"已开 {med_days}天" if med_days else f"共 {len(rx_list)} 张处方" + herb_part = "、".join(herb_names) if herb_names else (f"共 {len(herbs)} 味" if herbs else "") + rx_herbs_summary = ( + " · ".join(p for p in (rx_title, herb_part) if p) + or f"已开电子处方 #{first_value(latest_rx, 'id', default=1)}" + ) + med_days = first_value( + latest_rx, "medication_days", "usage_days", "dose_count", "dosage_count", default="" + ) + rx_badge = f"已开 {med_days}剂" if med_days else f"共 {len(rx_list)} 张处方" rx_tone = "emerald" elif has_rx: rx_herbs_summary = "已关联有效电子处方(可在已开处方查看明细)" @@ -1098,12 +1297,12 @@ def derive_cockpit_snapshot( recorded_Zone_flags=(z_head_heat, z_oral_heat, z_abd_heat, z_low_heat), ) - # ── 4. Bottom 21-Day Real Check-in & Revisit Due Track ─────────────── - start_21 = today - timedelta(days=20) - days_21: list[JourneyDayCell] = [] + # ── 4. Bottom 14-Day Real Check-in & Revisit Due Track ─────────────── + start_14 = today - timedelta(days=13) + days_14: list[JourneyDayCell] = [] checked_in_days = 0 - for idx in range(21): - d_obj = start_21 + timedelta(days=idx) + for idx in range(14): + d_obj = start_14 + timedelta(days=idx) d_iso = d_obj.isoformat() b_list = blood_by_date.get(d_iso, []) f_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "fasting_blood_sugar", default=None))) is not None] @@ -1142,25 +1341,29 @@ def derive_cockpit_snapshot( else: cell_state = "planned" - days_21.append( + days_14.append( JourneyDayCell( day_num=idx + 1, date_iso=d_iso, - label_text=str(d_obj.day), + label_text=f"{d_obj.month}/{d_obj.day}" if d_obj.day == 1 else str(d_obj.day), state=cell_state, tooltip="\n".join(tip_lines), - has_dot=is_high_day, + has_dot=is_high_day or (d_obj == today and has_any), ) ) # Parse `revisit_due` (Contract C from `RevisitNodeCell.vue`) if present revisit_due = first_value(diag, "revisit_due", default=first_value(appt, "revisit_due", default=None)) - if isinstance(revisit_due, Mapping) and str(revisit_due.get("state") or "none") not in {"none", ""}: - slot_n = int(revisit_due.get("current_slot") or 0) - med_d = int(revisit_due.get("medication_days") or 0) - due_dt = _clean_text(revisit_due.get("due_date")) - st_txt = _clean_text(revisit_due.get("state_text")) or "复诊跟踪中" - st_code = str(revisit_due.get("state") or "") + st_code = ( + str(first_value(revisit_due, "state", "status", default="none") or "none") + if isinstance(revisit_due, Mapping) + else "none" + ) + if isinstance(revisit_due, Mapping) and st_code not in {"none", ""}: + slot_n = int(first_value(revisit_due, "current_slot", "visit_count", default=0) or 0) + med_d = int(first_value(revisit_due, "medication_days", default=0) or 0) + due_dt = _clean_text(first_value(revisit_due, "due_date", "medication_end_date", default="")) + st_txt = _clean_text(first_value(revisit_due, "state_text", "status_text", default="")) or "复诊跟踪中" j_sub = " · ".join( p for p in (f"第 {slot_n} 诊" if slot_n > 0 else "", f"开药 {med_d} 天" if med_d > 0 else "", f"药尽 {due_dt[5:]}" if len(due_dt) >= 10 else "") if p ) or "复诊用药周期跟踪" @@ -1168,51 +1371,42 @@ def derive_cockpit_snapshot( j_tone = "coral" if st_code in {"overdue", "missed", "warning", "no_days"} else "emerald" end_cap = f"药尽 {due_dt[5:]}" if len(due_dt) >= 10 else st_txt[:4] else: - j_sub = f"{start_21.strftime('%m-%d')} 至 {today.strftime('%m-%d')} 血糖·饮食·运动实录" + j_sub = f"{start_14.strftime('%m-%d')} 至 {today.strftime('%m-%d')} 血糖·饮食·运动实录" j_pill = rx_status_str j_tone = "emerald" if has_rx else "neutral" end_cap = "已开方" if has_rx else "待开方" journey_vm = CareJourneyVM( - title="近 21 天健康打卡与复诊", + title="近 14 天健康打卡与复诊", plan_subtitle=j_sub, primary_metric_text=f"{checked_in_days}", - total_unit_text="/ 21 天有打卡", + total_unit_text="/ 14 天有打卡", status_pill=j_pill, status_tone=j_tone, end_capsule_text=end_cap, phases=( JourneyPhaseSpan( - "第1周", - "早期基线周", - f"{start_21.strftime('%m-%d')}–{(start_21 + timedelta(days=6)).strftime('%m-%d')}", + "上周", + "前7天基线", + f"{start_14.strftime('%m-%d')}–{(start_14 + timedelta(days=6)).strftime('%m-%d')}", 1, 7, False, ), JourneyPhaseSpan( - "第2周", - "中期观察周", - f"{(start_21 + timedelta(days=7)).strftime('%m-%d')}–{(start_21 + timedelta(days=13)).strftime('%m-%d')}", + "本周", + "近7天窗口", + f"{(start_14 + timedelta(days=7)).strftime('%m-%d')}–{today.strftime('%m-%d')}", 8, 14, - False, - ), - JourneyPhaseSpan( - "近7天", - "本周实测窗口", - f"{(start_21 + timedelta(days=14)).strftime('%m-%d')}–{today.strftime('%m-%d')}", - 15, - 21, True, ), ), - days=tuple(days_21), + days=tuple(days_14), milestones=( - (1, start_21.strftime("%m-%d")), - (8, (start_21 + timedelta(days=7)).strftime("%m-%d")), - (15, (start_21 + timedelta(days=14)).strftime("%m-%d")), - (21, "今日"), + (1, start_14.strftime("%m-%d")), + (8, (start_14 + timedelta(days=7)).strftime("%m-%d")), + (14, "今日"), ), ) diff --git a/app/src/doctor_workstation/ui/visuals/ai_report_wing.py b/app/src/doctor_workstation/ui/visuals/ai_report_wing.py new file mode 100644 index 000000000..5d9b65a57 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/ai_report_wing.py @@ -0,0 +1,880 @@ +"""High-density Clinical AI Report Companion Wing Panel (Clinical OS 4.0). + +Replaces the legacy wide center-blocking `_ReceptionAiAnalysisDialog` in Spatial mode +with a scannable, 520px-optimized clinical evidence companion wing featuring: +- Segmented model pills (`千问` / `OpenAI` / `豆包`) + compact snapshot version selector +- Auto-extracted 3-brick Syndrome / Eight-Principles / Visceral-Locus key takeaways +- 2-column clinical risk stratification grid (zero wasted horizontal whitespace) +- Tagged Four-Examination (`望 / 闻 / 问 / 切`) evidence rows +- Prominent Treatment & Regimen card + non-intrusive inline copy feedback +""" + +from __future__ import annotations + +import html +import re +from collections.abc import Mapping, Sequence +from typing import Any + +from PySide6.QtCore import QSize, Qt, QTimer, Signal +from PySide6.QtGui import QIcon +from PySide6.QtWidgets import ( + QApplication, + QComboBox, + QFrame, + QGridLayout, + QHBoxLayout, + QLabel, + QPushButton, + QScrollArea, + QStackedWidget, + QVBoxLayout, + QWidget, +) + +from .. import icons +from ..reception_style import body_family, heading_family +from ..report_provenance import report_provenance_lines +from ..widgets import clear_layout, display_text, first_value + +AI_MODELS: tuple[tuple[str, str], ...] = ( + ("qwen", "千问"), + ("openai", "OpenAI"), + ("doubao", "豆包"), +) +MODEL_LABELS = dict(AI_MODELS) + +AI_REPORT_WING_QSS = """ +QWidget#ClinicalAiReportWingPanel { + background-color: #FFFFFF; +} +QFrame#AiWingTopBar { + background-color: #F7FAF9; + border: 0; + border-bottom: 1px solid #E4EDE9; +} +QFrame#AiWingModelIsland { + background-color: #EAF1EF; + border-radius: 15px; +} +QPushButton#AiWingModelPill { + min-height: 26px; + max-height: 26px; + padding: 0 13px; + border-radius: 13px; + border: 0; + background-color: transparent; + color: #4F6662; + font-size: 12px; + font-weight: 600; +} +QPushButton#AiWingModelPill:hover { + color: #0E6F5C; +} +QPushButton#AiWingModelPill:checked { + background-color: #111918; + color: #FFFFFF; +} +QComboBox#AiWingVersionCombo { + min-height: 28px; + max-height: 28px; + padding: 0 10px; + border-radius: 14px; + border: 1px solid #D8E5E1; + background-color: #FFFFFF; + color: #263C39; + font-size: 11px; + font-weight: 500; +} +QFrame#AiWingTakeawayTile { + background-color: #F5F9F8; + border: 1px solid #E1ECE8; + border-radius: 14px; +} +QFrame#AiWingTakeawayTile[emphasis="true"] { + background-color: #EAF6F2; + border: 1px solid #C3E3D8; +} +QFrame#AiWingCard { + background-color: #FFFFFF; + border: 1px solid #E2ECE9; + border-radius: 16px; +} +QFrame#AiWingTreatmentCard { + background-color: #F6FBF9; + border: 1px solid #CBE5DC; + border-radius: 16px; +} +QFrame#AiWingBottomBar { + background-color: #F7FAF9; + border: 0; + border-top: 1px solid #E3ECE9; + border-bottom-left-radius: 20px; + border-bottom-right-radius: 20px; +} +QPushButton#AiWingGhostBtn { + min-height: 34px; + max-height: 34px; + padding: 0 14px; + border-radius: 17px; + border: 1px solid #D7E5E1; + background-color: #FFFFFF; + color: #1C322F; + font-size: 12px; + font-weight: 600; +} +QPushButton#AiWingGhostBtn:hover { + background-color: #E7F4F0; + border-color: #9ED0C3; + color: #0E6F5C; +} +QPushButton#AiWingGhostBtn:disabled { + color: #9CB0AC; + background-color: #F4F7F6; +} +QPushButton#AiWingPrimaryBtn { + min-height: 34px; + max-height: 34px; + padding: 0 16px; + border-radius: 17px; + border: 0; + background-color: #0E6F5C; + color: #FFFFFF; + font-size: 12px; + font-weight: 600; +} +QPushButton#AiWingPrimaryBtn:hover { + background-color: #0A5949; +} +""" + +_TAG_PATTERNS: tuple[tuple[str, str, str, str], ...] = ( + ("望诊", "望诊", "#E5F3EE", "#0E6F5C"), + ("闻诊", "闻诊", "#EEF3F2", "#4E6562"), + ("问诊", "问诊", "#E8F1FA", "#1E5C96"), + ("切诊", "切诊", "#FBF4E5", "#986C1B"), + ("八纲", "八纲", "#EAF4F1", "#185E50"), + ("气血津液", "病位病机", "#F4F0E7", "#7E5D20"), + ("脏腑定位", "脏腑病位", "#F4F0E7", "#7E5D20"), + ("证名", "辨证结论", "#DEF2EC", "#0B5E4E"), + ("已知事实", "已知事实", "#E8F1FA", "#1E5C96"), + ("合理推断", "临床推断", "#E5F3EE", "#0E6F5C"), + ("临床推断", "临床推断", "#E5F3EE", "#0E6F5C"), + ("信息缺口", "待补信息", "#FBF4E5", "#986C1B"), + ("核心病机", "核心病机", "#EAF4F1", "#185E50"), + ("辨证分析", "辨证分析", "#EEF5F3", "#2A4A45"), +) + + +def _format_prose_html(text: str, *, color: str = "#223634", size_px: int = 13, line_pct: int = 168) -> str: + """Render clinical prose with true breathing room (`line-height` via HTML since Qt QSS ignores it).""" + + chunks = [c.strip() for c in text.splitlines() if c.strip()] + if not chunks: + return "" + paragraphs: list[str] = [] + for chunk in chunks: + escaped = html.escape(chunk) + # Subtle visual anchor for numbered prefixes ("1. 治法方药:") without shouting + escaped = re.sub( + r"^(\d+[\.、]\s*[^::]{2,8}[::])", + r"\1", + escaped, + ) + paragraphs.append( + f"
{escaped}
" + ) + # Remove bottom margin on last paragraph + if paragraphs: + paragraphs[-1] = paragraphs[-1].replace("margin:0 0 6px 0;", "margin:0;") + return "".join(paragraphs) + + +def _clean_text(value: Any) -> str: + if value in (None, "", [], {}): + return "" + if isinstance(value, (list, tuple)): + parts = [_clean_text(item) for item in value] + return "\n".join(p for p in parts if p) + txt = str(value).strip() + return "" if txt in {"—", "-", "None", "null"} else txt + + +def _extract_key_takeaways(diagnosis_text: str) -> tuple[tuple[str, str], ...]: + """Extract concise (caption, value) takeaways from structured TCM AI output.""" + + syndrome = "" + eight_prin = "" + locus = "" + + for raw_line in diagnosis_text.splitlines(): + line = raw_line.strip().lstrip("•·-*0123456789.、 ") + if not line: + continue + if line.startswith("证名") and (":" in line or ":" in line): + syndrome = re.split(r"[::]", line, maxsplit=1)[1].strip() + elif line.startswith("八纲") and (":" in line or ":" in line): + eight_prin = re.split(r"[::]", line, maxsplit=1)[1].strip() + elif any(line.startswith(k) for k in ("气血津液", "脏腑定位", "病位", "病机")) and ( + ":" in line or ":" in line + ): + val = re.split(r"[::]", line, maxsplit=1)[1].strip() + m_loc = re.search(r"病位[^,。;]*[在属]([^,。;]+)", val) + locus = m_loc.group(1).strip() if m_loc else val + + def _short(text: str, limit: int = 16) -> str: + # Strip parenthetical explanations for the compact headline tile + stripped = re.sub(r"([^)]*)|\([^)]*\)", "", text).strip(" ,。;、") + base = stripped or text + return f"{base[: limit - 1]}…" if len(base) > limit else base + + items: list[tuple[str, str, str]] = [] + if syndrome: + items.append(("辨证证名", _short(syndrome, 15), syndrome)) + if eight_prin: + items.append(("八纲属性", _short(eight_prin, 15), eight_prin)) + if locus: + items.append(("病位病机", _short(locus, 15), locus)) + return tuple(items) # type: ignore[return-value] + + +def _split_evidence_rows(diagnosis_text: str) -> list[tuple[str, str, str, str]]: + """Split `diagnosis_advice` (including inline `【已知事实】` sections) into calm structured rows.""" + + rows: list[tuple[str, str, str, str]] = [] + for raw_line in diagnosis_text.splitlines(): + base = raw_line.strip().lstrip("•·-* ") + if not base: + continue + # Split inline bracketed sections like "【已知事实】...【合理推断】...【信息缺口】..." + segments = [s.strip() for s in re.split(r"(?=【[^】]{2,12}】)", base) if s.strip()] + for line in segments: + # Unwrap leading 【标签】 into prefix matching + m_bracket = re.match(r"^【([^】]{2,12})】\s*(.*)$", line) + if m_bracket: + tag_key = m_bracket.group(1).strip() + rest = m_bracket.group(2).strip() + line = f"{tag_key}:{rest}" if rest else tag_key + if line.startswith(("四诊:", "四诊:")): + line = re.split(r"[::]", line, maxsplit=1)[1].strip() + matched = False + for prefix, badge, bg, fg in _TAG_PATTERNS: + if line.startswith(prefix): + body = line[len(prefix) :].lstrip("::、 ") + if not body: + body = line + rows.append((badge, bg, fg, body)) + matched = True + break + if not matched: + rows.append(("辨证分析", "#EEF5F3", "#2A4A45", line)) + return rows + + +class ClinicalAiReportWingPanel(QWidget): + """High-density companion wing for viewing Qwen / OpenAI / Doubao patient AI reports.""" + + model_selected = Signal(str) + regenerate_requested = Signal() + open_ai_consult_requested = Signal() + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("ClinicalAiReportWingPanel") + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.setStyleSheet(AI_REPORT_WING_QSS) + + self._histories: dict[str, list[dict[str, Any]]] = {k: [] for k, _ in AI_MODELS} + self._states: dict[str, str] = {k: "empty" for k, _ in AI_MODELS} + self._messages: dict[str, str] = {k: "" for k, _ in AI_MODELS} + self._active_model = "qwen" + self._active_version_idx = 0 + self._patient_name = "" + self._copy_reset_timer = QTimer(self) + self._copy_reset_timer.setSingleShot(True) + self._copy_reset_timer.timeout.connect(self._reset_copy_button) + + root = QVBoxLayout(self) + root.setContentsMargins(0, 0, 0, 0) + root.setSpacing(0) + + # 1. Segmented Model Pill Bar + Compact Version Selector + top_bar = QFrame(self) + top_bar.setObjectName("AiWingTopBar") + top_layout = QHBoxLayout(top_bar) + top_layout.setContentsMargins(16, 10, 16, 10) + top_layout.setSpacing(10) + + island = QFrame(top_bar) + island.setObjectName("AiWingModelIsland") + island_layout = QHBoxLayout(island) + island_layout.setContentsMargins(3, 2, 3, 2) + island_layout.setSpacing(2) + self._model_pills: dict[str, QPushButton] = {} + for m_key, m_label in AI_MODELS: + pill = QPushButton(m_label, island) + pill.setObjectName("AiWingModelPill") + pill.setCheckable(True) + pill.setCursor(Qt.CursorShape.PointingHandCursor) + pill.clicked.connect(lambda _c=False, k=m_key: self._on_model_clicked(k)) + island_layout.addWidget(pill) + self._model_pills[m_key] = pill + top_layout.addWidget(island) + + top_layout.addStretch(1) + + self.version_combo = QComboBox(top_bar) + self.version_combo.setObjectName("AiWingVersionCombo") + self.version_combo.setCursor(Qt.CursorShape.PointingHandCursor) + self.version_combo.setMinimumWidth(178) + self.version_combo.currentIndexChanged.connect(self._on_version_changed) + top_layout.addWidget(self.version_combo) + root.addWidget(top_bar) + + # 2. Content Stack (Page 0: Rich Clinical Evidence Flow | Page 1: Honest Empty/Loading State) + self.stack = QStackedWidget(self) + root.addWidget(self.stack, 1) + + # Page 0: Scrollable Evidence Cards + self.scroll = QScrollArea(self.stack) + self.scroll.setWidgetResizable(True) + self.scroll.setFrameShape(QFrame.Shape.NoFrame) + self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.scroll.setStyleSheet("QScrollArea { background: #FFFFFF; border: 0; }") + + self.body_host = QWidget(self.scroll) + self.body_host.setStyleSheet("background: #FFFFFF;") + self.body_layout = QVBoxLayout(self.body_host) + self.body_layout.setContentsMargins(16, 14, 16, 16) + self.body_layout.setSpacing(12) + + # Row A: 3-Column Syndrome Takeaways Host + self.takeaway_host = QWidget(self.body_host) + self.takeaway_layout = QHBoxLayout(self.takeaway_host) + self.takeaway_layout.setContentsMargins(0, 0, 0, 0) + self.takeaway_layout.setSpacing(8) + self.body_layout.addWidget(self.takeaway_host) + + # Row B: 2-Column Risk Stratification Card + self.risk_card = QFrame(self.body_host) + self.risk_card.setObjectName("AiWingCard") + risk_outer = QVBoxLayout(self.risk_card) + risk_outer.setContentsMargins(14, 12, 14, 12) + risk_outer.setSpacing(8) + risk_head = QHBoxLayout() + risk_head.setSpacing(6) + risk_icon = QLabel(self.risk_card) + risk_icon.setPixmap(icons.pixmap("warning", "#C94534", 15)) + risk_icon.setFixedSize(16, 16) + risk_icon.setAlignment(Qt.AlignmentFlag.AlignCenter) + risk_head.addWidget(risk_icon) + self.risk_title_lbl = QLabel("临床风险分层", self.risk_card) + self.risk_title_lbl.setStyleSheet( + f"color: #132523; font-family: '{heading_family()}'; font-size: 13px; font-weight: 600;" + ) + risk_head.addWidget(self.risk_title_lbl) + risk_head.addStretch(1) + self.risk_count_badge = QLabel("0 项", self.risk_card) + self.risk_count_badge.setStyleSheet( + "background: #FCEBE6; color: #C94534; border-radius: 9px; padding: 1px 8px; font-size: 11px; font-weight: 600;" + ) + risk_head.addWidget(self.risk_count_badge) + risk_outer.addLayout(risk_head) + + self.risk_grid_host = QWidget(self.risk_card) + self.risk_grid = QGridLayout(self.risk_grid_host) + self.risk_grid.setContentsMargins(0, 0, 0, 0) + self.risk_grid.setHorizontalSpacing(8) + self.risk_grid.setVerticalSpacing(7) + risk_outer.addWidget(self.risk_grid_host) + self.body_layout.addWidget(self.risk_card) + + # Row C: Structured Four-Examination & Syndrome Reasoning Card + self.diag_card = QFrame(self.body_host) + self.diag_card.setObjectName("AiWingCard") + diag_outer = QVBoxLayout(self.diag_card) + diag_outer.setContentsMargins(14, 12, 14, 14) + diag_outer.setSpacing(9) + diag_head = QHBoxLayout() + diag_head.setSpacing(6) + diag_icon = QLabel(self.diag_card) + diag_icon.setPixmap(icons.pixmap("report", "#0E6F5C", 15)) + diag_icon.setFixedSize(16, 16) + diag_icon.setAlignment(Qt.AlignmentFlag.AlignCenter) + diag_head.addWidget(diag_icon) + diag_title = QLabel("四诊合参依据与辨证分析", self.diag_card) + diag_title.setStyleSheet( + f"color: #132523; font-family: '{heading_family()}'; font-size: 13px; font-weight: 600;" + ) + diag_head.addWidget(diag_title) + diag_head.addStretch(1) + diag_outer.addLayout(diag_head) + self.diag_rows_host = QWidget(self.diag_card) + self.diag_rows_layout = QVBoxLayout(self.diag_rows_host) + self.diag_rows_layout.setContentsMargins(0, 0, 0, 0) + self.diag_rows_layout.setSpacing(7) + diag_outer.addWidget(self.diag_rows_host) + self.body_layout.addWidget(self.diag_card) + + # Row D: Prominent Treatment & Lifestyle Advice Card + self.treat_card = QFrame(self.body_host) + self.treat_card.setObjectName("AiWingTreatmentCard") + treat_outer = QVBoxLayout(self.treat_card) + treat_outer.setContentsMargins(14, 12, 14, 14) + treat_outer.setSpacing(8) + treat_head = QHBoxLayout() + treat_head.setSpacing(6) + treat_icon = QLabel(self.treat_card) + treat_icon.setPixmap(icons.pixmap("meds", "#0B5949", 15)) + treat_icon.setFixedSize(16, 16) + treat_icon.setAlignment(Qt.AlignmentFlag.AlignCenter) + treat_head.addWidget(treat_icon) + treat_title = QLabel("治法方药与调护建议", self.treat_card) + treat_title.setStyleSheet( + f"color: #0B5949; font-family: '{heading_family()}'; font-size: 13px; font-weight: 600;" + ) + treat_head.addWidget(treat_title) + treat_head.addStretch(1) + treat_outer.addLayout(treat_head) + self.treat_body_lbl = QLabel("—", self.treat_card) + self.treat_body_lbl.setWordWrap(True) + self.treat_body_lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + self.treat_body_lbl.setStyleSheet( + f"color: #172E2B; font-family: '{body_family()}'; font-size: 13px; line-height: 1.5;" + ) + treat_outer.addWidget(self.treat_body_lbl) + self.body_layout.addWidget(self.treat_card) + + # Row E: Subtle 1-Line Provenance & Medical Disclaimer + self.provenance_lbl = QLabel( + "注:仅供临床辅助参考,不可替代医师诊断与处方决策 · 悬停查看报告出处与安全声明", + self.body_host, + ) + self.provenance_lbl.setWordWrap(True) + self.provenance_lbl.setStyleSheet("color: #7D918E; font-size: 11px; padding: 2px 2px;") + self.body_layout.addWidget(self.provenance_lbl) + self.body_layout.addStretch(1) + + self.scroll.setWidget(self.body_host) + self.stack.addWidget(self.scroll) + + # Page 1: Honest State Card (Loading / Missing Snapshot / Error) + state_page = QWidget(self.stack) + state_page.setStyleSheet("background: #FFFFFF;") + state_layout = QVBoxLayout(state_page) + state_layout.setContentsMargins(28, 48, 28, 48) + state_layout.addStretch(1) + state_card = QFrame(state_page) + state_card.setStyleSheet( + "QFrame { background: #F6FAF9; border: 1px solid #DFEBE7; border-radius: 18px; }" + ) + sc_layout = QVBoxLayout(state_card) + sc_layout.setContentsMargins(24, 26, 24, 26) + sc_layout.setSpacing(10) + self.state_title_lbl = QLabel("正在读取 AI 循证报告", state_card) + self.state_title_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.state_title_lbl.setStyleSheet( + f"color: #112220; font-family: '{heading_family()}'; font-size: 15px; font-weight: 600; border: 0;" + ) + sc_layout.addWidget(self.state_title_lbl) + self.state_desc_lbl = QLabel("请稍候或点击下方「重新生成」获取当前模型分析快照。", state_card) + self.state_desc_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.state_desc_lbl.setWordWrap(True) + self.state_desc_lbl.setStyleSheet("color: #667D79; font-size: 12px; border: 0;") + sc_layout.addWidget(self.state_desc_lbl) + state_layout.addWidget(state_card) + state_layout.addStretch(1) + self.stack.addWidget(state_page) + + # 3. Sticky Bottom Action Dock + bottom_bar = QFrame(self) + bottom_bar.setObjectName("AiWingBottomBar") + bottom_bar.setFixedHeight(56) + b_layout = QHBoxLayout(bottom_bar) + b_layout.setContentsMargins(16, 10, 16, 10) + b_layout.setSpacing(8) + + self.regen_btn = QPushButton("重新生成", bottom_bar) + self.regen_btn.setObjectName("AiWingGhostBtn") + self.regen_btn.setIcon(icons.icon("refresh", "#24423E", 14)) + self.regen_btn.setIconSize(QSize(14, 14)) + self.regen_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.regen_btn.clicked.connect(self.regenerate_requested.emit) + b_layout.addWidget(self.regen_btn) + + b_layout.addStretch(1) + + self.copy_btn = QPushButton("复制报告", bottom_bar) + self.copy_btn.setObjectName("AiWingGhostBtn") + self.copy_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.copy_btn.clicked.connect(self._copy_current_report) + b_layout.addWidget(self.copy_btn) + + self.consult_btn = QPushButton("AI 深度追问", bottom_bar) + self.consult_btn.setObjectName("AiWingPrimaryBtn") + self.consult_btn.setIcon(icons.icon("ai", "#FFFFFF", 14)) + self.consult_btn.setIconSize(QSize(14, 14)) + self.consult_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.consult_btn.clicked.connect(self.open_ai_consult_requested.emit) + b_layout.addWidget(self.consult_btn) + root.addWidget(bottom_bar) + + def set_report_context( + self, + *, + histories: Mapping[str, Sequence[Mapping[str, Any]]], + model_states: Mapping[str, str] | None = None, + model_messages: Mapping[str, str] | None = None, + active_model: str = "qwen", + patient_name: str = "", + can_regenerate: bool = True, + ) -> None: + self._patient_name = patient_name + self._histories = { + k: [dict(item) for item in (histories.get(k) or ()) if isinstance(item, Mapping)] + for k, _ in AI_MODELS + } + if model_states is not None: + self._states = {k: str(model_states.get(k, "empty")) for k, _ in AI_MODELS} + if model_messages is not None: + self._messages = {k: str(model_messages.get(k, "")) for k, _ in AI_MODELS} + if active_model in MODEL_LABELS: + self._active_model = active_model + self._active_version_idx = 0 + self.regen_btn.setEnabled(bool(can_regenerate)) + self._refresh_ui() + + def _on_model_clicked(self, model_key: str) -> None: + if model_key not in MODEL_LABELS: + return + self._active_model = model_key + self._active_version_idx = 0 + self._refresh_ui() + self.model_selected.emit(model_key) + + def _on_version_changed(self, index: int) -> None: + if index < 0: + return + self._active_version_idx = index + self._render_active_snapshot() + + def _refresh_ui(self) -> None: + for k, btn in self._model_pills.items(): + has_snap = bool(self._histories.get(k)) + st = self._states.get(k, "empty") + base_lbl = MODEL_LABELS[k] + if st == "loading" and not has_snap: + btn.setText(f"{base_lbl} · 生成中") + elif has_snap: + btn.setText(base_lbl) + else: + btn.setText(base_lbl) + btn.setChecked(k == self._active_model) + + snapshots = self._histories.get(self._active_model, []) + blocked = self.version_combo.blockSignals(True) + try: + self.version_combo.clear() + total = len(snapshots) + for idx, snap in enumerate(snapshots): + ver = first_value(snap, "version", default=total - idx) + ts = display_text(first_value(snap, "generated_at", "created_at", default=""), "")[:16] + label = f"第 {ver} 版 · {ts[5:]}" if len(ts) >= 10 else f"第 {ver} 版" + self.version_combo.addItem(label) + self.version_combo.setVisible(total > 0) + if total > 0: + self._active_version_idx = min(self._active_version_idx, total - 1) + self.version_combo.setCurrentIndex(self._active_version_idx) + finally: + self.version_combo.blockSignals(blocked) + + self._render_active_snapshot() + + def _current_snapshot(self) -> dict[str, Any] | None: + snapshots = self._histories.get(self._active_model, []) + if not snapshots: + return None + idx = max(0, min(self._active_version_idx, len(snapshots) - 1)) + return snapshots[idx] + + def _render_active_snapshot(self) -> None: + snap = self._current_snapshot() + model_label = MODEL_LABELS.get(self._active_model, self._active_model) + if snap is None: + st = self._states.get(self._active_model, "missing") + msg = self._messages.get(self._active_model, "") + if st == "loading": + self.state_title_lbl.setText(f"正在生成 {model_label} 循证分析报告…") + self.state_desc_lbl.setText("正在结合患者实采四诊病历、近期血糖与用药信息进行推理,完成后将自动刷新。") + elif st == "error": + self.state_title_lbl.setText(f"{model_label} 报告加载未成功") + self.state_desc_lbl.setText(msg or "请检查网络或点击左下方「↻ 重新生成」重试。") + else: + self.state_title_lbl.setText(f"尚无已保存的 {model_label} 报告快照") + self.state_desc_lbl.setText( + msg or f"当前患者暂无 {model_label} 历史快照,可切换上方其他模型或点击左下角「↻ 重新生成」。" + ) + self.copy_btn.setEnabled(False) + self.stack.setCurrentIndex(1) + return + + self.copy_btn.setEnabled(True) + self.stack.setCurrentIndex(0) + + diag_advice = _clean_text(first_value(snap, "diagnosis_advice", "diagnosis_suggestion")) + treat_advice = _clean_text(first_value(snap, "treatment_advice", "treatment_suggestion")) + raw_risks = first_value(snap, "risk_assessment", "risk_warning", default=[]) or [] + + # A. Takeaways Strip + clear_layout(self.takeaway_layout) + takeaways = _extract_key_takeaways(diag_advice) + self.takeaway_host.setVisible(bool(takeaways)) + for idx, (cap, short_val, full_val) in enumerate(takeaways[:3]): + tile = QFrame(self.takeaway_host) + tile.setObjectName("AiWingTakeawayTile") + tile.setProperty("emphasis", idx == 0) + tile.setMinimumWidth(0) + tile.setToolTip(f"{cap}:{full_val}") + tl = QVBoxLayout(tile) + tl.setContentsMargins(11, 8, 11, 9) + tl.setSpacing(3) + c_lbl = QLabel(cap, tile) + c_lbl.setStyleSheet("color: #67807C; font-size: 11px; border: 0; background: transparent;") + v_lbl = QLabel(short_val, tile) + v_lbl.setWordWrap(True) + v_lbl.setStyleSheet( + f"color: {'#0B5949' if idx == 0 else '#132624'};" + " font-size: 12px; font-weight: 600; border: 0; background: transparent;" + ) + tl.addWidget(c_lbl) + tl.addWidget(v_lbl) + self.takeaway_layout.addWidget(tile, 1) + + # B. 2-Column Risk Matrix + clear_layout(self.risk_grid) + norm_risks: list[tuple[str, str]] = [] + level_aliases = { + "high": "high", + "danger": "high", + "critical": "high", + "medium": "medium", + "warning": "medium", + "warn": "medium", + "low": "low", + "info": "low", + } + if isinstance(raw_risks, Sequence) and not isinstance(raw_risks, (str, bytes)): + for r in raw_risks: + if isinstance(r, Mapping): + r_lbl = _clean_text(first_value(r, "label", "text", "name", "title")) + raw_lvl = str(first_value(r, "level", "severity", default="medium") or "medium").strip().lower() + if r_lbl: + norm_risks.append((level_aliases.get(raw_lvl, "medium"), r_lbl)) + elif isinstance(r, str) and _clean_text(r): + norm_risks.append(("medium", _clean_text(r))) + + self.risk_count_badge.setText(f"共 {len(norm_risks)} 项" if norm_risks else "未见显著高危") + if not norm_risks: + self.risk_count_badge.setStyleSheet( + "background: #E2F3EE; color: #0E6F5C; border-radius: 9px; padding: 1px 8px; font-size: 11px; font-weight: 600;" + ) + safe_lbl = QLabel("当前病历快照未提示特殊高危项,请结合临床实测指标动态复核。", self.risk_grid_host) + safe_lbl.setWordWrap(True) + safe_lbl.setStyleSheet("color: #5C7470; font-size: 12px;") + self.risk_grid.addWidget(safe_lbl, 0, 0, 1, 2) + else: + has_high = any(lvl == "high" for lvl, _ in norm_risks) + self.risk_count_badge.setStyleSheet( + f"background: {'#FCEBE6' if has_high else '#FBF5E6'};" + f" color: {'#C94534' if has_high else '#9A6B16'};" + " border-radius: 9px; padding: 1px 8px; font-size: 11px; font-weight: 600;" + ) + palette_map = { + "high": ("高危", "#FDF3F1", "#D94F3D", "#C43E2D"), + "medium": ("关注", "#FCF8EE", "#C98E24", "#966914"), + "low": ("提示", "#EFF7F4", "#1B856E", "#0E6F5C"), + } + # Use calm full-width structured rows when risks carry clinical explanations (> 22 chars), + # avoiding cramped 2-column pink/yellow walls of text! + use_single_column = any(len(txt) > 22 for _, txt in norm_risks) + for idx, (lvl, lbl_txt) in enumerate(norm_risks): + tag_txt, pill_bg, left_accent, fg = palette_map[lvl] + chip = QFrame(self.risk_grid_host) + chip.setStyleSheet( + "QFrame {" + " background: #FAFCFB;" + " border: 1px solid #E5EEEC;" + f" border-left: 3px solid {left_accent};" + " border-radius: 10px;" + "}" + ) + if use_single_column: + cv = QVBoxLayout(chip) + cv.setContentsMargins(12, 9, 12, 10) + cv.setSpacing(5) + # Split "风险标题:具体临床解释..." cleanly into Headline + Calm Body + if ":" in lbl_txt or ":" in lbl_txt: + head_part, detail_part = re.split(r"[::]", lbl_txt, maxsplit=1) + head_part = head_part.strip() + detail_part = detail_part.strip() + else: + head_part, detail_part = lbl_txt, "" + + top_r = QHBoxLayout() + top_r.setContentsMargins(0, 0, 0, 0) + top_r.setSpacing(8) + tag = QLabel(tag_txt, chip) + tag.setFixedWidth(36) + tag.setAlignment(Qt.AlignmentFlag.AlignCenter) + tag.setStyleSheet( + f"background: {pill_bg}; color: {fg}; border-radius: 6px;" + " font-size: 11px; font-weight: 600; padding: 1px 0; border: 0;" + ) + top_r.addWidget(tag, 0, Qt.AlignmentFlag.AlignVCenter) + h_lbl = QLabel(head_part, chip) + h_lbl.setWordWrap(True) + h_lbl.setStyleSheet( + "color: #152624; font-size: 13px; font-weight: 600; border: 0; background: transparent;" + ) + top_r.addWidget(h_lbl, 1) + cv.addLayout(top_r) + + if detail_part: + d_lbl = QLabel(_format_prose_html(detail_part, color="#425855", size_px=13, line_pct=162), chip) + d_lbl.setTextFormat(Qt.TextFormat.RichText) + d_lbl.setWordWrap(True) + d_lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + d_lbl.setStyleSheet("border: 0; background: transparent;") + cv.addWidget(d_lbl) + self.risk_grid.addWidget(chip, idx, 0, 1, 2) + else: + cl = QHBoxLayout(chip) + cl.setContentsMargins(10, 8, 10, 8) + cl.setSpacing(8) + tag = QLabel(tag_txt, chip) + tag.setFixedWidth(36) + tag.setAlignment(Qt.AlignmentFlag.AlignCenter) + tag.setStyleSheet( + f"background: {pill_bg}; color: {fg}; border-radius: 6px;" + " font-size: 11px; font-weight: 600; padding: 1px 0; border: 0;" + ) + cl.addWidget(tag, 0, Qt.AlignmentFlag.AlignVCenter) + txt = QLabel(lbl_txt, chip) + txt.setWordWrap(True) + txt.setStyleSheet( + "color: #182B29; font-size: 13px; font-weight: 500; border: 0; background: transparent;" + ) + cl.addWidget(txt, 1) + row, col = divmod(idx, 2) + col_span = 2 if (idx == len(norm_risks) - 1 and col == 0) else 1 + self.risk_grid.addWidget(chip, row, col, 1, col_span) + self.risk_grid.setColumnStretch(0, 1) + self.risk_grid.setColumnStretch(1, 1) + + # C. Structured Four-Examination & Syndrome Reasoning Rows + clear_layout(self.diag_rows_layout) + evidence_rows = _split_evidence_rows(diag_advice) if diag_advice else [] + if not evidence_rows: + empty_d = QLabel("暂无结构化辨证说明。", self.diag_rows_host) + empty_d.setStyleSheet("color: #7A908C; font-size: 13px;") + self.diag_rows_layout.addWidget(empty_d) + else: + for r_idx, (badge_txt, bg_hex, fg_hex, body_txt) in enumerate(evidence_rows): + if r_idx > 0: + sep = QFrame(self.diag_rows_host) + sep.setFixedHeight(1) + sep.setStyleSheet("background-color: #EEF3F1; border: 0;") + self.diag_rows_layout.addWidget(sep) + row_w = QWidget(self.diag_rows_host) + rl = QHBoxLayout(row_w) + rl.setContentsMargins(0, 4, 0, 4) + rl.setSpacing(10) + b_lbl = QLabel(badge_txt, row_w) + b_lbl.setFixedWidth(62) + b_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) + b_lbl.setStyleSheet( + f"background: {bg_hex}; color: {fg_hex}; border-radius: 7px;" + " padding: 3px 4px; font-size: 11.5px; font-weight: 600;" + ) + rl.addWidget(b_lbl, 0, Qt.AlignmentFlag.AlignTop) + + is_missing_hint = "未采集" in body_txt + val_lbl = QLabel( + _format_prose_html( + body_txt, + color="#9A6B16" if is_missing_hint else "#213533", + size_px=13, + line_pct=168, + ), + row_w, + ) + val_lbl.setTextFormat(Qt.TextFormat.RichText) + val_lbl.setWordWrap(True) + val_lbl.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) + val_lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + val_lbl.setStyleSheet("background: transparent; border: 0;") + rl.addWidget(val_lbl, 1) + self.diag_rows_layout.addWidget(row_w) + + # D. Treatment & Regimen Card + treat_source = treat_advice or "服务端该版快照暂未附带治疗建议。" + self.treat_body_lbl.setTextFormat(Qt.TextFormat.RichText) + self.treat_body_lbl.setText( + _format_prose_html( + treat_source, + color="#1E3431" if treat_advice else "#6E8581", + size_px=13, + line_pct=168, + ) + ) + + # E. Provenance Tooltip + prov_lines = report_provenance_lines(snap) + self.provenance_lbl.setToolTip( + "\n".join( + [ + *prov_lines, + "", + "医疗安全声明:仅供临床辅助参考,不可替代执业医师诊断,不得直接用于开方或调药。", + ] + ) + ) + + def _copy_current_report(self) -> None: + snap = self._current_snapshot() + if snap is None: + return + model_label = MODEL_LABELS.get(self._active_model, self._active_model) + diag_advice = _clean_text(first_value(snap, "diagnosis_advice", "diagnosis_suggestion")) + treat_advice = _clean_text(first_value(snap, "treatment_advice", "treatment_suggestion")) + raw_risks = first_value(snap, "risk_assessment", "risk_warning", default=[]) or [] + risk_str = "、".join( + _clean_text(first_value(r, "label", "text", "name", "title") if isinstance(r, Mapping) else r) + for r in raw_risks + if _clean_text(first_value(r, "label", "text", "name", "title") if isinstance(r, Mapping) else r) + ) + header = f"【{self._patient_name or '当前患者'} · {model_label} AI 循证报告】" + formatted = "\n\n".join( + part + for part in ( + header, + f"■ 辨证分析:\n{diag_advice}" if diag_advice else "", + f"■ 风险分层:{risk_str}" if risk_str else "", + f"■ 治疗建议:\n{treat_advice}" if treat_advice else "", + ) + if part + ) + clipboard = QApplication.clipboard() + if clipboard is not None: + clipboard.setText(formatted) + self.copy_btn.setIcon(icons.icon("check", "#0E6F5C", 14)) + self.copy_btn.setIconSize(QSize(14, 14)) + self.copy_btn.setText("已复制结论") + self._copy_reset_timer.start(1800) + + def _reset_copy_button(self) -> None: + self.copy_btn.setIcon(QIcon()) + self.copy_btn.setText("复制报告") + + +__all__ = ["ClinicalAiReportWingPanel"] diff --git a/app/src/doctor_workstation/ui/visuals/aurora_sheet.py b/app/src/doctor_workstation/ui/visuals/aurora_sheet.py index ef17c2dfa..db02a3724 100644 --- a/app/src/doctor_workstation/ui/visuals/aurora_sheet.py +++ b/app/src/doctor_workstation/ui/visuals/aurora_sheet.py @@ -39,9 +39,9 @@ class AuroraGlassCardWidget(QWidget): super().__init__(parent) self.setObjectName("AuroraGlassCardWidget") self.setCursor(Qt.CursorShape.PointingHandCursor) - self.setMinimumSize(196, 152) + self.setMinimumSize(132, 148) self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) - self.setFixedHeight(162) + self.setFixedHeight(156) self._vm: AuroraCardVM | None = None self._hovered = False @@ -117,38 +117,43 @@ class AuroraGlassCardWidget(QWidget): painter.setBrush(accent_c) painter.drawEllipse(QPointF(left + 5, rect.top() + 21), 4.0, 4.0) - t_font = QFont(heading_family()) - t_font.setPixelSize(14) - t_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(t_font) - painter.setPen(QColor("#F6FAF9")) - painter.drawText( - QRectF(left + 15, rect.top() + 11, avail_w - 86, 20), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.title, - ) - b_font = QFont(body_family()) b_font.setPixelSize(10) b_font.setWeight(QFont.Weight.DemiBold) painter.setFont(b_font) - bw = float(painter.fontMetrics().horizontalAdvance(vm.badge_text) + 16) + bw = min(avail_w * 0.44, float(painter.fontMetrics().horizontalAdvance(vm.badge_text) + 14)) b_rect = QRectF(right - bw, rect.top() + 12, bw, 19) bp = QPainterPath() bp.addRoundedRect(b_rect, 9.5, 9.5) painter.setBrush(Qt.BrushStyle.NoBrush) painter.fillPath(bp, QColor(255, 255, 255, 28)) painter.setPen(accent_c) - painter.drawText(b_rect, Qt.AlignmentFlag.AlignCenter, vm.badge_text) + painter.drawText( + b_rect, + Qt.AlignmentFlag.AlignCenter, + painter.fontMetrics().elidedText(vm.badge_text, Qt.TextElideMode.ElideRight, int(max(24, bw - 8))), + ) + + t_font = QFont(heading_family()) + t_font.setPixelSize(13 if avail_w < 170 else 14) + t_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(t_font) + painter.setPen(QColor("#F6FAF9")) + title_max_w = max(40.0, avail_w - bw - 22.0) + painter.drawText( + QRectF(left + 14, rect.top() + 11, title_max_w, 20), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(vm.title, Qt.TextElideMode.ElideRight, int(title_max_w)), + ) s_font = QFont(body_family()) s_font.setPixelSize(11) painter.setFont(s_font) painter.setPen(QColor(215, 230, 227, 160)) painter.drawText( - QRectF(left + 15, rect.top() + 31, avail_w - 16, 15), + QRectF(left + 14, rect.top() + 31, max(40.0, avail_w - 16), 15), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.subtitle, + painter.fontMetrics().elidedText(vm.subtitle, Qt.TextElideMode.ElideRight, int(max(40, avail_w - 16))), ) # Divider line @@ -160,25 +165,25 @@ class AuroraGlassCardWidget(QWidget): body_font.setPixelSize(12) painter.setFont(body_font) painter.setPen(QColor("#EEF5F3")) - body_box = QRectF(left, rect.top() + 57, avail_w, 74) + body_box = QRectF(left, rect.top() + 55, avail_w, 66) opt = QTextOption(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) opt.setWrapMode(QTextOption.WrapMode.WordWrap) text_to_draw = vm.body_text - if len(text_to_draw) > 108: - text_to_draw = f"{text_to_draw[:106]}…" + if len(text_to_draw) > 96: + text_to_draw = f"{text_to_draw[:94]}…" painter.drawText(body_box, text_to_draw, opt) # Footer metadata painter.setFont(s_font) - painter.setPen(QColor(210, 226, 223, 155)) + painter.setPen(QColor(210, 226, 223, 165)) painter.drawText( - QRectF(left, rect.bottom() - 23, avail_w * 0.62, 16), + QRectF(left, rect.bottom() - 26, avail_w * 0.62, 18), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, vm.foot_left, ) painter.setPen(accent_c) painter.drawText( - QRectF(right - avail_w * 0.38, rect.bottom() - 23, avail_w * 0.38, 16), + QRectF(right - avail_w * 0.38, rect.bottom() - 26, avail_w * 0.38, 18), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, vm.foot_right, ) @@ -191,7 +196,7 @@ class ArcRhythmGaugeWidget(QWidget): super().__init__(parent) self.setObjectName("ArcRhythmGaugeWidget") self.setMouseTracking(True) - self.setFixedSize(202, 162) + self.setFixedSize(202, 156) self._value_text = "0/6" self._unit_text = "项" self._caption = "病历实采完备度" @@ -226,8 +231,8 @@ class ArcRhythmGaugeWidget(QWidget): rect = QRectF(self.rect()) cx = rect.center().x() - cy = rect.top() + 92.0 - radius = 66.0 + cy = rect.top() + 86.0 + radius = 62.0 arc_box = QRectF(cx - radius, cy - radius, radius * 2.0, radius * 2.0) hemi = QRadialGradient(QPointF(cx, cy), radius) @@ -305,7 +310,7 @@ class CollapsibleObsidianSheet(QWidget): self._vm: ObsidianAuroraVM | None = None root = QVBoxLayout(self) - root.setContentsMargins(22, 24, 22, 14) + root.setContentsMargins(22, 18, 22, 14) root.setSpacing(10) top_bar = QHBoxLayout() @@ -319,10 +324,11 @@ class CollapsibleObsidianSheet(QWidget): top_bar.addWidget(self.title_label) self.summary_label = QLabel("选择患者后自动读取千问 / OpenAI / 豆包实采病历分析报告", self) + self.summary_label.setMinimumWidth(0) self.summary_label.setStyleSheet( "color: rgba(220, 234, 231, 185); font-size: 12px; background: transparent;" ) - self.summary_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + self.summary_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) top_bar.addWidget(self.summary_label, 1) self._model_buttons: dict[str, QPushButton] = {} @@ -376,7 +382,8 @@ class CollapsibleObsidianSheet(QWidget): body_layout.setSpacing(14) left_col = QWidget(self.body_widget) - left_col.setFixedWidth(196) + left_col.setFixedWidth(188) + self.left_meta_col = left_col left_layout = QVBoxLayout(left_col) left_layout.setContentsMargins(0, 0, 0, 0) left_layout.setSpacing(8) @@ -452,10 +459,25 @@ class CollapsibleObsidianSheet(QWidget): def toggle_expanded(self) -> None: self.set_expanded(not self._expanded) + def _sync_responsive_columns(self) -> None: + w = self.width() + if w <= 0: + return + self.summary_label.setVisible(w >= 720) + if hasattr(self, "left_meta_col"): + self.left_meta_col.setVisible(w >= 1060) + if hasattr(self, "gauge"): + self.gauge.setVisible(w >= 860) + + def resizeEvent(self, event: object) -> None: # noqa: N802 + super().resizeEvent(event) # type: ignore[arg-type] + self._sync_responsive_columns() + def _apply_expanded_geometry(self) -> None: self.body_widget.setVisible(self._expanded) self.toggle_button.setText("收起分析舱 ▼" if self._expanded else "展开分析舱 ▲") self.setFixedHeight(238 if self._expanded else 64) + self._sync_responsive_columns() self.update() def set_view_model(self, vm: ObsidianAuroraVM) -> None: diff --git a/app/src/doctor_workstation/ui/visuals/diurnal_strip.py b/app/src/doctor_workstation/ui/visuals/diurnal_strip.py index 1ce5bb856..272629baf 100644 --- a/app/src/doctor_workstation/ui/visuals/diurnal_strip.py +++ b/app/src/doctor_workstation/ui/visuals/diurnal_strip.py @@ -1,8 +1,10 @@ -"""Real postprandial 2h blood glucose, 14-day check-in strip, and 3 vital bricks.""" +"""Real postprandial 2h blood glucose & dated clinical indicators — ONLY Real Data + Dates.""" from __future__ import annotations -from PySide6.QtCore import QPointF, QRectF, QSize, Qt +import html + +from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen from PySide6.QtWidgets import QToolTip, QWidget @@ -11,16 +13,21 @@ from ..viewmodels.cockpit_vm import DiurnalSlot, DiurnalStabilityVM, VitalMiniBr class DiurnalStabilityCard(QWidget): - """Render real 2h postprandial glucose, 14-day daily records, and BP/BMI/Meds bricks.""" + """Render real 2h postprandial glucose, real dated check-in bars, and real dated clinical bricks.""" + + open_daily_requested = Signal() + vital_clicked = Signal(str) def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) self.setObjectName("DiurnalStabilityCard") self.setMouseTracking(True) - self.setMinimumHeight(218) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setMinimumHeight(168) self._vm: DiurnalStabilityVM | None = None self._slot_rects: list[tuple[QRectF, DiurnalSlot]] = [] self._brick_rects: list[tuple[QRectF, VitalMiniBrick]] = [] + self._missing_rect = QRectF() def sizeHint(self) -> QSize: # noqa: N802 return QSize(330, 300) @@ -32,16 +39,51 @@ class DiurnalStabilityCard(QWidget): def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 pos = event.position() for rect, slot in self._slot_rects: - if rect.adjusted(-1, -6, 1, 6).contains(pos) and slot.tooltip: - QToolTip.showText(event.globalPosition().toPoint(), slot.tooltip, self) + if rect.adjusted(-3, -14, 3, 16).contains(pos) and slot.tooltip: + safe_tip = "