Files
zyt/app/src/doctor_workstation/ui/shell.py
T
2026-11-26 15:46:20 +08:00

2282 lines
93 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Authenticated application shell with permission-aware navigation."""
from __future__ import annotations
import math
import sqlite3
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from functools import wraps
from typing import Any
from PySide6.QtCore import (
QElapsedTimer,
QPointF,
QRectF,
QSize,
Qt,
QTimer,
Signal,
)
from PySide6.QtGui import (
QColor,
QFont,
QIcon,
QKeySequence,
QMouseEvent,
QPainter,
QPainterPath,
QPen,
QPixmap,
QShortcut,
)
from PySide6.QtWidgets import (
QApplication,
QButtonGroup,
QFrame,
QHBoxLayout,
QLabel,
QLineEdit,
QMainWindow,
QMenu,
QPushButton,
QSizePolicy,
QStackedWidget,
QStyle,
QStyleOptionButton,
QTabBar,
QToolButton,
QVBoxLayout,
QWidget,
)
from doctor_workstation.resources import app_icon_path
from . import icons, motion
from .chat_notifications import (
CONSULTATION_COMPLETE,
PATIENT_OPENED_CHAT,
ChatNotification,
ChatNotificationCenter,
)
from .design_system import PALETTE, clinical_stylesheet
from .dialogs.ai_consult import can_open_ai_consult
from .dialogs.ai_consult_picker import select_and_present_ai_consult
from .dialogs.diagnosis import DiagnosisDialog
from .dialogs.esign_doctor import EsignDoctorDialog
from .dialogs.local_audio_queue import LocalAudioQueueDialog
from .dialogs.prescription_esign import can_open_esign_doctor
from .pages import (
AppointmentsPage,
ConsultationsPage,
PatientsPage,
PrescriptionLibraryPage,
PrescriptionsPage,
ReceptionPage,
)
from .reception_style import TECH_BLUE, body_family, heading_family, number_family
from .theme import COLORS, METRICS, TYPE, crisp_pixmap
from .widgets import (
EmptyState,
StatusBadge,
display_text,
first_value,
get_value,
has_permission,
show_toast,
)
_SHELL_EXPANDED_WIDTH = 190
_SHELL_COLLAPSED_WIDTH = 68
_SHELL_TOPBAR_HEIGHT = 62
_SHELL_TABS_HEIGHT = 0
_SHELL_OUTER_GUTTER = 13
_SHELL_PANEL_GAP = 0
_SHELL_DESIGN_SIZE = QSize(1710, 920)
_SHELL_MINIMUM_SIZE = QSize(1024, 640)
_RECEPTION_SIDEBAR_WIDTH = 208
_RECEPTION_TOPBAR_HEIGHT = 76
_RECEPTION_SIDEBAR_COLOR = PALETTE["sidebar"]
_RECEPTION_CHROME_LINE = PALETTE["line"]
# Approved pages share one chrome state, so navigation among them keeps it intact.
_TECH_BLUE_PAGES = frozenset({"appointments", "consultations", "patients", "prescriptions", "prescription_library", "reception"})
def _bounded_initial_window_size(available_size: QSize | None) -> QSize:
"""Fit the design viewport inside the screen's logical available geometry."""
if available_size is None or not available_size.isValid():
return QSize(_SHELL_DESIGN_SIZE.width(), _SHELL_DESIGN_SIZE.height())
return QSize(
max(
_SHELL_MINIMUM_SIZE.width(),
min(_SHELL_DESIGN_SIZE.width(), available_size.width()),
),
max(
_SHELL_MINIMUM_SIZE.height(),
min(_SHELL_DESIGN_SIZE.height(), available_size.height()),
),
)
@dataclass(frozen=True)
class NavigationItem:
key: str
title: str
glyph: str
page_type: type[QWidget]
permissions: tuple[str, ...]
NAVIGATION = (
NavigationItem(
# 挂号与诊单是两条独立队列,早期两项都叫“问诊列表”,侧边栏出现两个同名
# 入口,医生无法判断该点哪个。按各自的业务对象命名以消除歧义。
"appointments",
"挂号列表",
"号",
AppointmentsPage,
("doctor.appointment/lists",),
),
NavigationItem(
"reception",
"接诊台",
"◎",
ReceptionPage,
("doctor.appointment/lists",),
),
NavigationItem(
"prescription_library",
"处方库",
"方",
PrescriptionLibraryPage,
("tcm.prescriptionLibrary/lists",),
),
NavigationItem(
"prescriptions",
"已开处方",
"笺",
PrescriptionsPage,
("tcm.prescription/lists",),
),
NavigationItem(
"patients",
"我的患者",
"患",
PatientsPage,
("firstvisit.myPatient/lists",),
),
NavigationItem(
"consultations",
"问诊列表",
"询",
ConsultationsPage,
("tcm.diagnosis/lists",),
),
)
# Shared ``doctor.appointment/lists`` is intentionally mapped only to reception;
# the appointment list page is resolved by menu route/component identity.
_NAVIGATION_BY_PERMISSION = {
item.permissions[0]: item for item in NAVIGATION if item.key != "appointments"
}
_MENU_ROUTE_IDENTIFIERS = {
"reception": {
"reception",
"patient/reception",
"patient/reception/index",
},
"appointments": {
"appointments",
"tcm/appointment",
"tcm/appointment/list",
"appointment/list",
},
"prescription_library": {
"prescription-library",
"prescription_library",
"consumer/prescription/list",
},
"prescriptions": {
"prescriptions",
"consumer/prescription/index",
},
"patients": {
"patients",
"first_visit/my_patients",
"first_visit/my_patients/index",
},
"consultations": {
"consultations",
"tcm/diagnosis",
"tcm/diagnosis/index",
},
}
def _canonical_allowed(permissions: Any, code: str) -> bool:
"""Apply the core exact/wildcard semantics without slash-dot aliases."""
if permissions is None:
return True
for method_name in ("allows", "has", "can_access_page", "has_page", "can"):
method = getattr(permissions, method_name, None)
if callable(method):
try:
return bool(method(code))
except (TypeError, ValueError):
continue
raw = permissions
for attr in ("codes", "permissions", "values"):
candidate = getattr(permissions, attr, None)
if candidate is not None and not callable(candidate):
raw = candidate
break
if isinstance(raw, Mapping):
nested = first_value(raw, "codes", "permissions", "values", default=None)
if nested is not None:
raw = nested
if isinstance(raw, Mapping):
available = {str(key) for key, enabled in raw.items() if enabled}
elif isinstance(raw, str):
available = {raw}
else:
try:
available = {str(value) for value in raw}
except TypeError:
return False
if "*" in available or code in available:
return True
return any(
grant.endswith("/*") and code.startswith(grant[:-1]) for grant in available
)
def _menu_rows(value: Any) -> list[Mapping[str, Any]]:
if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)):
return []
return [row for row in value if isinstance(row, Mapping)]
def _menu_visible(row: Mapping[str, Any]) -> bool:
value = get_value(row, "is_show", 1)
if isinstance(value, str):
return value.strip().lower() not in {"0", "false", "hidden", "no"}
return value != 0
def _menu_enabled(row: Mapping[str, Any]) -> bool:
value = get_value(row, "is_disable", 0)
if isinstance(value, str):
return value.strip().lower() not in {"1", "true", "disabled", "yes"}
return value != 1
def _menu_sort(row: Mapping[str, Any]) -> float:
try:
return float(first_value(row, "sort", "sort_order", "order", default=0))
except (TypeError, ValueError):
return 0.0
def _visible_menu_nodes(value: Any) -> list[Mapping[str, Any]]:
"""Flatten visible, enabled nodes; larger admin sort values come first."""
nodes = _menu_rows(value)
ordered = sorted(enumerate(nodes), key=lambda pair: (-_menu_sort(pair[1]), pair[0]))
result: list[Mapping[str, Any]] = []
for _index, node in ordered:
if not _menu_visible(node) or not _menu_enabled(node):
continue
result.append(node)
children = first_value(node, "children", "child", "childs", default=[])
result.extend(_visible_menu_nodes(children))
return result
def _normalise_route(value: Any) -> str:
route = str(value or "").strip().replace("\\", "/").lower()
route = route.split("?", 1)[0].split("#", 1)[0].strip("/")
if route.endswith(".vue"):
route = route[:-4]
return route
def _menu_permissions(row: Mapping[str, Any]) -> tuple[str, ...]:
value = first_value(row, "perms", "permission", "meta.perms", default="")
if isinstance(value, str):
return (value.strip(),) if value.strip() else ()
if isinstance(value, Sequence):
return tuple(str(item).strip() for item in value if str(item).strip())
return ()
def _match_navigation(row: Mapping[str, Any]) -> NavigationItem | None:
"""Prefer route/component identity when pages share the same permission code."""
identifiers = {
_normalise_route(first_value(row, "paths", "path")),
_normalise_route(get_value(row, "component", "")),
}
identifiers.discard("")
for item in NAVIGATION:
if identifiers & _MENU_ROUTE_IDENTIFIERS.get(item.key, set()):
return item
for permission in _menu_permissions(row):
item = _NAVIGATION_BY_PERMISSION.get(permission)
if item is not None:
return item
return None
def _resolve_navigation(
menu: Any,
permissions: Any,
*,
demo_mode: bool,
) -> list[tuple[NavigationItem, str]]:
"""Resolve only locally supported pages from the authoritative menu tree."""
rows = _menu_rows(menu)
if rows:
resolved: list[tuple[NavigationItem, str]] = []
seen: set[str] = set()
for row in _visible_menu_nodes(rows):
item = _match_navigation(row)
if item is None or item.key in seen:
continue
if not _canonical_allowed(permissions, item.permissions[0]):
continue
if item.key in {"appointments", "reception", "patients"}:
# Keep the product-facing navigation titles stable even when
# the server still carries an older menu label.
title = item.title
else:
title_value = first_value(
row, "name", "title", "meta.title", default=item.title
)
title = str(title_value).strip() or item.title
resolved.append((item, title))
seen.add(item.key)
resolved.sort(key=lambda entry: entry[0].key != "appointments")
return resolved
if demo_mode:
return [
(item, item.title)
for item in NAVIGATION
if _canonical_allowed(permissions, item.permissions[0])
]
return []
def _painted_shell_icon(kind: str, size: int = 18, *, reception: bool = False) -> QIcon:
"""Return a shell chrome icon from the shared 24-unit icon grid."""
color = "accent" if kind == "ai" else "muted"
if reception:
color = TECH_BLUE["accent" if kind == "ai" else "text"]
if kind in {"settings", "fullscreen"}:
canvas = crisp_pixmap(size)
painter = QPainter(canvas)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.scale(size / 24.0, size / 24.0)
painter.setPen(QPen(QColor(color), 1.55, Qt.PenStyle.SolidLine,
Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin))
painter.setBrush(Qt.BrushStyle.NoBrush)
if kind == "fullscreen":
painter.drawRoundedRect(QRectF(4, 4, 16, 16), 1, 1)
else:
gear = QPainterPath()
for index in range(48):
radius = (10, 10, 7.9, 7.9, 10, 10)[index % 6]
angle = index * math.pi / 24.0
point = QPointF(12 + radius * math.cos(angle), 12 + radius * math.sin(angle))
if index == 0:
gear.moveTo(point)
else:
gear.lineTo(point)
gear.closeSubpath()
painter.drawPath(gear)
painter.drawEllipse(QRectF(8.6, 8.6, 6.8, 6.8))
painter.end()
return QIcon(canvas)
return icons.icon(kind, color, size)
def _painted_navigation_icon(kind: str, size: int = 18, *, reception: bool = False) -> QIcon:
"""Return a navigation icon that carries its own selected/hover colours."""
return icons.state_icon(
kind,
size=size,
normal=TECH_BLUE["text"] if reception else "muted",
active=TECH_BLUE["heading"] if reception else "strong",
checked=TECH_BLUE["selected_text"] if reception else "on_accent",
disabled="disabled",
)
class _ShellBrandMark(QWidget):
"""Render the approved application brand mark in the navigation rail."""
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self._brand_pixmap = QPixmap(str(app_icon_path()))
#: The brand PNG carries an opaque white field behind the logo, so drawing it
#: straight put a hard-cornered white square inside a rail whose every other
#: edge is rounded. Clipping the tile is enough - the artwork is untouched.
_TILE_RADIUS = 10.0
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
del event
reception = bool(self.property("receptionTechBlue"))
if not reception and self._brand_pixmap.isNull():
return
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
rect = QRectF(self.rect()).adjusted(0.75, 0.75, -0.75, -0.75)
if reception:
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(TECH_BLUE["accent"]))
painter.drawEllipse(rect)
painter.scale(self.width() / 36.0, self.height() / 36.0)
cross = QPainterPath()
cross.moveTo(16, 9)
for x, y in ((20, 9), (20, 15), (26, 15), (26, 20), (20, 20),
(20, 26), (15, 26), (15, 20), (9, 20), (9, 15), (15, 15), (15, 9)):
cross.lineTo(x, y)
cross.closeSubpath()
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.setPen(QPen(QColor(TECH_BLUE["surface"]), 2.0,
Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap,
Qt.PenJoinStyle.RoundJoin))
painter.drawPath(cross)
return
clip = QPainterPath()
clip.addRoundedRect(rect, self._TILE_RADIUS, self._TILE_RADIUS)
painter.setClipPath(clip)
painter.drawPixmap(rect, self._brand_pixmap, QRectF(self._brand_pixmap.rect()))
class _ShellNavigationButton(QPushButton):
"""Use the approved icon-to-label spacing in the shared blue chrome."""
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
if not self.property("receptionTechBlue"):
super().paintEvent(event)
return
option = QStyleOptionButton()
self.initStyleOption(option)
painter = QPainter(self)
self.style().drawControl(QStyle.ControlElement.CE_PushButtonBevel, option, painter, self)
collapsed = bool(self.property("collapsed"))
settings = self.objectName() == "ShellSettingsButton"
x = (self.width() - 20) // 2 if collapsed else (30 if settings else 22)
self.icon().paint(
painter, x, (self.height() - 20) // 2, 20, 20,
Qt.AlignmentFlag.AlignCenter,
QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled,
QIcon.State.On if self.isChecked() else QIcon.State.Off,
)
if not collapsed:
painter.setFont(self.font())
painter.setPen(QColor(TECH_BLUE["selected_text"] if self.isChecked() else TECH_BLUE["text"]))
painter.drawText(
QRectF(65 if settings else 56, 0, self.width() - 69, self.height()),
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
"设置" if settings else self.text(),
)
if settings:
_painted_shell_icon("right", 16, reception=True).paint(
painter, 112, (self.height() - 16) // 2, 16, 16
)
class _AssistantRobot(QWidget):
"""Legacy illustration, with the approved AI tile in the shared blue chrome."""
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setFixedSize(56, 56)
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
del event
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
if self.property("receptionTechBlue"):
painter.setBrush(QColor(TECH_BLUE["accent"]))
tile = QRectF(6, 6, 36, 36)
painter.drawRoundedRect(tile, 6, 6)
painter.setPen(QColor(TECH_BLUE["surface"]))
font = QFont(number_family())
font.setPixelSize(18)
font.setWeight(QFont.Weight.DemiBold)
painter.setFont(font)
painter.drawText(tile, Qt.AlignmentFlag.AlignCenter, "AI")
return
painter.setBrush(QColor(COLORS["indigo_pale"]))
painter.drawEllipse(QRectF(1, 1, 54, 54))
painter.setBrush(QColor("#E4E4E5"))
painter.drawEllipse(QRectF(9, 13, 38, 36))
pen = QPen(QColor(COLORS["indigo"]), 1.5)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
painter.setBrush(QColor("#FFFFFF"))
painter.drawRoundedRect(QRectF(12, 17, 32, 25), 9, 9)
painter.setBrush(QColor("#223D83"))
painter.drawRoundedRect(QRectF(16, 22, 24, 13), 6, 6)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor("#65D7F0"))
painter.drawEllipse(QRectF(21, 26, 3.5, 3.5))
painter.drawEllipse(QRectF(31.5, 26, 3.5, 3.5))
painter.setBrush(QColor(COLORS["indigo"]))
painter.drawRoundedRect(QRectF(19, 40, 18, 9), 4, 4)
painter.setPen(pen)
painter.drawLine(QPointF(28, 17), QPointF(28, 10))
painter.setBrush(QColor(COLORS["indigo"]))
painter.drawEllipse(QRectF(25.5, 6.5, 5, 5))
painter.drawLine(QPointF(12, 28), QPointF(7.5, 31))
painter.drawLine(QPointF(44, 28), QPointF(48.5, 31))
class _AssistantStatus(QLabel):
"""Status copy with a painted dot instead of a Unicode circle glyph."""
def __init__(self, text: str, parent: QWidget | None = None) -> None:
super().__init__(text, parent)
self._online = True
self.setFixedHeight(18)
def set_online(self, online: bool) -> None:
self._online = online
self.update()
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
del event
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
reception = bool(self.property("receptionTechBlue"))
online_color = TECH_BLUE["accent"] if reception else "#28B98B"
color = QColor(online_color if self._online else "#EC5266")
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(color)
diameter = 6
painter.drawEllipse(QRectF(1, (self.height() - diameter) / 2, diameter, diameter))
painter.setPen(color)
painter.setFont(self.font())
painter.drawText(
QRectF(12, 0, self.width() - 12, self.height()),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
self.text(),
)
class _PaintedIconButton(QToolButton):
"""Font-independent shell icon used for every directional affordance."""
def __init__(
self,
kind: str,
*,
size: int = 42,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.kind = kind
# The close glyph used to be drawn at 12 px next to 18 px siblings, so
# the title bar's three controls never lined up optically. All of
# them are authored on the same grid now, so they share one size.
icon_size = 18
self.setObjectName("ShellPaintedIconButton")
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setAutoRaise(True)
self.setFixedSize(size, size)
self.setIcon(_painted_shell_icon(kind, icon_size))
self.setIconSize(QSize(icon_size, icon_size))
content_size = max(0, size - 2)
self.setStyleSheet(
f"""
QToolButton#ShellPaintedIconButton {{
min-width: {content_size}px;
max-width: {content_size}px;
min-height: {content_size}px;
max-height: {content_size}px;
background: transparent;
border: 1px solid transparent;
border-radius: 9px;
}}
QToolButton#ShellPaintedIconButton:hover {{
background: #F7F7F7;
border-color: #EDEDEE;
}}
QToolButton#ShellPaintedIconButton:pressed {{ background: #F0F0F0; }}
QToolButton#ShellPaintedIconButton:focus {{ border-color: #8B9AD9; }}
QToolButton#ShellPaintedIconButton[windowControl="close"]:hover {{
background: #FFF0F2;
border-color: #F4C4CC;
}}
QToolButton#ShellPaintedIconButton::menu-indicator {{ image: none; width: 0; }}
"""
)
class _UserMenuButton(QToolButton):
"""Compact admin-style user dropdown without font-glyph arrows."""
def __init__(self, display_name: str, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.display_name = display_name or "医生"
self.setObjectName("ShellUserMenu")
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
self.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.setFixedHeight(_SHELL_TOPBAR_HEIGHT)
name_width = self.fontMetrics().horizontalAdvance(self.display_name)
self.setFixedWidth(max(104, min(174, name_width + 72)))
self.setAccessibleName(f"用户菜单:{self.display_name}")
self.setText(self.display_name)
avatar = crisp_pixmap(34)
painter = QPainter(avatar)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(COLORS["indigo_pale"]))
painter.drawEllipse(QRectF(0, 0, 34, 34))
painter.setPen(QColor(COLORS["indigo"]))
avatar_font = QFont(painter.font())
avatar_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(avatar_font)
painter.drawText(
QRectF(0, 0, 34, 34), Qt.AlignmentFlag.AlignCenter, self.display_name[:1]
)
painter.end()
self.setIcon(QIcon(avatar))
self._legacy_avatar = self.icon()
self.setIconSize(QSize(34, 34))
self.setStyleSheet(
"""
QToolButton#ShellUserMenu {
color: #1A1C1F;
background: transparent;
border: 1px solid transparent;
border-radius: 9px;
padding: 0 18px 0 7px;
font-size: 13px;
font-weight: 500;
}
QToolButton#ShellUserMenu:hover { background: #F7F7F7; border-color: #EDEDEE; }
QToolButton#ShellUserMenu:pressed { background: #F0F0F0; }
QToolButton#ShellUserMenu:focus { border-color: #8B9AD9; }
QToolButton#ShellUserMenu::menu-indicator {
subcontrol-origin: padding;
subcontrol-position: right center;
right: 7px;
}
"""
)
def set_reception_avatar(self, active: bool) -> None:
if not active:
self.setIcon(self._legacy_avatar)
self.setIconSize(QSize(34, 34))
return
avatar = crisp_pixmap(44)
painter = QPainter(avatar)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(TECH_BLUE["selection"]))
painter.drawEllipse(QRectF(0, 0, 44, 44))
painter.setPen(QColor(TECH_BLUE["accent"]))
font = QFont(heading_family())
font.setPixelSize(17)
font.setWeight(QFont.Weight.DemiBold)
painter.setFont(font)
painter.drawText(
QRectF(0, 0, 44, 44), Qt.AlignmentFlag.AlignCenter, self.display_name[:1]
)
painter.end()
self.setIcon(QIcon(avatar))
self.setIconSize(QSize(44, 44))
class _RefreshButton(_PaintedIconButton):
"""Top-bar refresh whose icon turns while the page is reloading.
List loads are silent - they no longer raise a banner into the layout - so
this button is the only place left that can say "your click did something".
Without it a refresh on a slow query looks like a dead control.
"""
_FRAMES = 12
_FRAME_MS = 55
#: Spin for at least this long even if the reload was instant, or a fast
#: refresh flickers once and reads as a glitch rather than as feedback.
_MIN_MS = 420
#: And never longer than this, so a page that forgets to clear its loading
#: flag cannot leave the icon spinning for the rest of the session.
_CAP_MS = 10_000
def __init__(self, *, size: int = 38, parent: QWidget | None = None) -> None:
super().__init__("refresh", size=size, parent=parent)
self._is_busy: Callable[[], bool] = lambda: False
self._resting = self.icon()
self._frames = [
QIcon(self._rotated(index * 360 / self._FRAMES)) for index in range(self._FRAMES)
]
self._frame = 0
self._elapsed = QElapsedTimer()
self._timer = QTimer(self)
self._timer.setInterval(self._FRAME_MS)
self._timer.timeout.connect(self._tick)
def _rotated(self, angle: float) -> QPixmap:
color = TECH_BLUE["text"] if self.property("receptionTechBlue") else "muted"
source = icons.pixmap("refresh", color, self.iconSize().width())
size = self.iconSize().width()
canvas = crisp_pixmap(size)
painter = QPainter(canvas)
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
painter.translate(size / 2.0, size / 2.0)
painter.rotate(angle)
painter.translate(-size / 2.0, -size / 2.0)
painter.drawPixmap(QRectF(0, 0, size, size), source, QRectF(source.rect()))
painter.end()
return canvas
def set_busy_probe(self, probe: Callable[[], bool]) -> None:
self._is_busy = probe
def set_reception_palette(self, active: bool) -> None:
self.setProperty("receptionTechBlue", active)
self._resting = _painted_shell_icon("refresh", self.iconSize().width(), reception=active)
self._frames = [
QIcon(self._rotated(index * 360 / self._FRAMES)) for index in range(self._FRAMES)
]
self.setIcon(self._frames[self._frame] if self._timer.isActive() else self._resting)
def start_spin(self) -> None:
self._frame = 0
self._elapsed.restart()
if not self._timer.isActive():
self._timer.start()
def _tick(self) -> None:
elapsed = self._elapsed.elapsed()
if elapsed >= self._CAP_MS or (elapsed >= self._MIN_MS and not self._is_busy()):
self._timer.stop()
self.setIcon(self._resting)
return
self._frame = (self._frame + 1) % self._FRAMES
self.setIcon(self._frames[self._frame])
class _ShellCanvas(QWidget):
"""Outer frameless-window ground, with native edge resizing.
This is the bottom-most layer of the application, so it is the one that
carries the window's corner. It used to be a plain square fill from the
global ``QMainWindow`` rule, which meant the only rounded things at the
window edge were the panels sitting on top of it - a corner inside a corner.
"""
_RESIZE_MARGIN = 8
#: The workspace card is inset by the gutter and rounded at ``r_xl``; a
#: concentric outer corner is therefore that radius plus the gutter, which
#: is what keeps the two curves parallel instead of merely both-rounded.
_RADIUS = 16.0 + _SHELL_OUTER_GUTTER
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
del event
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setPen(Qt.PenStyle.NoPen)
reception = bool(self.property("receptionTechBlue"))
color = TECH_BLUE["surface"] if reception else COLORS["canvas"]
painter.setBrush(QColor(color))
if reception:
painter.drawRect(self.rect())
else:
painter.drawRoundedRect(QRectF(self.rect()), self._RADIUS, self._RADIUS)
def _resize_edges(self, position: QPointF) -> Qt.Edge:
edges = Qt.Edge(0)
if position.x() <= self._RESIZE_MARGIN:
edges |= Qt.Edge.LeftEdge
elif position.x() >= self.width() - self._RESIZE_MARGIN:
edges |= Qt.Edge.RightEdge
if position.y() <= self._RESIZE_MARGIN:
edges |= Qt.Edge.TopEdge
elif position.y() >= self.height() - self._RESIZE_MARGIN:
edges |= Qt.Edge.BottomEdge
return edges
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual
edges = self._resize_edges(event.position())
diagonal_down = Qt.Edge.LeftEdge | Qt.Edge.TopEdge
diagonal_up = Qt.Edge.LeftEdge | Qt.Edge.BottomEdge
if edges in (diagonal_down, Qt.Edge.RightEdge | Qt.Edge.BottomEdge):
self.setCursor(Qt.CursorShape.SizeFDiagCursor)
elif edges in (diagonal_up, Qt.Edge.RightEdge | Qt.Edge.TopEdge):
self.setCursor(Qt.CursorShape.SizeBDiagCursor)
elif edges in (Qt.Edge.LeftEdge, Qt.Edge.RightEdge):
self.setCursor(Qt.CursorShape.SizeHorCursor)
elif edges in (Qt.Edge.TopEdge, Qt.Edge.BottomEdge):
self.setCursor(Qt.CursorShape.SizeVerCursor)
else:
self.unsetCursor()
super().mouseMoveEvent(event)
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual
if event.button() == Qt.MouseButton.LeftButton:
edges = self._resize_edges(event.position())
handle = self.window().windowHandle()
if edges and handle is not None and handle.startSystemResize(edges):
event.accept()
return
super().mousePressEvent(event)
class _ShellTopBar(QFrame):
"""Integrated title bar that retains native system move/maximize behavior."""
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual
if event.button() == Qt.MouseButton.LeftButton:
window = self.window()
handle = window.windowHandle()
if handle is not None and handle.startSystemMove():
event.accept()
return
super().mousePressEvent(event)
def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual
if event.button() == Qt.MouseButton.LeftButton:
window = self.window()
if window.isMaximized():
window.showNormal()
else:
window.showMaximized()
event.accept()
return
super().mouseDoubleClickEvent(event)
class ShellWindow(QMainWindow):
"""Main workstation window.
The expected construction signature is ``ShellWindow(repository, session,
permissions=None)``. ``session`` may be a Session dataclass, the payload
emitted by :class:`LoginWindow`, or a plain mapping.
"""
logout_requested = Signal()
close_requested = Signal()
video_requested = Signal(dict)
page_changed = Signal(str)
update_check_requested = Signal()
def __init__(
self,
repository: Any,
session: Any,
permissions: Any = None,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.setProperty("doctorMainWindow", True)
self.setWindowTitle("甄养堂 · 问诊中心")
self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
# The ground paints its own rounded corner, so everything outside that
# corner has to be genuinely empty rather than filled by the global
# QMainWindow background.
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
self.setStyleSheet("QMainWindow { background: transparent; }")
self.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True)
self.repository = repository
self.login_payload = session
self.session = get_value(session, "session", None) or session
self.current_user = (
get_value(session, "user", None)
or get_value(self.session, "user", None)
or get_value(session, "current_user", None)
or session
)
if permissions is not None:
self.permissions = permissions
else:
session_permissions = get_value(self.session, "permissions", None)
self.permissions = (
session_permissions
if session_permissions is not None
else get_value(self.current_user, "permissions", None)
)
self._can_ai_assistant = can_open_ai_consult(self.permissions)
session_menu = get_value(self.session, "menu", None)
self.menu = (
session_menu if session_menu is not None else get_value(session, "menu", [])
)
self.demo_mode = bool(
get_value(session, "demo_mode", False)
or get_value(self.session, "metadata.demo", False)
or get_value(self.session, "metadata.demo_mode", False)
)
self.navigation = _resolve_navigation(
self.menu,
self.permissions,
demo_mode=self.demo_mode,
)
self.pages: dict[str, QWidget] = {}
self.nav_buttons: dict[str, QPushButton] = {}
self.page_titles: dict[int, str] = {}
self._fixed_tab_key: str | None = None
self._sidebar_collapsed = False
self._reception_chrome_active = False
self._active_page_key: str | None = None
self._activation_page: QWidget | None = None
self._activation_generation = 0
self._activation_refreshed = False
self._local_audio_settings_dialog: LocalAudioQueueDialog | None = None
self._global_diagnosis_dialog: DiagnosisDialog | None = None
# 与后台 chat-notify-toast 同一份数据源,登录后常驻轮询。
self.chat_notifications = ChatNotificationCenter(repository, self)
self.chat_notifications.notification_activated.connect(
self._open_chat_notification
)
self.setMinimumSize(_SHELL_MINIMUM_SIZE)
screen = self.screen() or QApplication.primaryScreen()
available_size = screen.availableGeometry().size() if screen is not None else None
self.resize(_bounded_initial_window_size(available_size))
canvas = _ShellCanvas(self)
canvas.setObjectName("AppCanvas")
canvas.setMouseTracking(True)
self.setCentralWidget(canvas)
root = QHBoxLayout(canvas)
root.setContentsMargins(
_SHELL_OUTER_GUTTER,
_SHELL_OUTER_GUTTER,
_SHELL_OUTER_GUTTER,
_SHELL_OUTER_GUTTER,
)
root.setSpacing(_SHELL_PANEL_GAP)
self.sidebar = self._build_sidebar()
root.addWidget(self.sidebar)
self.workspace = QWidget()
self.workspace.setObjectName("ShellWorkspace")
self.workspace.setStyleSheet(
"""
QWidget#ShellWorkspace {
background-color: #FFFFFF;
border: 0;
border-radius: 16px;
}
"""
)
workspace_layout = QVBoxLayout(self.workspace)
workspace_layout.setContentsMargins(0, 0, 0, 0)
workspace_layout.setSpacing(0)
self.topbar = self._build_topbar()
workspace_layout.addWidget(self.topbar)
self.tabs_host = self._build_tab_strip()
workspace_layout.addWidget(self.tabs_host)
self.stack = QStackedWidget()
self.stack.setObjectName("ShellPageStack")
self.stack.setStyleSheet(
"QStackedWidget#ShellPageStack {"
" background-color: #FFFFFF; border: 0;"
" border-bottom-left-radius: 16px; border-bottom-right-radius: 16px;"
" }"
)
workspace_layout.addWidget(self.stack, 1)
root.addWidget(self.workspace, 1)
# Deliberately no shadow layer here. The window is itself a rounded
# floating surface, so a shadow around the two panels inside it stacks a
# third rounded outline into a 13 px gutter and each window corner ends
# up showing three nested edges. Elevation belongs to the cards inside a
# page, where there is a real surface behind them to lift off.
# Every override targets a chrome object by ID, so page fonts and
# dialogs remain independent of the reception appearance.
chrome_widgets = [self.sidebar, self.workspace, self.stack, self.topbar,
self.tabs_host, self.user_menu_button]
chrome_widgets.extend(self.topbar.findChildren(_PaintedIconButton))
chrome_widgets.append(self.tabs_menu_button)
self._legacy_chrome_styles = {
widget: clinical_stylesheet(widget.styleSheet()) for widget in chrome_widgets
}
self._register_pages()
self.search_shortcut = QShortcut(QKeySequence("Ctrl+K"), self)
self.search_shortcut.activated.connect(self._focus_global_search)
def _build_sidebar(self) -> QWidget:
sidebar = QWidget()
sidebar.setObjectName("Sidebar")
sidebar.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
sidebar.setFixedWidth(_SHELL_EXPANDED_WIDTH)
sidebar.setStyleSheet(
"""
/* The rail is the ground, not a panel on it. It used to carry a
diagonal gradient against a flat canvas
canvas, so it never matched at any point along its own left edge -
a permanent faint seam down the window, and a second rounded
corner nested inside the window's own. Painting nothing lets the
canvas show through, which makes the two one surface and leaves
the bottom-most layer as the only thing with a corner. */
QWidget#Sidebar {
background-color: transparent;
border: 0;
border-radius: 0;
}
QFrame#ShellBrand {
background-color: transparent;
border: 0;
border-radius: 0;
}
QLabel#ShellBrandName { color: #1A1C1F; font-size: 15px; font-weight: 600; }
QLabel#ShellBrandSubtitle { color: #6A6B6D; font-size: 12px; }
QPushButton#ShellNavButton {
min-height: 45px;
max-height: 45px;
padding: 0 14px;
margin: 0;
border: 1px solid transparent;
border-radius: 8px;
background-color: transparent;
color: #606163;
text-align: left;
font-size: 14px;
font-weight: 500;
}
QPushButton#ShellNavButton:hover {
background-color: #EEF1FA;
border-color: #DEE4F6;
color: #1A1C1F;
}
QPushButton#ShellNavButton:pressed { background-color: #E3E8F8; }
QPushButton#ShellNavButton:focus { border-color: #8B9AD9; }
QPushButton#ShellNavButton:checked {
color: #FFFFFF;
background-color: #4F63D9;
border-color: transparent;
font-weight: 500;
}
QPushButton#ShellNavButton:checked:hover { background-color: #4156C4; }
QPushButton#ShellNavButton:checked:pressed { background-color: #354BB4; }
QPushButton#ShellNavButton[collapsed="true"] {
padding: 0;
text-align: center;
margin: 0;
}
QFrame#ShellAssistantCard {
background-color: rgba(255, 255, 255, 230);
border: 1px solid #EDEDEE;
border-radius: 12px;
}
QLabel#ShellAssistantGlyph {
color: #4F63D9;
background-color: #EEF1FA;
border: 1px solid rgba(82, 101, 246, 48);
border-radius: 18px;
font-size: 13px;
font-weight: 600;
}
QLabel#ShellAssistantName { color: #1A1C1F; font-size: 13px; font-weight: 500; }
QLabel#ShellAssistantStatus { color: #287B65; font-size: 12px; }
QPushButton#ShellAssistantButton {
min-height: 34px;
color: #FFFFFF;
background-color: #4F63D9;
border: 0;
border-radius: 9px;
font-weight: 500;
}
QPushButton#ShellAssistantButton:hover { background-color: #4156C4; }
QPushButton#ShellAssistantButton:pressed { background-color: #354BB4; }
QPushButton#ShellSettingsButton {
min-height: 42px;
color: #606163;
font-size: 13px;
font-weight: 500;
background-color: transparent;
border: 1px solid transparent;
border-radius: 10px;
}
QPushButton#ShellSettingsButton:hover {
color: #1A1C1F;
background-color: #F0F0F0;
}
QPushButton#ShellSettingsButton:focus { border-color: #8B9AD9; }
"""
)
layout = QVBoxLayout(sidebar)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
brand = QFrame(sidebar)
self.brand = brand
brand.setObjectName("ShellBrand")
brand.setFixedHeight(75)
brand_layout = QHBoxLayout(brand)
self.brand_layout = brand_layout
brand_layout.setContentsMargins(21, 17, 10, 8)
brand_layout.setSpacing(10)
self.brand_mark = _ShellBrandMark(brand)
self.brand_mark.setObjectName("ShellBrandMark")
self.brand_mark.setFixedSize(36, 36)
brand_layout.addWidget(self.brand_mark)
self.brand_copy = QWidget(brand)
brand_copy_layout = QVBoxLayout(self.brand_copy)
brand_copy_layout.setContentsMargins(0, 0, 0, 0)
brand_copy_layout.setSpacing(1)
self.brand_name = QLabel("问诊中心", self.brand_copy)
self.brand_name.setObjectName("ShellBrandName")
brand_copy_layout.addWidget(self.brand_name)
self.brand_subtitle = QLabel("糖尿病专科版", self.brand_copy)
self.brand_subtitle.setObjectName("ShellBrandSubtitle")
brand_copy_layout.addWidget(self.brand_subtitle)
brand_layout.addWidget(self.brand_copy, 1)
layout.addWidget(brand)
self.nav_layout = QVBoxLayout()
self.nav_layout.setContentsMargins(12, 19, 12, 0)
self.nav_layout.setSpacing(0)
layout.addLayout(self.nav_layout)
layout.addStretch(1)
self.assistant_card = QFrame(sidebar)
self.assistant_card.setObjectName("ShellAssistantCard")
self.assistant_card.setFixedHeight(157)
assistant_layout = QVBoxLayout(self.assistant_card)
self.assistant_layout = assistant_layout
assistant_layout.setContentsMargins(12, 12, 12, 20)
assistant_layout.setSpacing(0)
assistant_head_host = QWidget(self.assistant_card)
assistant_head_host.setFixedHeight(60)
assistant_head = QHBoxLayout(assistant_head_host)
self.assistant_head_layout = assistant_head
assistant_head.setContentsMargins(0, 0, 0, 0)
assistant_head.setSpacing(9)
self.assistant_glyph = _AssistantRobot(assistant_head_host)
assistant_head.addWidget(self.assistant_glyph)
assistant_copy = QVBoxLayout()
assistant_copy.setContentsMargins(0, 5, 0, 5)
assistant_copy.setSpacing(1)
assistant_name = QLabel("AI 助手", self.assistant_card)
assistant_name.setObjectName("ShellAssistantName")
assistant_copy.addWidget(assistant_name)
self.assistant_status = _AssistantStatus("在线", assistant_head_host)
self.assistant_status.setObjectName("ShellAssistantStatus")
assistant_copy.addWidget(self.assistant_status)
assistant_head.addLayout(assistant_copy, 1)
assistant_layout.addWidget(assistant_head_host)
assistant_layout.addStretch(1)
self.assistant_button = QPushButton("开始对话", self.assistant_card)
self.assistant_button.setObjectName("ShellAssistantButton")
self.assistant_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.assistant_button.setFixedHeight(36)
self.assistant_button.clicked.connect(self._open_ai_assistant)
assistant_layout.addWidget(self.assistant_button)
outer_assistant = QHBoxLayout()
self.assistant_outer_layout = outer_assistant
outer_assistant.setContentsMargins(13, 0, 13, 0)
outer_assistant.addWidget(self.assistant_card)
layout.addLayout(outer_assistant)
self.assistant_card.setVisible(self._can_ai_assistant)
self.upload_settings_button = _ShellNavigationButton("设置 ›", sidebar)
self.upload_settings_button.setObjectName("ShellSettingsButton")
self.upload_settings_button.setAccessibleName("本机录音上传设置")
self.upload_settings_button.setToolTip("查看本机录音上传记录")
self.upload_settings_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.upload_settings_button.setFixedHeight(76)
self.upload_settings_button.clicked.connect(self._open_local_audio_settings)
# Keep the former attribute as a compatibility alias for integrations
# that inspect the bottom sidebar control.
self.model_label = self.upload_settings_button
layout.addWidget(self.upload_settings_button)
return sidebar
def _build_topbar(self) -> QWidget:
topbar = _ShellTopBar(self.workspace)
topbar.setObjectName("TopBar")
topbar.setFixedHeight(_SHELL_TOPBAR_HEIGHT)
topbar.setStyleSheet(
"""
QFrame#TopBar {
background-color: #FFFFFF;
border: 0;
border-bottom: 1px solid #F0F0F0;
border-top-left-radius: 16px;
border-top-right-radius: 16px;
}
QFrame#ShellGlobalSearch {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
border-radius: 10px;
}
QLineEdit#ShellGlobalSearchInput {
min-height: 34px;
max-height: 34px;
padding: 0 8px;
color: #606163;
background-color: transparent;
border: 0;
border-radius: 9px;
}
QLineEdit#ShellGlobalSearchInput QToolButton {
min-width: 22px;
max-width: 22px;
min-height: 18px;
max-height: 18px;
margin: 0;
padding: 0;
background-color: transparent;
border: 0;
border-radius: 0;
}
QLineEdit#ShellGlobalSearchInput QToolButton:hover,
QLineEdit#ShellGlobalSearchInput QToolButton:pressed,
QLineEdit#ShellGlobalSearchInput QToolButton:focus {
background-color: transparent;
border: 0;
}
QLabel#ShellShortcutHint {
color: #6A6B6D;
background-color: #F7F7F7;
border: 1px solid #EDEDEE;
border-radius: 6px;
padding: 2px 6px;
font-size: 10px;
}
QPushButton#ShellAiEntry {
min-width: 38px;
max-width: 38px;
min-height: 38px;
max-height: 38px;
padding: 0;
color: #4F63D9;
background-color: transparent;
border: 0;
border-radius: 9px;
font-weight: 500;
}
QPushButton#ShellAiEntry:hover { background-color: #EEF1FA; }
QLabel#ShellConnectionBadge {
color: #606163;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
border-radius: 10px;
padding: 4px 10px;
font-size: 13px;
font-weight: 500;
}
QLabel#ShellConnectionBadge[kind="success"] {
color: #287B65;
background-color: #E8F6F1;
border-color: #B9E3D7;
}
QLabel#ShellConnectionBadge[kind="danger"] {
color: #EC5266;
background-color: #FFF0F2;
border-color: #F4C4CC;
}
QToolButton#ShellPaintedIconButton[windowControl="close"]:hover {
background-color: #FFF0F2;
border-color: #F4C4CC;
}
QMenu {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
border-radius: 10px;
padding: 6px;
}
QMenu::item { min-width: 112px; min-height: 32px; padding: 0 12px; border-radius: 6px; }
QMenu::item:selected { color: #1A1C1F; background-color: #EEF1FA; }
QMenu::item:disabled { color: #8E8F90; }
QMenu::separator { height: 1px; background: #EDEDEE; margin: 5px 8px; }
"""
)
layout = QHBoxLayout(topbar)
layout.setContentsMargins(20, 0, 10, 0)
layout.setSpacing(5)
self.fold_button = _PaintedIconButton("fold", size=38, parent=topbar)
self.fold_button.setToolTip("收起或展开菜单")
self.fold_button.setAccessibleName("收起或展开菜单")
self.fold_button.clicked.connect(self.toggle_sidebar)
layout.addWidget(self.fold_button)
layout.addSpacing(9)
self._fold_spacing = layout.itemAt(layout.count() - 1).spacerItem()
search_host = QFrame(topbar)
self.search_host = search_host
search_host.setObjectName("ShellGlobalSearch")
search_host.setFixedSize(265, 36)
search_layout = QHBoxLayout(search_host)
search_layout.setContentsMargins(4, 0, 7, 0)
search_layout.setSpacing(3)
self.search_mark = QToolButton(search_host)
self.search_mark.setObjectName("ShellSearchMark")
self.search_mark.setFixedSize(20, 20)
self.search_mark.setAutoRaise(True)
self.search_mark.setCursor(Qt.CursorShape.PointingHandCursor)
self.search_mark.setAccessibleName("搜索患者")
self.search_mark.setToolTip("搜索患者(回车)")
self.search_mark.setStyleSheet("background: transparent; border: 0; padding: 0;")
self.search_mark.clicked.connect(self._run_global_search)
self.search_mark.hide()
search_layout.addWidget(self.search_mark)
self.global_search = QLineEdit(search_host)
self.global_search.setObjectName("ShellGlobalSearchInput")
self.global_search.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed
)
self.global_search.setPlaceholderText("搜索患者姓名、手机号...")
self.global_search.setToolTip("输入患者姓名或手机号,按回车或点击放大镜搜索")
self.global_search.setClearButtonEnabled(True)
self._global_search_icon_action = self.global_search.addAction(
_painted_shell_icon("search", 16),
QLineEdit.ActionPosition.LeadingPosition,
)
self._global_search_icon_action.setToolTip("搜索患者(回车)")
self._global_search_icon_action.triggered.connect(self._run_global_search)
self.global_search.returnPressed.connect(self._run_global_search)
search_layout.addWidget(self.global_search, 1)
shortcut_hint = QLabel("Ctrl K", search_host)
self.search_shortcut_hint = shortcut_hint
shortcut_hint.setObjectName("ShellShortcutHint")
shortcut_hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
shortcut_hint.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
search_layout.addWidget(shortcut_hint, 0, Qt.AlignmentFlag.AlignVCenter)
layout.addWidget(search_host)
self.context_label = QLabel("工作台", topbar)
self.context_label.setObjectName("ShellBreadcrumbCurrent")
self.context_label.hide()
layout.addStretch(1)
self.refresh_button = _RefreshButton(size=38, parent=topbar)
self.refresh_button.setToolTip("刷新当前页面(F5)")
self.refresh_button.setAccessibleName("刷新当前页面")
self.refresh_button.set_busy_probe(self._current_page_is_loading)
self.refresh_button.clicked.connect(self.refresh_current_page)
layout.addWidget(self.refresh_button)
self.ai_top_button = QPushButton("", topbar)
self.ai_top_button.setObjectName("ShellAiEntry")
self.ai_top_button.setIcon(_painted_shell_icon("ai", 18))
self.ai_top_button.setIconSize(QSize(18, 18))
self.ai_top_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.ai_top_button.setToolTip("AI 助手")
self.ai_top_button.setAccessibleName("AI 助手")
self.ai_top_button.clicked.connect(self._open_ai_assistant)
layout.addWidget(self.ai_top_button)
self.ai_top_button.setVisible(self._can_ai_assistant)
self.notification_button = _PaintedIconButton(
"notification", size=38, parent=topbar
)
self.notification_button.setToolTip("消息通知")
self.notification_button.clicked.connect(self._show_chat_notification_summary)
layout.addWidget(self.notification_button)
self.settings_button = _PaintedIconButton("settings", size=38, parent=topbar)
self.settings_button.setToolTip("设置中心")
self.settings_button.clicked.connect(
lambda: show_toast(self, "设置中心将沿用当前账号的系统配置。", "info")
)
layout.addWidget(self.settings_button)
self.user_separator = QFrame(topbar)
self.user_separator.setObjectName("ShellUserSeparator")
self.user_separator.setFixedSize(1, 44)
self.user_separator.hide()
layout.addWidget(self.user_separator)
self.connection_badge = StatusBadge("服务正常", "success", topbar)
self.connection_badge.setObjectName("ShellConnectionBadge")
self.connection_badge.hide()
display_name = display_text(
first_value(
self.current_user,
"name",
"display_name",
"nickname",
"account",
default="医生",
)
)
self.user_menu_button = _UserMenuButton(display_name, topbar)
self.user_menu_button.setToolTip(f"{display_name} · {self._role_text()}")
user_menu = QMenu(self.user_menu_button)
account_action = user_menu.addAction(self._role_text())
account_action.setEnabled(False)
user_menu.addSeparator()
self.menu_sidebar_action = user_menu.addAction("收起或展开菜单")
self.menu_sidebar_action.triggered.connect(self.toggle_sidebar)
self.menu_sidebar_action.setVisible(False)
self.menu_ai_action = user_menu.addAction("AI 助手")
self.menu_ai_action.triggered.connect(self._open_ai_assistant)
self.menu_ai_action.setVisible(False)
if "1" in self._role_ids() and can_open_esign_doctor(self.repository, self.permissions):
user_menu.addAction("医生电子签署身份", self._open_esign_doctor)
update_action = user_menu.addAction("检查更新")
update_action.triggered.connect(self.update_check_requested.emit)
user_menu.addSeparator()
logout_action = user_menu.addAction("退出登录")
logout_action.triggered.connect(lambda: self.logout_requested.emit())
self.user_menu_button.setMenu(user_menu)
layout.addWidget(self.user_menu_button)
self.minimize_button = _PaintedIconButton("minimize", size=34, parent=topbar)
self.minimize_button.setToolTip("最小化")
self.minimize_button.clicked.connect(self.showMinimized)
layout.addWidget(self.minimize_button)
self.fullscreen_button = _PaintedIconButton(
"fullscreen", size=34, parent=topbar
)
self.fullscreen_button.setToolTip("最大化")
self.fullscreen_button.setAccessibleName("切换最大化")
self.fullscreen_button.clicked.connect(self._toggle_maximized)
layout.addWidget(self.fullscreen_button)
self.close_button = _PaintedIconButton("close", size=34, parent=topbar)
self.close_button.setProperty("windowControl", "close")
self.close_button.setToolTip("关闭")
self.close_button.clicked.connect(self.close)
layout.addWidget(self.close_button)
return topbar
def _build_tab_strip(self) -> QWidget:
tabs_host = QFrame()
tabs_host.setObjectName("MultipleTabs")
tabs_host.setFixedHeight(_SHELL_TABS_HEIGHT)
tabs_host.setStyleSheet(
"""
QFrame#MultipleTabs {
background-color: #FFFFFF;
border-top: 0;
border-bottom: 1px solid #E4E4E5;
}
QTabBar#ShellTabs { background-color: #FFFFFF; }
QTabBar#ShellTabs::tab {
min-height: 40px;
max-height: 40px;
min-width: 84px;
padding: 0 14px;
margin: 0 2px;
color: #606163;
background-color: transparent;
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
font-size: 13px;
font-weight: 500;
}
QTabBar#ShellTabs::tab:hover { color: #1A1C1F; background-color: #F7F7F7; }
QTabBar#ShellTabs::tab:selected {
color: #4F63D9;
background-color: #EEF1FA;
border-bottom: 2px solid #4F63D9;
font-weight: 500;
}
QMenu {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #E4E4E5;
border-radius: 10px;
padding: 6px;
}
QMenu::item { min-width: 112px; min-height: 32px; padding: 0 12px; border-radius: 6px; }
QMenu::item:selected { color: #1A1C1F; background-color: #EEF1FA; }
QMenu::item:disabled { color: #8E8F90; }
QMenu::separator { height: 1px; background: #E4E4E5; margin: 5px 8px; }
"""
)
layout = QHBoxLayout(tabs_host)
layout.setContentsMargins(16, 0, 0, 0)
layout.setSpacing(0)
self.tab_bar = QTabBar()
self.tab_bar.setObjectName("ShellTabs")
self.tab_bar.setDocumentMode(True)
self.tab_bar.setDrawBase(False)
self.tab_bar.setExpanding(False)
self.tab_bar.setUsesScrollButtons(True)
self.tab_bar.setElideMode(Qt.TextElideMode.ElideRight)
self.tab_bar.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed
)
self.tab_bar.currentChanged.connect(self._tab_selected)
layout.addWidget(self.tab_bar, 1)
self.tabs_menu_button = _PaintedIconButton("down")
self.tabs_menu_button.setToolTip("标签页操作")
self.tabs_menu_button.setAccessibleName("标签页操作")
self.tabs_menu_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
tabs_menu = QMenu(self.tabs_menu_button)
self.close_current_action = tabs_menu.addAction("关闭当前")
self.close_current_action.triggered.connect(self.close_current_tab)
self.close_other_action = tabs_menu.addAction("关闭其他")
self.close_other_action.triggered.connect(self.close_other_tabs)
self.close_all_action = tabs_menu.addAction("关闭全部")
self.close_all_action.triggered.connect(self.close_all_tabs)
self.tabs_menu_button.setMenu(tabs_menu)
layout.addWidget(self.tabs_menu_button)
self._update_tab_actions()
tabs_host.hide()
return tabs_host
def _role_text(self) -> str:
department = first_value(
self.current_user, "department_name", "department.name", default=""
)
role_values = self._role_ids()
role = (
"医生"
if "1" in role_values
else "医助"
if "2" in role_values
else "医疗人员"
)
return f"{department} · {role}" if department else role
def _role_ids(self) -> set[str]:
role_ids = first_value(self.current_user, "role_ids", "role_id", default=[]) or []
if not isinstance(role_ids, (list, tuple, set, frozenset)):
role_ids = [role_ids]
return {str(value) for value in role_ids}
def toggle_sidebar(self) -> None:
"""Toggle the admin-style compact menu while preserving the page state."""
self._sidebar_collapsed = not self._sidebar_collapsed
self.sidebar.setFixedWidth(
_SHELL_COLLAPSED_WIDTH
if self._sidebar_collapsed
else self._expanded_sidebar_width()
)
self.brand_copy.setVisible(not self._sidebar_collapsed)
self.assistant_card.setVisible(
self._can_ai_assistant and not self._sidebar_collapsed
)
self.upload_settings_button.setVisible(not self._sidebar_collapsed)
margins = self._navigation_margins()
self.nav_layout.setContentsMargins(*margins)
self.fold_button.kind = "expand" if self._sidebar_collapsed else "fold"
self.fold_button.setIcon(
_painted_shell_icon(self.fold_button.kind, reception=self._reception_chrome_active)
)
for button in self.nav_buttons.values():
title = str(button.property("navTitle") or "")
button.setText("" if self._sidebar_collapsed else title)
button.setToolTip(title if self._sidebar_collapsed else "")
button.setProperty("collapsed", self._sidebar_collapsed)
button.style().unpolish(button)
button.style().polish(button)
self._set_reception_geometry(self._reception_chrome_active)
def _expanded_sidebar_width(self, key: str | None = None) -> int:
reception = key in _TECH_BLUE_PAGES if key is not None else self._reception_chrome_active
return _RECEPTION_SIDEBAR_WIDTH if reception else _SHELL_EXPANDED_WIDTH
def _navigation_margins(self) -> tuple[int, int, int, int]:
if self._sidebar_collapsed:
return (7, 19 if self._reception_chrome_active else 14, 7, 0)
return (9, 19, 10, 0) if self._reception_chrome_active else (12, 19, 12, 0)
def _set_reception_geometry(self, active: bool) -> None:
"""Keep the approved geometry page-local, including compact-rail state."""
gutter = 0 if active else _SHELL_OUTER_GUTTER
self.centralWidget().layout().setContentsMargins(gutter, gutter, gutter, gutter)
self.sidebar.setFixedWidth(
_SHELL_COLLAPSED_WIDTH if self._sidebar_collapsed else self._expanded_sidebar_width()
)
self.topbar.setFixedHeight(_RECEPTION_TOPBAR_HEIGHT if active else _SHELL_TOPBAR_HEIGHT)
self.brand.setFixedHeight(80 if active else 75)
brand_margins = (26, 14, 10, 9) if active else (21, 17, 10, 8)
if active and self._sidebar_collapsed:
brand_margins = (15, 14, 15, 9)
self.brand_layout.setContentsMargins(*brand_margins)
self.brand_layout.setSpacing(13 if active else 10)
self.brand_mark.setFixedSize(38 if active else 36, 38 if active else 36)
self.nav_layout.setContentsMargins(*self._navigation_margins())
self.nav_layout.setSpacing(4 if active else 0)
self.assistant_card.setFixedHeight(132 if active else 157)
self.assistant_layout.setContentsMargins(*(13, 12, 13, 12) if active else (12, 12, 12, 20))
self.assistant_head_layout.setContentsMargins(4 if active else 0, 0, 0, 0)
self.assistant_head_layout.setSpacing(8 if active else 9)
self.assistant_glyph.setFixedSize(48 if active else 56, 48 if active else 56)
self.assistant_outer_layout.setContentsMargins(*(20, 0, 20, 0) if active else (13, 0, 13, 0))
self.assistant_status.setFixedHeight(18)
self.assistant_button.setFixedHeight(36 if active else 34)
self.upload_settings_button.setFixedHeight(52 if active else 44)
self.upload_settings_button.setIcon(_painted_shell_icon("settings", 20, reception=True) if active else QIcon())
self.upload_settings_button.setIconSize(QSize(20, 20) if active else QSize(16, 16))
self.upload_settings_button.setText("设置 ›" if active else "设置 ›")
self.topbar.layout().setContentsMargins(*(26, 0, 8, 0) if active else (20, 0, 10, 0))
self.topbar.layout().setSpacing(7 if active else 5)
self.fold_button.setVisible(not active)
self._fold_spacing.changeSize(0 if active else 9, 0)
self.search_host.setFixedSize(QSize(384, 44) if active else QSize(265, 36))
self.search_host.layout().setContentsMargins(*(20, 0, 9, 0) if active else (4, 0, 7, 0))
self.search_host.layout().setSpacing(6 if active else 3)
self.search_mark.setVisible(active)
self._global_search_icon_action.setVisible(not active)
self.global_search.setPlaceholderText("搜索患者姓名、手机号...")
self.search_shortcut_hint.setText("Ctrl K")
self.ai_top_button.setVisible(self._can_ai_assistant and not active)
self.menu_sidebar_action.setVisible(active)
self.menu_ai_action.setVisible(active and self._can_ai_assistant)
self.user_separator.setVisible(active)
if active:
self.user_menu_button.setFixedSize(179, _RECEPTION_TOPBAR_HEIGHT)
elif hasattr(self, "_legacy_user_menu_size"):
self.user_menu_button.setFixedSize(self._legacy_user_menu_size)
self.topbar.layout().invalidate()
self._fit_reception_search()
def _fit_reception_search(self) -> None:
if not self._reception_chrome_active:
return
# Preserve every user/window action at the supported 1024 px minimum;
# the approved 384 px field fits unchanged at 1280 px and above.
controls_width = 26 + 8 + 3 * 50 + 179 + 3 * 34 + 1 + 8 * 7
width = self.width() - self.sidebar.width() - controls_width
self.search_host.setFixedWidth(min(384, max(220, width)))
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
super().resizeEvent(event)
if getattr(self, "_reception_chrome_active", False):
self._fit_reception_search()
def _set_reception_chrome(self, active: bool) -> None:
"""Apply approved pages' shared chrome and restore the exact legacy QSS."""
if active == self._reception_chrome_active:
return
if active:
# Qt styles can adjust a fixed control by its border width during
# polish; restore the effective size that the user actually saw.
self._legacy_user_menu_size = self.user_menu_button.size()
self._reception_chrome_active = active
replacements = {
"#4F63D9": TECH_BLUE["accent"],
"#4156C4": TECH_BLUE["accent_hover"],
"#354BB4": TECH_BLUE["accent_pressed"],
"#EEF1FA": TECH_BLUE["selection"],
"#E3E8F8": TECH_BLUE["selection"],
"#DEE4F6": TECH_BLUE["line"],
"#8B9AD9": TECH_BLUE["focus"],
"#1A1C1F": TECH_BLUE["heading"],
"#606163": TECH_BLUE["text"],
"#6A6B6D": TECH_BLUE["muted"],
"#F7F7F7": TECH_BLUE["raised"],
"#F0F0F0": TECH_BLUE["line"],
"#EDEDEE": TECH_BLUE["line"],
"#E4E4E5": TECH_BLUE["line"],
"#287B65": TECH_BLUE["selected_text"],
"#E8F6F1": TECH_BLUE["selection"],
"#B9E3D7": TECH_BLUE["line"],
}
for widget, original in self._legacy_chrome_styles.items():
stylesheet = original
if active:
for old_color, new_color in replacements.items():
stylesheet = stylesheet.replace(old_color, new_color)
if widget in (self.sidebar, self.topbar, self.tabs_host):
stylesheet += f"""
QWidget {{ font-family: "{body_family()}"; font-weight: 400; }}
"""
if widget is self.sidebar:
stylesheet += f"""
QWidget#Sidebar {{
background-color: {_RECEPTION_SIDEBAR_COLOR};
border-right: 1px solid {_RECEPTION_CHROME_LINE};
}}
QLabel#ShellBrandName {{
font-family: "{heading_family()}"; font-weight: 600;
color: {TECH_BLUE['heading']}; font-size: {TYPE['fs_section']};
}}
QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['muted']}; font-size: {TYPE['fs_small']}; }}
QPushButton#ShellNavButton {{
font-family: "{body_family()}"; font-weight: 400;
min-height: 44px; max-height: 44px;
border: 0; border-left: 5px solid transparent;
border-radius: {METRICS["r_md"]};
padding: 0 16px; font-size: {TYPE['fs_body']};
color: {TECH_BLUE['text']};
}}
QPushButton#ShellNavButton:checked,
QPushButton#ShellNavButton:checked:hover,
QPushButton#ShellNavButton:checked:pressed {{
color: {TECH_BLUE['selected_text']};
background-color: {TECH_BLUE['selection']};
border-left: 5px solid {TECH_BLUE['accent']};
font-weight: 400;
}}
QPushButton#ShellNavButton:focus {{
border: 1px solid {TECH_BLUE['focus']};
border-left: 5px solid {TECH_BLUE['accent']};
}}
QPushButton#ShellNavButton[collapsed="true"] {{ padding: 0; }}
QFrame#ShellAssistantCard {{
background-color: {TECH_BLUE['surface']}; border-radius: {METRICS["r_lg"]};
border: 1px solid {_RECEPTION_CHROME_LINE};
}}
QLabel#ShellAssistantName {{
font-family: "{heading_family()}"; font-weight: 500; font-size: {TYPE['fs_body']};
}}
QLabel#ShellAssistantStatus {{
font-size: {TYPE['fs_small']};
}}
QPushButton#ShellAssistantButton, QPushButton#ShellSettingsButton {{
font-family: "{body_family()}"; font-weight: 400; font-size: {TYPE['fs_body']};
}}
QPushButton#ShellAssistantButton {{ border-radius: {METRICS["r_md"]}; }}
QPushButton#ShellSettingsButton {{
min-height: 50px; max-height: 50px;
text-align: left; padding: 0 32px;
}}
QPushButton#ShellAssistantButton:focus {{
border: 2px solid {TECH_BLUE['focus']};
}}
"""
if widget is self.topbar:
stylesheet += f"""
QFrame#TopBar {{
border-radius: 0;
border-bottom: 1px solid {_RECEPTION_CHROME_LINE};
}}
QFrame#ShellGlobalSearch {{ background-color: {PALETTE["surface_alt"]}; border: 1px solid transparent; border-radius: {METRICS["r_md"]}; }}
QFrame#ShellUserSeparator {{ background: {_RECEPTION_CHROME_LINE}; border: 0; }}
QLabel#ShellShortcutHint {{
font-family: "{number_family()}"; font-size: {TYPE['fs_small']};
padding: 4px 9px; border-radius: 4px;
border: 1px solid {_RECEPTION_CHROME_LINE};
}}
QLineEdit#ShellGlobalSearchInput {{
color: {TECH_BLUE['text']}; font-size: {TYPE['fs_body']};
min-height: 40px; max-height: 40px;
}}
QPushButton#ShellAiEntry:pressed {{ background: {TECH_BLUE['selection']}; }}
QPushButton#ShellAiEntry:focus {{ border: 1px solid {TECH_BLUE['focus']}; }}
QLabel#ShellConnectionBadge {{ font-weight: 400; }}
"""
if widget is self.user_menu_button:
stylesheet += f"""
QToolButton#ShellUserMenu {{
font-family: "{body_family()}"; font-weight: 400;
color: {TECH_BLUE['heading']}; font-size: 13px;
}}
"""
if widget is self.workspace:
stylesheet += "QWidget#ShellWorkspace { border-radius: 0; }"
if widget is self.stack:
stylesheet += "QStackedWidget#ShellPageStack { border-radius: 0; }"
if isinstance(widget, _PaintedIconButton):
side = 50 if widget in (self.refresh_button, self.notification_button, self.settings_button) else 34
stylesheet += f"QToolButton#ShellPaintedIconButton {{ min-width: {side - 2}px; max-width: {side - 2}px; min-height: {side - 2}px; max-height: {side - 2}px; }}"
widget.setStyleSheet(clinical_stylesheet(stylesheet))
self._set_reception_geometry(active)
for widget in (
self.centralWidget(), self.brand_mark, self.assistant_glyph, self.assistant_status,
self.upload_settings_button,
):
widget.setProperty("receptionTechBlue", active)
widget.update()
self.user_menu_button.set_reception_avatar(active)
for widget in self.topbar.findChildren(_PaintedIconButton):
size = 20 if active else 18
widget.setIconSize(QSize(size, size))
if isinstance(widget, _RefreshButton):
widget.set_reception_palette(active)
else:
widget.setIcon(_painted_shell_icon(widget.kind, size, reception=active))
self.ai_top_button.setIcon(_painted_shell_icon("ai", reception=active))
self._global_search_icon_action.setIcon(
_painted_shell_icon("search", 20 if active else 16, reception=active)
)
self.search_mark.setIcon(_painted_shell_icon("search", 20, reception=True))
self.search_mark.setIconSize(QSize(20, 20))
for key, button in self.nav_buttons.items():
size = 20 if active else 18
button.setProperty("receptionTechBlue", active)
button.setIconSize(QSize(size, size))
button.setIcon(_painted_navigation_icon(key, size, reception=active))
button.update()
def _toggle_maximized(self) -> None:
if self.isMaximized():
self.showNormal()
self.fullscreen_button.setToolTip("最大化")
else:
self.showMaximized()
self.fullscreen_button.setToolTip("还原")
def _toggle_fullscreen(self) -> None:
if self.isFullScreen():
self.showNormal()
self.fullscreen_button.setToolTip("全屏模式")
else:
self.showFullScreen()
self.fullscreen_button.setToolTip("退出全屏")
def _focus_global_search(self) -> None:
self.global_search.setFocus(Qt.FocusReason.ShortcutFocusReason)
self.global_search.selectAll()
def _run_global_search(self) -> None:
query = self.global_search.text().strip()
keys = ("patients", "consultations") if self._active_page_key == "patients" else (
"consultations", "patients",
)
for key in keys:
# Only use patient pages already registered by permission-aware navigation.
page = self.pages.get(key)
search = getattr(page, "search_patient", None)
if page is None or key not in self.nav_buttons or not callable(search):
continue
self._navigate(
self.stack.indexOf(page), key, on_activate=lambda search=search: search(query),
)
return
show_toast(self, "当前账号没有可用的患者搜索页面。", "warning")
def _open_ai_assistant(self) -> None:
if not self._can_ai_assistant:
show_toast(self, "当前账号没有使用 AI 问诊助手的权限。", "danger")
return
# The shell assistant is the global entry point. Always let the doctor
# choose from the complete permission-scoped patient list, even when a
# page happens to retain a selected row. Page-level AI actions keep the
# faster "open the selected patient" behaviour.
select_and_present_ai_consult(
self.repository,
self.permissions,
self,
initial_query=self.global_search.text().strip(),
)
def _open_esign_doctor(self) -> None:
dialog = EsignDoctorDialog(self.repository, parent=self)
dialog.exec()
dialog.deleteLater()
def _open_local_audio_settings(self) -> None:
current = self._local_audio_settings_dialog
if current is not None and current.isVisible():
current.raise_()
current.activateWindow()
return
try:
dialog = LocalAudioQueueDialog(self.repository, None, self)
except (OSError, RuntimeError, ValueError, sqlite3.Error) as error:
show_toast(self, f"无法打开本机录音上传设置:{error}", "error")
return
self._local_audio_settings_dialog = dialog
def clear_dialog(_result: int) -> None:
if self._local_audio_settings_dialog is dialog:
self._local_audio_settings_dialog = None
dialog.finished.connect(clear_dialog)
dialog.open()
def _tab_index_for_key(self, key: str) -> int:
for index in range(self.tab_bar.count()):
if self.tab_bar.tabData(index) == key:
return index
return -1
def visited_tab_keys(self) -> tuple[str, ...]:
"""Return open tabs in visit order for tests and session diagnostics."""
return tuple(
str(self.tab_bar.tabData(index)) for index in range(self.tab_bar.count())
)
def _ensure_tab(self, key: str, title: str) -> int:
index = self._tab_index_for_key(key)
if index >= 0:
self.tab_bar.setTabText(index, title)
return index
index = self.tab_bar.addTab(title)
self.tab_bar.setTabData(index, key)
if self._fixed_tab_key is None:
self._fixed_tab_key = key
else:
close_button = _PaintedIconButton("close", size=18, parent=self.tab_bar)
close_button.setToolTip(f"关闭 {title}")
close_button.setAccessibleName(f"关闭标签页:{title}")
close_button.clicked.connect(
lambda _checked=False, page_key=key: self.close_tab(page_key)
)
self.tab_bar.setTabButton(
index, QTabBar.ButtonPosition.RightSide, close_button
)
self._update_tab_actions()
return index
def _set_current_tab(self, key: str) -> None:
index = self._tab_index_for_key(key)
if index < 0:
return
blocked = self.tab_bar.blockSignals(True)
self.tab_bar.setCurrentIndex(index)
self.tab_bar.blockSignals(blocked)
self._update_tab_actions()
def _tab_selected(self, index: int) -> None:
if index < 0:
return
key = str(self.tab_bar.tabData(index) or "")
page = self.pages.get(key)
if page is None:
return
self._navigate(self.stack.indexOf(page), key)
def _update_tab_actions(self) -> None:
if not hasattr(self, "close_current_action"):
return
current_index = self.tab_bar.currentIndex()
current_key = (
str(self.tab_bar.tabData(current_index) or "") if current_index >= 0 else ""
)
removable = [
key for key in self.visited_tab_keys() if key != self._fixed_tab_key
]
self.close_current_action.setEnabled(
bool(current_key and current_key != self._fixed_tab_key)
)
self.close_other_action.setEnabled(any(key != current_key for key in removable))
self.close_all_action.setEnabled(bool(removable))
def close_tab(self, key: str) -> bool:
"""Close one non-fixed visited page and re-route if it was active."""
index = self._tab_index_for_key(key)
if index < 0 or key == self._fixed_tab_key:
return False
active_key = ""
if self.tab_bar.currentIndex() >= 0:
active_key = str(self.tab_bar.tabData(self.tab_bar.currentIndex()) or "")
keys = list(self.visited_tab_keys())
fallback = keys[index - 1] if index > 0 else keys[index + 1]
close_button = self.tab_bar.tabButton(index, QTabBar.ButtonPosition.RightSide)
blocked = self.tab_bar.blockSignals(True)
self.tab_bar.removeTab(index)
self.tab_bar.blockSignals(blocked)
if close_button is not None:
close_button.deleteLater()
if active_key == key:
self.navigate(fallback)
else:
self._set_current_tab(active_key)
self._update_tab_actions()
return True
def close_current_tab(self) -> bool:
index = self.tab_bar.currentIndex()
if index < 0:
return False
return self.close_tab(str(self.tab_bar.tabData(index) or ""))
def close_other_tabs(self) -> None:
current_index = self.tab_bar.currentIndex()
current_key = (
str(self.tab_bar.tabData(current_index) or "") if current_index >= 0 else ""
)
keep = {current_key, self._fixed_tab_key}
for key in reversed(self.visited_tab_keys()):
if key not in keep:
self.close_tab(key)
if current_key:
self._set_current_tab(current_key)
self._update_tab_actions()
def close_all_tabs(self) -> None:
for key in reversed(self.visited_tab_keys()):
if key != self._fixed_tab_key:
self.close_tab(key)
if self._fixed_tab_key:
self.navigate(self._fixed_tab_key)
self._update_tab_actions()
def _register_pages(self) -> None:
self.nav_group = QButtonGroup(self)
self.nav_group.setExclusive(True)
first_button: QPushButton | None = None
for item, title in self.navigation:
page = item.page_type(
self.repository,
permissions=self.permissions,
current_user=self.current_user,
parent=self.stack,
)
self._install_activation_refresh_gate(page)
if hasattr(page, "video_requested"):
page.video_requested.connect(
lambda payload: self.video_requested.emit(payload)
)
index = self.stack.addWidget(page)
self.pages[item.key] = page
self.page_titles[index] = title
button = _ShellNavigationButton(title)
button.setObjectName("ShellNavButton")
button.setIcon(_painted_navigation_icon(item.key))
button.setIconSize(QSize(18, 18))
button.setProperty("navGlyph", item.glyph)
button.setProperty("navTitle", title)
button.setCheckable(True)
button.setCursor(Qt.CursorShape.PointingHandCursor)
button.clicked.connect(
lambda _checked=False, page_index=index, key=item.key: self._navigate(
page_index, key
)
)
self.nav_group.addButton(button, index)
self.nav_layout.addWidget(button)
self.nav_buttons[item.key] = button
if first_button is None:
first_button = button
if first_button is None:
denied = EmptyState(
"暂无可用工作区",
"当前账号没有医生工作站页面权限,请联系管理员调整授权。",
)
index = self.stack.addWidget(denied)
self.page_titles[index] = "权限受限"
self.stack.setCurrentIndex(index)
self.context_label.setText("权限受限")
return
first_button.setChecked(True)
first_index = self.nav_group.id(first_button)
self._navigate(
first_index,
next(
key
for key, button in self.nav_buttons.items()
if button is first_button
),
)
def _install_activation_refresh_gate(self, page: QWidget) -> None:
"""Coalesce lifecycle and shell refreshes during one page activation."""
refresh = getattr(page, "refresh", None)
if not callable(refresh):
return
@wraps(refresh)
def activation_refresh(*args: Any, **kwargs: Any) -> Any:
if page is self._activation_page:
if self._activation_refreshed:
return None
self._activation_refreshed = True
return refresh(*args, **kwargs)
page.refresh = activation_refresh # type: ignore[attr-defined,method-assign]
def _ensure_activation_refresh(self, page: QWidget, generation: int) -> None:
if generation != self._activation_generation or page is not self._activation_page:
return
if not self._activation_refreshed:
refresh = getattr(page, "refresh", None)
if callable(refresh):
refresh()
def _finish_activation(self, page: QWidget, generation: int) -> None:
if generation != self._activation_generation or page is not self._activation_page:
return
self._ensure_activation_refresh(page, generation)
self._activation_page = None
def _navigate(
self, index: int, key: str, *, on_activate: Callable[[], None] | None = None,
) -> None:
if index < 0 or index >= self.stack.count():
return
page = self.stack.widget(index)
if page is None:
return
if self._active_page_key == key and self.stack.currentWidget() is page:
if on_activate is not None:
self._activation_refreshed = False
on_activate()
return
self._activation_generation += 1
activation_generation = self._activation_generation
self._activation_page = page
self._activation_refreshed = False
if on_activate is not None:
on_activate()
# A stack swap is otherwise a hard cut between two frames: this is the
# transition a doctor sees on every sidebar click all day.
motion.switch_stack(self.stack, index)
title = self.page_titles.get(index, "工作台")
self.context_label.setText(title)
self._ensure_tab(key, title)
self._set_current_tab(key)
button = self.nav_buttons.get(key)
if button is not None:
button.setChecked(True)
self._active_page_key = key
self._set_reception_chrome(key in _TECH_BLUE_PAGES)
self._ensure_activation_refresh(page, activation_generation)
if self.isVisible():
QTimer.singleShot(
0,
lambda page=page, generation=activation_generation: self._finish_activation(
page, generation
),
)
self.page_changed.emit(key)
def navigate(self, key: str) -> bool:
"""Navigate to a visible page by stable key; return whether it exists."""
button = self.nav_buttons.get(key)
page = self.pages.get(key)
if button is None or page is None:
return False
self._navigate(self.stack.indexOf(page), key)
return True
#: Attributes the pages use to say "a request is in flight". Nothing forces
#: a page to have one, so a page without any of these simply gets the
#: minimum spin rather than an accurate one.
_LOADING_FLAGS = ("_loading", "_queue_loading", "_detail_loading")
def _current_page_is_loading(self) -> bool:
page = self.stack.currentWidget()
return any(bool(getattr(page, flag, False)) for flag in self._LOADING_FLAGS)
def refresh_current_page(self) -> None:
page = self.stack.currentWidget()
refresh = getattr(page, "refresh", None)
if not callable(refresh):
return
button = getattr(self, "refresh_button", None)
if isinstance(button, _RefreshButton):
button.start_spin()
refresh()
def _ensure_global_diagnosis_dialog(self) -> DiagnosisDialog:
dialog = self._global_diagnosis_dialog
if dialog is None:
dialog = DiagnosisDialog(
self.repository,
self,
permissions=self.permissions,
)
dialog.saved.connect(self.refresh_current_page)
self._global_diagnosis_dialog = dialog
else:
dialog.refresh_permissions(self.permissions)
return dialog
def open_diagnosis_by_id(
self,
diagnosis_id: Any,
*,
modeless: bool = False,
) -> DiagnosisDialog | None:
"""Open one authoritative diagnosis in the strongest permitted mode."""
try:
normalized_id = int(diagnosis_id)
except (TypeError, ValueError):
normalized_id = 0
if normalized_id <= 0:
show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600)
return None
if has_permission(self.permissions, "tcm.diagnosis/edit", default=False):
dialog = self._ensure_global_diagnosis_dialog()
dialog.open_for(normalized_id, editable=True, modeless=modeless)
elif has_permission(
self.permissions,
"tcm.diagnosis/readonlyDetail",
default=False,
):
dialog = self._ensure_global_diagnosis_dialog()
dialog.open_view_only(normalized_id, modeless=modeless)
else:
show_toast(self, "当前账号没有查看该诊单的权限。", "danger", 4200)
return None
dialog.raise_()
dialog.activateWindow()
return dialog
def showEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
super().showEvent(event)
# 登录后就开始轮询:不管医生停在哪个页面,患者进入会话都要提示。
self.chat_notifications.start()
page = self.stack.currentWidget()
if page is None or page is not self._activation_page:
return
generation = self._activation_generation
QTimer.singleShot(
0,
lambda page=page, generation=generation: self._finish_activation(page, generation),
)
def closeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
self.chat_notifications.stop()
super().closeEvent(event)
if event.isAccepted():
self.close_requested.emit()
def _open_chat_notification(self, notification: ChatNotification) -> None:
"""Take the doctor where the notification's work actually lives."""
if notification.kind == CONSULTATION_COMPLETE and notification.diagnosis_id > 0:
self.open_diagnosis_by_id(notification.diagnosis_id, modeless=True)
return
if notification.kind == PATIENT_OPENED_CHAT and self.navigate("reception"):
return
show_toast(self, notification.description, "info", 4200)
def _show_chat_notification_summary(self) -> None:
pending = self.chat_notifications.pending
if not pending:
show_toast(self, "当前没有新的系统通知。", "info")
return
latest = pending[0]
show_toast(
self,
f"待处理通知 {len(pending)} 条,最新:{latest.title} · {latest.description}",
"info",
4200,
)
def setVisible(self, visible: bool) -> None: # noqa: N802 - Qt API
if visible:
self.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, False)
super().setVisible(visible)
def set_connection_state(self, online: bool, message: str = "") -> None:
self.connection_badge.set_status(
message or ("服务正常" if online else "连接中断"),
"success" if online else "danger",
)
self.assistant_status.setText("在线" if online else "服务离线")
self.assistant_status.set_online(online)
__all__ = ["NAVIGATION", "NavigationItem", "ShellWindow"]