Replace leaf entry with persistent horizontal toolbar and shared panel state

This commit is contained in:
阿白叔 committed 2026-10-11 11:31:07 +08:00
1 parent d2501d0112
commit 19361fd1cc
18 files changed
+1010 -454

No files matched your search

@@ -0,0 +1,32 @@
# Toolbar shell and shared state report
Implemented approved tasks 1 and 2 in the horizontal-toolbar worktree.
## Delivered behavior
- A persistent 772×44 logical-pixel toolbar replaces the leaf entry. Seven primary functions retain their existing page indices and full accessible names. History, settings, refresh, theme, and exit are available from More. At narrow widths display/check/network/BOM overflow in that order; Start, refdes, attributes, PDF and status retain priority.
- Standalone CLI launch shows the toolbar; `--feature` shows the existing corresponding page. Clicking the same active function hides its panel. Expand restores the last page. Close and minimize hide the panel; explicit exit stops owned timers, shuts down business workers and closes both windows. Startup registration protects actual exit and update installation.
- RefDes preview/apply controls and signals now live on RefDesPage. MainWindow's apply_button/preview_button references refer to those local controls for existing integration callers; there are no global visible apply/preview buttons.
- Central project/bridge/selection/operation setters synchronize the panel and toolbar. Fixed status width and elision prevent selection changes from resizing the toolbar. Tooltip includes project, page, complete selected references and operation. A shared lifecycle timer observes existing controllers' task flags, including PDF threads, without changing controllers or creating another bridge session.
- Lightweight selection watcher keeps running while hidden. Pause, disconnected state, missing previously valid channel and project changes stop presenting old references as current. Selection resumes through the same existing controllers and preserves pending edits and PDF inputs.
- UI placement and per-page dimensions are independently validated and atomically saved to `%LOCALAPPDATA%/DxProductivity/ui-layout.json`. Panel anchoring chooses below/above, accounts for native frames, and clamps to available bounds. Dragging is restricted to the handle and moves an open panel with the toolbar. Screen changes reapply bounds.
- Added CollapsibleSection for subsequent page work: content_layout, set_summary(), set_expanded(), is_expanded, expanded_changed. Removed floating_button.py and old sidebar widgets. Existing business controllers, CLI feature IDs and bridge sessions are preserved.
- UI tests explicitly call request_exit at teardown because ordinary close is intentionally a hide operation; this prevents workers remaining alive during Qt cleanup.
## Verification
Before implementation, test_horizontal_toolbar.py failed 2/2 with missing show_toolbar(), proving the new behavior tests exercised the unimplemented contract.
Consolidated targeted shell suite: **48 passed in 71.24 seconds**. Command used supplied Python, worktree src PYTHONPATH, PYTHONUTF8=1 and QT_QPA_PLATFORM=offscreen:
`python -m pytest tests/ui/test_horizontal_toolbar.py tests/ui/test_main_window.py tests/ui/test_compact_floating_window.py tests/ui/test_live_selection.py tests/ui/test_layout_preferences.py tests/ui/test_update_launch.py tests/ui/test_snapshot_refresh.py tests/ui/test_inspection_controller.py -q`
After final snapshot-status initialization and monitor-change hookups, the affected main-window/live-selection/snapshot/update/toolbar suite was rerun: **29 passed in 34.86 seconds**. Accessibility enumeration was then broadened from icon buttons to all toolbar buttons and its targeted test passed. `git diff --check` passed.
Coverage includes seven button routes and More routes, repeated toggles, inputs/timer retention, minimization, drag-only handle, native-frame screen clamping, per-page persistence, malformed JSON, negative monitor coordinates, single/multi/empty selection, hidden-panel pause/recovery/project change, unchanged watcher/page instances, passive focus retention, in-flight operation status, menu registration guards, and update handoff shutdown.
Screenshot `toolbar-shell.png` beside this report was generated and visually reviewed; it shows all seven functions and selected CE18 in a single readable row, with grip and expand icons rendered correctly.
## Remaining acceptance boundary
This is the shell stage. Existing pages retain their current content layout except the required local RefDes action row; subsequent page tasks must remove redundant headings and reduce their own parameter-area heights. Native host operations, multiple physical displays and Windows 100%/125%/150% DPI were not performed by this worker; root owns those acceptance checks. Synthetic negative coordinates, offscreen native-frame bounds, passive focus, and screen-change connections are covered here. No user DxDesigner process or project was touched. Packaging and acceptance scripts modified by root were excluded from this worker's commit.
+44 -36
View File
@@ -61,7 +61,7 @@ def _load_windows_ui_fonts(application: QApplication) -> None:
path = font_root / filename
if path.exists():
QFontDatabase.addApplicationFont(str(path))
application.setFont(QFont("Microsoft YaHei UI", 11))
application.setFont(QFont("Microsoft YaHei UI", 10))
def build_parser() -> argparse.ArgumentParser:
@@ -96,6 +96,14 @@ def _status_text(state: str) -> str:
return STATUS_TEXT.get(state, state)
def _set_snapshot_status(window: MainWindow, snapshot) -> None:
window.set_project_status(Path(snapshot.design_path).name or snapshot.design_id, snapshot.design_path)
window.set_bridge_status('桥接已连接')
refs = [component.refdes or '未标注器件' for component in snapshot.components if component.selected]
summary = f'已选 {refs[0]}' if len(refs) == 1 else f'已选 {len(refs)} 个' + (f':{refs[0]}' if refs else '器件')
window.set_selection_status(summary, f'当前页:{snapshot.active_block_name} / {snapshot.current_sheet_name}\n选中器件:' + ('、'.join(refs) or '无'))
def create_main_window(request_path: Path | None = None) -> MainWindow:
window = MainWindow()
page = RefDesPage()
@@ -125,7 +133,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
window.set_page(0, page, "自动位号")
controller.can_apply_changed.connect(window.apply_button.setEnabled)
controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
lambda state: window.set_operation_status(_status_text(state))
)
controller.apply_failed.connect(
lambda message: _report_error(window, "应用位号失败", message)
@@ -133,7 +141,9 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
window.refresh_requested.connect(
lambda: _request_refresh(window, controller, run_paths)
)
page.preview_requested.connect(controller.refresh_plan)
window.preview_requested.connect(controller.refresh_plan)
page.apply_requested.connect(controller.apply)
window.apply_requested.connect(controller.apply)
history_page = HistoryPage()
window.set_page(6, history_page, "操作历史")
@@ -145,7 +155,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
run_paths=run_paths,
)
history_controller.status_changed.connect(
lambda state: window.operation_status.setText(_status_text(state))
lambda state: window.set_operation_status(_status_text(state))
)
history_controller.restore_failed.connect(
lambda message: _report_error(window, "恢复位号失败", message)
@@ -162,7 +172,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
property_change_page.set_can_apply
)
property_change_controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
lambda state: window.set_operation_status(_status_text(state))
)
property_change_controller.apply_failed.connect(
lambda message: _report_error(window, "应用属性修改失败", message)
@@ -179,7 +189,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
property_visibility_page.set_can_apply
)
property_visibility_controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
lambda state: window.set_operation_status(_status_text(state))
)
property_visibility_controller.apply_failed.connect(
lambda message: _report_error(window, "应用显示状态失败", message)
@@ -191,12 +201,12 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
inspection_page,
run_paths=run_paths,
)
inspection_controller.status_changed.connect(window.operation_status.setText)
inspection_controller.status_changed.connect(window.set_operation_status)
window.set_page(3, inspection_page, "设计检查")
window.inspection_controller = inspection_controller
network_page = InspectionPage(network_only=True)
network_controller = InspectionController(network_page, run_paths=run_paths)
network_controller.status_changed.connect(window.operation_status.setText)
network_controller.status_changed.connect(window.set_operation_status)
window.set_page(4, network_page, "网络工具")
window.network_controller = network_controller
bom_page = BomPage()
@@ -208,12 +218,12 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
Path(snapshot.design_path).name if snapshot is not None else ""
),
)
bom_controller.status_changed.connect(window.operation_status.setText)
bom_controller.status_changed.connect(window.set_operation_status)
bom_controller.export_failed.connect(
lambda message: _report_error(window, "BOM 导出失败", message)
)
bom_controller.export_completed.connect(
lambda path: window.operation_status.setText(f"BOM 已导出:{path}")
lambda path: window.set_operation_status(f"BOM 已导出:{path}")
)
window.set_page(5, bom_page, "BOM 工具")
window.bom_controller = bom_controller
@@ -266,20 +276,18 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
pdf_export_page,
tool_root=_tool_root(),
)
pdf_export_controller.status_changed.connect(window.operation_status.setText)
pdf_export_controller.status_changed.connect(window.set_operation_status)
window.set_page(FEATURE_PAGE_INDEX["pdf-export"], pdf_export_page, "PDF 导出")
window.pdf_export_controller = pdf_export_controller
if settings_controller.auto_check_due(persisted_settings):
QTimer.singleShot(
0,
lambda: settings_page.check_requested.emit(
lambda: not window._closing and settings_page.check_requested.emit(
settings_page.source_input.text().strip(), settings_page.channel_combo.currentData()
),
)
if snapshot is not None:
window.project_label.setText(Path(snapshot.design_path).name or snapshot.design_id)
window.project_label.setToolTip(snapshot.design_path)
window.bridge_status.setText("桥接已连接")
_set_snapshot_status(window, snapshot)
controller.load_snapshot(snapshot)
if window.property_change_controller is not None:
window.property_change_controller.load_snapshot(snapshot)
@@ -303,17 +311,15 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
if watcher is not None:
watcher.snapshot_reloaded.connect(pdf_export_controller.load_snapshot)
window.selection_watcher = SelectionWatcher(window, request_path)
window.navigation.setCurrentRow(0)
window.pages.setCurrentIndex(0)
window.page_title.setText("自动位号")
window.set_active_page(0)
startup_controller = StartupController(_tool_root(), window)
window.startup_controller = startup_controller
window.start_requested.connect(startup_controller.start)
startup_controller.started.connect(lambda: window.start_button.setEnabled(False))
startup_controller.started.connect(lambda: window.operation_status.setText("正在自动加入 DxDesigner 菜单…"))
startup_controller.started.connect(lambda: window.set_operation_status("正在自动加入 DxDesigner 菜单…"))
def startup_finished(success: bool, message: str) -> None:
window.start_button.setEnabled(True)
window.operation_status.setText(message)
window.set_operation_status(message)
if not success:
QMessageBox.warning(window, "Start 未完成", message)
startup_controller.completed.connect(startup_finished)
@@ -331,7 +337,7 @@ def _request_refresh(
refresh_request = run_paths.root / "refresh.request"
try:
refresh_request.write_text("snapshot\n", encoding="utf-8")
window.operation_status.setText("已请求宿主刷新设计快照…")
window.set_operation_status("已请求宿主刷新设计快照…")
except OSError as error:
_report_error(window, "刷新失败", str(error))
@@ -380,12 +386,9 @@ class _SnapshotWatcher(QObject):
):
if controller is not None:
controller.load_snapshot(snapshot)
self._window.project_label.setText(
Path(snapshot.design_path).name or snapshot.design_id
)
self._window.project_label.setToolTip(snapshot.design_path)
_set_snapshot_status(self._window, snapshot)
self.snapshot_reloaded.emit(snapshot)
self._window.operation_status.setText("设计快照已刷新")
self._window.set_operation_status("设计快照已刷新")
def _install_snapshot_watcher(
@@ -398,7 +401,7 @@ def _install_snapshot_watcher(
def _report_error(window: MainWindow, title: str, message: str) -> None:
window.operation_status.setText(f"{title}:{message}")
window.set_operation_status(f"{title}:{message}")
QMessageBox.warning(window, title, message)
@@ -428,12 +431,16 @@ def _tool_root() -> Path:
def _launch_update(window: MainWindow, controller: SettingsController, manifest: object) -> None:
"""Write a post-exit install plan and hand control to the portable updater."""
startup = getattr(window, 'startup_controller', None)
if startup is not None and startup.is_running():
window.set_operation_status('正在完成菜单注册,请稍候再安装更新')
return
staged_zip = controller.staged_path(manifest)
if staged_zip is None or not staged_zip.is_file():
window.operation_status.setText("更新包尚未准备好,请重新检查")
window.set_operation_status("更新包尚未准备好,请重新检查")
return
if not getattr(sys, "frozen", False):
window.operation_status.setText("开发运行环境已完成校验,便携式包中可执行安装")
window.set_operation_status("开发运行环境已完成校验,便携式包中可执行安装")
return
from dx_productivity.update.installer import InstallPlan, prepare_updater
@@ -461,12 +468,13 @@ def _launch_update(window: MainWindow, controller: SettingsController, manifest:
close_fds=True,
)
except OSError as error:
window.operation_status.setText(f"无法启动更新器:{error}")
window.set_operation_status(f"无法启动更新器:{error}")
return
window.operation_status.setText(f"已确认安装 {manifest.version},程序即将退出更新")
application = QApplication.instance()
if application is not None:
application.quit()
window.set_operation_status(f"已确认安装 {manifest.version},程序即将退出更新")
if window.request_exit():
application = QApplication.instance()
if application is not None:
application.quit()
def main(argv: Sequence[str] | None = None) -> int:
@@ -479,10 +487,10 @@ def main(argv: Sequence[str] | None = None) -> int:
app = create_application([sys.argv[0], *arguments])
window = create_main_window(options.request)
window.window_closed.connect(app.quit)
window.show()
window.show_toolbar()
if options.feature is not None:
index = FEATURE_PAGE_INDEX[options.feature]
window.set_active_page(index)
window.show_panel(index)
if options.smoke_test_ms is not None:
QTimer.singleShot(options.smoke_test_ms, app.quit)
QTimer.singleShot(options.smoke_test_ms, window.request_exit)
return app.exec()
@@ -0,0 +1,47 @@
"""Advanced options with an always-visible effective summary."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QLabel, QToolButton, QVBoxLayout, QWidget
class CollapsibleSection(QWidget):
expanded_changed = Signal(bool)
def __init__(self, title: str, parent=None):
super().__init__(parent)
self._title = title
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(4)
self.toggle_button = QToolButton()
self.toggle_button.setObjectName('sectionToggle')
self.toggle_button.setCheckable(True)
self.toggle_button.setAccessibleName(title)
self.toggle_button.setToolTip('展开或收起' + title)
self.summary_label = QLabel()
self.summary_label.setObjectName('secondaryLabel')
self.summary_label.setWordWrap(True)
self.summary_label.hide()
self.content = QWidget()
self.content_layout = QVBoxLayout(self.content)
self.content_layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.toggle_button)
layout.addWidget(self.summary_label)
layout.addWidget(self.content)
self.toggle_button.toggled.connect(self._update_expanded)
self._update_expanded(False)
@property
def is_expanded(self) -> bool:
return self.toggle_button.isChecked()
def set_expanded(self, expanded: bool) -> None:
self.toggle_button.setChecked(expanded)
def _update_expanded(self, expanded: bool) -> None:
self.toggle_button.setText(('▾ ' if expanded else '▸ ') + self._title)
self.content.setVisible(expanded)
self.expanded_changed.emit(expanded)
def set_summary(self, text: str) -> None:
self.summary_label.setText(text)
self.summary_label.setVisible(bool(text))
-87
View File
@@ -1,87 +0,0 @@
"""Small draggable launcher for a hidden, still-running tool window."""
from __future__ import annotations
from PySide6.QtCore import QPoint, QSize, Qt, Signal
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QApplication, QMenu, QPushButton
from dx_productivity.ui.theme import Theme, theme_tokens, themed_icon
class FloatingButton(QPushButton):
open_requested = Signal()
exit_requested = Signal()
def __init__(self) -> None:
super().__init__()
self.setWindowFlags(Qt.WindowType.Tool | Qt.WindowType.FramelessWindowHint
| Qt.WindowType.WindowStaysOnTopHint)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setWindowTitle("一叶知秋悬浮入口")
self.setObjectName("floatingEntry")
self.setAccessibleName("一叶知秋悬浮入口:点击展开,拖动移动")
self.setToolTip("一叶知秋 · 点击展开\n拖动移动,右键可退出")
self.setFixedSize(56, 56)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self._press_position: QPoint | None = None
self._start_position = QPoint()
self._dragged = False
self.clicked.connect(self.open_requested)
self.refresh_theme(Theme.LIGHT)
def refresh_theme(self, theme: Theme) -> None:
tokens = theme_tokens(theme)
self.setIcon(themed_icon("fa6s.leaf", theme, color=tokens.accent_text))
self.setIconSize(QSize(26, 26))
self.setStyleSheet(f"""
QPushButton#floatingEntry {{
min-width: 56px; max-width: 56px; min-height: 56px; max-height: 56px;
padding: 0; border-radius: 28px; border: 1px solid {tokens.border};
background: {tokens.accent}; color: {tokens.accent_text};
}}
QPushButton#floatingEntry:hover {{ background: {tokens.accent_hover}; }}
""")
def move_within_screen(self, position: QPoint, screen=None) -> None:
screen = screen or QGuiApplication.screenAt(position) or self.screen()
if screen is None:
self.move(position)
return
bounds = screen.availableGeometry()
self.move(max(bounds.left(), min(position.x(), bounds.right() - self.width() + 1)),
max(bounds.top(), min(position.y(), bounds.bottom() - self.height() + 1)))
def mousePressEvent(self, event) -> None:
if event.button() == Qt.MouseButton.LeftButton:
self._press_position = event.globalPosition().toPoint()
self._start_position = self.pos()
self._dragged = False
super().mousePressEvent(event)
def mouseMoveEvent(self, event) -> None:
if self._press_position is not None and event.buttons() & Qt.MouseButton.LeftButton:
delta = event.globalPosition().toPoint() - self._press_position
if self._dragged or delta.manhattanLength() >= QApplication.startDragDistance():
self._dragged = True
self.setDown(False)
self.move_within_screen(self._start_position + delta,
QGuiApplication.screenAt(event.globalPosition().toPoint()))
event.accept()
return
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event) -> None:
self._press_position = None
if event.button() == Qt.MouseButton.LeftButton and self._dragged:
self._dragged = False
self.setDown(False)
event.accept()
return
super().mouseReleaseEvent(event)
def contextMenuEvent(self, event) -> None:
menu = QMenu(self)
menu.addAction("打开工具", lambda: self.open_requested.emit())
menu.addAction("退出工具", lambda: self.exit_requested.emit())
menu.exec(event.globalPos())
+185
View File
@@ -0,0 +1,185 @@
"""Persistent single-row entry points; business actions belong to pages."""
from __future__ import annotations
from PySide6.QtCore import QPoint, QSize, Qt, Signal
from PySide6.QtGui import QAction
from PySide6.QtWidgets import QApplication, QHBoxLayout, QLabel, QMenu, QPushButton, QToolButton, QWidget
from dx_productivity.ui.theme import Theme, themed_icon
NAVIGATION = (
('自动位号', 'fa6s.hashtag'), ('属性批改', 'fa6s.pen'),
('属性显示', 'fa6s.tag'), ('设计检查', 'fa6s.clipboard-check'),
('网络工具', 'fa6s.share-nodes'), ('BOM 工具', 'fa6s.table'),
('操作历史', 'fa6s.clock-rotate-left'), ('PDF 导出', 'fa6s.file-pdf'),
('设置', 'fa6s.gear'),
)
PRIMARY_PAGES = (0, 1, 2, 3, 4, 5, 7)
class DragHandle(QLabel):
dragged = Signal(QPoint)
def __init__(self, parent):
super().__init__('⋮⋮', parent)
self.setFixedWidth(20)
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.setCursor(Qt.CursorShape.SizeAllCursor)
self.setToolTip('拖动工具栏')
self.setAccessibleName('拖动工具栏')
self._offset = None
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self._offset = event.globalPosition().toPoint() - self.window().pos()
event.accept()
def mouseMoveEvent(self, event):
if self._offset is not None and event.buttons() & Qt.MouseButton.LeftButton:
self.dragged.emit(event.globalPosition().toPoint() - self._offset)
event.accept()
def mouseReleaseEvent(self, event):
self._offset = None
event.accept()
class FloatingToolbar(QWidget):
page_requested = Signal(int)
start_requested = Signal()
refresh_requested = Signal()
theme_requested = Signal()
toggle_panel_requested = Signal()
exit_requested = Signal()
position_changed = Signal(QPoint)
def __init__(self):
super().__init__(None, Qt.WindowType.Tool | Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
self.setWindowTitle('一叶知秋悬浮工具栏')
self.setObjectName('floatingToolbar')
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setFixedHeight(44)
self._exiting = False
self._theme = Theme.LIGHT
self._available_width = 780
self._status_text = '桥接待连接'
layout = QHBoxLayout(self)
layout.setContentsMargins(5, 4, 5, 4)
layout.setSpacing(4)
self.drag_handle = DragHandle(self)
self.drag_handle.dragged.connect(self.move_within_screen)
layout.addWidget(self.drag_handle)
self.start_button = QPushButton('Start')
self.start_button.setFixedWidth(64)
self.start_button.setAccessibleName('Start:加入菜单并打开 DxDesigner')
self.start_button.setToolTip('加入工具菜单并打开 DxDesigner;连接状态独立显示')
self.start_button.clicked.connect(self.start_requested)
layout.addWidget(self.start_button)
self.page_buttons = {}
for index, short in zip(PRIMARY_PAGES, ('位号', '属性', '显示', '检查', '网络', 'BOM', 'PDF')):
button = QPushButton(short)
button.setObjectName('toolbarFeature')
button.setAccessibleName(NAVIGATION[index][0])
button.setToolTip(NAVIGATION[index][0])
button.setCheckable(True)
button.setFixedWidth(58)
button.clicked.connect(lambda _checked=False, i=index: self.page_requested.emit(i))
self.page_buttons[index] = button
layout.addWidget(button)
self.status_label = QLabel(self._status_text)
self.status_label.setFixedWidth(164)
self.status_label.setAccessibleName('当前桥接、选择与任务状态')
layout.addWidget(self.status_label)
self.more_button = QToolButton()
self.more_button.setText('更多')
self.more_button.setAccessibleName('更多')
self.more_button.setToolTip('更多功能与应用操作')
self.more_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
self.more_menu = QMenu(self.more_button)
self.more_button.setMenu(self.more_menu)
self.page_actions = {}
for index in PRIMARY_PAGES + (6, 8):
action = QAction(NAVIGATION[index][0], self)
action.setCheckable(True)
action.triggered.connect(lambda _checked=False, i=index: self.page_requested.emit(i))
self.page_actions[index] = action
self.more_menu.addAction(action)
self.more_menu.addSeparator()
for name, attribute, signal in (('刷新设计快照', 'refresh_action', self.refresh_requested),
('切换明暗主题', 'theme_action', self.theme_requested),
('退出工具', 'exit_action', self.exit_requested)):
action = self.more_menu.addAction(name)
action.triggered.connect(signal)
setattr(self, attribute, action)
layout.addWidget(self.more_button)
self.toggle_button = QPushButton()
self.toggle_button.setFixedWidth(32)
self.toggle_button.clicked.connect(self.toggle_panel_requested)
layout.addWidget(self.toggle_button)
self.set_panel_state(0, False)
self.refresh_theme(Theme.LIGHT)
def set_panel_state(self, index: int, visible: bool):
for i, button in self.page_buttons.items():
button.setChecked(i == index and visible)
for i, action in self.page_actions.items():
action.setChecked(i == index and visible)
self.toggle_button.setIcon(themed_icon('fa6s.chevron-up' if visible else 'fa6s.chevron-down', self._theme))
name = '收起面板' if visible else '展开面板'
self.toggle_button.setAccessibleName(name)
self.toggle_button.setToolTip(name)
def set_status(self, text: str, detail: str):
self._status_text = text
self.status_label.setText(self.status_label.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, self.status_label.width()))
self.status_label.setToolTip(detail)
self.status_label.setAccessibleDescription(detail)
def fit_available_width(self, width: int):
self._available_width = max(1, width)
self.status_label.setFixedWidth(164)
for index, button in self.page_buttons.items():
button.setVisible(True)
self.page_actions[index].setVisible(False)
for index in (2, 3, 4, 5):
if self.layout().sizeHint().width() <= width:
break
self.page_buttons[index].hide()
self.page_actions[index].setVisible(True)
# A very narrow monitor can shrink the status, keeping priority actions.
excess = self.layout().sizeHint().width() - width
if excess > 0:
self.status_label.setFixedWidth(max(24, 164 - excess))
self.setFixedWidth(min(width, self.layout().sizeHint().width()))
self.set_status(self._status_text, self.status_label.toolTip())
def move_within_screen(self, position: QPoint, screen=None):
screen = screen or QApplication.screenAt(position) or self.screen() or QApplication.primaryScreen()
if screen is not None:
bounds = screen.availableGeometry()
self.fit_available_width(bounds.width())
position = QPoint(max(bounds.left(), min(position.x(), bounds.right() - self.width() + 1)),
max(bounds.top(), min(position.y(), bounds.bottom() - self.height() + 1)))
self.move(position)
def moveEvent(self, event):
super().moveEvent(event)
self.position_changed.emit(self.pos())
def closeEvent(self, event):
if self._exiting:
event.accept()
else:
event.ignore()
self.exit_requested.emit()
def refresh_theme(self, theme):
self._theme = theme
self.drag_handle.setPixmap(themed_icon('fa6s.grip-vertical', theme).pixmap(14, 20))
self.toggle_button.setIcon(themed_icon('fa6s.chevron-up' if self.toggle_button.accessibleName() == '收起面板' else 'fa6s.chevron-down', theme))
self.start_button.setIcon(themed_icon('fa6s.play', theme))
for index, button in self.page_buttons.items():
button.setIcon(themed_icon(NAVIGATION[index][1], theme))
button.setIconSize(QSize(14, 14))
for index, action in self.page_actions.items():
action.setIcon(themed_icon(NAVIGATION[index][1], theme))
@@ -0,0 +1,59 @@
"""Validated, independent storage for toolbar placement and page sizes."""
from __future__ import annotations
import json
import os
from pathlib import Path
import tempfile
from PySide6.QtCore import QPoint, QSize
class LayoutPreferences:
def __init__(self, path: Path | None = None) -> None:
self.path = path or Path(os.environ.get('LOCALAPPDATA', Path.home())) / 'DxProductivity' / 'ui-layout.json'
self.position: QPoint | None = None
self.page_sizes: dict[int, QSize] = {}
self.screen_name = ''
self.load()
def load(self) -> None:
try:
data = json.loads(self.path.read_text(encoding='utf-8'))
except (OSError, ValueError):
return
if not isinstance(data, dict):
return
position = data.get('toolbar_position')
if self._pair(position) and all(abs(n) <= 100000 for n in position):
self.position = QPoint(*position)
screen = data.get('screen')
if isinstance(screen, str):
self.screen_name = screen
sizes = data.get('page_sizes')
if isinstance(sizes, dict):
for index, size in sizes.items():
if isinstance(index, str) and index in tuple(str(i) for i in range(9)) and self._pair(size) and all(100 <= n <= 10000 for n in size):
self.page_sizes[int(index)] = QSize(*size)
@staticmethod
def _pair(value) -> bool:
return isinstance(value, list) and len(value) == 2 and all(type(n) is int for n in value)
def save(self) -> None:
data = {'version': 1, 'toolbar_position': [self.position.x(), self.position.y()] if self.position is not None else None,
'screen': self.screen_name,
'page_sizes': {str(index): [size.width(), size.height()] for index, size in self.page_sizes.items()}}
temporary = None
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=self.path.parent, suffix='.tmp', delete=False) as stream:
temporary = Path(stream.name)
json.dump(data, stream, ensure_ascii=False, indent=2)
temporary.replace(self.path)
except OSError:
# Placement is optional; a read-only user directory must not block UI.
pass
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
+270 -251
View File
@@ -1,40 +1,12 @@
"""Shared productivity-suite window shell."""
"""Shared compact feature panel coordinated with a persistent toolbar."""
from __future__ import annotations
from PySide6.QtCore import QEvent, QPoint, QSize, QTimer, Qt, Signal
from PySide6.QtWidgets import (
QFrame,
QHBoxLayout,
QLabel,
QListWidget,
QListWidgetItem,
QMainWindow,
QPushButton,
QSizePolicy,
QApplication,
QStackedWidget,
QToolButton,
QVBoxLayout,
QWidget,
)
from PySide6.QtCore import QEvent, QPoint, QSize, QTimer, Signal
from PySide6.QtWidgets import QApplication, QFrame, QHBoxLayout, QLabel, QMainWindow, QPushButton, QSizePolicy, QStackedWidget, QVBoxLayout, QWidget
from dx_productivity import __version__
from dx_productivity.ui.floating_button import FloatingButton
from dx_productivity.ui.theme import Theme, apply_theme, themed_icon, theme_tokens
NAVIGATION = (
("自动位号", "fa6s.hashtag"),
("属性批改", "fa6s.pen"),
("属性显示", "fa6s.tag"),
("设计检查", "fa6s.clipboard-check"),
("网络工具", "fa6s.share-nodes"),
("BOM 工具", "fa6s.table"),
("操作历史", "fa6s.clock-rotate-left"),
("PDF 导出", "fa6s.file-pdf"),
("设置", "fa6s.gear"),
)
from dx_productivity.ui.floating_toolbar import FloatingToolbar, NAVIGATION
from dx_productivity.ui.layout_preferences import LayoutPreferences
from dx_productivity.ui.theme import Theme, apply_theme
class MainWindow(QMainWindow):
@@ -45,244 +17,308 @@ class MainWindow(QMainWindow):
page_changed = Signal(int)
window_closed = Signal()
def __init__(self, *, theme: Theme = Theme.LIGHT) -> None:
def __init__(self, *, theme: Theme = Theme.LIGHT, layout_path=None) -> None:
super().__init__()
self._closing = False
self._floating_positioned = False
self._expanded_geometry = None
self._was_maximized = False
self.floating_button = FloatingButton()
self.floating_button.open_requested.connect(self.restore_from_floating)
self.floating_button.exit_requested.connect(self.close)
self._placing = False
self._active_page = 0
self._toolbar_positioned = False
self._operation_text = '就绪'
self.layout_preferences = LayoutPreferences(layout_path)
self.theme = theme
self.setWindowTitle("一叶知秋_重构版")
self.setMinimumSize(860, 540)
self.resize(960, 600)
self.setWindowTitle('一叶知秋_重构版')
self.toolbar = FloatingToolbar()
self.start_button = self.toolbar.start_button
self.theme_action = self.toolbar.theme_action
self.toolbar.page_requested.connect(self._page_requested)
self.toolbar.start_requested.connect(self.start_requested)
self.toolbar.refresh_requested.connect(self.refresh_requested)
self.toolbar.theme_requested.connect(self._toggle_theme)
self.toolbar.toggle_panel_requested.connect(self._toggle_panel)
self.toolbar.exit_requested.connect(self.request_exit)
self.toolbar.position_changed.connect(self._toolbar_moved)
self._build_ui()
self._refresh_icons()
self._set_page_size(0)
application = QApplication.instance()
if application is not None:
apply_theme(application, self.theme)
application.screenAdded.connect(self._screen_added)
application.screenRemoved.connect(self._screens_changed)
for screen in application.screens():
self._screen_added(screen)
self._refresh_icons()
self._sync_status()
self._operation_timer = QTimer(self)
self._operation_timer.setInterval(150)
self._operation_timer.timeout.connect(self._sync_status)
self._operation_timer.start()
def navigation_items(self) -> list[str]:
return [self.navigation.item(index).text() for index in range(self.navigation.count())]
return [text for text, _ in NAVIGATION]
def set_page(self, index: int, widget: QWidget, title: str) -> None:
previous = self.pages.widget(index)
self.pages.removeWidget(previous)
previous.deleteLater()
self.pages.insertWidget(index, widget)
self.pages.setCurrentIndex(index)
self.page_title.setText(title)
self.pages.setCurrentIndex(self._active_page)
if index == 0 and hasattr(widget, 'apply_button'):
self.apply_button = widget.apply_button
self.preview_button = widget.preview_button
def set_active_page(self, index: int) -> None:
if 0 <= index < self.pages.count():
self.navigation.setCurrentRow(index)
self.pages.setCurrentIndex(index)
self.page_title.setText(NAVIGATION[index][0])
def closeEvent(self, event) -> None:
startup = getattr(self, "startup_controller", None)
if startup is not None and startup.is_running():
self.operation_status.setText("正在完成菜单注册,请稍候再关闭")
event.ignore()
if not 0 <= index < self.pages.count():
return
if index != self._active_page:
self._remember_size()
self._active_page = index
self.pages.setCurrentIndex(index)
self._set_page_size(index)
self.page_changed.emit(index)
self.page_title.setText(NAVIGATION[index][0])
self.toolbar.set_panel_state(index, self.isVisible())
if self.isVisible():
self._anchor_panel()
def show_toolbar(self) -> None:
if self._closing:
return
if not self._toolbar_positioned:
screen = self.toolbar.screen() or QApplication.primaryScreen()
position = self.layout_preferences.position
if position is None and screen is not None:
bounds = screen.availableGeometry()
position = QPoint(bounds.left() + 24, bounds.top() + 24)
self.toolbar.move_within_screen(position or QPoint(24, 24))
self._toolbar_positioned = True
else:
self.toolbar.move_within_screen(self.toolbar.pos())
self.toolbar.show()
def show_panel(self, index: int | None = None) -> None:
if self._closing:
return
self.show_toolbar()
self.set_active_page(self._active_page if index is None else index)
self._anchor_panel()
self.showNormal()
self._anchor_panel()
self.toolbar.set_panel_state(self._active_page, True)
self.raise_()
self.activateWindow()
def hide_panel(self) -> None:
if self._closing:
return
self._remember_size()
self.hide()
self.show_toolbar()
self.toolbar.set_panel_state(self._active_page, False)
collapse_to_floating = hide_panel
restore_from_floating = show_panel
def _page_requested(self, index: int) -> None:
if self.isVisible() and index == self._active_page:
self.hide_panel()
else:
self.show_panel(index)
def _toggle_panel(self) -> None:
self.hide_panel() if self.isVisible() else self.show_panel()
def request_exit(self) -> bool:
if self._closing:
return True
startup = getattr(self, 'startup_controller', None)
if startup is not None and startup.is_running():
self.set_operation_status('正在完成菜单注册,请稍候再关闭')
return False
self._remember_size()
self._closing = True
for controller in (
getattr(self, "settings_controller", None),
getattr(self, "refdes_controller", None),
getattr(self, "history_controller", None),
getattr(self, "pdf_export_controller", None),
):
shutdown = getattr(controller, "shutdown", None)
for timer in self.findChildren(QTimer):
timer.stop()
for name in ('settings_controller', 'refdes_controller', 'property_change_controller',
'property_visibility_controller', 'inspection_controller', 'network_controller',
'bom_controller', 'history_controller', 'pdf_export_controller'):
shutdown = getattr(getattr(self, name, None), 'shutdown', None)
if callable(shutdown):
shutdown()
self.floating_button.close()
super().closeEvent(event)
if event.isAccepted():
self.window_closed.emit()
self.toolbar._exiting = True
self.toolbar.close()
self.close()
self.window_closed.emit()
return True
def closeEvent(self, event) -> None:
if self._closing:
super().closeEvent(event)
else:
event.ignore()
self.hide_panel()
def showEvent(self, event) -> None:
super().showEvent(event)
if not self._closing:
self.show_toolbar()
self.toolbar.set_panel_state(self._active_page, True)
def changeEvent(self, event) -> None:
super().changeEvent(event)
if event.type() == QEvent.Type.WindowStateChange and self.isMinimized() and not self._closing:
QTimer.singleShot(0, self.collapse_to_floating)
QTimer.singleShot(0, self.hide_panel)
def collapse_to_floating(self) -> None:
if self._closing or self.floating_button.isVisible():
return
self._expanded_geometry = self.normalGeometry() if self.isMinimized() or self.isMaximized() else self.geometry()
self._was_maximized = self.isMaximized()
if not self._floating_positioned:
screen = self.screen()
if screen is not None:
bounds = screen.availableGeometry()
self.floating_button.move_within_screen(QPoint(bounds.right() - 80, bounds.bottom() - 160), screen)
self._floating_positioned = True
else:
self.floating_button.move_within_screen(self.floating_button.pos())
self.hide()
self.floating_button.show()
def resizeEvent(self, event) -> None:
super().resizeEvent(event)
if hasattr(self, 'layout_preferences') and self.isVisible() and not self._placing and not self.isMinimized():
self._remember_size()
def restore_from_floating(self) -> None:
def _remember_size(self) -> None:
if self.isVisible() and not self._placing and not self.isMinimized():
self.layout_preferences.page_sizes[self._active_page] = self.size()
self.layout_preferences.save()
def _set_page_size(self, index: int) -> None:
self._placing = True
compact = index in (7, 8)
self.setMinimumSize(660 if compact else 720, 340 if compact else 420)
self.resize(self.layout_preferences.page_sizes.get(index, QSize(660, 390) if compact else QSize(780, 480)))
self._placing = False
def _toolbar_moved(self, position: QPoint) -> None:
self.layout_preferences.position = position
screen = QApplication.screenAt(self.toolbar.frameGeometry().center()) or self.toolbar.screen()
if screen is not None:
self.layout_preferences.screen_name = screen.name()
self.layout_preferences.save()
if self.isVisible():
self._anchor_panel()
def _screen_added(self, screen) -> None:
screen.availableGeometryChanged.connect(self._screens_changed)
if self.toolbar.isVisible():
self._screens_changed()
def _screens_changed(self, *_args) -> None:
if self._closing:
return
self.floating_button.hide()
if self._was_maximized:
self.showMaximized()
else:
self.showNormal()
if self._expanded_geometry is not None:
self.setGeometry(self._expanded_geometry)
self.raise_()
self.activateWindow()
if self.toolbar.isVisible():
self.toolbar.move_within_screen(self.toolbar.pos())
if self.isVisible():
self._anchor_panel()
def _anchor_panel(self) -> None:
screen = QApplication.screenAt(self.toolbar.frameGeometry().center()) or self.toolbar.screen()
if screen is None:
return
bounds = screen.availableGeometry()
self._placing = True
frame_extra = self.frameGeometry().size() - self.size()
max_width = max(1, bounds.width() - max(0, frame_extra.width()))
max_height = max(1, bounds.height() - max(0, frame_extra.height()))
self.setMinimumSize(min(self.minimumWidth(), max_width), min(self.minimumHeight(), max_height))
self.resize(min(self.width(), max_width), min(self.height(), max_height))
toolbar_rect = self.toolbar.frameGeometry()
height = self.frameGeometry().height()
below = toolbar_rect.bottom() + 6
y = below if below + height <= bounds.bottom() + 1 else toolbar_rect.top() - height - 6
y = max(bounds.top(), min(y, bounds.bottom() - height + 1))
x = max(bounds.left(), min(toolbar_rect.left(), bounds.right() - self.frameGeometry().width() + 1))
self.move(x, y)
self._placing = False
def _build_ui(self) -> None:
root = QWidget()
root.setObjectName("appRoot")
root_layout = QVBoxLayout(root)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setSpacing(0)
root_layout.addWidget(self._build_title_bar())
body = QWidget()
body_layout = QHBoxLayout(body)
body_layout.setContentsMargins(0, 0, 0, 0)
body_layout.setSpacing(0)
body_layout.addWidget(self._build_navigation())
body_layout.addWidget(self._build_content(), 1)
root_layout.addWidget(body, 1)
root_layout.addWidget(self._build_status_strip())
self.setCentralWidget(root)
def _build_title_bar(self) -> QFrame:
bar = QFrame()
bar.setObjectName("titleBar")
bar.setFixedHeight(44)
layout = QHBoxLayout(bar)
layout.setContentsMargins(12, 0, 12, 0)
layout.setSpacing(8)
brand = QLabel("一叶知秋_重构版")
self.brand_label = brand
brand.setObjectName("brandLabel")
layout.addWidget(brand)
self.project_label = QLabel("未连接设计")
self.project_label.setObjectName("projectLabel")
self.project_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
self.project_label.setMinimumWidth(40)
layout.addWidget(self.project_label, 1)
self.start_button = QPushButton("Start")
self.start_button.setToolTip("自动加入工具菜单并打开 DxDesigner")
self.start_button.setAccessibleName("Start:加入菜单并打开 DxDesigner")
self.start_button.clicked.connect(self.start_requested)
layout.addWidget(self.start_button)
self.theme_button = self._tool_button("切换明暗主题")
self.theme_button.clicked.connect(self._toggle_theme)
layout.addWidget(self.theme_button)
self.refresh_button = self._tool_button("刷新设计快照")
self.refresh_button.clicked.connect(self.refresh_requested)
layout.addWidget(self.refresh_button)
self.preview_button = self._tool_button("生成预览")
self.preview_button.clicked.connect(self.preview_requested)
layout.addWidget(self.preview_button)
self.apply_button = QPushButton("应用位号")
self.apply_button.setObjectName("primaryButton")
self.apply_button.setMinimumWidth(112)
self.apply_button.setEnabled(False)
self.apply_button.clicked.connect(self.apply_requested)
layout.addWidget(self.apply_button)
self.collapse_button = self._tool_button("收起为悬浮窗")
self.collapse_button.clicked.connect(self.collapse_to_floating)
layout.addWidget(self.collapse_button)
return bar
def _build_navigation(self) -> QFrame:
rail = QFrame()
rail.setObjectName("navigationRail")
rail.setFixedWidth(172)
layout = QVBoxLayout(rail)
layout.setContentsMargins(8, 10, 8, 10)
layout.setSpacing(6)
section = QLabel("工作台")
section.setObjectName("secondaryLabel")
layout.addWidget(section)
self.navigation = QListWidget()
self.navigation.setObjectName("navigationList")
self.navigation.setIconSize(QSize(16, 16))
self.navigation.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
for text, _ in NAVIGATION:
self.navigation.addItem(QListWidgetItem(text))
self.navigation.setCurrentRow(0)
self.navigation.currentRowChanged.connect(self._select_page)
layout.addWidget(self.navigation, 1)
version = QLabel(f"DxDesigner 7.9.5 · v{__version__}")
version.setObjectName("secondaryLabel")
version.setWordWrap(True)
layout.addWidget(version)
return rail
def _build_content(self) -> QWidget:
content = QWidget()
layout = QVBoxLayout(content)
root.setObjectName('appRoot')
layout = QVBoxLayout(root)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
header = QFrame()
header.setObjectName("contentHeader")
header.setFixedHeight(44)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 0, 12, 0)
header.setObjectName('contentHeader')
header.setFixedHeight(34)
row = QHBoxLayout(header)
row.setContentsMargins(10, 0, 8, 0)
self.page_title = QLabel(NAVIGATION[0][0])
self.page_title.setObjectName("pageTitle")
header_layout.addWidget(self.page_title)
header_layout.addStretch(1)
self.page_title.setObjectName('pageTitle')
row.addWidget(self.page_title)
self.project_label = QLabel('未连接设计')
self.project_label.setObjectName('projectLabel')
self.project_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
row.addWidget(self.project_label, 1)
self.collapse_button = QPushButton('收起')
self.collapse_button.setAccessibleName('收起面板')
self.collapse_button.setToolTip('收起到工具栏;后台任务继续运行')
self.collapse_button.clicked.connect(self.hide_panel)
row.addWidget(self.collapse_button)
layout.addWidget(header)
self.pages = QStackedWidget()
for text, _ in NAVIGATION:
placeholder = QLabel(text)
placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)
placeholder.setObjectName("secondaryLabel")
self.pages.addWidget(placeholder)
for title, _ in NAVIGATION:
self.pages.addWidget(QLabel(title))
layout.addWidget(self.pages, 1)
return content
def _build_status_strip(self) -> QFrame:
strip = QFrame()
strip.setObjectName("statusStrip")
strip.setFixedHeight(28)
layout = QHBoxLayout(strip)
layout.setContentsMargins(14, 0, 14, 0)
self.bridge_status = QLabel("桥接待连接")
self.bridge_status.setObjectName("secondaryLabel")
layout.addWidget(self.bridge_status)
self.selection_status = QLabel("选择同步等待宿主")
self.selection_status.setObjectName("secondaryLabel")
self.selection_status.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
layout.addWidget(self.selection_status, 1)
self.operation_status = QLabel("就绪")
self.operation_status.setObjectName("secondaryLabel")
self.operation_status.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
self.operation_status.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
layout.addWidget(self.operation_status, 1)
return strip
strip.setObjectName('statusStrip')
strip.setFixedHeight(26)
row = QHBoxLayout(strip)
row.setContentsMargins(10, 0, 10, 0)
self.bridge_status = QLabel('桥接待连接')
self.selection_status = QLabel('选择同步等待宿主')
self.operation_status = QLabel('就绪')
for label in (self.bridge_status, self.selection_status, self.operation_status):
label.setObjectName('secondaryLabel')
label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
row.addWidget(label, 1)
layout.addWidget(strip)
self.setCentralWidget(root)
def _tool_button(self, label: str) -> QToolButton:
button = QToolButton()
button.setAccessibleName(label)
button.setToolTip(label)
button.setIconSize(QSize(16, 16))
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
return button
def set_project_status(self, name: str, path: str) -> None:
previous_path = self.project_label.toolTip()
self.project_label.setText(name)
self.project_label.setToolTip(path)
if previous_path and previous_path != path:
self.set_selection_status('等待当前工程选择同步')
self._sync_status()
def _select_page(self, index: int) -> None:
if index < 0:
return
self.pages.setCurrentIndex(index)
self.page_title.setText(NAVIGATION[index][0])
self.page_changed.emit(index)
def set_bridge_status(self, text: str) -> None:
self.bridge_status.setText(text)
if '断开' in text and self.selection_status.text().startswith('已选'):
self.set_selection_status('选择同步已暂停', '桥接断开,等待宿主重新连接。')
self._sync_status()
def set_selection_status(self, text: str, detail: str = '') -> None:
self.selection_status.setText(text)
self.selection_status.setToolTip(detail)
self._sync_status()
def set_operation_status(self, text: str) -> None:
self._operation_text = text
self.operation_status.setText(text)
self.operation_status.setToolTip(text)
self._sync_status()
def _sync_status(self) -> None:
bridge, selection = self.bridge_status.text(), self.selection_status.text()
operation = self._active_operation() or self._operation_text
self.operation_status.setText(operation)
self.operation_status.setToolTip(operation)
busy = any(word in operation for word in ('导出中', '导出…', '正在', '应用中', '恢复中', '处理中'))
stale = any(word in selection for word in ('暂停', '切换', '未打开', '断开'))
text = '● ' + selection if stale else ('● ' + operation if busy else ('● ' + selection if bridge == '桥接已连接' else '○ ' + bridge))
detail = f'{bridge}\n工程:{self.project_label.text()}\n{self.project_label.toolTip()}\n{selection}\n{self.selection_status.toolTip()}\n任务:{operation}'
self.toolbar.set_status(text, detail)
def _active_operation(self) -> str:
pdf = getattr(self, 'pdf_export_controller', None)
thread = getattr(pdf, '_thread', None)
if thread is not None and thread.isRunning():
return 'PDF 导出中'
for name, text, flag in (('refdes_controller', '位号应用中', '_apply_in_flight'),
('property_change_controller', '属性应用中', '_apply_in_flight'),
('property_visibility_controller', '显示状态应用中', '_apply_in_flight'),
('history_controller', '位号恢复中', '_restore_in_flight'),
('bom_controller', 'BOM 导出中', '_export_in_flight')):
if getattr(getattr(self, name, None), flag, False):
return text
return ''
def _toggle_theme(self) -> None:
self.theme = Theme.DARK if self.theme is Theme.LIGHT else Theme.LIGHT
@@ -292,25 +328,8 @@ class MainWindow(QMainWindow):
self._refresh_icons()
def _refresh_icons(self) -> None:
tokens = theme_tokens(self.theme)
self.start_button.setIcon(themed_icon("fa6s.play", self.theme))
self.theme_button.setIcon(
themed_icon(
"fa6s.sun" if self.theme is Theme.DARK else "fa6s.moon",
self.theme,
)
)
self.refresh_button.setIcon(themed_icon("fa6s.arrows-rotate", self.theme))
self.preview_button.setIcon(themed_icon("fa6s.eye", self.theme))
self.collapse_button.setIcon(themed_icon("fa6s.down-left-and-up-right-to-center", self.theme))
self.floating_button.refresh_theme(self.theme)
self.apply_button.setIcon(
themed_icon("fa6s.check", self.theme, color=tokens.accent_text)
)
for index, (_, icon_name) in enumerate(NAVIGATION):
self.navigation.item(index).setIcon(themed_icon(icon_name, self.theme))
self.toolbar.refresh_theme(self.theme)
for index in range(self.pages.count()):
page = self.pages.widget(index)
refresh_icons = getattr(page, "refresh_icons", None)
if refresh_icons is not None:
refresh_icons(self.theme)
refresh = getattr(self.pages.widget(index), 'refresh_icons', None)
if callable(refresh):
refresh(self.theme)
+15 -1
View File
@@ -35,6 +35,8 @@ from dx_productivity.domain.models import (
class RefDesPage(QWidget):
preview_requested = Signal()
apply_requested = Signal()
settings_changed = Signal()
locate_requested = Signal(str)
@@ -233,7 +235,19 @@ class RefDesPage(QWidget):
self.issue_label = QLabel("0 项待更新")
self.issue_label.setObjectName("secondaryLabel")
layout.addWidget(self.issue_label)
actions = QHBoxLayout()
actions.addWidget(self.issue_label, 1)
self.preview_button = QPushButton("预览")
self.preview_button.setAccessibleName("生成预览")
self.preview_button.setToolTip("重新生成位号预览")
self.preview_button.clicked.connect(self.preview_requested)
self.apply_button = QPushButton("应用位号")
self.apply_button.setObjectName("primaryButton")
self.apply_button.setEnabled(False)
self.apply_button.clicked.connect(self.apply_requested)
actions.addWidget(self.preview_button)
actions.addWidget(self.apply_button)
layout.addLayout(actions)
return panel
def _connect_controls(self) -> None:
+18 -8
View File
@@ -45,8 +45,8 @@ class SelectionWatcher(QObject):
heartbeat = self.path.with_name('apply-progress.json')
try:
if heartbeat.exists() and time.time() - heartbeat.stat().st_mtime > 5:
self.window.selection_status.setText('选择同步已暂停')
self.window.selection_status.setToolTip('宿主桥接没有更新,请刷新快照或重新从 DxDesigner 菜单打开工具。')
self.window.set_bridge_status('桥接已断开')
self.window.set_selection_status('选择同步已暂停', '宿主桥接没有更新,请刷新快照或重新从 DxDesigner 菜单打开工具。')
self.last_signature = None
return
raw = self.path.read_text(encoding='utf-8-sig')
@@ -55,13 +55,21 @@ class SelectionWatcher(QObject):
return
data = json.loads(raw)
except (OSError, ValueError):
if self.last_signature is not None:
self.window.set_bridge_status('桥接已断开')
self.window.set_selection_status('选择同步已暂停', '选择状态无法读取,请刷新快照或重新连接宿主。')
self.last_signature = None
return
if not isinstance(data, dict) or data.get('run_id') != snapshot.run_id:
return
if os.path.normcase(str(data.get('design_path', ''))) != os.path.normcase(snapshot.design_path):
self.window.selection_status.setText('工程已切换,请重新打开工具')
self.window.set_bridge_status('工程已切换')
self.window.set_selection_status('工程已切换,请重新打开工具', str(data.get('design_path', '')))
self.last_signature = None
return
if data.get('snapshot_id') != snapshot.snapshot_id:
self.window.set_selection_status('等待设计快照刷新')
self.last_signature = None
return
if data.get('state') != 'ready':
fresh = replace(snapshot, components=tuple(replace(component, selected=False, current_sheet=False)
@@ -69,7 +77,9 @@ class SelectionWatcher(QObject):
current_sheet_name='', current_sheet_number=None)
self._load_snapshot(fresh, controllers)
self.last_signature = signature
self.window.selection_status.setText('未打开原理图页')
disconnected = data.get('state') in ('disconnected', 'closed', 'error')
self.window.set_bridge_status('桥接已断开' if disconnected else '桥接已连接')
self.window.set_selection_status('桥接已断开' if disconnected else '未打开原理图页')
return
selected = data.get('selected_keys')
current = data.get('current_sheet_keys')
@@ -87,11 +97,12 @@ class SelectionWatcher(QObject):
fresh = replace(snapshot, components=components, active_block_name=block, current_sheet_name=sheet,
current_sheet_number=page, selected_nets=tuple(nets))
self._load_snapshot(fresh, controllers)
self.window.set_bridge_status('桥接已连接')
self.last_signature = signature
known = {identity(component) for component in components}
refs = [component.refdes or '未标注器件' for component in components if component.selected]
if selected - known:
self.window.selection_status.setText('所选器件需刷新快照')
summary = '所选器件需刷新快照'
refresh = self.path.with_name('refresh.request')
if not refresh.exists():
try:
@@ -99,9 +110,8 @@ class SelectionWatcher(QObject):
except OSError:
pass
else:
summary = '、'.join(refs[:4]) + ('…' if len(refs) > 4 else '')
self.window.selection_status.setText(f'已选 {len(refs)} 个' + (f':{summary}' if summary else '器件'))
self.window.selection_status.setToolTip(
summary = f'已选 {refs[0]}' if len(refs) == 1 else f'已选 {len(refs)} 个' + (f':{refs[0]}' if refs else '器件')
self.window.set_selection_status(summary,
f'当前工程:{fresh.design_path}\n当前页:{block} / {sheet}\n选中器件:' + ('、'.join(refs) or '无')
)
+18 -2
View File
@@ -121,13 +121,29 @@ def _stylesheet(tokens: ThemeTokens) -> str:
return f"""
* {{
font-family: "Microsoft YaHei UI";
font-size: 11pt;
font-size: 10pt;
letter-spacing: 0px;
}}
QMainWindow, QWidget#appRoot {{
background: {tokens.canvas};
color: {tokens.text_primary};
}}
QWidget#floatingToolbar {{
background: {tokens.surface};
border: 1px solid {tokens.border};
border-radius: 6px;
}}
QPushButton#toolbarFeature:checked {{
background: {tokens.accent};
color: {tokens.accent_text};
border-color: {tokens.accent};
}}
QToolButton#sectionToggle {{
min-width: 100px;
max-width: 16777215px;
padding: 0 7px;
text-align: left;
}}
QFrame#titleBar, QFrame#contentHeader {{
background: {tokens.surface};
border-bottom: 1px solid {tokens.border};
@@ -208,7 +224,7 @@ def _stylesheet(tokens: ThemeTokens) -> str:
font-weight: 600;
}}
QLabel#pageTitle {{
font-size: 14pt;
font-size: 11pt;
font-weight: 600;
}}
QListWidget#navigationList {{
+16
View File
@@ -0,0 +1,16 @@
"""Explicit application shutdown: closing the feature panel only hides it."""
import pytest
from PySide6.QtWidgets import QApplication
from dx_productivity.ui.main_window import MainWindow
@pytest.fixture(autouse=True)
def shutdown_productivity_windows(qtbot):
yield
for window in QApplication.topLevelWidgets():
if isinstance(window, MainWindow):
startup = getattr(window, 'startup_controller', None)
if startup is not None and startup.is_running():
qtbot.waitUntil(lambda: not startup.is_running(), timeout=10000)
window.request_exit()
+100 -61
View File
@@ -1,106 +1,145 @@
from PySide6.QtCore import QCoreApplication, QEvent, QPoint, QPointF, QTimer, Qt
from PySide6.QtGui import QMouseEvent
from PySide6.QtWidgets import QAbstractButton
from dx_productivity.ui.app import FEATURE_PAGE_INDEX, create_main_window
from dx_productivity.ui.floating_toolbar import PRIMARY_PAGES
from dx_productivity.ui.pdf_export_page import PdfExportPage
from dx_productivity.ui.settings_page import SettingsPage
def make_window(qtbot, monkeypatch, tmp_path):
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = create_main_window()
qtbot.addWidget(window)
window.show()
qtbot.waitExposed(window)
window.show_toolbar()
return window
def test_pdf_is_above_settings_with_matching_page_routing(qtbot, monkeypatch, tmp_path):
def test_pdf_is_primary_before_settings_and_all_routes_are_accessible(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
assert window.navigation_items()[-2:] == ["PDF 导出", "设置"]
for feature, page_type in (("pdf-export", PdfExportPage), ("settings", SettingsPage)):
window.set_active_page(FEATURE_PAGE_INDEX[feature])
assert isinstance(window.pages.currentWidget(), page_type)
def test_all_pages_fit_compact_default_window(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
assert window.width() <= 1000
assert window.height() <= 640
assert tuple(window.toolbar.page_buttons) == PRIMARY_PAGES
for index in range(window.pages.count()):
window.set_active_page(index)
qtbot.wait(5)
assert window.width() <= 1000 and window.height() <= 640
for button in (window.start_button, window.collapse_button, window.apply_button):
assert window.rect().contains(button.mapTo(window, button.rect().bottomRight()))
window.toolbar.page_requested.emit(index)
assert window.isVisible() and window.pages.currentIndex() == index
for feature, page_type in (('pdf-export', PdfExportPage), ('settings', SettingsPage)):
window.show_panel(FEATURE_PAGE_INDEX[feature])
assert isinstance(window.pages.currentWidget(), page_type)
def test_floating_restore_retains_page_form_and_background_work(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.set_active_page(FEATURE_PAGE_INDEX["pdf-export"])
window.show_panel(FEATURE_PAGE_INDEX['pdf-export'])
page = window.pages.currentWidget()
page.output_input.setText("pending-user-folder")
page.output_input.setText('pending-user-folder')
ticks = []
timer = QTimer(window)
timer.setInterval(10)
timer.timeout.connect(lambda: ticks.append(1))
timer.start()
qtbot.mouseClick(window.collapse_button, Qt.MouseButton.LeftButton)
assert not window.isVisible()
assert window.floating_button.isVisible()
assert window.floating_button.windowFlags() & Qt.WindowType.WindowStaysOnTopHint
assert not window.isVisible() and window.toolbar.isVisible()
assert window.toolbar.windowFlags() & Qt.WindowType.WindowStaysOnTopHint
qtbot.waitUntil(lambda: len(ticks) >= 2)
qtbot.mouseClick(window.floating_button, Qt.MouseButton.LeftButton)
assert window.isVisible()
assert not window.floating_button.isVisible()
qtbot.mouseClick(window.toolbar.toggle_button, Qt.MouseButton.LeftButton)
assert window.isVisible() and window.toolbar.isVisible()
assert window.pages.currentWidget() is page
assert page.output_input.text() == "pending-user-folder"
assert page.output_input.text() == 'pending-user-folder'
def test_minimum_size_keeps_all_page_action_buttons_accessible(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.resize(860, 540)
for index in range(window.pages.count()):
window.set_active_page(index)
qtbot.wait(5)
assert window.width() == 860 and window.height() == 540
for button in window.findChildren(QAbstractButton):
if button.isVisibleTo(window):
assert window.rect().contains(button.mapTo(window, button.rect().bottomRight())), (index, button.text())
def test_native_minimize_becomes_floating_and_can_repeat(qtbot, monkeypatch, tmp_path):
def test_native_minimize_becomes_toolbar_and_can_repeat(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.show_panel(0)
for _ in range(2):
window.showMinimized()
qtbot.waitUntil(lambda: window.floating_button.isVisible() and not window.isVisible())
qtbot.mouseClick(window.floating_button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: window.toolbar.isVisible() and not window.isVisible())
qtbot.mouseClick(window.toolbar.toggle_button, Qt.MouseButton.LeftButton)
assert window.isVisible() and not window.isMinimized()
def test_drag_moves_floating_entry_without_opening_main_window(qtbot, monkeypatch, tmp_path):
def test_drag_only_handle_moves_toolbar_and_panel_without_switching(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.collapse_to_floating()
floating = window.floating_button
floating.move(40, 40)
start = QPointF(floating.mapToGlobal(QPoint(20, 20)))
window.show_panel(0)
floating = window.toolbar
floating.move_within_screen(QPoint(10, 40))
panel_position = window.pos()
handle = floating.drag_handle
start = QPointF(handle.mapToGlobal(QPoint(10, 10)))
for kind, local, global_pos, button, buttons in (
(QEvent.Type.MouseButtonPress, QPointF(20, 20), start, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton),
(QEvent.Type.MouseMove, QPointF(60, 40), start + QPointF(40, 20), Qt.MouseButton.NoButton, Qt.MouseButton.LeftButton),
(QEvent.Type.MouseButtonRelease, QPointF(20, 20), start + QPointF(40, 20), Qt.MouseButton.LeftButton, Qt.MouseButton.NoButton),
(QEvent.Type.MouseButtonPress, QPointF(10, 10), start, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton),
(QEvent.Type.MouseMove, QPointF(20, 30), start + QPointF(10, 20), Qt.MouseButton.NoButton, Qt.MouseButton.LeftButton),
(QEvent.Type.MouseButtonRelease, QPointF(10, 10), start + QPointF(10, 20), Qt.MouseButton.LeftButton, Qt.MouseButton.NoButton),
):
event = QMouseEvent(kind, local, global_pos, button, buttons, Qt.KeyboardModifier.NoModifier)
QCoreApplication.sendEvent(floating, event)
assert floating.pos() == QPoint(80, 60)
assert not window.isVisible() and floating.isVisible()
QCoreApplication.sendEvent(handle, event)
assert floating.pos() == QPoint(20, 60)
assert window.pos().y() == panel_position.y() + 20
assert window.pages.currentIndex() == 0
def test_close_while_collapsed_closes_floating_entry(qtbot, monkeypatch, tmp_path):
def test_close_hides_but_explicit_exit_closes_toolbar_and_stops_timers(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.collapse_to_floating()
timer = QTimer(window)
timer.start(100)
window.show_panel(0)
window.close()
assert not window.isVisible() and window.toolbar.isVisible() and timer.isActive()
with qtbot.waitSignal(window.window_closed):
window.close()
assert not window.floating_button.isVisible()
window.request_exit()
assert not window.toolbar.isVisible() and not timer.isActive()
def test_narrow_screen_keeps_priority_buttons_and_overflow_routes(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
toolbar = window.toolbar
toolbar.fit_available_width(520)
assert toolbar.width() <= 520
assert toolbar.height() == 44
for index in (0, 1, 7):
assert toolbar.page_buttons[index].isVisible()
for index in (2, 3, 4, 5):
if not toolbar.page_buttons[index].isVisible():
assert toolbar.page_actions[index].isVisible()
toolbar.page_actions[index].trigger()
assert window.pages.currentIndex() == index
def test_page_size_and_toolbar_position_restore_without_overwriting_settings(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
window.show_panel(0)
window.resize(750, 470)
window.show_panel(7)
window.resize(700, 410)
window.show_panel(0)
assert window.size().width() == 750 and window.size().height() == 470
window.toolbar.move_within_screen(QPoint(20, 50))
path = window.layout_preferences.path
window.request_exit()
from dx_productivity.ui.main_window import MainWindow
restored = MainWindow(layout_path=path)
qtbot.addWidget(restored)
restored.show_panel(7)
assert restored.size().width() == 700 and restored.size().height() == 410
assert restored.toolbar.pos() == QPoint(20, 50)
def test_menu_registration_blocks_exit_but_not_panel_hide(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
from types import SimpleNamespace
window.startup_controller = SimpleNamespace(is_running=lambda: True)
window.show_panel(0)
window.close()
assert not window.isVisible() and window.toolbar.isVisible()
assert not window.request_exit()
assert not window._closing
window.startup_controller = None
def test_saved_offscreen_position_and_bottom_anchor_are_clamped(qtbot, monkeypatch, tmp_path):
window = make_window(qtbot, monkeypatch, tmp_path)
screen = window.toolbar.screen()
bounds = screen.availableGeometry()
window.toolbar.move_within_screen(QPoint(99999, 99999), screen)
assert bounds.contains(window.toolbar.frameGeometry())
window.show_panel(0)
assert bounds.contains(window.frameGeometry())
assert window.frameGeometry().bottom() < window.toolbar.frameGeometry().top()
+82
View File
@@ -0,0 +1,82 @@
from PySide6.QtCore import Qt
from dx_productivity.ui.main_window import MainWindow
def test_toolbar_routes_toggle_and_explicit_exit(qtbot, tmp_path, monkeypatch):
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = MainWindow()
qtbot.addWidget(window)
window.show_toolbar()
assert window.toolbar.isVisible() and not window.isVisible()
assert window.toolbar.windowTitle() == '一叶知秋悬浮工具栏'
for index, button in window.toolbar.page_buttons.items():
qtbot.mouseClick(button, Qt.MouseButton.LeftButton)
assert window.isVisible() and window.pages.currentIndex() == index
assert button.isChecked()
qtbot.mouseClick(button, Qt.MouseButton.LeftButton)
assert not window.isVisible() and window.toolbar.isVisible()
window.show_panel(0)
window.close()
assert not window.isVisible() and window.toolbar.isVisible()
with qtbot.waitSignal(window.window_closed):
assert window.request_exit()
assert not window.toolbar.isVisible()
def test_status_setters_update_hidden_toolbar_without_showing_panel(qtbot, tmp_path, monkeypatch):
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = MainWindow()
qtbot.addWidget(window)
window.show_toolbar()
window.set_project_status('design.prj', 'C:/design.prj')
window.set_bridge_status('桥接已连接')
window.set_selection_status('已选 C18', '当前页:ROOT / 1\n选中器件:C18')
assert 'C18' in window.toolbar.status_label.text()
assert 'ROOT / 1' in window.toolbar.status_label.toolTip()
window.set_operation_status('PDF 导出中')
assert 'PDF 导出中' in window.toolbar.status_label.text()
assert 'C18' in window.toolbar.status_label.toolTip()
assert not window.isVisible()
def test_passive_status_keeps_host_focus_and_tracks_background_task(qtbot, qapp, tmp_path, monkeypatch):
from types import SimpleNamespace
from PySide6.QtWidgets import QWidget
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = MainWindow()
qtbot.addWidget(window)
window.show_toolbar()
host = QWidget()
qtbot.addWidget(host)
host.show()
host.activateWindow()
qapp.processEvents()
active = qapp.activeWindow()
window.set_bridge_status('桥接已连接')
window.set_selection_status('已选 C1', '选中器件:C1')
window.refdes_controller = SimpleNamespace(_apply_in_flight=True)
window._sync_status()
assert window.operation_status.text() == '位号应用中'
assert '位号应用中' in window.toolbar.status_label.text()
assert 'C1' in window.toolbar.status_label.toolTip()
assert qapp.activeWindow() is active and not window.isVisible()
window.refdes_controller._apply_in_flight = False
window.set_operation_status('位号已应用')
assert 'C1' in window.toolbar.status_label.text()
window.set_bridge_status('桥接已断开')
assert 'C1' not in window.toolbar.status_label.text()
assert 'C1' not in window.selection_status.text()
def test_toolbar_clamps_negative_monitor_coordinates(qtbot, tmp_path, monkeypatch):
from PySide6.QtCore import QPoint, QRect
from types import SimpleNamespace
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path))
window = MainWindow()
qtbot.addWidget(window)
bounds = QRect(-1400, -100, 1400, 900)
screen = SimpleNamespace(availableGeometry=lambda: bounds)
window.toolbar.move_within_screen(QPoint(-1600, -300), screen)
assert window.toolbar.pos() == bounds.topLeft()
assert bounds.contains(window.toolbar.frameGeometry())
+1 -1
View File
@@ -107,7 +107,7 @@ def test_network_navigation_has_live_list_and_locator(qtbot, tmp_path, fixture_p
window = create_main_window(request)
qtbot.addWidget(window)
window.navigation.setCurrentRow(4)
window.set_active_page(4)
page = window.pages.currentWidget()
assert isinstance(page, InspectionPage)
+33
View File
@@ -0,0 +1,33 @@
import json
from PySide6.QtCore import QPoint, QSize
from dx_productivity.ui.layout_preferences import LayoutPreferences
def test_layout_preferences_validate_types_and_recover_from_corruption(tmp_path):
path = tmp_path / 'ui-layout.json'
path.write_text('{broken', encoding='utf-8')
assert LayoutPreferences(path).position is None
path.write_text(json.dumps({'toolbar_position': [True, 40], 'page_sizes': {'0': [720, '420'], '7': [660, 380], '999': [900, 600]}, 'screen': 123}), encoding='utf-8')
preferences = LayoutPreferences(path)
assert preferences.position is None
assert preferences.screen_name == ''
assert preferences.page_sizes == {7: QSize(660, 380)}
def test_layout_preferences_round_trip_negative_monitor_position_and_atomic_write(tmp_path):
path = tmp_path / 'DxProductivity' / 'ui-layout.json'
settings = tmp_path / 'DxProductivity' / 'settings.json'
settings.parent.mkdir()
settings.write_text('{"channel":"stable"}', encoding='utf-8')
preferences = LayoutPreferences(path)
preferences.position = QPoint(-1200, 80)
preferences.screen_name = 'Second monitor'
preferences.page_sizes[0] = QSize(780, 490)
preferences.save()
fresh = LayoutPreferences(path)
assert fresh.position == QPoint(-1200, 80)
assert fresh.page_sizes[0] == QSize(780, 490)
assert fresh.screen_name == 'Second monitor'
assert settings.read_text(encoding='utf-8') == '{"channel":"stable"}'
assert not tuple(path.parent.glob('*.tmp'))
+54
View File
@@ -86,3 +86,57 @@ def test_selection_switches_current_sheet_without_overwriting_form(qtbot, fixtur
window.selection_watcher._check()
assert window.pdf_export_controller.snapshot.current_sheet_name == '2'
assert not any(c.current_sheet for c in window.bom_controller.snapshot.components)
def test_hidden_toolbar_selection_disconnect_recovery_and_project_switch(qtbot, fixture_path, tmp_path, monkeypatch):
import os
import time
window, data = setup_window(qtbot, fixture_path, tmp_path, monkeypatch)
window.show_toolbar()
publish(tmp_path, data, ['uid:uid-c-a'])
window.selection_watcher._check()
assert 'C1' in window.toolbar.status_label.text()
assert 'ROOT / 1' in window.toolbar.status_label.toolTip()
width = window.toolbar.width()
publish(tmp_path, data, ['uid:uid-r-a', 'uid:uid-c-a'])
window.selection_watcher._check()
assert '2 个' in window.toolbar.status_label.text()
assert 'C1' in window.toolbar.status_label.toolTip()
assert window.toolbar.width() == width
publish(tmp_path, data, [])
window.selection_watcher._check()
assert '0' in window.toolbar.status_label.text()
heartbeat = tmp_path / 'apply-progress.json'
heartbeat.write_text('{}', encoding='utf-8')
os.utime(heartbeat, (time.time() - 10, time.time() - 10))
window.selection_watcher._check()
assert '暂停' in window.toolbar.status_label.text()
assert 'C1' not in window.toolbar.status_label.text()
assert window.bridge_status.text() == '桥接已断开'
heartbeat.unlink()
publish(tmp_path, data, ['uid:uid-c-a'])
window.selection_watcher._check()
assert 'C1' in window.toolbar.status_label.text()
publish(tmp_path, data, ['uid:uid-c-a'], design_path='C:/other.prj')
window.selection_watcher._check()
assert '切换' in window.toolbar.status_label.text()
assert 'C1' not in window.toolbar.status_label.text()
assert not window.isVisible()
def test_repeated_panel_toggle_keeps_single_watcher_and_page_instances(qtbot, fixture_path, tmp_path, monkeypatch):
from PySide6.QtCore import QTimer
from dx_productivity.ui.selection_watcher import SelectionWatcher
window, data = setup_window(qtbot, fixture_path, tmp_path, monkeypatch)
pages = tuple(window.pages.widget(i) for i in range(window.pages.count()))
timers = tuple(window.selection_watcher.findChildren(QTimer))
for index in range(window.pages.count()):
window.show_panel(index)
window.hide_panel()
publish(tmp_path, data, ['uid:uid-c-a'])
window.selection_watcher._check()
window.show_panel(1)
assert tuple(window.pages.widget(i) for i in range(window.pages.count())) == pages
assert tuple(window.selection_watcher.findChildren(QTimer)) == timers
assert len(window.findChildren(SelectionWatcher)) == 1
assert window.property_change_controller.page.model.item(0, 0).text() == 'C1'
+8 -7
View File
@@ -1,5 +1,5 @@
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QToolButton
from PySide6.QtWidgets import QAbstractButton, QToolButton
from dx_productivity.ui.main_window import MainWindow
from dx_productivity.ui.app import create_application, create_main_window
@@ -12,17 +12,18 @@ def test_main_window_has_approved_minimum_and_navigation(qtbot):
window = MainWindow()
qtbot.addWidget(window)
assert window.minimumWidth() == 860
assert window.minimumHeight() == 540
assert window.minimumWidth() == 720
assert window.minimumHeight() == 420
assert window.navigation_items()[:3] == ["自动位号", "属性批改", "属性显示"]
assert window.apply_button.text() == "应用位号"
assert not hasattr(window, "navigation")
assert window.toolbar.page_buttons[0].accessibleName() == "自动位号"
def test_icon_buttons_have_accessible_names(qtbot):
window = MainWindow()
qtbot.addWidget(window)
for button in window.findChildren(QToolButton):
for button in window.toolbar.findChildren(QAbstractButton):
assert button.accessibleName()
assert button.toolTip()
@@ -38,7 +39,7 @@ def test_theme_toggle_changes_window_theme(qtbot):
window = MainWindow(theme=Theme.LIGHT)
qtbot.addWidget(window)
qtbot.mouseClick(window.theme_button, Qt.MouseButton.LeftButton)
window.theme_action.trigger()
assert window.theme is Theme.DARK
@@ -100,7 +101,7 @@ def test_main_window_uses_yiyezhqiu_brand_and_feature_pages(qtbot):
qtbot.addWidget(window)
assert window.windowTitle() == "一叶知秋_重构版"
assert window.brand_label.text() == "一叶知秋_重构版"
assert window.toolbar.windowTitle() == "一叶知秋悬浮工具栏"
assert isinstance(window.pages.widget(1), PropertyChangePage)
assert isinstance(window.pages.widget(2), PropertyVisibilityPage)
assert isinstance(window.pages.widget(3), InspectionPage)
+28
View File
@@ -109,3 +109,31 @@ def test_ui_update_starts_persistent_application_after_successful_smoke(qtbot, t
("smoke", (executable, "ui", "--smoke-test-ms", "1000")),
("launch", (executable, "ui")),
]
def test_update_handoff_exits_both_windows_and_shutdowns_controllers(qtbot, tmp_path, monkeypatch):
from types import SimpleNamespace
from PySide6.QtCore import QTimer
window, controller, manifest, commands = _launch_fixture(qtbot, tmp_path, monkeypatch)
current = _portable(tmp_path, 'portable-exit')
monkeypatch.setattr(sys, 'executable', str(current / 'DxDesignerTools.exe'))
shutdowns = []
window.settings_controller = SimpleNamespace(shutdown=lambda: shutdowns.append('settings'))
timer = QTimer(window)
timer.start(100)
window.show_panel(0)
with qtbot.waitSignal(window.window_closed):
app_module._launch_update(window, controller, manifest)
assert commands and shutdowns == ['settings']
assert window._closing and not window.isVisible() and not window.toolbar.isVisible()
assert not timer.isActive()
def test_update_does_not_spawn_updater_while_menu_registration_is_running(qtbot, tmp_path, monkeypatch):
from types import SimpleNamespace
window, controller, manifest, commands = _launch_fixture(qtbot, tmp_path, monkeypatch)
window.startup_controller = SimpleNamespace(is_running=lambda: True)
app_module._launch_update(window, controller, manifest)
assert not commands and not window._closing
assert '菜单注册' in window.operation_status.text()
window.startup_controller = None