fix: preserve live selection validity and preferred panel geometry

This commit is contained in:
阿白叔 committed 2026-10-11 11:44:00 +08:00
1 parent 9caf33df38
commit d6df3f99fb
8 files changed
+268 -15

No files matched your search

@@ -1,5 +1,5 @@
"""Advanced options with an always-visible effective summary."""
from PySide6.QtCore import Signal
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QLabel, QToolButton, QVBoxLayout, QWidget
@@ -15,6 +15,7 @@ class CollapsibleSection(QWidget):
self.toggle_button = QToolButton()
self.toggle_button.setObjectName('sectionToggle')
self.toggle_button.setCheckable(True)
self.toggle_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.toggle_button.setAccessibleName(title)
self.toggle_button.setToolTip('展开或收起' + title)
self.summary_label = QLabel()
@@ -38,7 +39,8 @@ class CollapsibleSection(QWidget):
self.toggle_button.setChecked(expanded)
def _update_expanded(self, expanded: bool) -> None:
self.toggle_button.setText(('▾ ' if expanded else '▸ ') + self._title)
self.toggle_button.setText(self._title)
self.toggle_button.setArrowType(Qt.ArrowType.DownArrow if expanded else Qt.ArrowType.RightArrow)
self.content.setVisible(expanded)
self.expanded_changed.emit(expanded)
+64 -2
View File
@@ -15,6 +15,9 @@ NAVIGATION = (
('设置', 'fa6s.gear'),
)
PRIMARY_PAGES = (0, 1, 2, 3, 4, 5, 7)
SHORT_LABELS = dict(zip(PRIMARY_PAGES, ('位号', '属性', '显示', '检查', '网络', 'BOM', 'PDF')))
# Below this width a 28-pixel clickable control cannot fit its frame.
MINIMUM_TOOLBAR_WIDTH = 34
class DragHandle(QLabel):
@@ -76,7 +79,7 @@ class FloatingToolbar(QWidget):
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')):
for index, short in SHORT_LABELS.items():
button = QPushButton(short)
button.setObjectName('toolbarFeature')
button.setAccessibleName(NAVIGATION[index][0])
@@ -97,6 +100,9 @@ class FloatingToolbar(QWidget):
self.more_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
self.more_menu = QMenu(self.more_button)
self.more_button.setMenu(self.more_menu)
self.start_action = self.more_menu.addAction('Start:加入菜单并打开 DxDesigner')
self.start_action.triggered.connect(self.start_requested)
self.start_action.setVisible(False)
self.page_actions = {}
for index in PRIMARY_PAGES + (6, 8):
action = QAction(NAVIGATION[index][0], self)
@@ -105,6 +111,12 @@ class FloatingToolbar(QWidget):
self.page_actions[index] = action
self.more_menu.addAction(action)
self.more_menu.addSeparator()
self.toggle_action = self.more_menu.addAction('展开面板')
self.toggle_action.triggered.connect(self.toggle_panel_requested)
self.toggle_action.setVisible(False)
self.status_action = self.more_menu.addAction('状态:桥接待连接')
self.status_action.setEnabled(False)
self.status_action.setVisible(False)
for name, attribute, signal in (('刷新设计快照', 'refresh_action', self.refresh_requested),
('切换明暗主题', 'theme_action', self.theme_requested),
('退出工具', 'exit_action', self.exit_requested)):
@@ -128,18 +140,40 @@ class FloatingToolbar(QWidget):
name = '收起面板' if visible else '展开面板'
self.toggle_button.setAccessibleName(name)
self.toggle_button.setToolTip(name)
self.toggle_action.setText(name)
def set_status(self, text: str, detail: str):
self._status_text = text
self.status_label.setAccessibleName(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)
self.status_action.setText('状态:' + self.status_label.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, 240))
self.status_action.setToolTip(detail)
self.more_button.setToolTip('更多功能与应用操作' + ('\n' + detail if self.status_label.isHidden() else ''))
self.start_action.setEnabled(self.start_button.isEnabled())
def fit_available_width(self, width: int):
self._available_width = max(1, width)
width = max(MINIMUM_TOOLBAR_WIDTH, width)
self._available_width = width
layout = self.layout()
layout.setContentsMargins(5, 4, 5, 4)
layout.setSpacing(4)
self.drag_handle.show()
self.drag_handle.setFixedWidth(20)
self.start_button.show()
self.start_button.setText('Start')
self.start_button.setFixedWidth(64)
self.start_action.setVisible(False)
self.toggle_button.show()
self.toggle_action.setVisible(False)
self.status_label.show()
self.status_label.setFixedWidth(164)
self.status_action.setVisible(False)
for index, button in self.page_buttons.items():
button.setVisible(True)
button.setText(SHORT_LABELS[index])
button.setFixedWidth(58)
self.page_actions[index].setVisible(False)
for index in (2, 3, 4, 5):
if self.layout().sizeHint().width() <= width:
@@ -150,7 +184,35 @@ class FloatingToolbar(QWidget):
excess = self.layout().sizeHint().width() - width
if excess > 0:
self.status_label.setFixedWidth(max(24, 164 - excess))
if layout.sizeHint().width() > width:
# Icon mode retains names/tooltips, then overflows remaining entries
# in priority order. Start and PDF stay direct until the last stage.
layout.setContentsMargins(2, 4, 2, 4)
layout.setSpacing(2)
self.drag_handle.setFixedWidth(12)
self.start_button.setText('')
self.start_button.setFixedWidth(28)
for button in self.page_buttons.values():
button.setText('')
button.setFixedWidth(32)
self.page_buttons[7].setFixedWidth(28)
for index in (1, 0):
if layout.sizeHint().width() <= width:
break
self.page_buttons[index].hide()
self.page_actions[index].setVisible(True)
for widget, action in ((self.status_label, self.status_action),
(self.toggle_button, self.toggle_action),
(self.drag_handle, None),
(self.start_button, self.start_action),
(self.page_buttons[7], self.page_actions[7])):
if layout.sizeHint().width() <= width:
break
widget.hide()
if action is not None:
action.setVisible(True)
self.setFixedWidth(min(width, self.layout().sizeHint().width()))
layout.activate()
self.set_status(self._status_text, self.status_label.toolTip())
def move_within_screen(self, position: QPoint, screen=None):
+18 -5
View File
@@ -21,6 +21,7 @@ class MainWindow(QMainWindow):
super().__init__()
self._closing = False
self._placing = False
self._effective_page_size = None
self._active_page = 0
self._toolbar_positioned = False
self._operation_text = '就绪'
@@ -171,18 +172,27 @@ class MainWindow(QMainWindow):
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()
if self.size() != self._effective_page_size:
# Internal placement sets its expected size before resizing.
# A different resize is a new user preference, including an
# external resize() call used by window-management clients.
self._effective_page_size = self.size()
self.layout_preferences.page_sizes[self._active_page] = self.size()
self.layout_preferences.save()
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 _preferred_page_size(self, index: int) -> QSize:
return self.layout_preferences.page_sizes.get(index, QSize(660, 390) if index in (7, 8) else QSize(780, 480))
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._effective_page_size = self._preferred_page_size(index)
self.resize(self._effective_page_size)
self._placing = False
def _toolbar_moved(self, position: QPoint) -> None:
@@ -216,8 +226,11 @@ class MainWindow(QMainWindow):
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))
compact = self._active_page in (7, 8)
self.setMinimumSize(min(660 if compact else 720, max_width), min(340 if compact else 420, max_height))
preferred = self._preferred_page_size(self._active_page)
self._effective_page_size = QSize(min(preferred.width(), max_width), min(preferred.height(), max_height))
self.resize(self._effective_page_size)
toolbar_rect = self.toolbar.frameGeometry()
height = self.frameGeometry().height()
below = toolbar_rect.bottom() + 6
+24 -5
View File
@@ -21,6 +21,9 @@ class SelectionWatcher(QObject):
self.window = window
self.path = request_path.with_name('selection.json')
self.last_signature = None
self._channel_confirmed = False
self._initial_deadline = time.monotonic() + 5.0
self._initial_detail = window.selection_status.toolTip()
self.timer = QTimer(self)
self.timer.setInterval(150)
self.timer.timeout.connect(self._check)
@@ -55,12 +58,10 @@ 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
self._channel_unavailable('选择状态无法读取,请刷新快照或重新连接宿主。')
return
if not isinstance(data, dict) or data.get('run_id') != snapshot.run_id:
self._channel_unavailable('选择状态不属于当前宿主会话。')
return
if os.path.normcase(str(data.get('design_path', ''))) != os.path.normcase(snapshot.design_path):
self.window.set_bridge_status('工程已切换')
@@ -68,15 +69,21 @@ class SelectionWatcher(QObject):
self.last_signature = None
return
if data.get('snapshot_id') != snapshot.snapshot_id:
self.window.set_bridge_status('等待设计快照刷新')
self.window.set_selection_status('等待设计快照刷新')
self.last_signature = None
return
if data.get('state') != 'ready':
state = data.get('state')
if state not in ('ready', 'unavailable', 'disconnected', 'closed', 'error'):
self._channel_unavailable('选择状态格式无效。')
return
if state != 'ready':
fresh = replace(snapshot, components=tuple(replace(component, selected=False, current_sheet=False)
for component in snapshot.components), selected_nets=(), active_block_name='',
current_sheet_name='', current_sheet_number=None)
self._load_snapshot(fresh, controllers)
self.last_signature = signature
self._channel_confirmed = True
disconnected = data.get('state') in ('disconnected', 'closed', 'error')
self.window.set_bridge_status('桥接已断开' if disconnected else '桥接已连接')
self.window.set_selection_status('桥接已断开' if disconnected else '未打开原理图页')
@@ -85,11 +92,13 @@ class SelectionWatcher(QObject):
current = data.get('current_sheet_keys')
nets = data.get('selected_nets', [])
if any(not isinstance(value, list) or any(not isinstance(item, str) for item in value) for value in (selected, current, nets)):
self._channel_unavailable('选择列表格式无效。')
return
block = data.get('active_block_name')
sheet = data.get('current_sheet_name')
page = data.get('current_sheet_number')
if not isinstance(block, str) or not isinstance(sheet, str) or (page is not None and type(page) is not int):
self._channel_unavailable('当前页信息格式无效。')
return
selected, current = set(selected), set(current)
components = tuple(replace(component, selected=identity(component) in selected,
@@ -99,6 +108,7 @@ class SelectionWatcher(QObject):
self._load_snapshot(fresh, controllers)
self.window.set_bridge_status('桥接已连接')
self.last_signature = signature
self._channel_confirmed = True
known = {identity(component) for component in components}
refs = [component.refdes or '未标注器件' for component in components if component.selected]
if selected - known:
@@ -115,6 +125,15 @@ class SelectionWatcher(QObject):
f'当前工程:{fresh.design_path}\n当前页:{block} / {sheet}\n选中器件:' + ('、'.join(refs) or '无')
)
def _channel_unavailable(self, detail: str) -> None:
self.last_signature = None
if not self._channel_confirmed and time.monotonic() < self._initial_deadline:
self.window.set_bridge_status('等待宿主选择通道')
self.window.set_selection_status('等待选择同步', detail + '\n初始快照(尚未确认实时选择):\n' + self._initial_detail)
else:
self.window.set_bridge_status('桥接已断开')
self.window.set_selection_status('选择同步已暂停', detail)
def _load_snapshot(self, fresh, controllers) -> None:
for item in controllers:
load = getattr(item, 'load_selection_snapshot', None)
+6 -1
View File
@@ -140,7 +140,8 @@ def _stylesheet(tokens: ThemeTokens) -> str:
}}
QToolButton#sectionToggle {{
min-width: 100px;
max-width: 16777215px;
max-width: 16777000px;
min-height: 28px;
padding: 0 7px;
text-align: left;
}}
@@ -215,6 +216,10 @@ def _stylesheet(tokens: ThemeTokens) -> str:
QLabel {{
color: {tokens.text_primary};
}}
QCheckBox, QRadioButton {{
min-height: 28px;
color: {tokens.text_primary};
}}
QLabel#secondaryLabel, QLabel#projectLabel {{
color: {tokens.text_secondary};
font-size: 10pt;
+68
View File
@@ -143,3 +143,71 @@ def test_saved_offscreen_position_and_bottom_anchor_are_clamped(qtbot, monkeypat
window.show_panel(0)
assert bounds.contains(window.frameGeometry())
assert window.frameGeometry().bottom() < window.toolbar.frameGeometry().top()
def test_screen_clamp_preserves_preferred_sizes_through_hide_switch_and_restore(qtbot, monkeypatch, tmp_path):
from types import SimpleNamespace
from PySide6.QtCore import QRect, QSize
from PySide6.QtWidgets import QApplication
from dx_productivity.ui.main_window import MainWindow
bounds = [QRect(0, 0, 1800, 1000)]
screen = SimpleNamespace(availableGeometry=lambda: bounds[0], name=lambda: 'test-monitor')
monkeypatch.setattr(QApplication, 'screenAt', lambda _point: screen)
window = MainWindow(layout_path=tmp_path / 'ui-layout.json')
qtbot.addWidget(window)
window.show_panel(0)
window.resize(1000, 700)
assert window.layout_preferences.page_sizes[0] == QSize(1000, 700)
bounds[0] = QRect(0, 0, 800, 600)
window._screens_changed()
assert window.width() < 1000 and window.height() < 700
window.hide_panel()
assert window.layout_preferences.page_sizes[0] == QSize(1000, 700)
from dx_productivity.ui.layout_preferences import LayoutPreferences
assert LayoutPreferences(window.layout_preferences.path).page_sizes[0] == QSize(1000, 700)
window.show_panel(7)
window.show_panel(0)
assert window.layout_preferences.page_sizes[0] == QSize(1000, 700)
bounds[0] = QRect(0, 0, 1800, 1000)
window._screens_changed()
assert window.size() == QSize(1000, 700)
window.resize(900, 650)
window.hide_panel()
assert window.layout_preferences.page_sizes[0] == QSize(900, 650)
def test_extremely_narrow_toolbar_keeps_children_in_bounds_and_routes_accessible(qtbot, monkeypatch, tmp_path):
from dx_productivity.ui.main_window import MainWindow
from PySide6.QtWidgets import QAbstractButton
window = MainWindow(layout_path=tmp_path / 'ui-layout.json')
qtbot.addWidget(window)
window.show_toolbar()
toolbar = window.toolbar
for width in (340, 240, 180, 120, 96):
toolbar.fit_available_width(width)
toolbar.layout().activate()
assert toolbar.width() <= width and toolbar.height() == 44
for child in toolbar.findChildren(QAbstractButton):
if child.isVisibleTo(toolbar):
assert toolbar.rect().contains(child.geometry()), (width, child.accessibleName(), child.geometry())
visible = [toolbar.layout().itemAt(i).widget() for i in range(toolbar.layout().count())
if not toolbar.layout().itemAt(i).widget().isHidden()]
for left, right in zip(visible, visible[1:]):
assert left.geometry().right() < right.geometry().left(), (width, left.geometry(), right.geometry())
assert toolbar.start_button.isVisible() and toolbar.page_buttons[7].isVisible()
assert toolbar.more_button.isVisible()
for index in range(window.pages.count()):
assert index in toolbar.page_buttons and toolbar.page_buttons[index].isVisible() or toolbar.page_actions[index].isVisible()
with qtbot.waitSignal(toolbar.page_requested) as received:
toolbar.page_actions[0].trigger()
assert received.args == [0]
for width in (80, 48, 34):
toolbar.fit_available_width(width)
for child in toolbar.findChildren(QAbstractButton):
if child.isVisibleTo(toolbar):
assert toolbar.rect().contains(child.geometry())
assert toolbar.more_button.isVisible()
assert toolbar.start_action.isVisible() or toolbar.start_button.isVisible()
assert toolbar.page_actions[7].isVisible() or toolbar.page_buttons[7].isVisible()
with qtbot.waitSignal(toolbar.start_requested):
toolbar.start_action.trigger()
+54
View File
@@ -33,7 +33,15 @@ def test_status_setters_update_hidden_toolbar_without_showing_panel(qtbot, tmp_p
window.set_bridge_status('桥接已连接')
window.set_selection_status('已选 C18', '当前页:ROOT / 1\n选中器件:C18')
assert 'C18' in window.toolbar.status_label.text()
assert 'C18' in window.toolbar.status_label.accessibleName()
assert 'ROOT / 1' in window.toolbar.status_label.toolTip()
from PySide6.QtGui import QAccessible
long_reference = 'C18_' + 'LONG_REFERENCE_' * 15
window.set_selection_status('已选 ' + long_reference, '选中器件:' + long_reference)
label = window.toolbar.status_label
assert long_reference not in label.text()
assert long_reference in QAccessible.queryAccessibleInterface(label).text(QAccessible.Text.Name)
assert long_reference in label.accessibleDescription()
window.set_operation_status('PDF 导出中')
assert 'PDF 导出中' in window.toolbar.status_label.text()
assert 'C18' in window.toolbar.status_label.toolTip()
@@ -80,3 +88,49 @@ def test_toolbar_clamps_negative_monitor_coordinates(qtbot, tmp_path, monkeypatc
window.toolbar.move_within_screen(QPoint(-1600, -300), screen)
assert window.toolbar.pos() == bounds.topLeft()
assert bounds.contains(window.toolbar.frameGeometry())
def test_advanced_section_title_fits_natural_button_geometry(qtbot, qapp):
from dx_productivity.ui.app import create_application
from dx_productivity.ui.collapsible_section import CollapsibleSection
from dx_productivity.ui.theme import apply_theme, Theme
create_application([])
section = CollapsibleSection('高级 PDF 导出与兼容选项')
qtbot.addWidget(section)
section.resize(350, 80)
section.show()
for theme in (Theme.LIGHT, Theme.DARK):
apply_theme(qapp, theme)
qapp.processEvents()
button = section.toggle_button
assert button.width() >= button.fontMetrics().horizontalAdvance(button.text()) + 14
assert button.height() >= 28
assert section.rect().contains(button.geometry())
assert button.text() == '高级 PDF 导出与兼容选项'
assert button.arrowType() == Qt.ArrowType.RightArrow
section.set_expanded(True)
assert button.arrowType() == Qt.ArrowType.DownArrow
section.set_expanded(False)
def test_compact_page_check_and_radio_hit_targets_fit(qtbot, qapp):
from PySide6.QtWidgets import QCheckBox, QRadioButton, QAbstractButton
from dx_productivity.ui.app import create_application
from dx_productivity.ui.pdf_export_page import PdfExportPage
from dx_productivity.ui.settings_page import SettingsPage
from dx_productivity.ui.bom_page import BomPage
from dx_productivity.ui.theme import apply_theme, Theme
create_application([])
apply_theme(qapp, Theme.LIGHT)
for page, width, height in ((PdfExportPage(), 660, 390), (SettingsPage(current_version='0.1.0'), 660, 390), (BomPage(), 780, 480)):
qtbot.addWidget(page)
page.resize(width, height)
page.show()
qapp.processEvents()
assert page.width() <= width and page.height() <= height
targets = [child for child in page.findChildren(QAbstractButton)
if isinstance(child, (QCheckBox, QRadioButton)) and child.isVisibleTo(page)]
assert targets
for child in targets:
assert child.height() >= 28, (type(page).__name__, child.text(), child.geometry())
assert page.rect().contains(child.mapTo(page, child.rect().bottomRight()))
+30
View File
@@ -1,4 +1,5 @@
import json
import pytest
from pathlib import Path
from dx_productivity.ui.app import create_main_window
@@ -140,3 +141,32 @@ def test_repeated_panel_toggle_keeps_single_watcher_and_page_instances(qtbot, fi
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'
@pytest.mark.parametrize('content', [None, '{malformed', '[]', '{"state":"ready"}'])
def test_initial_unavailable_selection_waits_then_pauses_and_recovers(qtbot, fixture_path, tmp_path, monkeypatch, content):
from dx_productivity.ui import selection_watcher as watcher_module
now = [100.0]
monkeypatch.setattr(watcher_module.time, 'monotonic', lambda: now[0])
if content is not None:
(tmp_path / 'selection.json').write_text(content, encoding='utf-8')
window, data = setup_window(qtbot, fixture_path, tmp_path, monkeypatch)
window.show_toolbar()
original = window.refdes_controller.snapshot
assert '等待' in window.selection_status.text()
assert window.bridge_status.text() != '桥接已连接'
assert '已选' not in window.toolbar.status_label.text()
now[0] += 10
window.selection_watcher._check()
assert '暂停' in window.selection_status.text()
assert window.refdes_controller.snapshot is original
publish(tmp_path, data, ['uid:uid-c-a'])
window.selection_watcher._check()
assert window.bridge_status.text() == '桥接已连接'
assert 'C1' in window.toolbar.status_label.text()
payload = json.loads((tmp_path / 'selection.json').read_text(encoding='utf-8'))
payload['selected_keys'] = 12
(tmp_path / 'selection.json').write_text(json.dumps(payload), encoding='utf-8')
window.selection_watcher._check()
assert '暂停' in window.selection_status.text()
assert 'C1' not in window.toolbar.status_label.text()