fix: stabilize ICDB preflight and organize UI into tabs
This commit is contained in:
1 parent
29959e2988
commit
223655fe00
10 files changed
+352
-57
No files matched your search
@@ -32,7 +32,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
session. Unknown windows, live database addresses and other desktops are
|
||||
retained. WM_CLOSE is cooperative; no save prompt is accepted or killed.
|
||||
"""
|
||||
import win32con, win32gui, win32process
|
||||
import win32api, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
from .native_repair_ui import _current_desktop_name
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
@@ -86,18 +86,19 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
break
|
||||
time.sleep(.2)
|
||||
continue
|
||||
_, executable, command, _ = records[0]
|
||||
args = _command_args(command)
|
||||
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
if not sent:
|
||||
_, executable, command, _ = records[0]
|
||||
args = _command_args(command)
|
||||
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
||||
and win32gui.IsWindowVisible(hwnd)):
|
||||
windows.append(hwnd)
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
main = [w for w in windows if win32gui.GetClassName(w).startswith('Afx:')
|
||||
and win32gui.GetWindowText(w).strip() in (
|
||||
@@ -112,6 +113,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if window['class'] == 'Internet Explorer_Hidden' and window['title'] == '':
|
||||
window['rect'] = list(win32gui.GetWindowRect(window['hwnd']))
|
||||
window['children'] = []
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(window['hwnd'],
|
||||
lambda hwnd, _: window['children'].append(int(hwnd)), None)
|
||||
left, top, right, bottom = window['rect']
|
||||
@@ -126,6 +128,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
and win32gui.GetWindow(hwnd, win32con.GW_CHILD)):
|
||||
documents.append(hwnd)
|
||||
if len(main) == 1:
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(main[0], child, None)
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if len(main) == 1 and not unknown and not documents and not addresses:
|
||||
@@ -135,6 +138,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
# Observe exit even when the caller requested no extra wait.
|
||||
continue
|
||||
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
|
||||
# After the single owned WM_CLOSE, WMI may lose the executable/
|
||||
# command fields before removing the PID. Only observe exit here;
|
||||
# never issue another close or treat missing fields as release.
|
||||
if time.monotonic() >= deadline:
|
||||
if sent:
|
||||
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
|
||||
|
||||
@@ -9,6 +9,7 @@ import json
|
||||
import os
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import re
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
@@ -43,11 +44,14 @@ def address_snapshot(paths):
|
||||
for path in paths}
|
||||
|
||||
|
||||
def _scoped_addresses(request, *, check=None):
|
||||
def _scoped_addresses(request, *, check=None, entries=None):
|
||||
from .scoped_manifest import scan_tree
|
||||
root = Path(request.lmc_file).parent
|
||||
addresses = []
|
||||
for path in scan_tree(root, check=check):
|
||||
if entries is None:
|
||||
entries = scan_tree(root, check=check)
|
||||
if check is not None: check()
|
||||
for path in entries:
|
||||
if path.name.casefold() != 'saddress.adr':
|
||||
continue
|
||||
parts = tuple(part.casefold() for part in path.relative_to(root).parts)
|
||||
@@ -81,7 +85,7 @@ def maintenance_project_files(project, pcb):
|
||||
return (project,)
|
||||
|
||||
|
||||
def select_maintenance_target(request, *, check=None):
|
||||
def select_maintenance_target(request, *, check=None, entries=None):
|
||||
from .verify_runner import preflight
|
||||
from .backup_recovery import _project_text
|
||||
from .native_repair import RepairTarget
|
||||
@@ -109,7 +113,7 @@ def select_maintenance_target(request, *, check=None):
|
||||
if not (database/'icdb.dat').is_file():
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少 icdb.dat')
|
||||
candidates.append(RepairTarget(candidate, candidate.parent/'database'))
|
||||
addresses = _scoped_addresses(request, check=check)
|
||||
addresses = _scoped_addresses(request, check=check, entries=entries)
|
||||
if not addresses:
|
||||
# A crashed project may retain its internal open state after the server
|
||||
# advertisement disappears. Explicit maintenance must still inspect it.
|
||||
@@ -137,7 +141,11 @@ def maintenance_target_guard(request, expected=None, *, stop=None):
|
||||
if stop is not None and stop.is_set():
|
||||
raise ValueError('MAINTENANCE_CANCELLED: 已取消占用检查')
|
||||
check()
|
||||
target, project, pcb, addresses = select_maintenance_target(request, check=check)
|
||||
library_root = Path(request.lmc_file).parent
|
||||
# Share one complete snapshot for target/address selection and file locks.
|
||||
# Refresh it again while the handles are held; do not reuse across guards.
|
||||
entries = scan_tree(library_root, check=check)
|
||||
target, project, pcb, addresses = select_maintenance_target(request, check=check, entries=entries)
|
||||
baseline = address_snapshot(addresses)
|
||||
context = {'library': str(Path(request.lmc_file).resolve()), 'block': request.block_name,
|
||||
'project': str(target.project.resolve()), 'database': str(target.database.resolve()),
|
||||
@@ -148,17 +156,21 @@ def maintenance_target_guard(request, expected=None, *, stop=None):
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 目标或地址记录在检查后变化')
|
||||
assert_native_idle()
|
||||
check()
|
||||
entries = scan_tree(Path(request.lmc_file).parent, check=check)
|
||||
files = [path for path in entries if (
|
||||
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')) and path.is_file()]
|
||||
def native_files(snapshot):
|
||||
return {path for path, info in snapshot.items() if stat.S_ISREG(info.st_mode) and (
|
||||
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))}
|
||||
files = native_files(entries)
|
||||
with ExitStack() as stack:
|
||||
for path in files:
|
||||
for path in sorted(files):
|
||||
check()
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
assert_native_idle()
|
||||
current_addresses = _scoped_addresses(request, check=check)
|
||||
current = scan_tree(library_root, check=check)
|
||||
if native_files(current) != files:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 检查期间库文件集合发生变化')
|
||||
current_addresses = _scoped_addresses(request, check=check, entries=current)
|
||||
if address_snapshot(current_addresses) != baseline:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 地址记录在检查期间变化')
|
||||
yield {'target': target, 'context': context, 'project': project, 'pcb': pcb}
|
||||
|
||||
@@ -98,7 +98,7 @@ def _repair_command(executable):
|
||||
|
||||
|
||||
def _windows(pid):
|
||||
import win32gui, win32process
|
||||
import win32api, win32gui, win32process
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
|
||||
@@ -109,10 +109,14 @@ def _windows(pid):
|
||||
children.append({'hwnd': handle, 'text': win32gui.GetWindowText(handle),
|
||||
'class': win32gui.GetClassName(handle), 'id': win32gui.GetDlgCtrlID(handle),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(handle))})
|
||||
# Empty window lists are valid. pywin32 otherwise interprets a stale
|
||||
# thread error (observed ERROR_FILE_NOT_FOUND) as an enum failure.
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
windows.append({'hwnd': hwnd, 'title': win32gui.GetWindowText(hwnd),
|
||||
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
|
||||
'children': children})
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
return windows
|
||||
|
||||
@@ -226,12 +230,35 @@ def _inspect_project(job, process, emit):
|
||||
return result
|
||||
|
||||
|
||||
class _CancellationFile:
|
||||
def __init__(self, path):
|
||||
self.path = Path(path)
|
||||
self._next_poll = 0.0
|
||||
self._cancelled = False
|
||||
self.polls = 0
|
||||
self.poll_seconds = 0.0
|
||||
|
||||
def is_set(self):
|
||||
# scan_tree checks between every entry. Avoid issuing tens of
|
||||
# thousands of filesystem requests just to observe one IPC flag.
|
||||
# The direct checks before Popen/Repair remain immediate.
|
||||
now = time.monotonic()
|
||||
if not self._cancelled and now >= self._next_poll:
|
||||
self._cancelled = self.path.exists()
|
||||
finished = time.monotonic()
|
||||
self.polls += 1
|
||||
self.poll_seconds += finished-now
|
||||
self._next_poll = finished + .1
|
||||
return self._cancelled
|
||||
|
||||
|
||||
def repair_worker_main(job_path):
|
||||
import win32con, win32gui
|
||||
from .native_repair import RepairTarget, check_repair_access
|
||||
from .mentor_paths import discover_sdd_home
|
||||
from .icdb_recovery import snapshot_log
|
||||
job = json.loads(Path(job_path).read_text('utf-8'))
|
||||
stop = _CancellationFile(job['cancel_signal'])
|
||||
root = Path(job['root'])
|
||||
project, database = Path(job['project']), Path(job['database'])
|
||||
result = {'status': 'BLOCKED', 'project': str(project), 'database': str(database),
|
||||
@@ -265,17 +292,21 @@ def repair_worker_main(job_path):
|
||||
maintenance_request = VerifyRequest(Path(maintenance_context['library']),
|
||||
maintenance_context['block'], root, maintenance=True)
|
||||
emit(stage='native_preflight', detail='正在核对本次原生工具的目标及占用')
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context) as checked:
|
||||
if (checked['target'].project.resolve() != project.resolve()
|
||||
or checked['target'].database.resolve() != database.resolve()):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
|
||||
check_repair_access(RepairTarget(project, database))
|
||||
emit(stage='backup_skipped', reason='manual_backup_policy',
|
||||
detail='应用不自动备份;Mentor 原生修复仍可能生成自身备份。')
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
if maintenance_context is not None:
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context): pass
|
||||
# Manual backup policy leaves no mutation between preparation and
|
||||
# launch. Run the complete guard once here, retaining its identity,
|
||||
# address and exclusive-access checks immediately before Popen.
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context, stop=stop) as checked:
|
||||
if (checked['target'].project.resolve() != project.resolve()
|
||||
or checked['target'].database.resolve() != database.resolve()):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
|
||||
emit(stage='native_preflight_complete', cancellation_polls=stop.polls,
|
||||
cancellation_poll_seconds=round(stop.poll_seconds, 3))
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
|
||||
@@ -391,6 +422,8 @@ def repair_worker_main(job_path):
|
||||
detail='原生 Repair 未取得完整成功/释放证据,未重试校验')
|
||||
except Exception as error:
|
||||
result.update(detail=str(error), status='RETAINED' if process and process.poll() is None else 'BLOCKED')
|
||||
result['preflight_cancellation'] = {'polls': stop.polls,
|
||||
'seconds': round(stop.poll_seconds, 3)}
|
||||
# Never terminate a repair or its database owner. Retained PID/desktop is
|
||||
# reported to the parent, including unknown native prompts.
|
||||
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
@@ -9,7 +9,8 @@ from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||
from PySide6.QtGui import QColor, QIcon
|
||||
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
|
||||
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QGroupBox, QVBoxLayout, QProgressBar, QComboBox)
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
|
||||
QTabBar, QStackedWidget, QSizePolicy)
|
||||
from PySide6.QtWidgets import QStyle
|
||||
try:
|
||||
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
|
||||
@@ -170,41 +171,54 @@ class MainWindow(QWidget):
|
||||
self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。')
|
||||
self.status_label.setWordWrap(True)
|
||||
self.status_label.setMinimumHeight(self.status_label.fontMetrics().lineSpacing()*2)
|
||||
self.status_label.setMaximumHeight(self.status_label.fontMetrics().lineSpacing()*3 + 4)
|
||||
self.status_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
|
||||
self.output = QTextEdit(); self.output.setReadOnly(True)
|
||||
# Integration emits repeated status snapshots. Keep the visible
|
||||
# diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI
|
||||
# document without limit.
|
||||
self.output.document().setMaximumBlockCount(2000)
|
||||
layout = QFormLayout(self)
|
||||
row = QHBoxLayout(); row.addWidget(self.lmc_edit); row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
||||
layout.addRow('中心库 .lmc', row)
|
||||
self.output.setMaximumHeight(180)
|
||||
layout = QVBoxLayout(self)
|
||||
row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit)
|
||||
row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
||||
layout.addLayout(row)
|
||||
self.library_notice = QLabel()
|
||||
self.library_notice.setWordWrap(True)
|
||||
self.library_notice.setTextFormat(Qt.PlainText)
|
||||
self.library_notice.setStyleSheet('QLabel { color: #8a4b08; background: #fff3d6; padding: 6px; }')
|
||||
self.library_notice.hide()
|
||||
layout.addRow(self.library_notice)
|
||||
layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel)
|
||||
layout.addWidget(self.library_notice)
|
||||
self.section_tabs = QTabBar()
|
||||
self.section_tabs.setExpanding(True)
|
||||
for name in ('检验', 'ICDB 维护', '中心库管理'):
|
||||
self.section_tabs.addTab(name)
|
||||
layout.addWidget(self.section_tabs)
|
||||
filters = QHBoxLayout()
|
||||
for widget in (self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button):
|
||||
filters.addWidget(widget)
|
||||
layout.addRow('搜索 / 筛选', filters)
|
||||
layout.addRow(self.counts_label)
|
||||
layout.addRow('CBB 清单(勾选后可批量)', self.cbb_table); layout.addRow('超时', self.timeout_spin)
|
||||
layout.addRow(QLabel('逐项校验 CBB,完成后刷新状态。'))
|
||||
layout.addLayout(filters)
|
||||
layout.addWidget(self.counts_label)
|
||||
layout.addWidget(self.cbb_table, 1)
|
||||
self.section_stack = QStackedWidget()
|
||||
self.section_stack.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
|
||||
self.section_tabs.currentChanged.connect(self.section_stack.setCurrentIndex)
|
||||
verify_page = QWidget()
|
||||
verify_layout = QVBoxLayout(verify_page); verify_layout.setContentsMargins(0, 0, 0, 0)
|
||||
controls = QHBoxLayout()
|
||||
for widget in (self.selected_batch_button, self.batch_button, self.stop_button, self.logs_button): controls.addWidget(widget)
|
||||
layout.addRow(controls)
|
||||
maintenance = QGroupBox('数据库维护')
|
||||
for widget in (self.selected_batch_button, self.batch_button): controls.addWidget(widget)
|
||||
controls.addStretch(); controls.addWidget(QLabel('超时')); controls.addWidget(self.timeout_spin)
|
||||
controls.addWidget(self.advanced_toggle)
|
||||
verify_layout.addLayout(controls); verify_layout.addWidget(self.advanced_panel)
|
||||
self.section_stack.addWidget(verify_page)
|
||||
maintenance = QWidget()
|
||||
maintenance_layout = QVBoxLayout(maintenance)
|
||||
maintenance_layout.setContentsMargins(0, 0, 0, 0)
|
||||
maintenance_row = QHBoxLayout()
|
||||
maintenance_row.addWidget(self.icdb_repair_button)
|
||||
description = QLabel('处理可见非 READY 项;有勾选时仅处理勾选中的可用项。未确认不等于损坏。\n操作前请手动备份;应用不自动备份。无法确认会话安全时停止。')
|
||||
description.setWordWrap(True)
|
||||
maintenance_row.addWidget(description, 1)
|
||||
maintenance_row.addWidget(self.backup_restore_button)
|
||||
maintenance_row.addWidget(self.reimport_button)
|
||||
maintenance_layout.addLayout(maintenance_row)
|
||||
maintenance_layout.addWidget(self.backup_restore_button)
|
||||
maintenance_layout.addWidget(self.reimport_button)
|
||||
self.icdb_progress = QProgressBar()
|
||||
self.icdb_progress.setVisible(False)
|
||||
self.icdb_phase = QLabel('')
|
||||
@@ -212,12 +226,13 @@ class MainWindow(QWidget):
|
||||
self.icdb_phase.setVisible(False)
|
||||
maintenance_layout.addWidget(self.icdb_progress)
|
||||
maintenance_layout.addWidget(self.icdb_phase)
|
||||
layout.addRow(maintenance)
|
||||
management = QGroupBox('CBB 管理(可处理 READY 项)')
|
||||
self.section_stack.addWidget(maintenance)
|
||||
management = QWidget()
|
||||
management_layout = QVBoxLayout(management)
|
||||
management_layout.setContentsMargins(0, 0, 0, 0)
|
||||
management_buttons = QHBoxLayout()
|
||||
self.add_button = QPushButton('新增 CBB…')
|
||||
self.update_button = QPushButton('用工程替换已选 CBB…(原生重新导入)')
|
||||
self.update_button = QPushButton('用工程替换已选 CBB…')
|
||||
self.remove_button = QPushButton('移除已选…')
|
||||
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
|
||||
widget.clicked.connect(lambda _=False, op=operation: self.manage_cbb(op))
|
||||
@@ -229,17 +244,20 @@ class MainWindow(QWidget):
|
||||
management_layout.insertWidget(0, self.management_capability_label)
|
||||
self.unfinished_label = QLabel(); self.unfinished_label.setWordWrap(True)
|
||||
management_layout.addWidget(self.unfinished_label)
|
||||
self.release_library_button = QPushButton('检查会话释放并解除协调阻止…')
|
||||
self.release_library_button = QPushButton('检查占用…')
|
||||
self.release_library_button.clicked.connect(self.check_library_release)
|
||||
management_layout.addWidget(self.release_library_button)
|
||||
layout.addRow(management)
|
||||
layout.addRow(self.status_label)
|
||||
management_buttons.addWidget(self.release_library_button)
|
||||
self.section_stack.addWidget(management)
|
||||
layout.addWidget(self.section_stack)
|
||||
layout.addWidget(self.status_label)
|
||||
self.runtime_log_toggle = QToolButton(); self.runtime_log_toggle.setText('查看运行日志')
|
||||
self.runtime_log_toggle.setCheckable(True)
|
||||
self.runtime_log_toggle.toggled.connect(self.output.setVisible)
|
||||
self.output.hide()
|
||||
layout.addRow(self.runtime_log_toggle); layout.addRow(self.output)
|
||||
layout.addRow(self.recovery_button)
|
||||
footer = QHBoxLayout()
|
||||
for widget in (self.stop_button, self.runtime_log_toggle, self.logs_button, self.recovery_button):
|
||||
footer.addWidget(widget)
|
||||
layout.addLayout(footer); layout.addWidget(self.output)
|
||||
self.lmc_edit.textChanged.connect(self._invalidate)
|
||||
for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit):
|
||||
field.textChanged.connect(lambda _text: self._update())
|
||||
|
||||
Reference in new issue
Block a user