Compare commits

..
Author SHA1 Message Date
阿白叔 650dfd5491 fix: restore the main window geometry across sessions
Core regression / JavaScript syntax (pull_request) Waiting to run
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m28s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) In progress
2026-11-25 09:58:38 +08:00
5 changed files with 143 additions and 38 deletions

No files matched your search

@@ -0,0 +1,21 @@
# Issue #33 D3 主窗口布局恢复
原来的 `ui-layout.ini` 只保存分栏、表头与排序,`TrialTaskCenterWindow` 每次启动都会重用默认窗口尺寸。复现时,保存进程关闭前的普通窗口为 `(45, 55, 1200, 760)` 且已最大化,重启后普通窗口变为 `(2, 2, 1280, 880)` 且未最大化。
正常接受关闭后,现通过 Qt `saveGeometry()` 持久化普通窗口几何和最大化状态。启动时调用 `restoreGeometry()`。若配置损坏、DPI 改变导致 Qt 拒绝恢复,或普通窗口超出当前可用屏幕,窗口会在当前可用屏幕内重新定位,并保留产品定义的最小尺寸。
## Windows 原生窗口实测
```powershell
$env:QT_QPA_PLATFORM = 'windows'
python -m pytest -q -s tests/v1_1/test_window_geometry.py
```
| 场景 | 结果 |
| --- | --- |
| 正常退出并启动新进程 | 普通窗口几何保持 `(45, 55, 1200, 760)`,最大化状态保持为真 |
| 新进程设 `QT_SCALE_FACTOR=1.5` | 普通窗口回退为 `(8, 36, 1008, 700)`,窗口位于可用屏幕,采用普通状态 |
| 配置值为错误类型或截断的字节 | 窗口仍能打开,普通窗口位置可达 |
| 配置保存位置为 `(50000, 50000)` | 窗口回到可用屏幕 |
测试通过 4 项。屏外场景用坐标模拟显示器移除,DPI 变化由 Qt 环境设置触发。
@@ -4,7 +4,7 @@ from threading import Event
from ..stop_control import StopControl from ..stop_control import StopControl
from shiboken6 import isValid from shiboken6 import isValid
import time import time
from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt from PySide6.QtCore import QByteArray, QElapsedTimer, QRect, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
from PySide6.QtGui import QAction, QActionGroup from PySide6.QtGui import QAction, QActionGroup
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QMessageBox, from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QMessageBox,
QPushButton, QLabel, QSizePolicy, QSplitter, QStackedWidget, QTabWidget, QToolButton, QVBoxLayout, QWidget) QPushButton, QLabel, QSizePolicy, QSplitter, QStackedWidget, QTabWidget, QToolButton, QVBoxLayout, QWidget)
@@ -184,6 +184,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self.archive_on_close_check.setToolTip('默认关闭。仅归档安全任务,保留计划、日志和文件;待核验或资源未释放的任务保留在当前列表。') self.archive_on_close_check.setToolTip('默认关闭。仅归档安全任务,保留计划、日志和文件;待核验或资源未释放的任务保留在当前列表。')
self._build_layout() self._build_layout()
self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat) self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat)
self._restore_window_geometry()
self.auto_intervention_check.setChecked(self._layout_settings.value( self.auto_intervention_check.setChecked(self._layout_settings.value(
'dsh/auto_intervention', True, type=bool)) 'dsh/auto_intervention', True, type=bool))
self.auto_intervention_check.toggled.connect(self._set_auto_intervention) self.auto_intervention_check.toggled.connect(self._set_auto_intervention)
@@ -319,6 +320,34 @@ class TrialTaskCenterWindow(MaterialMainWindow):
return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter, return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter,
'rules': self.mapping_table.horizontalHeader(), 'targets': self.plan_panel.table.horizontalHeader()} 'rules': self.mapping_table.horizontalHeader(), 'targets': self.plan_panel.table.horizontalHeader()}
def _restore_window_geometry(self):
saved = self._layout_settings.value('main_window/geometry')
if saved is None:
return
default = self.geometry()
restored = isinstance(saved, QByteArray) and self.restoreGeometry(saved)
normal = self.normalGeometry() if restored else default
screen = QApplication.screenAt(normal.center()) if restored else None
screen = screen or QApplication.primaryScreen()
if screen is None:
return
available = screen.availableGeometry()
if restored and available.contains(normal) and normal.size().expandedTo(self.minimumSize()) == normal.size():
return
# Qt may reject a saved geometry after a DPI change. Keep the normal
# window reachable on the current display, even when its minimum exceeds it.
available = available.adjusted(8, 36, -8, -8)
state = self.windowState()
self.setWindowState(Qt.WindowState.WindowNoState)
size = normal.size().boundedTo(available.size()).expandedTo(self.minimumSize())
fallback = QRect(available.topLeft(), size)
fallback.moveCenter(available.center())
fallback.moveLeft(max(fallback.left(), available.left()))
fallback.moveTop(max(fallback.top(), available.top()))
self.setGeometry(fallback)
self.setWindowState(state)
def _reset_layout(self): def _reset_layout(self):
self.workspace_splitter.setSizes((240, 1040)) self.workspace_splitter.setSizes((240, 1040))
self.detail_splitter.setSizes((650, 110)) self.detail_splitter.setSizes((650, 110))
@@ -416,9 +445,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
QTimer.singleShot(100, self.close) QTimer.singleShot(100, self.close)
return return
self._cancel_dsh_diagnosis() self._cancel_dsh_diagnosis()
self._layout_settings.setValue('main_window/geometry', self.saveGeometry())
for name, widget in self._layout_widgets().items(): for name, widget in self._layout_widgets().items():
self._layout_settings.setValue(f'single_project/{name}', widget.saveState()) self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData()) self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
self._layout_settings.sync()
self._closed = True self._closed = True
self._dsh_status.close() self._dsh_status.close()
self._dsh_stall_timer.stop() self._dsh_stall_timer.stop()
@@ -79,10 +79,6 @@ class TaskList(QWidget):
self.recycle_button = QPushButton('回收站', objectName='taskRecycleBin') self.recycle_button = QPushButton('回收站', objectName='taskRecycleBin')
self.recycle_button.setCheckable(True) self.recycle_button.setCheckable(True)
self.count = QLabel(objectName='taskCount') self.count = QLabel(objectName='taskCount')
self.empty_hint = QLabel(objectName='taskEmptyHint')
self.empty_hint.setTextFormat(Qt.TextFormat.PlainText)
self.empty_hint.setWordWrap(True)
self.empty_hint.hide()
self.filter = QComboBox(objectName="taskFilter") self.filter = QComboBox(objectName="taskFilter")
for label, key, picture in (('全部任务', 'all', 'grid'), ('未完成', 'unfinished', 'clock'), for label, key, picture in (('全部任务', 'all', 'grid'), ('未完成', 'unfinished', 'clock'),
('待开始', 'pending', 'clock'), ('执行中', 'running', 'clock'), ('待开始', 'pending', 'clock'), ('执行中', 'running', 'clock'),
@@ -150,7 +146,6 @@ class TaskList(QWidget):
layout.addWidget(self.filter) layout.addWidget(self.filter)
layout.addLayout(batch) layout.addLayout(batch)
layout.addLayout(selection) layout.addLayout(selection)
layout.addWidget(self.empty_hint)
layout.addWidget(self.list, 1) layout.addWidget(self.list, 1)
layout.addWidget(self.queue_button) layout.addWidget(self.queue_button)
layout.addLayout(footer) layout.addLayout(footer)
@@ -259,17 +254,6 @@ class TaskList(QWidget):
if getattr(task, "task_id") == selected: if getattr(task, "task_id") == selected:
self.list.setCurrentItem(item) self.list.setCurrentItem(item)
hidden = selected and self.current_task_id() is None hidden = selected and self.current_task_id() is None
if not tasks: self.count.setText(f'{len(tasks)} / {len(self._tasks)} 个任务' + (' · 当前任务已隐藏' if hidden else ''))
category_text = self.filter.currentText() if category != 'all' and not self.recycle_button.isChecked() else ''
if not self._tasks:
hint = '回收站为空。' if self.recycle_button.isChecked() else '暂无任务,点击“新建任务”导入工程。'
elif query:
scope = f'“{category_text}”中' if category_text else ''
hint = f'{scope}未找到与“{self.search.text().strip()}”匹配的任务。'
else:
hint = f'暂无“{category_text}”任务。'
self.empty_hint.setText(hint)
self.empty_hint.setVisible(not tasks)
self.count.setText(f'匹配 {len(tasks)} / 共 {len(self._tasks)} 个任务' + (' · 当前任务已隐藏' if hidden else ''))
self._update_selection_state() self._update_selection_state()
self.view_changed.emit() self.view_changed.emit()
-20
View File
@@ -27,26 +27,6 @@ def visible_ids(panel):
return [panel.list.item(index).data(Qt.ItemDataRole.UserRole) for index in range(panel.list.count())] return [panel.list.item(index).data(Qt.ItemDataRole.UserRole) for index in range(panel.list.count())]
def test_empty_list_explains_search_filter_and_initial_state(navigation, qtbot):
panel, tasks, opened = navigation
panel.populate(tasks[:1])
qtbot.keyClicks(panel.search, 'zzzz_no_match')
assert panel.empty_hint.isVisible()
assert 'zzzz_no_match' in panel.empty_hint.text()
assert '匹配 0 / 共 1 个任务' in panel.count.text()
panel.filter.setCurrentIndex(panel.filter.findData('completed'))
assert '已完成' in panel.empty_hint.text() and 'zzzz_no_match' in panel.empty_hint.text()
panel.search.clear()
assert '已完成' in panel.empty_hint.text()
panel.filter.setCurrentIndex(panel.filter.findData('all'))
assert not panel.empty_hint.isVisible() and len(visible_ids(panel)) == 1
panel.populate(())
assert '新建任务' in panel.empty_hint.text()
panel.recycle_button.setChecked(True)
panel.populate(())
assert '回收站' in panel.empty_hint.text()
@pytest.mark.parametrize(('category','expected'),[ @pytest.mark.parametrize(('category','expected'),[
('all',['draft','ready','running','paused','completed','failed','blocked']), ('all',['draft','ready','running','paused','completed','failed','blocked']),
('unfinished',['draft','ready','running','paused','failed','blocked']), ('unfinished',['draft','ready','running','paused','failed','blocked']),
+89
View File
@@ -0,0 +1,89 @@
import json
import os
from pathlib import Path
import subprocess
import sys
import pytest
from PySide6.QtCore import QByteArray
from test_ui_remediation import window
_GEOMETRY = 'main_window/geometry'
def test_geometry_persists_across_application_processes(tmp_path):
source = Path(__file__).resolve().parents[2] / 'src'
env = os.environ | {'PYTHONPATH': str(source)}
script = """
import json
import sys
from PySide6.QtCore import QTimer
from dx_productivity.trial_task_center import application
mode, root = sys.argv[1:]
window_type = application._load_window()
def open_window(service):
window = window_type(service)
def capture():
normal = window.normalGeometry()
area = window.screen().availableGeometry()
print(json.dumps({'normal': normal.getRect(), 'maximized': window.isMaximized(),
'reachable': area.contains(normal.topLeft()), 'fits': area.contains(normal)}),
flush=True)
window.close()
def arrange():
if mode == 'save':
window.setGeometry(45, 55, 1200, 760)
window.showMaximized()
QTimer.singleShot(200, capture)
QTimer.singleShot(0, arrange)
return window
application._load_window = lambda: open_window
raise SystemExit(application.main(['--data-root', root]))
"""
env.setdefault('QT_QPA_PLATFORM', 'offscreen')
def launch(mode, **overrides):
result = subprocess.run([sys.executable, '-c', script, mode, str(tmp_path)], env=env | overrides,
timeout=90, capture_output=True, text=True)
assert result.returncode == 0, result.stderr
return json.loads(result.stdout)
saved = launch('save')
reopened = launch('restore')
rescaled = launch('restore', QT_SCALE_FACTOR='1.5')
print(f'window geometry saved={saved}, reopened={reopened}')
print(f'window geometry at changed DPI={rescaled}')
assert saved['maximized'] and reopened['maximized']
assert saved['normal'][2:] == [1200, 760]
assert reopened['reachable'] and rescaled['reachable']
if saved['fits']:
assert reopened['normal'] == saved['normal']
@pytest.mark.parametrize('saved', ['broken', QByteArray(b'bad'), 'offscreen'])
def test_invalid_or_offscreen_settings_leave_window_visible(window, qtbot, saved):
if saved == 'offscreen':
window.setGeometry(50000, 50000, 1200, 760)
saved = window.saveGeometry()
window._layout_settings.setValue(_GEOMETRY, saved)
window._layout_settings.sync()
reopened = type(window)(window.service)
qtbot.addWidget(reopened)
try:
reopened.show()
rect = reopened.geometry()
area = reopened.screen().availableGeometry()
assert area.contains(rect.topLeft())
assert rect.intersects(area)
assert not reopened.isMaximized()
finally:
reopened.close()