diff --git a/src/dx_productivity/trial_task_center/isolated_desktop.py b/src/dx_productivity/trial_task_center/isolated_desktop.py index 4a4497e..1221bd6 100644 --- a/src/dx_productivity/trial_task_center/isolated_desktop.py +++ b/src/dx_productivity/trial_task_center/isolated_desktop.py @@ -100,7 +100,7 @@ class PrivateDesktop: self.close() def _create(self) -> None: - if os.name != "nt": + if os.name != "nt" and self._api is None: return self._api = self._api or _Win32Api() self._handle = self._api.create_desktop(self.name) diff --git a/src/dx_productivity/trial_task_center/ui/dialogs.py b/src/dx_productivity/trial_task_center/ui/dialogs.py new file mode 100644 index 0000000..1861568 --- /dev/null +++ b/src/dx_productivity/trial_task_center/ui/dialogs.py @@ -0,0 +1,102 @@ +"""Task metadata and replacement-rule editing dialogs.""" +from PySide6.QtWidgets import QWidget, QDialog, QLineEdit, QTextEdit, QFormLayout, QLabel, QDialogButtonBox, QCheckBox + +class _TaskDialog(QDialog): + def __init__(self, parent: QWidget | None, name: str = "", note: str = "") -> None: + super().__init__(parent) + self.setWindowTitle("任务") + self.name_edit = QLineEdit(name) + self.note_edit = QTextEdit(note) + self.note_edit.setFixedHeight(70) + form = QFormLayout(self) + form.addRow("名称", self.name_edit) + form.addRow("备注", self.note_edit) + self.validation = QLabel(objectName="taskValidation") + self.validation.setStyleSheet("color: #b42318") + self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) + self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定") + self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消") + self.buttons.accepted.connect(self._accept_if_valid) + self.buttons.rejected.connect(self.reject) + form.addRow(self.validation) + form.addRow(self.buttons) + + def values(self) -> tuple[str, str]: + return self.name_edit.text().strip(), self.note_edit.toPlainText().strip() + + def _accept_if_valid(self) -> None: + if not self.name_edit.text().strip(): + self.validation.setText("请输入任务名称。") + return + self.accept() + + +class _MappingDialog(QDialog): + def __init__( + self, + parent: QWidget | None, + old: str = "", + new: str = "", + enabled: bool = True, + custom_value_enabled: bool = False, + custom_value: str = "", + sync_nc: bool = True, + ) -> None: + super().__init__(parent) + self.setWindowTitle("替换规则") + self.old_edit = QLineEdit(old) + self.new_edit = QLineEdit(new) + self.enabled_check = QCheckBox("启用此规则") + self.enabled_check.setChecked(enabled) + self.custom_value_check = QCheckBox("替换后写入自定义 Value") + self.custom_value_check.setChecked(custom_value_enabled) + self.custom_value_edit = QLineEdit(custom_value) + self.custom_value_edit.setPlaceholderText("输入替换后的 Value") + self.custom_value_edit.setEnabled(custom_value_enabled) + self.custom_value_check.toggled.connect(self.custom_value_edit.setEnabled) + self.sync_nc_check = QCheckBox("识别并同步原 Value 中的 /NC") + self.sync_nc_check.setChecked(sync_nc) + form = QFormLayout(self) + form.addRow("旧物料编码", self.old_edit) + form.addRow("新物料编码", self.new_edit) + form.addRow("执行状态", self.enabled_check) + form.addRow("自定义 Value", self.custom_value_check) + form.addRow("Value 内容", self.custom_value_edit) + form.addRow("NC 处理", self.sync_nc_check) + self.validation = QLabel(objectName="mappingValidation") + self.validation.setStyleSheet("color: #b42318") + self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) + self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定") + self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消") + self.buttons.accepted.connect(self._accept_if_valid) + self.buttons.rejected.connect(self.reject) + form.addRow(self.validation) + form.addRow(self.buttons) + + def values(self) -> tuple[str, str, bool, bool, str, bool]: + return ( + self.old_edit.text().strip(), + self.new_edit.text().strip(), + self.enabled_check.isChecked(), + self.custom_value_check.isChecked(), + self.custom_value_edit.text().strip(), + self.sync_nc_check.isChecked(), + ) + + def _accept_if_valid(self) -> None: + old, new, _enabled, custom_enabled, custom_value, _sync_nc = self.values() + if not old or not new: + self.validation.setText("请输入旧料号和新料号。") + return + if old.casefold() == new.casefold(): + self.validation.setText("旧料号和新料号不能相同。") + return + if custom_enabled and not custom_value: + self.validation.setText("勾选自定义 Value 后请输入 Value 内容。") + return + if any(character in custom_value for character in "\t\r\n"): + self.validation.setText("自定义 Value 不能包含制表符或换行。") + return + self.accept() + + diff --git a/src/dx_productivity/trial_task_center/ui/execution_state.py b/src/dx_productivity/trial_task_center/ui/execution_state.py new file mode 100644 index 0000000..e6edbf6 --- /dev/null +++ b/src/dx_productivity/trial_task_center/ui/execution_state.py @@ -0,0 +1,39 @@ +"""Pure execution gates, calculated from one context without service calls.""" +from dataclasses import dataclass +from ..models import TaskStatus + + +@dataclass(frozen=True, slots=True) +class ExecutionState: + editable: bool = False + execute: bool = False + retry: bool = False + recover: bool = False + execute_text: str = '执行当前任务' + message: str = '点击新建,在弹窗中选择工程。' + + +def execution_state(context, *, busy=False, dirty=False): + if context is None: + return ExecutionState() + if context.legacy: + return ExecutionState(message='历史任务仅供查看,请为工程创建独立任务。') + task = context.task + project = context.project + if not project or task.status is TaskStatus.DELETED: + return ExecutionState(message='任务已删除,可从已删除列表恢复。') + editable = task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED} and not context.has_evidence and not busy + retry = context.phase == 'retry' and not context.interrupted and not busy and not dirty + pending = bool(context.progress.next_project_path) and not context.progress.queue_complete + execute = (pending and task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED} + and project.available and not context.interrupted and not busy and not dirty) + text = '继续当前任务' if task.status is TaskStatus.PAUSED else '执行当前任务' + message = ('结果待核验,请先恢复中断步骤。' if context.interrupted else + '位号计划有未保存编辑,请先保存。' if dirty else + '正在处理当前步骤,暂停会等待安全收尾。' if busy else + '任务已完成。' if context.progress.queue_complete and not retry else + '有失败项,可核对原因后重试。' if retry else + '工程不可用,请检查路径。' if not project.available else + '先填写旧、新料号,再采集并勾选位号。' if not pending else + '配置就绪,可执行当前任务或按顺序执行本批任务。') + return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message) diff --git a/src/dx_productivity/trial_task_center/ui/main_window.py b/src/dx_productivity/trial_task_center/ui/main_window.py index 933c0b3..2e62963 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -1,1830 +1,526 @@ -"""PySide6 task-center presentation layer. - -The window deliberately contains no persistence or DxDesigner knowledge. All -state changes go through :class:`TaskCenterService`; potentially slow calls -are dispatched with the small worker abstraction used by the other widgets. -""" - +"""Single-project task presentation; persistence and CAD remain in the service.""" from __future__ import annotations - -from collections.abc import Callable -from datetime import datetime -import json -import os from pathlib import Path -from typing import Any - -from PySide6.QtCore import QByteArray, QElapsedTimer, QSettings, QThreadPool, QTimer, Qt -from PySide6.QtWidgets import ( - QApplication, - QAbstractButton, - QCheckBox, - QDialog, - QDialogButtonBox, - QFileDialog, - QFormLayout, - QHBoxLayout, - QLabel, - QLineEdit, - QComboBox, - QMainWindow, - QTabWidget, - QMessageBox, - QPushButton, - QSplitter, - QTextEdit, - QVBoxLayout, - QWidget, -) -from shiboken6 import isValid - from threading import Event - +from typing import Callable +from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt +from PySide6.QtWidgets import (QApplication, QDialog, QHBoxLayout, QMainWindow, QMessageBox, + QPushButton, QSplitter, QTabWidget, QVBoxLayout, QWidget) from ..errors import TaskCenterError -from ..models import ProjectStatus, TaskStatus -from ..service import TaskCenterService +from ..models import TaskStatus from ..version import VERSION +from .dialogs import _TaskDialog, _MappingDialog +from .execution_state import execution_state from .mapping_table import MappingTable -from .project_table import ProjectTable +from .messages import ERROR_TEXT, DIALOG_ERROR_TEXT, _format_live_log_line, _format_task_log_lines, _nc_sync_log_lines from .project_plan import DirectoryTaskDialog, ProjectPlanPanel +from .project_summary import ProjectSummary from .run_panel import RunPanel from .styles import APP_STYLESHEET from .task_list import TaskList from .workers import ServiceWorker - -ERROR_TEXT = { - "task_required": "请先选择任务。", - "directory_required": "请先选择工程目录。", - "discovery_root_locked": "旧目录已有执行记录,不能在同一任务中更换目录;请新建任务。", - "disposable_copy_required": "请确认所选工程已保存,并允许程序在执行前创建完整备份。", - "selected_project_required": "请至少选择一个可用工程。", - "enabled_rule_required": "请至少添加并启用一条替换规则。", - "active_project_exists": "已有其他工程正在处理,请等待其结束。", - "probe_baseline_missing": "未找到探测结果文件,请先在 DxDesigner 中运行只读探测。", - "profile_unchanged": "探测结果没有更新,请重新运行只读探测。", - "comparison_failed": "替换前后数据核验失败,请查看日志和错误编号。", - "rules_locked": "任务执行期间不能修改替换规则。", - "task_running": "请先暂停任务,再删除任务。", - "task_not_deleted": "只有“已删除”中的任务可以彻底删除;任务状态可能已变化,请刷新后重试。", - "permanent_delete_confirmation": "彻底删除需要明确确认,此操作不能通过“恢复”撤销。", - "quick_run_pending": "检测到可能已改动图纸的旧替换任务,请先核对工程后再继续。", - "quick_run_status": "执行状态文件无效,已拒绝覆盖,请查看日志。", - "quick_run_execution": "当前替换步骤失败,图页可能已被修改,请查看具体原因和执行证据。", - "quick_run_rollback_verified": "替换校验失败,但原生回滚已验证,工程已恢复到替换前状态;请排除原因后重新确认。", - "quick_run_preflight": "当前项在替换前校验失败,未调用原生替换;后续项已停止。请核对目标料号及库配置,排除原因后再确认继续。", - "quick_run_session": "本次执行在启动或工程检查阶段停止,尚未开始本项替换。请按具体原因处理后重试。", - "quick_run_complete": "当前任务中的替换规则已经全部完成。", - "quick_run_cscript": "未找到 Windows 脚本运行组件,无法连接 DxDesigner。", - "quick_run_command": "替换命令文件无效,请查看日志。", - "quick_run_uncertain": "无法确认本次替换结果,请使用“核验并恢复中断任务”,不要直接清锁重跑。", - "quick_run_recovery": "中断任务恢复未通过,原保护状态仍保留。", - "quick_run_recovery_confirmation": "请先确认核验恢复范围。", - "quick_run_busy": "已有替换操作正在执行,请等待当前操作结束。", - "quick_run_manual_operation": "此任务使用自动队列,不能混用人工流程的跳过、采集和重试操作。", - "quick_run_task_state": "当前任务状态不允许执行自动队列,请先恢复任务或检查其状态。", - "quick_run_backup": "本项工程精简备份未通过,队列已停止,尚未开始本项替换。可排除原因后重试,或使用“忽略备份失败并继续”。", - "quick_run_queue_progress": "队列进度异常,已停止自动继续。", - "quick_run_options_locked": "已有自动队列证据,工程目录、工程选择及规则选项已冻结;请先完成或恢复当前队列。", - "quick_run_selection_changed": "待执行工程、规则或 Value 选项发生变化,请重新确认。", - "evidence_missing": "没有找到当前任务的执行证据。", - "duplicate_source": "同一旧料号只能配置一次。", - "mapping_chain": "替换规则不能形成连续替换链。", - "mapping_cycle": "替换规则不能形成循环。", - "equal_rule": "旧料号和新料号不能相同。", - "blank_part_number": "旧料号和新料号不能为空。", - "custom_value": "勾选自定义 Value 后必须填写内容,且不能包含制表符或换行。", - "task_name": "任务名称为空或已经存在。", -} - -DIALOG_ERROR_TEXT = { - "duplicate_source": "该旧料号已经存在,请修改现有规则或输入其他旧料号。", - "mapping_chain": "目标料号同时是另一条规则的旧料号,请拆分任务后再执行。", - "mapping_cycle": "这些规则形成了循环,请修改旧料号或新料号。", - "equal_rule": "旧料号和新料号不能相同。", - "blank_part_number": "请输入旧料号和新料号。", - "custom_value": "勾选自定义 Value 后必须填写内容,且不能包含制表符或换行。", - "task_name": "任务名称为空或已经存在,请使用其他名称。", -} - - -class _TaskDialog(QDialog): - def __init__(self, parent: QWidget | None, name: str = "", note: str = "") -> None: - super().__init__(parent) - self.setWindowTitle("任务") - self.name_edit = QLineEdit(name) - self.note_edit = QTextEdit(note) - self.note_edit.setFixedHeight(70) - form = QFormLayout(self) - form.addRow("名称", self.name_edit) - form.addRow("备注", self.note_edit) - self.validation = QLabel(objectName="taskValidation") - self.validation.setStyleSheet("color: #b42318") - self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) - self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定") - self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消") - self.buttons.accepted.connect(self._accept_if_valid) - self.buttons.rejected.connect(self.reject) - form.addRow(self.validation) - form.addRow(self.buttons) - - def values(self) -> tuple[str, str]: - return self.name_edit.text().strip(), self.note_edit.toPlainText().strip() - - def _accept_if_valid(self) -> None: - if not self.name_edit.text().strip(): - self.validation.setText("请输入任务名称。") - return - self.accept() - - -class _MappingDialog(QDialog): - def __init__( - self, - parent: QWidget | None, - old: str = "", - new: str = "", - enabled: bool = True, - custom_value_enabled: bool = False, - custom_value: str = "", - sync_nc: bool = True, - ) -> None: - super().__init__(parent) - self.setWindowTitle("替换规则") - self.old_edit = QLineEdit(old) - self.new_edit = QLineEdit(new) - self.enabled_check = QCheckBox("启用此规则") - self.enabled_check.setChecked(enabled) - self.custom_value_check = QCheckBox("替换后写入自定义 Value") - self.custom_value_check.setChecked(custom_value_enabled) - self.custom_value_edit = QLineEdit(custom_value) - self.custom_value_edit.setPlaceholderText("输入替换后的 Value") - self.custom_value_edit.setEnabled(custom_value_enabled) - self.custom_value_check.toggled.connect(self.custom_value_edit.setEnabled) - self.sync_nc_check = QCheckBox("识别并同步原 Value 中的 /NC") - self.sync_nc_check.setChecked(sync_nc) - form = QFormLayout(self) - form.addRow("旧物料编码", self.old_edit) - form.addRow("新物料编码", self.new_edit) - form.addRow("执行状态", self.enabled_check) - form.addRow("自定义 Value", self.custom_value_check) - form.addRow("Value 内容", self.custom_value_edit) - form.addRow("NC 处理", self.sync_nc_check) - self.validation = QLabel(objectName="mappingValidation") - self.validation.setStyleSheet("color: #b42318") - self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) - self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定") - self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消") - self.buttons.accepted.connect(self._accept_if_valid) - self.buttons.rejected.connect(self.reject) - form.addRow(self.validation) - form.addRow(self.buttons) - - def values(self) -> tuple[str, str, bool, bool, str, bool]: - return ( - self.old_edit.text().strip(), - self.new_edit.text().strip(), - self.enabled_check.isChecked(), - self.custom_value_check.isChecked(), - self.custom_value_edit.text().strip(), - self.sync_nc_check.isChecked(), - ) - - def _accept_if_valid(self) -> None: - old, new, _enabled, custom_enabled, custom_value, _sync_nc = self.values() - if not old or not new: - self.validation.setText("请输入旧料号和新料号。") - return - if old.casefold() == new.casefold(): - self.validation.setText("旧料号和新料号不能相同。") - return - if custom_enabled and not custom_value: - self.validation.setText("勾选自定义 Value 后请输入 Value 内容。") - return - if any(character in custom_value for character in "\t\r\n"): - self.validation.setText("自定义 Value 不能包含制表符或换行。") - return - self.accept() - - class TrialTaskCenterWindow(QMainWindow): - """Main task-center shell used by the desktop application and UI tests.""" - - def __init__( - self, - service: TaskCenterService, - directory_picker: Callable[[], str | Path | None] | None = None, - quick_run_confirmer: Callable[[str, int, int], bool] | None = None, - ) -> None: + def __init__(self, service, directory_picker=None, quick_run_confirmer=None): super().__init__() self.service = service - self.directory_picker = directory_picker or self._pick_directory self._quick_run_confirmer = quick_run_confirmer or self._confirm_quick_run - self._quick_run_phase = "selection" - self._confirmation_progress = None - self._confirmation_value_mode: str | None = None - self._task_id: str | None = None - self._discovery_root: Path | None = None - self._snapshot: Any | None = None - self._workers: set[ServiceWorker] = set() - self._ui_destroyed = False + self._task_id = None + self._context = None + self._tasks = () + self._workers = set() + self._closed = False + self._batch_stop = None + self._active_quick_run_task_id = None + self._project_queues = {} self._generation = 0 - self._button_generations: dict[QAbstractButton, int] = {} - self._domain_generations: dict[object, int] = {} - self._selection_generation: int | None = None - self._active_quick_run_task_id: str | None = None - self._batch_stop: Event | None = None - self._batch_rendered = None - self._live_log_text: str | None = None + self._message = '' + self._live_log_text = None self._quick_run_elapsed = QElapsedTimer() self._quick_run_timer = QTimer(self) self._quick_run_timer.setInterval(1000) self._quick_run_timer.timeout.connect(self._update_quick_run_elapsed) - self._last_error_task_id: str | None = None - self._last_error_project_id: str | None = None - self._backup_override_task_id: str | None = None - self.destroyed.connect(lambda: setattr(self, "_ui_destroyed", True)) - self._pool = QThreadPool.globalInstance() - self._project_queue_id = None - self._project_queue_ids = () - self.setWindowTitle(f"DxDesigner 器件批量替换任务中心 · {VERSION}") - self.setMinimumSize(900, 600) - self.resize(1080, 760) + self.setWindowTitle(f'DxDesigner 器件替换 · {VERSION}') + self.setMinimumSize(980, 700) + self.resize(1280, 880) self.setStyleSheet(APP_STYLESHEET) - self.task_list = TaskList(self.open_task) self.task_list.filter.currentTextChanged.connect(self._refresh_task_list) self.task_list.new_button.clicked.connect(self._new_task) self.task_list.edit_button.clicked.connect(self._edit_task) self.task_list.delete_button.clicked.connect(self._delete_task) self.task_list.restore_button.clicked.connect(self._restore_task) - self.task_list.queue_button.clicked.connect(self._execute_project_tasks) self.task_list.up_button.clicked.connect(lambda: self._move_project_task(-1)) self.task_list.down_button.clicked.connect(lambda: self._move_project_task(1)) - - self.directory_path = QLineEdit(objectName="directoryPath") - self.directory_path.setPlaceholderText("请选择 DxDesigner 工程所在目录") - self.browse_directory_button = QPushButton("选择目录", objectName="browseDirectoryButton") - self.scan_projects_button = QPushButton("扫描工程", objectName="scanProjectsButton") - self.browse_directory_button.clicked.connect(self._browse_directory) - self.scan_projects_button.clicked.connect(self._scan_projects) - self.directory_path.textChanged.connect(self._directory_changed) - - self.project_table = ProjectTable(self._project_selection_changed) - self.project_table.setMinimumHeight(40) - self.project_table.itemSelectionChanged.connect(self._project_row_changed) - self.project_filter = QComboBox(objectName="projectFilter") - self.project_filter.addItems(("全部", "待处理", "已完成")) - self.project_filter.currentTextChanged.connect(self._populate_projects) - self.select_all_projects_button = QPushButton("全选", objectName="selectAllProjectsButton") - self.clear_projects_button = QPushButton("清除选择", objectName="clearProjectsButton") - self.select_all_projects_button.clicked.connect(self._select_all_projects) - self.clear_projects_button.clicked.connect(self._clear_projects) - + self.task_list.queue_button.clicked.connect(self._execute_project_tasks) + self.project_summary = ProjectSummary() + self.project_summary.refresh_button.clicked.connect(self._refresh_bound_project) self.mapping_table = MappingTable(self._rule_enabled_changed) - self.mapping_table.setMinimumHeight(40) self.mapping_table.itemSelectionChanged.connect(self._update_gates) - self.add_mapping_button = QPushButton("添加", objectName="addMappingButton") - self.edit_mapping_button = QPushButton("编辑", objectName="editMappingButton") - self.delete_mapping_button = QPushButton("删除", objectName="deleteMappingButton") - self.move_mapping_up_button = QPushButton("上移", objectName="moveMappingUpButton") - self.move_mapping_down_button = QPushButton("下移", objectName="moveMappingDownButton") + self.add_mapping_button = QPushButton('添加料号规则', objectName='addMappingButton') + self.edit_mapping_button = QPushButton('编辑规则', objectName='editMappingButton') + self.delete_mapping_button = QPushButton('删除规则', objectName='deleteMappingButton') + self.move_mapping_up_button = QPushButton('上移规则') + self.move_mapping_down_button = QPushButton('下移规则') self.add_mapping_button.clicked.connect(self._add_mapping_dialog) self.edit_mapping_button.clicked.connect(self._edit_mapping) self.delete_mapping_button.clicked.connect(self._delete_mapping) self.move_mapping_up_button.clicked.connect(lambda: self._move_mapping(-1)) self.move_mapping_down_button.clicked.connect(lambda: self._move_mapping(1)) - + self.plan_panel = ProjectPlanPanel(self) self.run_panel = RunPanel() - self.run_panel.copy_value_check.toggled.connect(self._value_option_changed) - self.run_panel.reset_layout_button.clicked.connect(self._reset_layout) self.run_panel.quick_run_button.clicked.connect(self._prepare_quick_run) self.run_panel.stop_queue_button.clicked.connect(self._pause_queue) - self.run_panel.continue_without_backup_button.clicked.connect(self._continue_without_backup) + self.run_panel.retry_button.clicked.connect(self._retry_failed) self.run_panel.recover_button.clicked.connect(self._recover_quick_run) - self.run_panel.start_button.clicked.connect(self._start_task) - self.run_panel.pause_button.clicked.connect(lambda: self._run_action(self.service.pause_task, self.run_panel.pause_button)) - self.run_panel.resume_button.clicked.connect(lambda: self._run_action(self.service.resume_task, self.run_panel.resume_button)) - self.run_panel.capture_before_button.clicked.connect(self._capture_before) - self.run_panel.confirm_attempt_button.clicked.connect(self._confirm_attempt) - self.run_panel.capture_after_button.clicked.connect(self._capture_after) - - self.retry_button = QPushButton("重试工程", objectName="retryProjectButton") - self.skip_button = QPushButton("跳过工程", objectName="skipProjectButton") - self.retry_button.clicked.connect(lambda: self._run_project_action(self.service.retry_project, self.retry_button)) - self.skip_button.clicked.connect(lambda: self._run_project_action(self.service.skip_project, self.skip_button)) - self.plan_panel = ProjectPlanPanel(self) + self.run_panel.copy_value_check.toggled.connect(self._value_option_changed) + self.run_panel.reset_layout_button.clicked.connect(self._reset_layout) + self.run_panel.toggle_log_button.toggled.connect(lambda on: self._refresh_live_task_log() if on else None) self._build_layout() - self._layout_settings = QSettings(str(self.service.layout_settings_path), QSettings.Format.IniFormat) - self._restore_layout() + self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat) + for name, widget in self._layout_widgets().items(): + saved = self._layout_settings.value(f'single_project/{name}') + if saved is not None: + widget.restoreState(saved) self._refresh_task_list() self._update_gates() - def _build_layout(self) -> None: - workspace = QWidget(objectName="workspace") - root = QHBoxLayout(workspace) - root.setContentsMargins(8, 8, 8, 8) - root.setSpacing(8) - - directory_row = QHBoxLayout() - directory_row.addWidget(QLabel("工程目录")) - directory_row.addWidget(self.directory_path, 1) - directory_row.addWidget(self.browse_directory_button) - directory_row.addWidget(self.scan_projects_button) - - project_commands = QHBoxLayout() - project_commands.addWidget(self.select_all_projects_button) - project_commands.addWidget(self.clear_projects_button) - project_commands.addStretch(1) - project_commands.addWidget(self.retry_button) - project_commands.addWidget(self.skip_button) - - mapping_commands = QHBoxLayout() - for button in ( - self.add_mapping_button, - self.edit_mapping_button, - self.delete_mapping_button, - self.move_mapping_up_button, - self.move_mapping_down_button, - ): - mapping_commands.addWidget(button) - mapping_commands.addStretch(1) - - project_section = QWidget(objectName="projectSection") - project_layout = QVBoxLayout(project_section) - project_layout.setContentsMargins(0, 0, 0, 0) - project_layout.addLayout(directory_row) - project_heading = QHBoxLayout() - project_heading.addWidget(QLabel("工程列表")) - project_heading.addStretch(1) - project_heading.addWidget(self.project_filter) - project_layout.addLayout(project_heading) - project_layout.addWidget(self.project_table, 1) - project_layout.addLayout(project_commands) - - mapping_section = QTabWidget(objectName="mappingSection") + def _build_layout(self): rule_page = QWidget() - mapping_layout = QVBoxLayout(rule_page) - mapping_layout.setContentsMargins(0, 0, 0, 0) - mapping_layout.addWidget(QLabel("替换规则")) - mapping_layout.addWidget(self.mapping_table, 1) - mapping_layout.addLayout(mapping_commands) - mapping_section.addTab(rule_page, "料号规则") - mapping_section.addTab(self.plan_panel, "位号计划") - self.mapping_tabs = mapping_section - - self.detail_splitter = QSplitter(Qt.Orientation.Vertical, objectName="detailSplitter") + rules_layout = QVBoxLayout(rule_page) + rules_layout.setContentsMargins(0, 0, 0, 0) + rules_layout.addWidget(self.mapping_table, 1) + commands = QHBoxLayout() + for button in (self.add_mapping_button, self.edit_mapping_button, self.delete_mapping_button, + self.move_mapping_up_button, self.move_mapping_down_button): + commands.addWidget(button) + commands.addStretch() + rules_layout.addLayout(commands) + self.mapping_tabs = QTabWidget() + self.mapping_tabs.addTab(rule_page, '料号规则') + self.mapping_tabs.addTab(self.plan_panel, '位号计划') + self.detail_splitter = QSplitter(Qt.Orientation.Vertical) self.detail_splitter.setChildrenCollapsible(False) - self.detail_splitter.setHandleWidth(10) - self.detail_splitter.setToolTip("拖动分隔条调整工程、规则与操作区高度;日志可单独收起。") - self.detail_splitter.addWidget(project_section) - self.detail_splitter.addWidget(mapping_section) + self.detail_splitter.addWidget(self.mapping_tabs) self.detail_splitter.addWidget(self.run_panel) - self.detail_splitter.setStretchFactor(0, 1) - self.detail_splitter.setStretchFactor(1, 3) - self.detail_splitter.setStretchFactor(2, 2) - self.detail_splitter.setSizes((170, 340, 220)) - - self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal, objectName="workspaceSplitter") + self.detail_splitter.setStretchFactor(0, 4) + self.detail_splitter.setStretchFactor(1, 1) + details = QWidget() + details_layout = QVBoxLayout(details) + details_layout.setContentsMargins(0, 0, 0, 0) + details_layout.addWidget(self.project_summary) + details_layout.addWidget(self.detail_splitter, 1) + self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal) self.workspace_splitter.setChildrenCollapsible(False) - self.workspace_splitter.setHandleWidth(10) - self.workspace_splitter.setToolTip("拖动分隔条调整任务列表与工作区宽度。") self.workspace_splitter.addWidget(self.task_list) - self.workspace_splitter.addWidget(self.detail_splitter) - self.workspace_splitter.setStretchFactor(0, 0) + self.workspace_splitter.addWidget(details) self.workspace_splitter.setStretchFactor(1, 1) - self.workspace_splitter.setSizes((250, 830)) - root.addWidget(self.workspace_splitter) - self.setCentralWidget(workspace) + container = QWidget() + layout = QHBoxLayout(container) + layout.setContentsMargins(8, 8, 8, 8) + layout.addWidget(self.workspace_splitter) + self.setCentralWidget(container) + self._reset_layout() def _layout_widgets(self): - return { - "workspace": self.workspace_splitter, - "detail": self.detail_splitter, - "projects": self.project_table.horizontalHeader(), - "rules": self.mapping_table.horizontalHeader(), - } + return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter, + 'rules': self.mapping_table.horizontalHeader(), 'targets': self.plan_panel.table.horizontalHeader()} - def _restore_layout(self) -> None: - self.run_panel.toggle_log_button.setChecked(self._layout_settings.value("layout/log_visible", False, type=bool)) - for name, widget in self._layout_widgets().items(): - state = self._layout_settings.value(f"layout/{name}") - if isinstance(state, QByteArray): - widget.restoreState(state) - - def _save_layout(self) -> None: - for name, widget in self._layout_widgets().items(): - self._layout_settings.setValue(f"layout/{name}", widget.saveState()) - self._layout_settings.setValue("layout/log_visible", self.run_panel.toggle_log_button.isChecked()) - self._layout_settings.sync() - if self._layout_settings.status() is not QSettings.Status.NoError: - self._append_log("布局设置未能保存;不影响工程替换,请检查数据目录权限。") - - def _reset_layout(self) -> None: + def _reset_layout(self): + self.workspace_splitter.setSizes((240, 1040)) + self.detail_splitter.setSizes((500, 190)) self.run_panel.toggle_log_button.setChecked(False) - self.workspace_splitter.setSizes((250, 830)) - self.detail_splitter.setSizes((170, 340, 220)) - for section, width in enumerate((58, 150, 360, 90, 210)): - self.project_table.horizontalHeader().resizeSection(section, width) - for section, width in enumerate((220, 220, 180, 80, 70, 65)): - self.mapping_table.horizontalHeader().resizeSection(section, width) - self._save_layout() - def closeEvent(self, event) -> None: - queue_active = any( - button in self._button_generations - for button in ( - self.run_panel.quick_run_button, - self.run_panel.continue_without_backup_button, - self.run_panel.recover_button, - ) - ) - if self._workers or queue_active: - if queue_active: - self._pause_queue() - message = "当前替换步骤正在安全收尾,请等它结束后再关闭;不会强行中断 CAD 写入。" - else: - message = "后台操作尚未结束,请等操作完成后再关闭,避免任务数据库提前断开。" - self._set_operator_message(message, "warning") + def closeEvent(self, event): + if self._workers: + self._pause_queue() + self._set_operator_message('操作尚未结束,请等当前步骤安全收尾后关闭。', 'warning') event.ignore() return - self._save_layout() + for name, widget in self._layout_widgets().items(): + self._layout_settings.setValue(f'single_project/{name}', widget.saveState()) + self._closed = True + self._quick_run_timer.stop() super().closeEvent(event) - @staticmethod - def _pick_directory() -> str: - return QFileDialog.getExistingDirectory(None, "选择工程目录") - - def _refresh_task_list(self) -> None: + def _refresh_task_list(self): try: - selected = self.task_list.filter.currentText() - if selected == "已完成": - tasks = self.service.tasks(TaskStatus.COMPLETED) - elif selected == "已删除": - tasks = self.service.tasks(TaskStatus.DELETED) - else: - tasks = tuple(task for task in self.service.tasks() if task.status is not TaskStatus.COMPLETED) + self._tasks = self.service.tasks() + choice = self.task_list.filter.currentText() + wanted = {'已完成': TaskStatus.COMPLETED, '已删除': TaskStatus.DELETED}.get(choice) + tasks = tuple(t for t in self._tasks if t.status is wanted) if wanted else tuple( + t for t in self._tasks if t.status not in {TaskStatus.COMPLETED, TaskStatus.DELETED}) self.task_list.populate(tasks) - if self._task_id and any(task.task_id == self._task_id for task in tasks): - self._select_task_item(self._task_id) - elif tasks: - self.task_list.list.setCurrentRow(0) - else: - self._task_id = None - self._load_task_data() except Exception as error: self._show_error(error) - def _select_task_item(self, task_id: str) -> None: - for index in range(self.task_list.list.count()): - item = self.task_list.list.item(index) - if str(item.data(Qt.ItemDataRole.UserRole)) == task_id: - self.task_list.list.setCurrentItem(item) - return - - def open_task(self, task_id: str) -> None: - if not task_id: + def open_task(self, task_id): + if not task_id or self._workers: return - try: - if self._backup_override_task_id != task_id: - self._backup_override_task_id = None - self._task_id = task_id - task = self.service.get_task(task_id) - self._discovery_root = task.discovery_root - self.directory_path.setText(str(task.discovery_root) if task.discovery_root else "") - self._load_task_data() - except Exception as error: - self._show_error(error) + self._task_id = task_id + self._message = '' + self._load_task_data() - def _load_task_data(self) -> None: - task = self.service.get_task(self._task_id) if self._task_id else None - self.plan_panel.bind_task(self._task_id) - self._discovery_root = task.discovery_root if task else None - checkbox = self.run_panel.copy_value_check - checkbox.blockSignals(True) - checkbox.setChecked(bool(task and task.copy_part_number_to_value)) - checkbox.blockSignals(False) - if not self._task_id: - self._backup_override_task_id = None - self.project_table.populate(()) - self.mapping_table.populate(()) - self._snapshot = None - self.run_panel.queue_summary.setText("未选择任务") - self.run_panel.execution_status.setText("空闲") + def _load_task_data(self): + try: + self._context = self.service.task_context(self._task_id) if self._task_id else None + context = self._context + self.project_summary.populate(context) + self.plan_panel.bind_task(self._task_id, context.targets if context else ()) + self.mapping_table.populate(context.rules if context else ()) + with QSignalBlocker(self.run_panel.copy_value_check): + self.run_panel.copy_value_check.setChecked(bool(context and context.task.copy_part_number_to_value)) + if context: + progress = context.progress + targets = sum(row.enabled for row in context.targets) + self.run_panel.queue_summary.setText( + f'位号计划 {targets}/{len(context.targets)} · 步骤 {progress.completed_items}/{progress.total_items}' + f' · 已保存 {progress.saved_items} · 失败 {progress.failed_items} · 未命中 {progress.no_match_items}') + else: + self.run_panel.queue_summary.setText('未选择任务') + self._refresh_live_task_log() self._update_gates() - return - try: - self._sync_quick_run_phase() - self._projects = self.service.projects(self._task_id) - self._populate_projects() - self.mapping_table.populate(self.service.rules(self._task_id)) - self._snapshot = self.service.snapshot(self._task_id) - self._apply_snapshot(self._snapshot) - self._update_queue_summary() - if self._quick_run_phase in {"complete", "retry"}: - progress = self.service.quick_run_progress(self._task_id) - failed = getattr(progress, "failed_items", 0) - replaced = progress.completed_items - progress.no_match_items - failed - save_status = ( - "成功项已保存" - if progress.saved_items == replaced - else "请核对成功项的保存状态" - ) - self._set_operator_message( - f"队列处理结束:成功 {progress.saved_items},失败 {failed},未命中 {progress.no_match_items}。" - + ("可修改选项后重试失败项。" if failed else f"{save_status}。"), - "warning" if failed else "success", - ) except Exception as error: + self._context = None self._show_error(error) - self._update_gates() - def _sync_quick_run_phase(self) -> None: - if not self._task_id: - self._quick_run_phase = "selection" - return - self._quick_run_phase = self.service.quick_run_phase(self._task_id) - if self._quick_run_phase == "complete": - self.run_panel.quick_run_button.setText("当前队列已完成") - elif self._quick_run_phase == "retry": - self.run_panel.quick_run_button.setText("重试失败项") - else: - self.run_panel.quick_run_button.setText("继续队列" if self._current_task_status() is TaskStatus.PAUSED else "连续执行队列") - - def _update_queue_summary(self) -> None: - if not self._task_id: - self.run_panel.queue_summary.setText("未选择任务") - return - projects = self.service.projects(self._task_id) - rules = self._execution_rules(self._task_id) - selected = sum(1 for project in projects if project.selected and project.available) - enabled = sum(1 for rule in rules if rule.enabled) - progress = self.service.quick_run_progress(self._task_id) - no_match = getattr(progress, "no_match_items", 0) - failed = getattr(progress, "failed_items", 0) - queue_scope = "全工程图页队列" if progress.page_addressed else "待枚举队列" - self.run_panel.queue_summary.setText( - f"已选工程 {selected} | 启用规则 {enabled} | {queue_scope} {progress.completed_items}/{progress.total_items}" - f" | 失败 {failed} | 未命中 {no_match}" - ) - if self._active_quick_run_task_id is None: - if progress.queue_complete: - unsaved = progress.completed_items - no_match - failed - progress.saved_items - self.run_panel.execution_status.setText( - f"队列已完成,失败 {failed} 项" - if failed else f"队列已完成,{unsaved} 项尚未确认保存" - if unsaved else "队列已完成" - ) - elif progress.next_project_path is not None: - self.run_panel.execution_status.setText( - f"下一项:{progress.next_project_path.name}" - f"{f' | {progress.next_schematic_name}:{progress.next_sheet_number}' if progress.next_schematic_name else ''}" - f" | {progress.next_old_part_number} -> {progress.next_new_part_number}" - ) - else: - self.run_panel.execution_status.setText("配置工程和替换规则后可执行") - - def _populate_projects(self) -> None: - projects = getattr(self, "_projects", ()) - selected = self.project_filter.currentText() - if selected == "已完成": - projects = tuple(project for project in projects if project.status is ProjectStatus.COMPLETED) - elif selected == "待处理": - projects = tuple(project for project in projects if project.status is not ProjectStatus.COMPLETED) - self.project_table.populate(projects) - - def _apply_snapshot(self, snapshot: Any) -> None: - instruction = snapshot.instruction - if instruction is None: - if self._task_id is None: - message = "请选择任务,并扫描工程目录。" - elif not any(project.selected and project.available for project in self.service.projects(self._task_id)): - message = "请扫描并勾选至少一个工程。" - elif not any(rule.enabled for rule in self._execution_rules(self._task_id)): - message = "请添加并启用替换规则。" - else: - message = "配置就绪:确认后处理全部原理图页;未命中和普通失败记录后继续,状态不确定时停止。请先保存修改并关闭已有工程。" - if snapshot.task.status is TaskStatus.COMPLETED: - message = "自动队列已处理完成,未命中项已跳过;实际图页范围、替换数量和保存状态见进度及工程结果栏。" - elif snapshot.task.status is TaskStatus.PAUSED and self.service.has_quick_run_evidence(snapshot.task.task_id): - message = "自动队列已暂停。确认后从下一项继续;有待核验保护时请先恢复。任务可以移至已删除并在之后恢复,不会删除工程文件。" - self.run_panel.operator_band.setText(message) - else: - details = "; ".join( - f"{rule.old_part_number} -> {rule.new_part_number}(匹配 {rule.match_count} 个器件)" - for rule in instruction.rules - ) or "启用的替换规则未匹配到器件。" - self.run_panel.operator_band.setText(f"当前工程:{instruction.project_path};{details}") - self._set_task_log(self.service.tail_log(snapshot.task.task_id)) - - def _update_gates(self) -> None: - projects = () - rules = () - if not self._task_id: - enabled = False - else: - try: - projects = self.service.projects(self._task_id) - rules = self._execution_rules(self._task_id) - enabled = ( - self._directory_matches_saved_root() - and any(project.selected and project.available for project in projects) - and any(rule.enabled for rule in rules) - ) - except Exception: - enabled = False - has_task = self._task_id is not None - task_status = self._current_task_status() - active = getattr(self._snapshot, "active_project", None) - active_status = getattr(active, "status", None) - enabled = enabled and not self.plan_panel.table.dirty - self.run_panel.start_button.setEnabled(enabled and task_status in {TaskStatus.DRAFT, TaskStatus.READY}) - quick_run_busy = any( - button in self._button_generations - for button in ( - self.run_panel.quick_run_button, - self.run_panel.continue_without_backup_button, - ) - ) - recovery_pending = bool(self._task_id and self.service.has_interrupted_quick_run(self._task_id)) - recovery_busy = self.run_panel.recover_button in self._button_generations - quick_run_busy = quick_run_busy or recovery_busy + def _update_gates(self): + state = execution_state(self._context, busy=bool(self._workers), dirty=self.plan_panel.table.dirty) + busy = bool(self._workers) + context = self._context + self.run_panel.quick_run_button.setText(state.execute_text) + self.run_panel.quick_run_button.setEnabled(state.execute) + self.run_panel.retry_button.setVisible(bool(context and context.phase == 'retry')) + self.run_panel.retry_button.setEnabled(state.retry) + self.run_panel.recover_button.setVisible(bool(context and context.interrupted)) + self.run_panel.recover_button.setEnabled(state.recover) self.run_panel.stop_queue_button.setVisible(self._batch_stop is not None) - self.run_panel.stop_queue_button.setEnabled(self._batch_stop is not None and not self._batch_stop.is_set()) - self.run_panel.recover_button.setVisible(recovery_pending) - self.run_panel.recover_button.setEnabled(enabled and recovery_pending and not self._workers and task_status is not TaskStatus.DELETED) - backup_override_available = self._backup_override_task_id == self._task_id - self.run_panel.continue_without_backup_button.setVisible(backup_override_available) - self.run_panel.continue_without_backup_button.setEnabled( - enabled - and backup_override_available - and not quick_run_busy - and not recovery_pending - and not self._workers - and task_status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED} - ) - value_option_busy = self.run_panel.copy_value_check in self._button_generations - retryable_queue = self._quick_run_phase == "retry" - retry_selection_ready = any( - project.selected and project.available and project.status is ProjectStatus.FAILED - for project in projects - ) - self.run_panel.quick_run_button.setEnabled( - (retry_selection_ready if retryable_queue else enabled) - and (task_status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING} - or (task_status is TaskStatus.PAUSED and self.service.has_quick_run_evidence(self._task_id))) - and active is None - and self._quick_run_phase != "complete" - and not quick_run_busy - and not recovery_pending - and not value_option_busy - ) - self.run_panel.pause_button.setEnabled(task_status is TaskStatus.RUNNING) - self.run_panel.resume_button.setEnabled(task_status is TaskStatus.PAUSED) - self.run_panel.capture_before_button.setEnabled(task_status is TaskStatus.RUNNING and active_status is ProjectStatus.CAPTURING_BEFORE) - self.run_panel.confirm_attempt_button.setEnabled(task_status is TaskStatus.RUNNING and active_status is ProjectStatus.AWAITING_OPERATOR) - paused_capture_project = self._selected_project() - self.run_panel.capture_after_button.setEnabled( - (task_status is TaskStatus.RUNNING and active_status is ProjectStatus.AWAITING_OPERATOR) - or (task_status is TaskStatus.PAUSED and getattr(paused_capture_project, "status", None) is ProjectStatus.AWAITING_OPERATOR) - ) - has_quick_run_evidence = bool(self._task_id and self.service.has_quick_run_evidence(self._task_id)) - selected_project = self._selected_project() - selected_status = getattr(selected_project, "status", None) - manual_project_action = not quick_run_busy and not has_quick_run_evidence and not self._workers - self.retry_button.setEnabled(manual_project_action and selected_status is ProjectStatus.FAILED and task_status in {TaskStatus.FAILED, TaskStatus.PAUSED, TaskStatus.RUNNING}) - self.skip_button.setEnabled(manual_project_action and selected_status not in {None, ProjectStatus.COMPLETED, ProjectStatus.SKIPPED}) - inputs_editable = ( - has_task - and (task_status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED} or retryable_queue) - and not quick_run_busy - and (not has_quick_run_evidence or retryable_queue) - ) - self.run_panel.copy_value_check.setEnabled( - inputs_editable - and self.run_panel.copy_value_check not in self._button_generations - and (not has_quick_run_evidence or retryable_queue) - ) - self.task_list.edit_button.setEnabled(has_task and task_status is not TaskStatus.DELETED and not self._workers) - self.task_list.delete_button.setText("彻底删除" if task_status is TaskStatus.DELETED else "删除") - self.task_list.delete_button.setToolTip( - "永久删除任务及关联记录,不删除工程文件;诊断证据保留。" - if task_status is TaskStatus.DELETED else "移至已删除,可从已删除列表恢复。" - ) - self.task_list.delete_button.setEnabled(has_task and task_status is not TaskStatus.RUNNING and not self._workers) - self.task_list.restore_button.setEnabled(has_task and task_status is TaskStatus.DELETED and not self._workers) - selection_enabled = inputs_editable and self._selection_generation is None - self.select_all_projects_button.setEnabled(selection_enabled) - self.clear_projects_button.setEnabled(selection_enabled) - self.project_table.set_selection_enabled(selection_enabled) - directory_editable = inputs_editable and not retryable_queue - self.directory_path.setEnabled(directory_editable) - self.browse_directory_button.setEnabled( - directory_editable and self.browse_directory_button not in self._button_generations - ) - self.scan_projects_button.setEnabled(directory_editable and self.scan_projects_button not in self._button_generations) - self.mapping_table.set_rules_editable(inputs_editable) - self.add_mapping_button.setEnabled(inputs_editable) - has_rule = self.mapping_table.current_rule_id() is not None - self.edit_mapping_button.setEnabled(inputs_editable and has_rule) - self.delete_mapping_button.setEnabled(inputs_editable and has_rule) - self.move_mapping_up_button.setEnabled(inputs_editable and has_rule) - self.move_mapping_down_button.setEnabled(inputs_editable and has_rule) - plan_busy = bool(self._workers) - self.plan_panel.set_plan_editable(inputs_editable and not plan_busy) - self.task_list.new_button.setEnabled(not plan_busy) - task = self.service.get_task(self._task_id) if self._task_id else None - bound_task = bool(task and task.primary_project_id) - group_ids = tuple(item.task_id for item in self.service.tasks() - if task and item.group_id == task.group_id) - self.task_list.queue_button.setEnabled(bound_task and not plan_busy - and not self.plan_panel.has_unsaved_plan(group_ids)) - self.task_list.up_button.setEnabled(bound_task and not plan_busy) - self.task_list.down_button.setEnabled(bound_task and not plan_busy) - if bound_task: - self.directory_path.setEnabled(False) - self.browse_directory_button.setEnabled(False) - self.scan_projects_button.setEnabled(False) + self.run_panel.stop_queue_button.setEnabled(bool(self._batch_stop and not self._batch_stop.is_set())) + self.run_panel.copy_value_check.setEnabled(state.editable) + self.mapping_table.set_rules_editable(state.editable) + self.plan_panel.set_plan_editable(state.editable) + self.add_mapping_button.setEnabled(state.editable) + selected = self.mapping_table.current_rule_id() is not None + for button in (self.edit_mapping_button, self.delete_mapping_button, + self.move_mapping_up_button, self.move_mapping_down_button): + button.setEnabled(state.editable and selected) + self.project_summary.refresh_button.setEnabled(bool(context and not context.legacy and not busy)) + self.task_list.list.setEnabled(not busy) + self.task_list.filter.setEnabled(not busy) + self.task_list.new_button.setEnabled(not busy) + exists = bool(context) + deleted = bool(context and context.task.status is TaskStatus.DELETED) + self.task_list.edit_button.setEnabled(exists and not deleted and not busy) + self.task_list.delete_button.setEnabled(exists and not busy and context.task.status is not TaskStatus.RUNNING) + self.task_list.delete_button.setText('彻底删除' if deleted else '删除') + self.task_list.restore_button.setEnabled(deleted and not busy) + grouped = bool(context and not context.legacy and context.task.group_id and not deleted) + group_ids = tuple(t.task_id for t in self._tasks if context and t.group_id == context.task.group_id + and t.status is not TaskStatus.DELETED) + group_dirty = self.plan_panel.has_unsaved_plan(group_ids) + group_active = any(t.status in {TaskStatus.RUNNING, TaskStatus.PAUSED} for t in self._tasks if t.task_id in group_ids) + self.task_list.queue_button.setEnabled(grouped and not busy and not group_dirty and not bool(context.interrupted)) + for button in (self.task_list.up_button, self.task_list.down_button): + button.setEnabled(grouped and not busy and not group_active) + if not self._message: + self.run_panel.operator_band.setText(state.message) + if not busy: + self.run_panel.execution_status.setText('结果待核验' if context and context.interrupted else '空闲') - def _execution_rules(self, task_id): - task = self.service.get_task(task_id) - if task.target_plan_mode: - from ..target_plan import compile_target_rules - return compile_target_rules(self.service.target_plan(task_id)) - return self.service.rules(task_id) - - def _selected_project(self) -> Any | None: - project_id = self.project_table.current_project_id() - return next((project for project in getattr(self, "_projects", ()) if project.project_id == project_id), None) - - def _project_row_changed(self) -> None: - self._update_gates() - - def _current_task_status(self) -> TaskStatus | None: - if not self._task_id: - return None - try: - return self.service.get_task(self._task_id).status - except Exception: - return None - - def _new_task(self) -> None: + def _new_task(self): dialog = DirectoryTaskDialog(self.service, self) if dialog.exec() == QDialog.DialogCode.Accepted: - root, selected = dialog.values() - self._run_async(lambda: self.service.create_project_tasks(root, selected_paths=selected), + root, paths = dialog.values() + self._run_async(lambda: self.service.create_project_tasks(root, selected_paths=paths), self._project_tasks_created, self.task_list.new_button) def _project_tasks_created(self, tasks): - self.task_list.filter.setCurrentText("进行中") + self.task_list.filter.setCurrentText('进行中') self._refresh_task_list() if tasks: - self.open_task(tasks[0].task_id) - self._set_operator_message(f"已创建 {len(tasks)} 个任务;每个任务绑定一个工程。先填写料号规则,再采集位号。", "success") - else: - self._set_operator_message("所选工程已经有未完成任务,无需重复创建。", "warning") + self._task_id = tasks[0].task_id + self._load_task_data() + self._set_operator_message(f'创建 {len(tasks)} 个单工程任务。已有未完成任务的工程不会重复创建。') + + def _refresh_bound_project(self): + if self._task_id and not self._workers: + task_id = self._task_id + self._run_async(lambda: self.service.refresh_bound_project(task_id), + lambda _: self._load_task_data(), self.project_summary.refresh_button, + expected_task_id=task_id) + + def _edit_task(self): + if not self._context: + return + task = self._context.task + dialog = _TaskDialog(self, task.name, task.note) + if dialog.exec() == QDialog.DialogCode.Accepted: + name, note = dialog.values() + self._run_async(lambda: self.service.update_task(task.task_id, name=name, note=note), + self._metadata_changed, self.task_list.edit_button) + + def _metadata_changed(self, _): + self._refresh_task_list() + self._load_task_data() + + def _delete_task(self): + if not self._context: + return + task = self._context.task + permanent = task.status is TaskStatus.DELETED + if QMessageBox.question(self, '彻底删除任务' if permanent else '删除任务', + '永久删除任务记录,工程文件和诊断证据保留。此操作不可撤销。' if permanent else '移至已删除,之后可恢复。', + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes: + return + operation = (lambda: self.service.purge_task(task.task_id, confirmed=True)) if permanent else (lambda: self.service.delete_task(task.task_id)) + def done(_): + if permanent: + self.plan_panel._drafts.pop(task.task_id, None) + self._task_id = None + self._metadata_changed(None) + self._run_async(operation, done, self.task_list.delete_button) + + def _restore_task(self): + if self._task_id: + task_id = self._task_id + self._run_async(lambda: self.service.restore_task(task_id), self._metadata_changed, self.task_list.restore_button) def _move_project_task(self, offset): + if self._task_id and not self._workers: + task_id = self._task_id + self._run_async(lambda: self.service.move_project_task(task_id, offset), self._metadata_changed) + + def _add_mapping_dialog(self): + if not self.add_mapping_button.isEnabled(): + return + self._mapping_dialog(None) + + def _edit_mapping(self): + rule_id = self.mapping_table.current_rule_id() + rule = next((r for r in self._context.rules if r.rule_id == rule_id), None) if self._context else None + if rule: + self._mapping_dialog(rule) + + def _mapping_dialog(self, rule): + dialog = _MappingDialog(self, *(() if rule is None else (rule.old_part_number, rule.new_part_number, + rule.enabled, rule.custom_value_enabled, rule.custom_value, rule.sync_nc))) + if dialog.exec() != QDialog.DialogCode.Accepted: + return + old, new, enabled, custom_enabled, value, sync_nc = dialog.values() + task_id = self._task_id + options = dict(enabled=enabled, custom_value_enabled=custom_enabled, custom_value=value, sync_nc=sync_nc) + operation = (lambda: self.service.add_rule(task_id, old, new, **options)) if rule is None else ( + lambda: self.service.update_rule(rule.rule_id, old_part_number=old, new_part_number=new, **options)) + self._run_async(operation, lambda _: self._load_task_data(), expected_task_id=task_id) + + def _delete_mapping(self): + rule_id = self.mapping_table.current_rule_id() + if rule_id: + self._run_async(lambda: self.service.delete_rule(rule_id), lambda _: self._load_task_data()) + + def _move_mapping(self, offset): + rule_id = self.mapping_table.current_rule_id() + if rule_id: + self._run_async(lambda: self.service.move_rule(rule_id, offset), lambda _: self._load_task_data()) + + def _rule_enabled_changed(self, rule_id, enabled): + rule = next((r for r in self._context.rules if r.rule_id == rule_id), None) if self._context else None + if rule: + self._run_async(lambda: self.service.update_rule(rule_id, old_part_number=rule.old_part_number, + new_part_number=rule.new_part_number, enabled=enabled, custom_value_enabled=rule.custom_value_enabled, + custom_value=rule.custom_value, sync_nc=rule.sync_nc), lambda _: self._load_task_data()) + + def _value_option_changed(self, enabled): if self._task_id: - try: - self.service.move_project_task(self._task_id, offset) - self._refresh_task_list() - except Exception as error: - self._show_error(error) + task_id = self._task_id + self._run_async(lambda: self.service.set_copy_part_number_to_value(task_id, enabled), + lambda _: self._load_task_data(), self.run_panel.copy_value_check, expected_task_id=task_id) + + def _prepare_quick_run(self): + if not self.run_panel.quick_run_button.isEnabled(): + return + context = self._context + enabled = sum(row.enabled for row in context.targets) if context.task.target_plan_mode else sum(r.enabled for r in context.rules) + if not self._quick_run_confirmer('current', 1, enabled): + return + p = context.progress + expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number, + 'part_label' if context.task.copy_part_number_to_value else 'preserve') + task_id = context.task.task_id + self._begin_run(task_id) + stop = self._batch_stop + self._run_async(lambda: self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop), + self._show_batch_result, self.run_panel.quick_run_button, expected_task_id=task_id) def _execute_project_tasks(self): - if not self._task_id or self._workers or self.plan_panel.table.dirty: + if not self.task_list.queue_button.isEnabled(): return - task = self.service.get_task(self._task_id) - tasks = sorted((item for item in self.service.tasks() - if item.group_id == task.group_id and item.primary_project_id - and item.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}), - key=lambda item: item.group_position) + group = self._context.task.group_id + tasks = sorted((t for t in self._tasks if t.group_id == group and t.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}), + key=lambda t: t.group_position) if not tasks: return - ids = tuple(item.task_id for item in tasks) - if self._project_queue_id: - existing = {item.task_id: item for item in self.service.tasks()} - if all(task_id in existing and existing[task_id].group_id == task.group_id - and existing[task_id].status is not TaskStatus.DELETED - for task_id in self._project_queue_ids): - ids = self._project_queue_ids - tasks = [existing[task_id] for task_id in ids] + token, ids = self._project_queues.get(group, (None, tuple(t.task_id for t in tasks))) if self.plan_panel.has_unsaved_plan(ids): - self._set_operator_message('本批任务有未保存的位号编辑,请先逐个保存。', 'warning') + self._set_operator_message('本批任务有未保存计划,请先逐个保存。', 'warning') return - text = "按以下顺序处理,每次只打开一个工程:\n" + "\n".join( - f"{index + 1}. {item.name}" for index, item in enumerate(tasks)) - if QMessageBox.question(self, "确认顺序执行任务", text + "\n请先保存并关闭已有 CAD 工程。") != QMessageBox.StandardButton.Yes: + if not self._quick_run_confirmer('batch', len(ids), 0): return from ..task_queue import execute_task_queue - token = self._project_queue_id if ids == self._project_queue_ids else None - self._project_queue_ids = ids - self._batch_stop = Event() + self._begin_run(ids[0]) stop = self._batch_stop - self._active_quick_run_task_id = ids[0] - self._quick_run_elapsed.start() - self._quick_run_timer.start() - self.run_panel.busy_indicator.show() - self.run_panel.stop_queue_button.show() - self._run_async(lambda: execute_task_queue(self.service, ids, stop_event=stop, queue_id=token), - self._project_task_queue_finished, self.run_panel.quick_run_button) - - def _project_task_queue_finished(self, result): - self._project_queue_id = result.queue_id if result.paused else None - self._stop_quick_run_feedback() - self._refresh_task_list() - self._load_task_data() - completed = sum(entry.state == 'completed' for entry in result.entries) - failed = sum(entry.state in {'failed', 'blocked'} for entry in result.entries) - detail = '\n'.join(f"{self.service.get_task(entry.task_id).name}: {entry.message}" - for entry in result.entries if entry.state in {'failed', 'blocked'}) - self._set_operator_message(f"任务队列{'已暂停' if result.paused else '已结束'}:完成 {completed},失败/阻断 {failed}。\n{detail}", - "warning" if result.paused or failed else "success") - - def _edit_task(self) -> None: - if not self._task_id: - return - try: - task = self.service.get_task(self._task_id) - dialog = _TaskDialog(self, task.name, task.note) - while dialog.exec() == QDialog.DialogCode.Accepted: - name, note = dialog.values() - try: - self.service.update_task(task.task_id, name=name, note=note) - except TaskCenterError as error: - if error.code in DIALOG_ERROR_TEXT: - dialog.validation.setText(DIALOG_ERROR_TEXT[error.code]) - continue - raise - self._refresh_task_list() - self.open_task(task.task_id) - return - except Exception as error: - self._show_error(error) - - def _delete_task(self) -> None: - if not self._task_id or not self.task_list.delete_button.isEnabled(): - return - try: - if self.service.get_task(self._task_id).status is TaskStatus.DELETED: - self._purge_task() - return - self.service.delete_task(self._task_id) - self._refresh_task_list() - self._load_task_data() - except Exception as error: - self._show_error(error) - - def _purge_task(self) -> None: - if not self._task_id: - return - task = self.service.get_task(self._task_id) - task_id = task.task_id - dialog = QMessageBox( - QMessageBox.Icon.Warning, - "确认彻底删除任务", - f"确定彻底删除任务“{task.name}”?\n\n" - "将永久删除任务、工程关联、替换规则和尝试记录,删除后不能通过“恢复”撤销。\n" - "不会删除实际工程文件,也不会撤销已做的原理图修改。诊断日志和执行证据保留供排查。\n" - "任务已进入“已删除”后,可直接删除任务记录,不再受队列执行锁或未完成队列状态限制。", - parent=self, - ) - confirm = dialog.addButton("彻底删除", QMessageBox.ButtonRole.DestructiveRole) - cancel = dialog.addButton("取消", QMessageBox.ButtonRole.RejectRole) - dialog.setDefaultButton(cancel) - dialog.setEscapeButton(cancel) - dialog.exec() - if dialog.clickedButton() is not confirm: - return - self._run_async( - lambda: self.service.purge_task(task_id, confirmed=True), - self._task_purged, - self.task_list.delete_button, - ) - self._update_gates() - - def _task_purged(self, task_id: str) -> None: - if self._task_id == task_id: - self._task_id = None - self._refresh_task_list() - self._load_task_data() - self._set_operator_message("任务记录已彻底删除,无法恢复;工程文件及诊断证据未删除。", "success") - - def _restore_task(self) -> None: - if not self._task_id: - return - try: - self.service.restore_task(self._task_id) - self._refresh_task_list() - self._load_task_data() - except Exception as error: - self._show_error(error) - - def _browse_directory(self) -> None: - chosen = self.directory_picker() - if chosen: - self.directory_path.setText(str(chosen)) - - def _directory_changed(self, value: str) -> None: - if not self._task_id or self._directory_matches_saved_root(value): - return - self._projects = () - self.project_table.populate(()) - self.run_panel.queue_summary.setText("目录已更改,等待重新扫描") - self.run_panel.execution_status.setText("等待扫描") - self._set_operator_message("工程目录已更改,请重新扫描;旧目录项目不会带入新目录。", "warning") - self._update_gates() - - def _directory_matches_saved_root(self, value: str | None = None) -> bool: - current = self.directory_path.text() if value is None else value - return _directory_identity(current) == _directory_identity(self._discovery_root) - - def _scan_projects(self) -> None: - if not self._task_id: - self._show_error(TaskCenterError("task_required", "请先选择任务。")) - return - root = self.directory_path.text().strip() - if not root: - chosen = self.directory_picker() - if not chosen: - self._show_error(TaskCenterError("directory_required", "请先选择工程目录。")) - return - root = str(chosen) - self.directory_path.setText(root) - task_id = self._task_id - self._run_async( - lambda: self.service.scan_projects(task_id, Path(root)), - self._project_scan_finished, - self.scan_projects_button, - expected_task_id=task_id, - ) - - def _project_scan_finished(self, projects: tuple[object, ...]) -> None: - self._load_task_data() - if not any(bool(getattr(project, "available", False)) for project in projects): - self._set_operator_message( - "所选目录中未发现可用的 DxDesigner 原理图工程;PCB 工程和其他 .prj 文件已忽略。", - "warning", - ) - - def _project_selection_changed(self, project_id: str, selected: bool) -> None: - if not self._task_id: - return - task_id = self._task_id - self._run_async( - lambda: self.service.set_project_selected(project_id, selected), - lambda _project: self._load_task_data(), - expected_task_id=task_id, - selection_operation=True, - ) - - def _select_all_projects(self) -> None: - if self._task_id: - task_id = self._task_id - self._run_async(lambda: self.service.select_all_projects(task_id), lambda _projects: self._load_task_data(), expected_task_id=task_id, selection_operation=True) - - def _clear_projects(self) -> None: - if self._task_id: - task_id = self._task_id - self._run_async(lambda: self.service.clear_project_selection(task_id), lambda _projects: self._load_task_data(), expected_task_id=task_id, selection_operation=True) - - def add_mapping(self, old_part: str, new_part: str, *, enabled: bool = True) -> None: - """Add a rule through the service and immediately refresh the table.""" - if not self._task_id: - raise TaskCenterError("task_required", "请先选择任务。") - try: - self.service.add_rule(self._task_id, old_part, new_part, enabled=enabled) - self._load_task_data() - except Exception as error: - self._show_error(error) - raise - - def _add_mapping_dialog(self) -> None: - dialog = _MappingDialog(self) - while dialog.exec() == QDialog.DialogCode.Accepted: - old, new, enabled, custom_enabled, custom_value, sync_nc = dialog.values() - try: - self.service.add_rule( - self._task_id or "", old, new, enabled=enabled, - custom_value_enabled=custom_enabled, custom_value=custom_value, sync_nc=sync_nc, - ) - except TaskCenterError as error: - if error.code in DIALOG_ERROR_TEXT: - dialog.validation.setText(DIALOG_ERROR_TEXT[error.code]) - continue - self._show_error(error) - return - self._load_task_data() - return - - def _edit_mapping(self) -> None: - if not self._task_id: - return - rule_id = self.mapping_table.current_rule_id() - if not rule_id: - return - try: - rule = next(rule for rule in self.service.rules(self._task_id) if rule.rule_id == rule_id) - dialog = _MappingDialog( - self, - rule.old_part_number, - rule.new_part_number, - rule.enabled, - rule.custom_value_enabled, - rule.custom_value, - rule.sync_nc, - ) - while dialog.exec() == QDialog.DialogCode.Accepted: - old, new, enabled, custom_enabled, custom_value, sync_nc = dialog.values() - try: - self.service.update_rule( - rule_id, old_part_number=old, new_part_number=new, enabled=enabled, - custom_value_enabled=custom_enabled, custom_value=custom_value, sync_nc=sync_nc, - ) - except TaskCenterError as error: - if error.code in DIALOG_ERROR_TEXT: - dialog.validation.setText(DIALOG_ERROR_TEXT[error.code]) - continue - raise - self._load_task_data() - return - except Exception as error: - self._show_error(error) - - def _delete_mapping(self) -> None: - rule_id = self.mapping_table.current_rule_id() - if not rule_id: - return - try: - self.service.delete_rule(rule_id) - self._load_task_data() - except Exception as error: - self._show_error(error) - - def _move_mapping(self, offset: int) -> None: - rule_id = self.mapping_table.current_rule_id() - if not rule_id: - return - try: - self.service.move_rule(rule_id, offset) - self._load_task_data() - except Exception as error: - self._show_error(error) - - def _rule_enabled_changed(self, rule_id: str, enabled: bool) -> None: - if not self._task_id: - return - try: - rule = next(rule for rule in self.service.rules(self._task_id) if rule.rule_id == rule_id) - self.service.update_rule( - rule_id, - old_part_number=rule.old_part_number, - new_part_number=rule.new_part_number, - enabled=enabled, - custom_value_enabled=rule.custom_value_enabled, - custom_value=rule.custom_value, - sync_nc=rule.sync_nc, - ) - self._load_task_data() - except Exception as error: - self._load_task_data() - self._show_error(error) - - def _start_task(self) -> None: - if not self._task_id or not self.run_panel.start_button.isEnabled(): - return - task_id = self._task_id - selected = sum(1 for project in self.service.projects(task_id) if project.selected and project.available) - dialog = QMessageBox( - QMessageBox.Icon.Warning, - "确认开始任务", - f"将对选中的 {selected} 个工程开始任务。\n请确认工程已保存,并允许程序在执行前创建完整备份。", - parent=self, - ) - confirm = dialog.addButton("确认开始", QMessageBox.ButtonRole.AcceptRole) - dialog.addButton("取消", QMessageBox.ButtonRole.RejectRole) - dialog.exec() - if dialog.clickedButton() is not confirm: - return - self._run_async( - lambda: self.service.start_task(task_id, disposable_copy_confirmed=True), - self._apply_run_snapshot, - self.run_panel.start_button, - expected_task_id=task_id, - ) - - def _value_option_changed(self, enabled: bool) -> None: - if self._task_id is None: - return - task_id = self._task_id - self._run_async( - lambda: self.service.set_copy_part_number_to_value(task_id, enabled), - lambda task: self._load_task_data(), - self.run_panel.copy_value_check, - expected_task_id=task_id, - ) - self._update_gates() - - def _prepare_quick_run(self) -> None: - if self.run_panel.copy_value_check in self._button_generations: - return - if not self._task_id or not self.run_panel.quick_run_button.isEnabled(): - return - task_id = self._task_id - if self._quick_run_phase == "retry": - self._run_async( - lambda: self.service.prepare_failed_quick_run(task_id), - lambda _progress: self._resume_failed_quick_run(), - self.run_panel.quick_run_button, - expected_task_id=task_id, - ) - return - selected = sum(1 for project in self.service.projects(task_id) if project.selected and project.available) - enabled = sum(1 for rule in self._execution_rules(task_id) if rule.enabled) - progress = self.service.quick_run_progress(task_id) - self._confirmation_progress = progress - copy_value = self.service.get_task(task_id).copy_part_number_to_value - value_mode = "part_label" if copy_value else "preserve" - self._confirmation_value_mode = value_mode - checkbox = self.run_panel.copy_value_check - was_blocked = checkbox.blockSignals(True) - checkbox.setChecked(copy_value) - checkbox.blockSignals(was_blocked) - if not self._quick_run_confirmer(self._quick_run_phase, selected, enabled): - return - if progress.next_project_path is None: - return - expected_item = (str(progress.next_project_path), progress.next_old_part_number, progress.next_new_part_number, value_mode) - self._start_quick_run_queue(task_id, expected_item) - - def _resume_failed_quick_run(self) -> None: - self._quick_run_phase = "selection" - self._load_task_data() - self._prepare_quick_run() - - def _start_quick_run_queue( - self, - task_id: str, - expected_item: tuple[str, str, str, str], - *, - continue_after_backup_failure: bool = False, - ) -> None: - self._backup_override_task_id = None - progress = self.service.quick_run_progress(task_id) - self._active_quick_run_task_id = task_id - self._quick_run_elapsed.start() - self._quick_run_timer.start() - self.run_panel.busy_indicator.show() - if progress.next_project_path is not None: - sheet = f" | {progress.next_schematic_name}:{progress.next_sheet_number}" if progress.next_schematic_name else " | 正在准备图页清单" - self.run_panel.execution_status.setText( - f"正在执行 {progress.completed_items + 1}/{progress.total_items}:" - f"{progress.next_project_path.name}{sheet} | {progress.next_old_part_number} -> {progress.next_new_part_number} | 0 秒" - ) - stop_event = Event() - self._batch_stop = stop_event - self._batch_rendered = None - self.run_panel.stop_queue_button.setText("完成当前项后暂停") - message = ( - "正在尝试精简原理图备份;若仍失败,将按本次明确确认继续。" - if continue_after_backup_failure - else "正在逐工程创建精简原理图备份并只读枚举全部图页;清单固定后再串行处理。未命中自动跳过,每次只打开一个工程和一个图页。" - ) - self._set_operator_message(message, "busy") - self._run_async( - lambda: self.service.execute_quick_run_queue( - task_id, - expected_item=expected_item, - stop_event=stop_event, - continue_after_backup_failure=continue_after_backup_failure, - ), - self._show_batch_result, - ( - self.run_panel.continue_without_backup_button - if continue_after_backup_failure - else self.run_panel.quick_run_button - ), - expected_task_id=task_id, - ) - - def _continue_without_backup(self) -> None: - task_id = self._backup_override_task_id - if ( - not task_id - or task_id != self._task_id - or not self.run_panel.continue_without_backup_button.isEnabled() - ): - return - answer = QMessageBox.warning( - self, - "确认无备份继续", - "精简原理图备份仍然失败。继续后,备份失败的工程将没有本工具创建的可用回滚副本;" - "若替换或保存发生异常,只能依赖你自己的工程副本恢复。\n\n" - "该授权仅对这一次队列执行有效,程序仍会先尝试备份每个工程,并在任务日志中记录所有跳过。\n\n" - "请确认工程已经保存,并且你已有独立副本。是否继续?", - QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, - QMessageBox.StandardButton.No, - ) - if answer != QMessageBox.StandardButton.Yes: - return - progress = self.service.quick_run_progress(task_id) - if progress.next_project_path is None: - self._show_error(TaskCenterError("quick_run_complete", "all quick-run items are complete")) - return - copy_value = self.service.get_task(task_id).copy_part_number_to_value - value_mode = "part_label" if copy_value else "preserve" - expected_item = ( - str(progress.next_project_path), - progress.next_old_part_number, - progress.next_new_part_number, - value_mode, - ) - self._start_quick_run_queue( - task_id, - expected_item, - continue_after_backup_failure=True, - ) - - def _pause_queue(self) -> None: - if self._batch_stop is not None: - self._batch_stop.set() - self.run_panel.stop_queue_button.setEnabled(False) - self.run_panel.stop_queue_button.setText("正在完成当前项…") - self._set_operator_message("已请求暂停:当前项校验和保存收尾后停止,不会启动下一项。", "warning") - - def _show_batch_result(self, result: Any) -> None: - self._stop_quick_run_feedback() - if result.last_result is not None: - self._show_quick_run_result(result.last_result) - else: - self._load_task_data() - for item_message in getattr(result, "item_messages", ()): - nc_lines = _nc_sync_log_lines(item_message) - if nc_lines: - for line in nc_lines: - self._append_log(line) + def done(result): + if result.paused: + self._project_queues[group] = (result.queue_id, ids) else: - self._append_log(f"失败项:{item_message}") - progress = result.progress - unbacked_count = len(getattr(result, "unbacked_project_paths", ())) - failed_count = getattr(progress, "failed_items", 0) - if result.paused: - self._quick_run_phase = "selection" - self.run_panel.quick_run_button.setText("继续队列") - message = f"队列已暂停:{progress.completed_items}/{progress.total_items};失败 {failed_count},未命中 {progress.no_match_items}。确认后继续。" - else: - self._quick_run_phase = "retry" if failed_count else "complete" - self.run_panel.quick_run_button.setText("重试失败项" if failed_count else "当前队列已完成") - replaced = progress.completed_items - progress.no_match_items - failed_count - save_message = "" if not replaced or progress.saved_items == replaced else " 请核对成功项的保存状态。" - scope = "全工程图页队列" if progress.page_addressed else "旧版单页队列" - message = f"{scope}完成:成功 {progress.saved_items},失败 {failed_count},未命中 {progress.no_match_items}。{save_message}" - if unbacked_count: - message += f" 警告:{unbacked_count} 个工程未建立本工具备份,不能保证从本工具回滚。" - self.run_panel.execution_status.setText( - "队列已暂停" if result.paused else "队列处理中(存在可重试项)" if failed_count else "队列已完成(存在未备份工程)" if unbacked_count else "队列已完成" - ) - self._set_operator_message(message, "warning" if result.paused or unbacked_count or failed_count else "success") - self._append_log(message) - self._update_gates() + self._project_queues.pop(group, None) + self._finish_run() + self._metadata_changed(None) + failures = sum(e.state in {'failed', 'blocked'} for e in result.entries) + self._set_operator_message(f'本批任务已暂停。失败/阻断 {failures} 项。' if result.paused else f'本批任务已结束。失败 {failures} 项。', + 'warning' if result.paused or failures else 'success') + self._run_async(lambda: execute_task_queue(self.service, ids, stop_event=stop, queue_id=token), done, + self.task_list.queue_button) - def _recover_quick_run(self) -> None: - if not self._task_id or not self.run_panel.recover_button.isEnabled(): - return - answer = QMessageBox.question(self, "核验并恢复中断任务", - "会先备份工程和执行证据,再用新的 DxDesigner 会话检查已保存的当前图页。\n\n" - "已经完整替换:只补记完成,不改图。\n" - "全部仍是旧器件且与快照一致:准备新的执行编号,等待你确认重试。\n" - "全部已替换但属性恢复不完整:仅恢复原快照中的位置、显示样式及实例参数,并遵循原 Value 选项。\n" - "新旧器件混杂或连接异常:停止,不强行续跑。\n\n" - "此操作不会再次调用原生替换,也不会自动保存。请先自行处理需要保留的未保存修改并关闭 DxDesigner;" - "恢复会自动重新打开工程。确认继续?", - QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No) - if answer != QMessageBox.StandardButton.Yes: - return - task_id = self._task_id + def _begin_run(self, task_id): + self._batch_stop = Event() self._active_quick_run_task_id = task_id self._quick_run_elapsed.start() self._quick_run_timer.start() self.run_panel.busy_indicator.show() - self._set_operator_message("正在备份并核验中断步骤;不会重复调用原生替换。", "busy") - self._run_async(lambda: self.service.recover_quick_run(task_id, confirmed=True), - self._show_recovery_result, self.run_panel.recover_button, expected_task_id=task_id) + self._message = '' - def _show_recovery_result(self, result: Any) -> None: - self._stop_quick_run_feedback() - if result.state == "retry_ready": - self._quick_run_phase = "selection" - self.run_panel.quick_run_button.setText("确认后重新执行本项") - self._load_task_data() + def _finish_run(self): + self._quick_run_timer.stop() + self._active_quick_run_task_id = None + self._batch_stop = None + self.run_panel.busy_indicator.hide() + self.run_panel.stop_queue_button.setText('完成当前项后暂停') + + def _pause_queue(self): + if self._batch_stop: + self._batch_stop.set() + self.run_panel.stop_queue_button.setText('等待当前项收尾…') + self._set_operator_message('已请求暂停;当前项安全收尾后停止。', 'warning') + self._update_gates() + + def _show_batch_result(self, result): + self._finish_run() + self._metadata_changed(None) + for item in result.item_messages: + for line in _nc_sync_log_lines(item) or (item,): + self._append_log(line) + p = result.progress + self._set_operator_message(f"{'任务已暂停' if result.paused else '当前任务已结束'}:已保存 {p.saved_items},失败 {p.failed_items},未命中 {p.no_match_items}。", + 'warning' if result.paused or p.failed_items else 'success') + + def _retry_failed(self): + if self.run_panel.retry_button.isEnabled(): + task_id = self._task_id + self._run_async(lambda: self.service.prepare_failed_quick_run(task_id), + lambda _: self._load_task_data(), self.run_panel.retry_button, expected_task_id=task_id) + + def _recover_quick_run(self): + if not self.run_panel.recover_button.isEnabled(): + return + if QMessageBox.question(self, '核验并恢复', + '先备份工程和证据,再打开工程核验;不会重复调用原生替换,也不会自动保存。请先保存并关闭已有 CAD 工程。', + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes: + return + task_id = self._task_id + self._begin_run(task_id) + def done(result): + self._finish_run() + self._metadata_changed(None) + self._set_operator_message(result.message) + self._run_async(lambda: self.service.recover_quick_run(task_id, confirmed=True), done, + self.run_panel.recover_button, expected_task_id=task_id) + + def _confirm_quick_run(self, scope, selected_projects, enabled_rules): + context = self._context + names = context.project.path if scope == 'current' else '\n'.join( + f'{t.group_position+1}. {t.name}' for t in sorted(self._tasks, key=lambda t: t.group_position) + if t.group_id == context.task.group_id and t.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}) + text = (f'执行范围:{names}\n\n' + (f'勾选目标/规则:{enabled_rules}\n' if scope == 'current' else f'按顺序处理 {selected_projects} 个工程任务。\n') + + '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。' + + '\n请先保存并关闭已有 DxDesigner 工程。当前默认执行仍使用原生窗口;独立桌面后端处于研究阶段。' + + '\n确认后连续执行,暂停等待当前步骤收尾;状态不确定时停止。') + return QMessageBox.question(self, '确认执行当前任务' if scope == 'current' else '确认顺序执行本批任务', text, + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes + + def _update_quick_run_elapsed(self): + seconds = self._quick_run_elapsed.elapsed() // 1000 + feedback = getattr(self.service, '_task_queue_feedback', None) + if feedback: + _, task_id, position, total = feedback + self._active_quick_run_task_id = task_id + name = next((t.name for t in self._tasks if t.task_id == task_id), task_id) + self.run_panel.execution_status.setText(f'任务 {position}/{total}:{name} · {seconds} 秒') else: - self._show_quick_run_result(result) - self._set_operator_message(result.message, "success") - self._append_log(result.message) - self._update_gates() + batch = self.service.batch_feedback() + self.run_panel.execution_status.setText(f'{batch[2] if batch else "正在执行"} · {seconds} 秒') + if self.run_panel.toggle_log_button.isChecked(): + self._refresh_live_task_log() - def _show_quick_run_result(self, result: Any) -> None: - self._stop_quick_run_feedback() - no_match = getattr(result, "state", None) == "no_match" - result_state = getattr(result, "state", None) - failed = result_state in {"batch_failed", "batch_saved_unverified"} - saved_unverified = result_state == "batch_saved_unverified" - outcome = ( - "本图页未命中,继续下一项。" - if no_match else "本项失败,位号和原因已记录,继续下一项。" - if not saved_unverified and failed else "本项已保存但回读校验失败,已记录,继续下一项。" - if failed else "本项替换、保存和回读校验完成。" - ) - if result.next_project_path is not None: - self._quick_run_phase = "selection" - operator_state = "warning" if failed else "info" if no_match else "success" - instruction = ( - outcome + "下一项将检查并打开目标工程(切换前请保存并关闭当前工程):" - f"{result.next_project_path}" - f"{f';图页 {result.next_schematic_name}:{result.next_sheet_number}' if result.next_schematic_name else ''}" - f";替换 {result.next_old_part_number} 为 {result.next_new_part_number}。" - ) - self.run_panel.quick_run_button.setText("自动执行下一条") - else: - progress = self.service.quick_run_progress(self._task_id or "") - missed = getattr(progress, "no_match_items", 0) - failed_count = getattr(progress, "failed_items", 0) - self._quick_run_phase = "retry" if failed_count else "complete" - operator_state = "warning" if failed_count else "success" - instruction = ( - outcome + f"{'全工程图页队列' if progress.page_addressed else '旧版单页队列'}处理结束:" - f"成功 {progress.saved_items} 项,失败 {failed_count} 项,未命中 {missed} 项。" - + ("可修改选项后重试失败项。" if failed_count else "保存状态请以工程结果栏为准。") - ) - self.run_panel.quick_run_button.setText("重试失败项" if failed_count else "当前队列已完成") - if not failed_count and self.task_list.filter.currentText() == "进行中": - self.task_list.filter.blockSignals(True) - self.task_list.filter.setCurrentText("已完成") - self.task_list.filter.blockSignals(False) - self._refresh_task_list() - self._projects = self.service.projects(self._task_id) if self._task_id else () - self._populate_projects() - self._update_queue_summary() - self._set_operator_message(instruction, operator_state) - if no_match or failed: - self._append_log(result.message) - self._append_log(instruction) - self._update_gates() + def _refresh_live_task_log(self): + if not self.run_panel.toggle_log_button.isChecked(): + return + task_id = self._active_quick_run_task_id or self._task_id + if task_id: + text = '\n'.join(_format_task_log_lines(self.service.tail_log(task_id))) + if text != self._live_log_text: + self.run_panel.log_view.setPlainText(text) + self._live_log_text = text - def _confirm_quick_run(self, phase: str, selected_projects: int, enabled_rules: int) -> bool: - del phase - progress = self._confirmation_progress or self.service.quick_run_progress(self._task_id or "") - if progress.next_project_path is None: - self._show_error(TaskCenterError("quick_run_complete", "all quick-run items are complete")) - return False - title = "确认自动替换" - value_mode = self._confirmation_value_mode - if value_mode is None: - value_mode = "part_label" if self.service.get_task(self._task_id or "").copy_part_number_to_value else "preserve" - message = ( - "将连接 DxDesigner 7.9.5;未运行时自动启动,没有打开工程时自动打开下方目标工程。随后调用原生 Replace Part 和 Library Wins," - "然后恢复实例参数并校验指定图页连接。\n\n" - f"队列起点:{progress.completed_items + 1}/{progress.total_items}{'(首次确认后将按实际图页数展开)' if not progress.next_schematic_name else ''}\n" - f"工程:{progress.next_project_path}\n" - f"图页:{f'{progress.next_schematic_name}:{progress.next_sheet_number}' if progress.next_schematic_name else '确认后只读枚举工程内全部原理图页'}\n" - f"规则:{progress.next_old_part_number} -> {progress.next_new_part_number}\n" - f"Value:{self._confirmed_rule_value_description(progress, value_mode)};继承已有 Value 显示样式。\n" - "图页清单在替换前固定;执行中若新增、删除或重命名图页,会在修改前停止并要求重新确认。\n\n" - "本次确认后连续执行余下队列:未命中仅记录提示并自动跳过,不会要求每项重新点击。真正失败或结果不确定时停止。\n" - "每个工程先校验并备份,再只读枚举图页;全部图页清单固定后才开始串行处理。本项替换通过后自动保存、关闭并重新打开回读核验,再处理下一项。不会同时打开多个工程。\n" - "暂停只发生在图页规则项收尾后,不强行打断写入;继续时不会重复已完成图页。\n" - "有效进度持续更新时不会因总耗时超过 150 秒而中断;持续无进展时先请求安全停止,已开始改图则优先完成校验与收尾。\n" - "本版本不移动或锁定系统鼠标;执行期间请勿编辑、切换或关闭正在处理的 CAD 图页。\n\n" - f"任务包含 {selected_projects} 个已选工程、{enabled_rules} 条启用规则。" - "请确认以上工程均已保存,并同意程序创建原理图精简备份及自动保存。无需预先启动 DxDesigner;请先处理并关闭已有工程,批量模式不会接管你手动打开的工程。" - ) - confirm_label = "确认备份、自动保存并连续执行" - dialog = QMessageBox( - QMessageBox.Icon.Warning, - title, - message, - parent=self, - ) - confirm = dialog.addButton(confirm_label, QMessageBox.ButtonRole.AcceptRole) - dialog.addButton("取消", QMessageBox.ButtonRole.RejectRole) - dialog.exec() - return dialog.clickedButton() is confirm - - def _confirmed_rule_value_description(self, progress, value_mode: str) -> str: - rules = self._execution_rules(self._task_id or "") - rule = next( - ( - item for item in rules - if item.enabled - and item.old_part_number == progress.next_old_part_number - and item.new_part_number == progress.next_new_part_number - ), - None, - ) - if rule is not None and rule.custom_value_enabled: - source = f"写入自定义值 {rule.custom_value}" - else: - source = "复制目标 Part Label" if value_mode == "part_label" else "保留原 Value,不额外改写" - nc_policy = "识别并同步 /NC" if rule is None or rule.sync_nc else "不识别、不追加 /NC" - return f"{source};{nc_policy}" - - def _run_action(self, action: Callable[[str], Any], button: QPushButton) -> None: - if self._task_id and button.isEnabled(): - task_id = self._task_id - self._run_async(lambda: action(task_id), self._apply_run_snapshot, button, expected_task_id=task_id) - - def _active_project_id(self) -> str | None: - return getattr(self._snapshot, "active_project", None) and self._snapshot.active_project.project_id - - def _run_project_action(self, action: Callable[[str, str], Any], button: QPushButton) -> None: - project_id = self.project_table.current_project_id() - if self._task_id and project_id and button.isEnabled(): - task_id = self._task_id - self._run_async(lambda: action(task_id, project_id), self._apply_run_snapshot, button, expected_task_id=task_id, expected_project_id=project_id, project_context="selected") - - def _capture_before(self) -> None: - self._capture_with(self.service.capture_before, "替换前") - - def _capture_after(self) -> None: - self._capture_with(self.service.capture_after, "替换后") - - def _capture_with(self, action: Callable[[str, str, Path], Any], title: str) -> None: - project_id = self._capture_project_id() - button = self.run_panel.capture_before_button if title.startswith("替换前") else self.run_panel.capture_after_button - if self._task_id and project_id and button.isEnabled(): - task_id = self._task_id - probe = self.service.expected_probe_path(task_id, project_id) - context = "active" if self._active_project_id() is not None else "selected" - self._run_async(lambda: action(task_id, project_id, probe), self._apply_run_snapshot, button, expected_task_id=task_id, expected_project_id=project_id, project_context=context) - - def _capture_project_id(self) -> str | None: - active = self._active_project_id() - if active is not None: - return active - selected = self._selected_project() - if self._current_task_status() is TaskStatus.PAUSED and getattr(selected, "status", None) is ProjectStatus.AWAITING_OPERATOR: - return selected.project_id - return None - - def _confirm_attempt(self) -> None: - project_id = self._active_project_id() - if self._task_id and project_id and self.run_panel.confirm_attempt_button.isEnabled(): - task_id = self._task_id - self._run_async(lambda: self.service.confirm_native_attempt(task_id, project_id), self._apply_run_snapshot, self.run_panel.confirm_attempt_button, expected_task_id=task_id, expected_project_id=project_id, project_context="active") - - def _apply_run_snapshot(self, snapshot: Any) -> None: - self._snapshot = snapshot - self._projects = snapshot.projects - self._populate_projects() - self._apply_snapshot(snapshot) - self._refresh_task_list() - self._update_gates() - - def _append_log(self, line: str) -> None: + def _append_log(self, line): self.run_panel.log_view.append(_format_live_log_line(line)) self._live_log_text = None - def _set_task_log(self, lines: tuple[str, ...]) -> None: - text = "\n".join(_format_task_log_lines(lines)) - if text == self._live_log_text: - return - scrollbar = self.run_panel.log_view.verticalScrollBar() - was_at_bottom = scrollbar.value() >= scrollbar.maximum() - 2 - old_position = scrollbar.value() - self.run_panel.log_view.setPlainText(text) - if was_at_bottom: - scrollbar.setValue(scrollbar.maximum()) - else: - scrollbar.setValue(min(old_position, scrollbar.maximum())) - self._live_log_text = text - - def _refresh_live_task_log(self) -> None: - task_id = self._active_quick_run_task_id or self._task_id - if task_id is None: - return - try: - self._set_task_log(self.service.tail_log(task_id)) - except Exception: - return - - def _set_operator_message(self, text: str, state: str = "") -> None: - self.run_panel.operator_band.setProperty("state", state) + def _set_operator_message(self, text, state='info'): + self._message = text self.run_panel.operator_band.setText(text) + self.run_panel.operator_band.setProperty('state', state) self.run_panel.operator_band.style().unpolish(self.run_panel.operator_band) self.run_panel.operator_band.style().polish(self.run_panel.operator_band) - def _update_quick_run_elapsed(self) -> None: - if self._active_quick_run_task_id is None or not self._quick_run_elapsed.isValid(): + def _run_async(self, operation, callback, button=None, *, expected_task_id=None, **_unused): + if self._workers or self._closed: return - seconds = self._quick_run_elapsed.elapsed() // 1000 - queue_feedback = getattr(self.service, '_task_queue_feedback', None) - if queue_feedback is not None: - _, task_id, position, total = queue_feedback - self._active_quick_run_task_id = task_id - self.run_panel.execution_status.setText(f"任务 {position}/{total}:{self.service.get_task(task_id).name} | 已运行 {seconds} 秒") - return - self._refresh_live_task_log() - feedback = self.service.batch_feedback() - if feedback is not None and feedback[0] == self._active_quick_run_task_id: - _, progress, stage = feedback - prefix = "" if self._task_id == feedback[0] else "其他任务:" - self.run_panel.execution_status.setText(f"{prefix}{stage} | 已处理 {progress.completed_items}/{progress.total_items},未命中跳过 {progress.no_match_items} | {seconds} 秒") - rendered = ( - feedback[0], - tuple(progress.completed_project_paths), - tuple(getattr(progress, "project_summaries", ())), - tuple(getattr(progress, "failed_project_summaries", ())), - ) - legacy_rendered = ( - self._batch_rendered == (feedback[0], len(progress.completed_project_paths)) - and not rendered[3] - ) - if self._task_id == feedback[0] and self._batch_rendered != rendered and not legacy_rendered: - self._batch_rendered = rendered - self._projects = self.service.projects(self._task_id) - self._populate_projects() - self._update_gates() - if self._task_id == feedback[0]: - self.run_panel.queue_summary.setText( - f"已处理 {progress.completed_items}/{progress.total_items} 项 · 未命中 {progress.no_match_items} 项" - ) - return - task_text = "当前任务" if self._active_quick_run_task_id == self._task_id else "其他任务" - self.run_panel.execution_status.setText(f"{task_text}的自动替换正在后台执行 | 已运行 {seconds} 秒") - - def _stop_quick_run_feedback(self) -> None: - self._quick_run_timer.stop() - self._active_quick_run_task_id = None - self.run_panel.busy_indicator.hide() - self._batch_stop = None - self.run_panel.stop_queue_button.hide() - - def _run_async( - self, - action: Callable[[], Any], - success: Callable[[Any], None], - busy_button: QAbstractButton | None = None, - *, - expected_task_id: str | None = None, - expected_project_id: str | None = None, - project_context: str | None = None, - selection_operation: bool = False, - ) -> None: + worker = ServiceWorker(operation) + self._workers.add(worker) self._generation += 1 generation = self._generation - domain: object = "selection" if selection_operation else busy_button or ("context", expected_task_id, expected_project_id) - self._domain_generations[domain] = generation - worker = ServiceWorker(action) - self._workers.add(worker) - if busy_button is not None: - self._button_generations[busy_button] = generation - busy_button.setEnabled(False) - if selection_operation: - self._selection_generation = generation - if selection_operation or busy_button in ( - self.run_panel.quick_run_button, - self.run_panel.continue_without_backup_button, - self.run_panel.recover_button, - ): - self._update_gates() - - def ui_is_valid() -> bool: - return not self._ui_destroyed and isValid(self) and isValid(self.run_panel) - - def matches_dispatch() -> bool: - if not ui_is_valid() or self._domain_generations.get(domain) != generation: - return False - if expected_task_id is not None and self._task_id != expected_task_id: - return False - if expected_project_id is not None: - current = self._active_project_id() if project_context == "active" else self.project_table.current_project_id() - return current == expected_project_id - return True - - def apply_success(result: Any) -> None: - if not matches_dispatch(): - return - success(result) - - worker.signals.succeeded.connect(apply_success) - - def apply_failure(error: object) -> None: - current_queue = ( - ui_is_valid() - and self._domain_generations.get(domain) == generation - and busy_button in ( - self.run_panel.quick_run_button, - self.run_panel.continue_without_backup_button, - self.run_panel.recover_button, - ) - ) - if not matches_dispatch() and not current_queue: - return - if busy_button in ( - self.run_panel.quick_run_button, - self.run_panel.continue_without_backup_button, - self.run_panel.recover_button, - ): - self._stop_quick_run_feedback() - if matches_dispatch(): - self._load_task_data() - if busy_button is self.run_panel.copy_value_check: + def valid(): + return not self._closed and generation == self._generation and (expected_task_id is None or expected_task_id == self._task_id) + def succeeded(result): + if valid(): + try: + callback(result) + except Exception as error: + self._show_error(error) + def failed(error): + self._finish_run() + if valid(): self._load_task_data() - self._show_error(error, task_id=expected_task_id, project_id=expected_project_id) - - worker.signals.failed.connect(apply_failure) - - def finished() -> None: + self._show_error(error) + def finished(): self._workers.discard(worker) - owns_button = busy_button is not None and self._button_generations.get(busy_button) == generation - if owns_button: - self._button_generations.pop(busy_button, None) - current_dispatch = self._domain_generations.get(domain) == generation - if current_dispatch: - self._domain_generations.pop(domain, None) - if selection_operation and self._selection_generation == generation: - self._selection_generation = None - if not ui_is_valid() or (busy_button is not None and not isValid(busy_button)): - return - if owns_button: - busy_button.setEnabled(True) - if busy_button in ( - self.run_panel.quick_run_button, - self.run_panel.continue_without_backup_button, - self.run_panel.recover_button, - ): - self._stop_quick_run_feedback() - if not current_dispatch: - return - if owns_button and busy_button in ( - self.run_panel.quick_run_button, - self.run_panel.continue_without_backup_button, - self.run_panel.recover_button, - ) and expected_task_id != self._task_id: - self._refresh_task_list() - self._load_task_data() - self._update_gates() - + if not self._closed: + self._update_gates() + worker.signals.succeeded.connect(succeeded) + worker.signals.failed.connect(failed) worker.signals.finished.connect(finished) - self._pool.start(worker) - - def _show_error( - self, - error: object, - *, - task_id: str | None = None, - project_id: str | None = None, - ) -> None: - stable_error = error if isinstance(error, TaskCenterError) else self.service.report_ui_error(error if isinstance(error, BaseException) else RuntimeError(str(error))) - if stable_error.code == "quick_run_complete": - self._stop_quick_run_feedback() - self._quick_run_phase = "complete" - self.run_panel.quick_run_button.setText("当前队列已完成") - message = "所选任务的替换队列已经完成,无需重复执行;实际图页范围和保存状态请以队列摘要及工程结果栏为准。" - self._set_operator_message(message, "success") - self._append_log(message) - self._update_gates() - return - self._last_error_task_id = task_id or self._task_id - current_context = task_id is None or task_id == self._task_id - if current_context: - self._backup_override_task_id = ( - self._last_error_task_id if stable_error.code == "quick_run_backup" else None - ) - self._last_error_project_id = project_id - if self._last_error_project_id is None and current_context: - self._last_error_project_id = self.project_table.current_project_id() or self._capture_project_id() - detail = ERROR_TEXT.get(stable_error.code, "操作未完成,请查看日志了解详细原因。") - reason = " ".join(stable_error.message.split())[:500] - context = "" - if self._last_error_task_id and stable_error.code.startswith("quick_run_"): - try: - progress = self.service.quick_run_progress(self._last_error_task_id) - if progress.next_project_path is not None: - context = ( - f"\n当前队列项:{progress.next_project_path} | " - f"{progress.next_old_part_number} -> {progress.next_new_part_number}" - ) - except Exception: - context = "" - write_state = "" - if stable_error.code in {"quick_run_execution", "quick_run_uncertain", "quick_run_pending"}: - write_state = "\n写入状态:不能假定图页未修改,请以执行证据和人工核对结果为准。" - message = f"操作失败:{detail}\n具体原因:{reason}{context}{write_state}\n错误编号:{stable_error.error_id}" - if current_context: - if stable_error.code.startswith("quick_run_"): - self.run_panel.execution_status.setText( - "执行已停止:本项尚未开始替换。" if stable_error.code in {"quick_run_session", "quick_run_preflight", "quick_run_backup"} - else "执行已停止:替换失败但回滚已验证。" if stable_error.code == "quick_run_rollback_verified" - else "执行已停止:结果待核验。" if stable_error.code in {"quick_run_uncertain", "quick_run_recovery"} - else "执行已停止,请按下方提示处理。" - ) - self._set_operator_message(message, "error") - else: - message = f"后台任务 {self._last_error_task_id}\n{message}" - self._append_log(f"错误:{message}") self._update_gates() - if self.isVisible() and QApplication.platformName().casefold() != "offscreen": - dialog = QMessageBox(QMessageBox.Icon.Critical, "任务中心错误", message, parent=self) - if stable_error.traceback_detail: - dialog.setDetailedText(stable_error.traceback_detail) - log = dialog.addButton("查看日志", QMessageBox.ButtonRole.ActionRole) - close = dialog.addButton(QMessageBox.StandardButton.Ok) - close.setText("关闭") - dialog.exec() - if dialog.clickedButton() is log and self._last_error_task_id: - task_id = self._last_error_task_id - self._run_async(lambda: self.service.open_task_log(task_id), lambda path: self._append_log(f"日志:{path}"), expected_task_id=task_id) + QThreadPool.globalInstance().start(worker) - -def _nc_sync_log_lines(message: str) -> tuple[str, ...]: - _, marker, details = str(message).partition("NC synced:") - if not marker: - return () - suffix = " (detected /NC and synchronized)" - return tuple( - f"位号 {entry.removesuffix(suffix).strip()},识别到 NC,已同步" - for entry in details.strip().split("; ") - if entry.strip() - ) - - -def _format_task_log_lines(lines: tuple[str, ...]) -> tuple[str, ...]: - return tuple(_format_task_log_line(line) for line in lines) - - -def _format_task_log_line(line: str) -> str: - try: - event = json.loads(line) - except (json.JSONDecodeError, TypeError): - return _aligned_log_line("", "INFO", "legacy", str(line)) - if not isinstance(event, dict): - return _aligned_log_line("", "INFO", "legacy", str(line)) - - timestamp = str(event.get("timestamp_utc") or "").replace("T", " ").removesuffix("Z")[:19] - level = str(event.get("level") or "INFO").upper() - if level not in {"INFO", "WARNING", "ERROR"}: - level = "INFO" - operation = str(event.get("operation") or "") - details = event.get("details") if isinstance(event.get("details"), dict) else {} - message = str(event.get("message") or "").strip() - - if operation == "value_policy_changed": - enabled = bool( - details.get( - "copy_part_label_to_value", - details.get("copy_part_number_to_value", False), - ) - ) - message = ( - "Value 选项已更新:替换后写入目标 Part Label。" - if enabled - else "Value 选项已更新:保留原生替换后的 Value。" - ) - elif operation == "quick_run_prepared": - message = "自动替换运行环境已准备。" - elif operation == "quick_run_executed" and details.get("state") == "no_match": - message = "当前规则在该图页未命中,已正常跳过。" - elif operation == "quick_run_queue_paused": - message = "自动队列已在项目边界暂停。" - elif operation == "confirm_native_attempt": - message = "已确认原生替换操作。" - elif not message: - message = operation.replace("_", " ") or "任务状态已更新。" - - error_id = str(event.get("error_id") or "").strip() - if error_id: - message = f"{message} 错误编号:{error_id}" - return _aligned_log_line(timestamp, level, operation or "task", message) - - -def _format_live_log_line(line: str) -> str: - message = str(line) - level = "ERROR" if message.startswith("错误") else "WARNING" if message.startswith(("失败", "警告")) else "INFO" - return _aligned_log_line(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), level, "ui", message) - - -def _aligned_log_line(timestamp: str, level: str, operation: str, message: str) -> str: - return ( - f"{_fit_log_column(timestamp, 19)} | " - f"{_fit_log_column(level, 7)} | " - f"{_fit_log_column(operation, 28)} | {message}" - ) - - -def _fit_log_column(value: str, width: int) -> str: - text = str(value) - if len(text) <= width: - return text.ljust(width) - return f"{text[: width - 3]}..." - - -def _directory_identity(value: str | Path | None) -> str | None: - text = str(value).strip() if value is not None else "" - if not text: - return None - return os.path.normcase(os.path.abspath(os.path.normpath(text))) - - -__all__ = ["TrialTaskCenterWindow"] + def _show_error(self, error, **_unused): + stable = error if isinstance(error, TaskCenterError) else self.service.report_ui_error(error) + message = f'{ERROR_TEXT.get(stable.code, "操作未完成")}\n{stable.message}\n错误编号:{stable.error_id}' + self._set_operator_message(message, 'error') + self._append_log(message) + self._update_gates() + if self.isVisible() and QApplication.platformName().casefold() != 'offscreen': + QMessageBox.warning(self, '操作未完成', message) diff --git a/src/dx_productivity/trial_task_center/ui/messages.py b/src/dx_productivity/trial_task_center/ui/messages.py new file mode 100644 index 0000000..451a21f --- /dev/null +++ b/src/dx_productivity/trial_task_center/ui/messages.py @@ -0,0 +1,141 @@ +"""Operator messages and log formatting shared by the desktop UI.""" +from datetime import datetime +import json + +ERROR_TEXT = { + "task_required": "请先选择任务。", + "directory_required": "请先选择工程目录。", + "discovery_root_locked": "旧目录已有执行记录,不能在同一任务中更换目录;请新建任务。", + "disposable_copy_required": "请确认所选工程已保存,并允许程序在执行前创建完整备份。", + "selected_project_required": "请至少选择一个可用工程。", + "enabled_rule_required": "请至少添加并启用一条替换规则。", + "active_project_exists": "已有其他工程正在处理,请等待其结束。", + "probe_baseline_missing": "未找到探测结果文件,请先在 DxDesigner 中运行只读探测。", + "profile_unchanged": "探测结果没有更新,请重新运行只读探测。", + "comparison_failed": "替换前后数据核验失败,请查看日志和错误编号。", + "rules_locked": "任务执行期间不能修改替换规则。", + "task_running": "请先暂停任务,再删除任务。", + "task_not_deleted": "只有“已删除”中的任务可以彻底删除;任务状态可能已变化,请刷新后重试。", + "permanent_delete_confirmation": "彻底删除需要明确确认,此操作不能通过“恢复”撤销。", + "quick_run_pending": "检测到可能已改动图纸的旧替换任务,请先核对工程后再继续。", + "quick_run_status": "执行状态文件无效,已拒绝覆盖,请查看日志。", + "quick_run_execution": "当前替换步骤失败,图页可能已被修改,请查看具体原因和执行证据。", + "quick_run_rollback_verified": "替换校验失败,但原生回滚已验证,工程已恢复到替换前状态;请排除原因后重新确认。", + "quick_run_preflight": "当前项在替换前校验失败,未调用原生替换;后续项已停止。请核对目标料号及库配置,排除原因后再确认继续。", + "quick_run_session": "本次执行在启动或工程检查阶段停止,尚未开始本项替换。请按具体原因处理后重试。", + "quick_run_complete": "当前任务中的替换规则已经全部完成。", + "quick_run_cscript": "未找到 Windows 脚本运行组件,无法连接 DxDesigner。", + "quick_run_command": "替换命令文件无效,请查看日志。", + "quick_run_uncertain": "无法确认本次替换结果,请使用“核验并恢复中断任务”,不要直接清锁重跑。", + "quick_run_recovery": "中断任务恢复未通过,原保护状态仍保留。", + "quick_run_recovery_confirmation": "请先确认核验恢复范围。", + "quick_run_busy": "已有替换操作正在执行,请等待当前操作结束。", + "quick_run_manual_operation": "此任务使用自动队列,不能混用人工流程的跳过、采集和重试操作。", + "quick_run_task_state": "当前任务状态不允许执行自动队列,请先恢复任务或检查其状态。", + "quick_run_backup": "本项工程精简备份未通过,队列已停止,尚未开始本项替换。可排除原因后重试,或使用“忽略备份失败并继续”。", + "quick_run_queue_progress": "队列进度异常,已停止自动继续。", + "quick_run_options_locked": "已有自动队列证据,工程目录、工程选择及规则选项已冻结;请先完成或恢复当前队列。", + "quick_run_selection_changed": "待执行工程、规则或 Value 选项发生变化,请重新确认。", + "evidence_missing": "没有找到当前任务的执行证据。", + "duplicate_source": "同一旧料号只能配置一次。", + "mapping_chain": "替换规则不能形成连续替换链。", + "mapping_cycle": "替换规则不能形成循环。", + "equal_rule": "旧料号和新料号不能相同。", + "blank_part_number": "旧料号和新料号不能为空。", + "custom_value": "勾选自定义 Value 后必须填写内容,且不能包含制表符或换行。", + "task_name": "任务名称为空或已经存在。", +} + +DIALOG_ERROR_TEXT = { + "duplicate_source": "该旧料号已经存在,请修改现有规则或输入其他旧料号。", + "mapping_chain": "目标料号同时是另一条规则的旧料号,请拆分任务后再执行。", + "mapping_cycle": "这些规则形成了循环,请修改旧料号或新料号。", + "equal_rule": "旧料号和新料号不能相同。", + "blank_part_number": "请输入旧料号和新料号。", + "custom_value": "勾选自定义 Value 后必须填写内容,且不能包含制表符或换行。", + "task_name": "任务名称为空或已经存在,请使用其他名称。", +} + + +def _nc_sync_log_lines(message: str) -> tuple[str, ...]: + _, marker, details = str(message).partition("NC synced:") + if not marker: + return () + suffix = " (detected /NC and synchronized)" + return tuple( + f"位号 {entry.removesuffix(suffix).strip()},识别到 NC,已同步" + for entry in details.strip().split("; ") + if entry.strip() + ) + + +def _format_task_log_lines(lines: tuple[str, ...]) -> tuple[str, ...]: + return tuple(_format_task_log_line(line) for line in lines) + + +def _format_task_log_line(line: str) -> str: + try: + event = json.loads(line) + except (json.JSONDecodeError, TypeError): + return _aligned_log_line("", "INFO", "legacy", str(line)) + if not isinstance(event, dict): + return _aligned_log_line("", "INFO", "legacy", str(line)) + + timestamp = str(event.get("timestamp_utc") or "").replace("T", " ").removesuffix("Z")[:19] + level = str(event.get("level") or "INFO").upper() + if level not in {"INFO", "WARNING", "ERROR"}: + level = "INFO" + operation = str(event.get("operation") or "") + details = event.get("details") if isinstance(event.get("details"), dict) else {} + message = str(event.get("message") or "").strip() + + if operation == "value_policy_changed": + enabled = bool( + details.get( + "copy_part_label_to_value", + details.get("copy_part_number_to_value", False), + ) + ) + message = ( + "Value 选项已更新:替换后写入目标 Part Label。" + if enabled + else "Value 选项已更新:保留原生替换后的 Value。" + ) + elif operation == "quick_run_prepared": + message = "自动替换运行环境已准备。" + elif operation == "quick_run_executed" and details.get("state") == "no_match": + message = "当前规则在该图页未命中,已正常跳过。" + elif operation == "quick_run_queue_paused": + message = "自动队列已在项目边界暂停。" + elif operation == "confirm_native_attempt": + message = "已确认原生替换操作。" + elif not message: + message = operation.replace("_", " ") or "任务状态已更新。" + + error_id = str(event.get("error_id") or "").strip() + if error_id: + message = f"{message} 错误编号:{error_id}" + return _aligned_log_line(timestamp, level, operation or "task", message) + + +def _format_live_log_line(line: str) -> str: + message = str(line) + level = "ERROR" if message.startswith("错误") else "WARNING" if message.startswith(("失败", "警告")) else "INFO" + return _aligned_log_line(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), level, "ui", message) + + +def _aligned_log_line(timestamp: str, level: str, operation: str, message: str) -> str: + return ( + f"{_fit_log_column(timestamp, 19)} | " + f"{_fit_log_column(level, 7)} | " + f"{_fit_log_column(operation, 28)} | {message}" + ) + + +def _fit_log_column(value: str, width: int) -> str: + text = str(value) + if len(text) <= width: + return text.ljust(width) + return f"{text[: width - 3]}..." + + diff --git a/src/dx_productivity/trial_task_center/ui/project_summary.py b/src/dx_productivity/trial_task_center/ui/project_summary.py new file mode 100644 index 0000000..cdf4f4d --- /dev/null +++ b/src/dx_productivity/trial_task_center/ui/project_summary.py @@ -0,0 +1,42 @@ +"""Read-only identity and result of the task's single bound project.""" +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget + + +class ProjectSummary(QWidget): + def __init__(self, parent=None): + super().__init__(parent) + self.name = QLabel('未选择任务') + self.path = QLabel(objectName='boundProjectPath') + self.path.setWordWrap(True) + self.path.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + self.state = QLabel() + self.state.setWordWrap(True) + self.refresh_button = QPushButton('重新读取工程', objectName='refreshBoundProject') + heading = QHBoxLayout() + heading.addWidget(self.name, 1) + heading.addWidget(self.refresh_button) + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.addLayout(heading) + layout.addWidget(self.path) + layout.addWidget(self.state) + + def populate(self, context): + if context is None: + self.name.setText('未选择任务') + self.path.clear() + self.state.setText('点击新建,在弹窗中读取并选择工程。') + return + project = context.project + self.name.setText(project.display_name if project else context.task.name) + self.path.setText(str(project.path) if project else '') + if context.legacy: + self.state.setText('历史任务仅供查看;请通过新建弹窗为工程创建独立任务。') + elif not project.available: + self.state.setText('工程不可用,请检查原路径后重新读取。') + else: + labels = {'draft': '待配置', 'ready': '待执行', 'running': '执行中', 'paused': '已暂停', + 'completed': '已完成', 'failed': '失败', 'deleted': '已删除'} + self.state.setText(f'工程已绑定 · {labels.get(context.task.status.value, context.task.status.value)}' + + (f' · {project.summary}' if project.summary else '')) diff --git a/src/dx_productivity/trial_task_center/ui/run_panel.py b/src/dx_productivity/trial_task_center/ui/run_panel.py index 5c8ea84..1bf22d4 100644 --- a/src/dx_productivity/trial_task_center/ui/run_panel.py +++ b/src/dx_productivity/trial_task_center/ui/run_panel.py @@ -1,71 +1,48 @@ -"""Operator guidance, commands, and read-only task log widgets.""" - -from __future__ import annotations - -from PySide6.QtWidgets import QCheckBox, QHBoxLayout, QLabel, QProgressBar, QPushButton, QTextEdit, QToolButton, QVBoxLayout, QWidget +"""Explicit single-task execution, recovery and safe pause controls.""" +from PySide6.QtWidgets import (QCheckBox, QHBoxLayout, QLabel, QProgressBar, + QPushButton, QTextEdit, QToolButton, QVBoxLayout, QWidget) class RunPanel(QWidget): - def __init__(self) -> None: + def __init__(self): super().__init__() - self.operator_band = QLabel("请选择任务,并扫描工程目录。", objectName="operatorBand") - self.operator_band.setWordWrap(True) - self.queue_summary = QLabel("未选择任务", objectName="queueSummary") - self.execution_status = QLabel("空闲", objectName="executionStatus") + self.queue_summary = QLabel('未选择任务', objectName='queueSummary') + self.execution_status = QLabel('空闲', objectName='executionStatus') self.execution_status.setWordWrap(True) - self.busy_indicator = QProgressBar(objectName="quickRunBusyIndicator") + self.operator_band = QLabel(objectName='operatorBand') + self.operator_band.setWordWrap(True) + self.busy_indicator = QProgressBar(objectName='quickRunBusyIndicator') self.busy_indicator.setRange(0, 0) self.busy_indicator.setTextVisible(False) self.busy_indicator.setFixedHeight(4) self.busy_indicator.hide() - self.start_button = QPushButton("开始任务", objectName="startTaskButton") - self.quick_run_button = QPushButton("确认并执行替换", objectName="quickRunButton") - self.stop_queue_button = QPushButton("完成当前项后暂停", objectName="stopQueueButton") - self.stop_queue_button.hide() - self.continue_without_backup_button = QPushButton( - "忽略备份失败并继续", objectName="continueWithoutBackupButton" - ) - self.continue_without_backup_button.setToolTip( - "仅在精简原理图备份失败后启用。继续执行将无法保证该工程可从本工具备份回滚。" - ) - self.continue_without_backup_button.hide() - self.recover_button = QPushButton("核验并恢复中断任务", objectName="recoverQuickRunButton") - self.recover_button.setToolTip("先备份并核验已保存工程;不重复调用原生替换。混合状态或连接异常时保留保护。") - self.pause_button = QPushButton("暂停", objectName="pauseTaskButton") - self.resume_button = QPushButton("继续", objectName="resumeTaskButton") - self.capture_before_button = QPushButton("采集替换前结果", objectName="captureBeforeButton") - self.confirm_attempt_button = QPushButton("已完成原生替换", objectName="confirmNativeAttemptButton") - self.capture_after_button = QPushButton("采集替换后结果", objectName="captureAfterButton") - self.copy_value_check = QCheckBox("替换后将 Part Label 写入 Value", objectName="copyPartNumberToValue") - self.copy_value_check.setToolTip("勾选:将替换后目标器件的 Part Label 写入 Value。未勾选:保留原生替换后的 Value,不创建缺失字段。两种模式均继承已有 Value 的位置、字体等显示样式。队列生成后不可更改。") - self.toggle_log_button = QToolButton(objectName="toggleLogButton") - self.toggle_log_button.setText("显示日志") + self.quick_run_button = QPushButton('执行当前任务', objectName='quickRunButton') + self.stop_queue_button = QPushButton('完成当前项后暂停', objectName='stopQueueButton') + self.retry_button = QPushButton('重试失败项', objectName='retryTaskItems') + self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton') + self.copy_value_check = QCheckBox('替换后将 Part Label 写入 Value', objectName='copyPartNumberToValue') + self.copy_value_check.setToolTip('每行自定义 Value 优先;同步 NC 由每行开关控制。开始执行后选项冻结。') + self.toggle_log_button = QToolButton(objectName='toggleLogButton') + self.toggle_log_button.setText('显示日志') self.toggle_log_button.setCheckable(True) - self.reset_layout_button = QToolButton(objectName="resetLayoutButton") - self.reset_layout_button.setText("重置布局") - self.log_view = QTextEdit(objectName="logView") + self.reset_layout_button = QToolButton(objectName='resetLayoutButton') + self.reset_layout_button.setText('重置布局') + self.log_view = QTextEdit(objectName='logView') self.log_view.setReadOnly(True) - self.log_view.setMinimumHeight(40) + self.log_view.setMinimumHeight(60) self.log_view.hide() self.toggle_log_button.toggled.connect(self.log_view.setVisible) - self.toggle_log_button.toggled.connect(lambda checked: self.toggle_log_button.setText("收起日志" if checked else "显示日志")) - commands = QHBoxLayout() - for button in ( - self.quick_run_button, - self.stop_queue_button, - self.continue_without_backup_button, - self.recover_button, - ): - commands.addWidget(button) - commands.addStretch(1) - commands.addWidget(self.toggle_log_button) - commands.addWidget(self.reset_layout_button) + self.toggle_log_button.toggled.connect(lambda on: self.toggle_log_button.setText('收起日志' if on else '显示日志')) + buttons = QHBoxLayout() + for button in (self.quick_run_button, self.retry_button, self.recover_button, self.stop_queue_button): + buttons.addWidget(button) + buttons.addStretch() + buttons.addWidget(self.toggle_log_button) + buttons.addWidget(self.reset_layout_button) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) - layout.addWidget(self.queue_summary) - layout.addWidget(self.execution_status) - layout.addWidget(self.busy_indicator) - layout.addWidget(self.operator_band) - layout.addWidget(self.copy_value_check) - layout.addLayout(commands) + for widget in (self.queue_summary, self.execution_status, self.busy_indicator, + self.operator_band, self.copy_value_check): + layout.addWidget(widget) + layout.addLayout(buttons) layout.addWidget(self.log_view, 1) diff --git a/tests/v1_1/test_project_task_ui.py b/tests/v1_1/test_project_task_ui.py index 948364f..1f67362 100644 --- a/tests/v1_1/test_project_task_ui.py +++ b/tests/v1_1/test_project_task_ui.py @@ -61,7 +61,7 @@ def test_original_window_edits_target_plan_and_nc_without_export(qtbot, tmp_path rows = service.target_plan(task.task_id) assert rows[0].enabled and not rows[0].sync_nc and not rows[1].enabled assert not table.dirty - assert not window.directory_path.isEnabled() + assert window.findChild(type(window.plan_panel.find_text), 'directoryPath') is None assert window.run_panel.quick_run_button.isEnabled() assert not (tmp_path / 'plan.xlsx').exists() # Switching tasks must not conceal an unsaved draft from group execution. @@ -70,3 +70,35 @@ def test_original_window_edits_target_plan_and_nc_without_export(qtbot, tmp_path assert window.plan_panel.has_unsaved_plan((task.task_id,)) window.close() store.close() + + +def test_single_project_summary_and_local_gates_do_not_query_service_again(qtbot, tmp_path, monkeypatch): + from dx_productivity.trial_task_center.service import TaskCenterService + from dx_productivity.trial_task_center.store import TaskStore + from dx_productivity.trial_task_center.logging_setup import configure_logging + from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow + from PySide6.QtWidgets import QPushButton, QTableWidget + + root = tmp_path / 'projects' + root.mkdir() + path = root / 'board.prj' + path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='ascii') + store = TaskStore(tmp_path / 'tasks.db') + service = TaskCenterService(store, configure_logging(tmp_path / 'data')) + task = service.create_project_tasks(root)[0] + service.add_rule(task.task_id, 'OLD', 'NEW') + window = TrialTaskCenterWindow(service) + qtbot.addWidget(window) + window.open_task(task.task_id) + assert window.findChild(QTableWidget, 'projectTable') is None + for name in ('scanProjectsButton', 'selectAllProjectsButton', 'clearProjectsButton', + 'retryProjectButton', 'skipProjectButton', 'startTaskButton'): + assert window.findChild(QPushButton, name) is None + assert window.project_summary.path.text() == str(path) + assert window.run_panel.quick_run_button.text() == '执行当前任务' + monkeypatch.setattr(service, 'get_task', lambda *a: (_ for _ in ()).throw(AssertionError('extra DB read'))) + monkeypatch.setattr(service, 'projects', lambda *a: (_ for _ in ()).throw(AssertionError('extra DB read'))) + window._update_gates() + assert window.run_panel.quick_run_button.isEnabled() + window.close() + store.close()