Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
315d2e85b3 |
No files matched your search
@@ -0,0 +1,17 @@
|
||||
# Issue #33 D1 同数据目录单实例
|
||||
|
||||
`application.main` 原先直接配置日志、打开 `task-center.db` 并执行启动恢复。现场 `data_lock` 日志有两次同根 `application_start`,两实例均成功读取任务列表。现有执行租约只在执行操作中生效。
|
||||
|
||||
GUI 现在先取得 `.gui-instance.lock` 的内核文件锁,再打开日志和数据库。第二次启动经 Qt 本地套接字请求激活现有窗口,该窗口写入 `instance_conflict` 并在状态栏提示。锁保持到 SQLite 和后台读线程关闭,进程强制结束时由操作系统回收。启动参数中的工作进程和 CLI 在 GUI 文件锁之前分流。
|
||||
|
||||
## Windows 复测
|
||||
|
||||
```powershell
|
||||
$env:QT_QPA_PLATFORM = 'offscreen'
|
||||
python -m pytest -q tests/v1_1/test_single_instance.py
|
||||
```
|
||||
|
||||
- 四个真实 GUI 子进程并发打开同一目录,其中两个使用大写路径。日志有一次 `application_start`、一次启动恢复和三次 `instance_conflict`,三个转发进程均返回 0。
|
||||
- 另一个数据目录的窗口与持锁窗口同时存活。同根 `--native-helper` 执行自身参数校验并返回 2,冲突计数仍为三次。
|
||||
- 强制结束持锁进程后,同根 `--smoke-test` 成功启动并正常关闭,预先写入的任务 ID 仍在 SQLite。另一数据目录的进程继续运行。
|
||||
- 修改前运行同一并发场景时,三个竞争进程没有退出,测试失败。测试使用 Qt offscreen,验证激活请求已处理。Windows 桌面前台切换和实际 CAD 写入需通过交互式验收复核。
|
||||
@@ -1,21 +0,0 @@
|
||||
# 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 环境设置触发。
|
||||
@@ -9,12 +9,13 @@ import platform
|
||||
import sys
|
||||
from typing import Sequence
|
||||
|
||||
from PySide6.QtCore import QTimer, QThreadPool
|
||||
from PySide6.QtCore import QTimer, QThreadPool, Qt
|
||||
from PySide6.QtGui import QIcon
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.single_instance import InstanceUnavailable, gui_instance, listen_for_activation
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.version import VERSION
|
||||
|
||||
@@ -161,10 +162,28 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
from dx_productivity.trial_task_center.sceneos_cli import run
|
||||
|
||||
return run(data_root)
|
||||
try:
|
||||
with gui_instance(data_root) as endpoint:
|
||||
if endpoint is None:
|
||||
return 0
|
||||
return _run_gui(argv, arguments, data_root, endpoint)
|
||||
except (OSError, InstanceUnavailable) as error:
|
||||
message = f'无法打开 DxPartReplace。\n{data_root}\n{error}'
|
||||
if sys.stderr is not None:
|
||||
print(message, file=sys.stderr)
|
||||
if os.name == 'nt' and bool(getattr(sys, 'frozen', False)):
|
||||
import ctypes
|
||||
|
||||
ctypes.windll.user32.MessageBoxW(None, message, 'DxPartReplace', 0x30)
|
||||
return 1
|
||||
|
||||
|
||||
def _run_gui(argv, arguments, data_root, endpoint):
|
||||
logging_context = configure_logging(data_root)
|
||||
install_exception_hooks(logging_context)
|
||||
store: TaskStore | None = None
|
||||
window = None
|
||||
activation_server = None
|
||||
try:
|
||||
database_path = data_root / "task-center.db"
|
||||
_log_startup(logging_context, data_root, database_path)
|
||||
@@ -177,6 +196,16 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
configure_application_identity(qt_application)
|
||||
window = _load_window()(service)
|
||||
window.show()
|
||||
|
||||
def activate():
|
||||
logging_context.logger.info('instance_conflict data_root=%s', data_root)
|
||||
window.setWindowState(window.windowState() & ~Qt.WindowState.WindowMinimized)
|
||||
window.show()
|
||||
window.raise_()
|
||||
window.activateWindow()
|
||||
window.statusBar().showMessage('此数据目录已在使用,已切换到现有窗口。', 6000)
|
||||
|
||||
activation_server = listen_for_activation(endpoint, activate)
|
||||
if arguments.smoke_test:
|
||||
QTimer.singleShot(0, lambda: (window.close(), qt_application.quit()))
|
||||
exit_code = qt_application.exec()
|
||||
@@ -187,6 +216,8 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
logging_context.report_exception("startup", error)
|
||||
return 1
|
||||
finally:
|
||||
if activation_server is not None:
|
||||
activation_server.close()
|
||||
if store is not None:
|
||||
# The window invalidates queued UI results on close. Finish the
|
||||
# remaining read before releasing the shared SQLite connection.
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Hold a data-root lock while the GUI owns its database and layout."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
import errno
|
||||
import os
|
||||
import time
|
||||
|
||||
from PySide6.QtNetwork import QLocalServer, QLocalSocket
|
||||
|
||||
from .path_access import internal_path
|
||||
from .task_queue import _os_lock
|
||||
|
||||
|
||||
class InstanceUnavailable(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def gui_instance(data_root):
|
||||
root = internal_path(data_root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
# OS locks release on process death. Keep the file so every contender locks the same inode.
|
||||
with (root / '.gui-instance.lock').open('a+b') as handle:
|
||||
identity = os.fstat(handle.fileno())
|
||||
endpoint = f'DxPartReplace-{identity.st_dev:x}-{identity.st_ino:x}'
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
_os_lock(handle, True)
|
||||
break
|
||||
except OSError as error:
|
||||
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
||||
raise
|
||||
if _activate(endpoint):
|
||||
yield None
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise InstanceUnavailable('此数据目录已在使用,现有窗口暂未响应。')
|
||||
time.sleep(.05)
|
||||
yield endpoint
|
||||
|
||||
|
||||
def _activate(endpoint):
|
||||
socket = QLocalSocket()
|
||||
socket.connectToServer(endpoint)
|
||||
if not socket.waitForConnected(100):
|
||||
return False
|
||||
if os.name == 'nt':
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
pid = wintypes.DWORD()
|
||||
get_pipe_pid = ctypes.windll.kernel32.GetNamedPipeServerProcessId
|
||||
get_pipe_pid.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
|
||||
if get_pipe_pid(int(socket.socketDescriptor()), ctypes.byref(pid)):
|
||||
ctypes.windll.user32.AllowSetForegroundWindow(pid.value)
|
||||
socket.write(b'activate\n')
|
||||
socket.flush()
|
||||
return (socket.bytesAvailable() > 0 or socket.waitForReadyRead(1000)) and socket.readAll() == b'1'
|
||||
|
||||
|
||||
def listen_for_activation(endpoint, activate):
|
||||
server = QLocalServer()
|
||||
server.setSocketOptions(QLocalServer.SocketOption.UserAccessOption)
|
||||
if os.name != 'nt':
|
||||
QLocalServer.removeServer(endpoint) # The lock owner can remove a crashed owner's socket.
|
||||
if not server.listen(endpoint):
|
||||
raise RuntimeError(server.errorString())
|
||||
|
||||
def accept():
|
||||
while server.hasPendingConnections():
|
||||
socket = server.nextPendingConnection()
|
||||
|
||||
def respond(socket=socket):
|
||||
if socket.canReadLine() and socket.readLine() == b'activate\n':
|
||||
activate()
|
||||
socket.write(b'1')
|
||||
socket.flush()
|
||||
socket.disconnectFromServer()
|
||||
|
||||
socket.disconnected.connect(socket.deleteLater)
|
||||
socket.readyRead.connect(respond)
|
||||
respond()
|
||||
|
||||
server.newConnection.connect(accept)
|
||||
return server
|
||||
@@ -4,7 +4,7 @@ from threading import Event
|
||||
from ..stop_control import StopControl
|
||||
from shiboken6 import isValid
|
||||
import time
|
||||
from PySide6.QtCore import QByteArray, QElapsedTimer, QRect, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
|
||||
from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
|
||||
from PySide6.QtGui import QAction, QActionGroup
|
||||
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QMessageBox,
|
||||
QPushButton, QLabel, QSizePolicy, QSplitter, QStackedWidget, QTabWidget, QToolButton, QVBoxLayout, QWidget)
|
||||
@@ -184,7 +184,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self.archive_on_close_check.setToolTip('默认关闭。仅归档安全任务,保留计划、日志和文件;待核验或资源未释放的任务保留在当前列表。')
|
||||
self._build_layout()
|
||||
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(
|
||||
'dsh/auto_intervention', True, type=bool))
|
||||
self.auto_intervention_check.toggled.connect(self._set_auto_intervention)
|
||||
@@ -320,34 +319,6 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter,
|
||||
'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):
|
||||
self.workspace_splitter.setSizes((240, 1040))
|
||||
self.detail_splitter.setSizes((650, 110))
|
||||
@@ -445,11 +416,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
QTimer.singleShot(100, self.close)
|
||||
return
|
||||
self._cancel_dsh_diagnosis()
|
||||
self._layout_settings.setValue('main_window/geometry', self.saveGeometry())
|
||||
for name, widget in self._layout_widgets().items():
|
||||
self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
|
||||
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
|
||||
self._layout_settings.sync()
|
||||
self._closed = True
|
||||
self._dsh_status.close()
|
||||
self._dsh_stall_timer.stop()
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
|
||||
|
||||
_SOURCE = Path(__file__).resolve().parents[2] / 'src'
|
||||
_APP = 'dx_productivity.trial_task_center.application'
|
||||
|
||||
|
||||
def _wait_for(predicate, description):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(.05)
|
||||
raise AssertionError(description)
|
||||
|
||||
|
||||
def test_concurrent_gui_launches_activate_one_owner_and_recover_after_kill(tmp_path):
|
||||
root = tmp_path / 'Shared Root'
|
||||
independent = tmp_path / 'Independent Root'
|
||||
root.mkdir()
|
||||
store = TaskStore(root / 'task-center.db')
|
||||
try:
|
||||
task = store.create_task('Existing task')
|
||||
finally:
|
||||
store.close()
|
||||
processes = []
|
||||
env = os.environ | {'PYTHONPATH': str(_SOURCE), 'QT_QPA_PLATFORM': 'offscreen'}
|
||||
|
||||
def launch(path, *arguments):
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, '-m', _APP, '--data-root', str(path), *arguments],
|
||||
env=env,
|
||||
)
|
||||
processes.append(process)
|
||||
return process
|
||||
|
||||
def log(path):
|
||||
logfile = path / 'logs/application.log'
|
||||
return logfile.read_text(encoding='utf-8') if logfile.exists() else ''
|
||||
|
||||
try:
|
||||
alias = root.with_name(root.name.upper()) if os.name == 'nt' else root
|
||||
contenders = [launch(root), launch(alias), launch(root), launch(alias)]
|
||||
_wait_for(lambda: sum(p.poll() is not None for p in contenders) >= 3,
|
||||
'Three concurrent launches should exit after handing off to one GUI')
|
||||
owners = [p for p in contenders if p.poll() is None]
|
||||
assert len(owners) == 1
|
||||
assert [p.returncode for p in contenders if p not in owners] == [0, 0, 0]
|
||||
_wait_for(lambda: log(root).count('instance_conflict') == 3,
|
||||
'The GUI should handle and log all three activation requests')
|
||||
assert log(root).count('application_start ') == 1
|
||||
|
||||
other = launch(independent)
|
||||
_wait_for(lambda: 'application_start ' in log(independent), 'Different root should start independently')
|
||||
assert other.poll() is None and owners[0].poll() is None
|
||||
|
||||
helper = launch(root, '--native-helper')
|
||||
assert helper.wait(timeout=60) == 2 # The helper validates its own required snapshot.
|
||||
assert log(root).count('instance_conflict') == 3
|
||||
|
||||
owners[0].kill()
|
||||
owners[0].wait(timeout=10)
|
||||
assert launch(root, '--smoke-test').wait(timeout=60) == 0
|
||||
assert log(root).count('application_start ') == 2
|
||||
assert log(root).count('application_clean_shutdown') == 1
|
||||
assert other.poll() is None
|
||||
store = TaskStore(root / 'task-center.db')
|
||||
try:
|
||||
assert [record.task_id for record in store.list_tasks()] == [task.task_id]
|
||||
finally:
|
||||
store.close()
|
||||
finally:
|
||||
for process in processes:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
@@ -1,89 +0,0 @@
|
||||
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()
|
||||
Reference in new issue
Block a user