From 734a10b5c727e13f6f8ba9b1f058c6f6e865feaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Sun, 11 Oct 2026 09:55:31 +0800 Subject: [PATCH] feat: add compact floating UI and reference PDF palette --- .../compact-pdf-acceptance-20261011.md | 45 +++++++ docs/user/PDF_export.md | 4 + docs/user/一叶知秋_重构版_更新说明.md | 12 ++ .../features/pdf_export/engine.py | 9 +- .../features/pdf_export/exporter.py | 10 +- .../features/pdf_export/models.py | 3 + .../features/pdf_export/native_profile.py | 47 +++++++ .../features/pdf_export/settings.py | 5 + src/dx_productivity/ui/app.py | 13 +- src/dx_productivity/ui/bom_page.py | 2 +- src/dx_productivity/ui/floating_button.py | 87 +++++++++++++ src/dx_productivity/ui/inspection_page.py | 2 +- src/dx_productivity/ui/main_window.py | 86 +++++++++--- src/dx_productivity/ui/pdf_export_page.py | 39 +++++- .../ui/property_change_page.py | 2 +- .../ui/property_visibility_page.py | 2 +- src/dx_productivity/ui/refdes_page.py | 22 +++- src/dx_productivity/ui/theme.py | 25 ++-- tests/features/test_pdf_export.py | 33 ++++- tests/features/test_pdf_export_settings.py | 23 +++- tests/features/test_pdf_native_palette.py | 49 +++++++ tests/ui/test_compact_floating_window.py | 106 +++++++++++++++ tests/ui/test_main_window.py | 6 +- tests/ui/test_pdf_export_page.py | 41 ++++++ tools/acceptance/compact_window.py | 122 ++++++++++++++++++ tools/acceptance/pdf_palette.py | 109 ++++++++++++++++ 26 files changed, 846 insertions(+), 58 deletions(-) create mode 100644 docs/testing/compact-pdf-acceptance-20261011.md create mode 100644 src/dx_productivity/features/pdf_export/native_profile.py create mode 100644 src/dx_productivity/ui/floating_button.py create mode 100644 tests/features/test_pdf_native_palette.py create mode 100644 tests/ui/test_compact_floating_window.py create mode 100644 tools/acceptance/compact_window.py create mode 100644 tools/acceptance/pdf_palette.py diff --git a/docs/testing/compact-pdf-acceptance-20261011.md b/docs/testing/compact-pdf-acceptance-20261011.md new file mode 100644 index 0000000..b3e4626 --- /dev/null +++ b/docs/testing/compact-pdf-acceptance-20261011.md @@ -0,0 +1,45 @@ +# 紧凑窗口、悬浮入口和 PDF 配色验收(2026-10-11) + +## 实现 + +- PDF 导出位于设置上方;页面路由和菜单打开的功能一致。 +- 默认窗口 960 × 600,最小 860 × 540;字体、间距和表格高度同步缩小,位号规则支持滚动。 +- 点击收起或原生最小化后显示置顶悬浮入口;拖动移动、点击展开、右键打开或退出。收起保留页面和输入,桥接继续工作。 +- PDF 默认采用 mentor_PDF_output 的工程参考颜色,另可选择原生配色。配色随设置保存,手动导出和自动导出共用设置。 +- 导出进程使用本次运行目录下独立的 DxDesigner.xml 和 WDIR;继承本机 Mentor 环境,未写入工程或全局颜色配置。 +- “打开输出目录”打开当前填写的目录,尚未创建时自动创建;导出期间可用,打开失败时显示原因。 + +## 验收结果 + +| 检查 | 结果 | 证据 | +|---|---|---| +| 源码回归 | 410 passed | build/test-evidence/compact-pdf-source.xml | +| 便携包 | 16 passed;九个页面及 CLI 在 PATH 不含 Python 时运行 | build/test-evidence/compact-pdf-packaged.xml | +| 紧凑布局 | 默认尺寸和最小尺寸所有页按钮可访问;PDF 新增控件正常显示 | tests/ui/test_compact_floating_window.py、build/ui-previews/compact/pdf-latest.png、pdf-minimum.png | +| 真实 GUI Start | 点击新版包的 Start,收到持久注册和当前宿主加载回执;关闭注册窗口后配置仍指向新版 | compact-floating-20261011/latest-package-ui.json | +| 原生菜单与桥接 | Sheet Menu Bar 的 PDF 动作打开新版 exe,桥接当前工程;原生 Dx 实例 PID 44008 保持运行 | latest-package-ui.json、native-ui.json | +| 悬浮窗 | 实机 125% DPI 下客户区 1200 × 750;真实拖动移动 30 × 20 像素,未误展开;展开保留 PDF 页,快照刷新成功;系统最小化恢复成功 | compact-floating-20261011/native-ui.json | +| 收起期间桥接 | apply-progress.json 更新继续增长;最终新版 GUI PID 66148 留在悬浮状态 | native-ui.json | +| 打开目录 | 真实按钮打开资源管理器中的当前工程输出目录;空值禁用、未创建目录创建、失败消息及导出期间可用由回归覆盖 | latest-package-ui.json、tests/ui/test_pdf_export_page.py | +| 原生 PDF 范围 | Audio 整工程 1 页;PON 当前 03_FLASH 页 1 页、指定 PON Block 17 页、整工程 24 页 | pdf-palette-20261011/palette-acceptance.json | +| 参考颜色 | 同一个 Audio 副本分别使用本工具与原工具参考配置导出,RGB 绘图颜色及出现次数一致 | palette-acceptance.json | +| exe 原生出图 | 冻结 exe 的自动导出命令实际生成一页 PDF,配色与参考样例一致;PATH 不含 Python,保留 Mentor 运行库目录 | frozen-palette-acceptance.json | +| 配置兼容 | 旧配置缺少配色字段时使用参考配色;原生配色持久化,保存事件转发原设置;父进程环境不变 | tests/features/test_pdf_export_settings.py、test_pdf_native_palette.py | + +外部证据目录均在 `%LOCALAPPDATA%/DxProductivity/acceptance` 下。本轮 PDF 使用上一轮的 Audio / PON 独立副本;用户当前工程只做快照读取、菜单和界面操作。 + +Audio 样例的主要 RGB 绘图颜色次数:蓝色 990、紫色 271、青绿色 288、绿色 65、红色 380、属性青色 286。工程中显式指定的其他颜色仍遵循原生规则。 + +## 发布包 + +- 目录:`release/一叶知秋_重构版_悬浮窗与PDF配色修复版`。 +- ZIP:同目录名加 `_Win11_x64.zip`。 +- SHA-256 清单:同目录名加 `_SHA256SUMS.txt`。 +- ZIP SHA-256:`f01336492799ac7afb82e5be6e4773cb69129b6fcd190aab2a0e3593efc4659c`。 +- exe SHA-256:`6da01d9e0a2e6fce35b60c0348d511cb44683eb39d885b85afd8cf97faa315b1`。 + +## 适用边界 + +颜色对齐通过原生参考样例和 RGB 内容比较验证;工程中显式对象颜色继续优先。三种导出范围保留本工具的当前工程绑定和精确书签筛页,没有引入原工具的批量扫描流程。 + +本机原生字体造成的中文乱码或裁切仍存在,已在渲染样例中记录;本轮处理配色。原生 PDF 引擎需要本机 Mentor 安装、许可和运行库路径。仅保留 Windows 系统 PATH 时引擎缺少 DLL;保留 Mentor 运行库、移除 Python 路径后,冻结 exe 导出通过。 diff --git a/docs/user/PDF_export.md b/docs/user/PDF_export.md index e3e8da5..81940c2 100644 --- a/docs/user/PDF_export.md +++ b/docs/user/PDF_export.md @@ -10,6 +10,10 @@ 默认输出到 `%LOCALAPPDATA%\DxProductivity\pdf-output` 下按工程区分的目录。可在页面选择其他输出目录,但不能选择源工程目录或其子目录。覆盖现有 PDF 前,手动导出会先询问;自动导出只在新 PDF 验证成功后替换原文件。 +点击“打开输出目录”可在资源管理器中打开当前填写的目录;尚未创建的目录会自动创建,导出过程中也可使用该按钮。 + +PDF 配色默认使用“工程参考配色(mentor_PDF_output)”:红色连线、青绿色引脚、蓝色图形和文字、紫色方框、绿色网络名。颜色通过本次导出进程的独立配置加载;原理图中明确指定的对象颜色仍按原生规则显示。也可选择“原生配色”,配色选择会保存,并用于保存工程后自动导出。 + “保存工程后自动导出”默认关闭。EE iCDB 工程会即时保存设计变更,工具收到原生变更事件、等待变更稳定后导出当前数据库;传统文件工程在保存完成后导出。重复通知会合并,已有导出进程结束后才执行下一次导出。监听器按配置中的工程路径绑定实例,关闭开关后自行退出。导出状态显示在 DxDesigner 状态栏,详细记录位于 `%LOCALAPPDATA%\DxProductivity\pdf-runs`。 PDF 使用本机 `sch2pdf.exe`、DxDesigner 配置和许可。原生出图可能更新工程数据库或运行记录;发布 PDF 前工具会检查工程文件变化,未确认的变化会阻止发布。 diff --git a/docs/user/一叶知秋_重构版_更新说明.md b/docs/user/一叶知秋_重构版_更新说明.md index 3924b70..beb4b6e 100644 --- a/docs/user/一叶知秋_重构版_更新说明.md +++ b/docs/user/一叶知秋_重构版_更新说明.md @@ -1,5 +1,17 @@ # 一叶知秋_重构版 更新说明 +## 紧凑窗口与悬浮入口 + +- 左侧 PDF 导出移到设置上方。 +- 默认窗口缩小为 960 × 600,可缩到 860 × 540;字体、导航和控件间距同步收紧,规则区和表格支持滚动。 +- 点击右上角“收起为悬浮窗”或窗口最小化,会显示置顶的叶子悬浮入口。拖动入口可移动,点击可恢复当前页面、窗口位置和输入内容;收起期间桥接及后台任务继续运行。 +- 右键悬浮入口可打开或退出工具;主窗口关闭按钮用于退出。 + +## PDF 配色与输出目录 + +- PDF 默认采用 mentor_PDF_output 的工程参考配色,也可选择原生配色;手动导出与保存后自动导出使用同一设置。 +- PDF 页新增“打开输出目录”按钮,可打开当前填写的目录,尚未创建时自动创建。 + ## 本版变更(原生迁移版) - 打开完整工具包中的 `DxDesignerTools.exe`,点击顶部 **Start**,即可自动加入 DxDesigner 菜单。已打开的 DxDesigner 会加载菜单;未打开时工具会带菜单配置启动它。 diff --git a/src/dx_productivity/features/pdf_export/engine.py b/src/dx_productivity/features/pdf_export/engine.py index 1a8167b..96fe46e 100644 --- a/src/dx_productivity/features/pdf_export/engine.py +++ b/src/dx_productivity/features/pdf_export/engine.py @@ -89,7 +89,7 @@ def _create_job(process: _WindowsProcess): def _start_windows_process( - args: Sequence[str], cwd: Path, stdout, stderr, cancel: Event + args: Sequence[str], cwd: Path, stdout, stderr, cancel: Event, env: dict[str, str] | None = None ): import _winapi import msvcrt @@ -125,7 +125,7 @@ def _start_windows_process( None, True, win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW, - None, + env, os.fspath(cwd), startup, ) @@ -176,6 +176,8 @@ def run_engine( cancel: Event, timeout: float, on_event: Callable[[str], None] | None = None, + *, + env: dict[str, str] | None = None, ) -> int: log_dir = Path(log_dir) log_dir.mkdir(parents=True, exist_ok=True) @@ -186,7 +188,7 @@ def run_engine( with (log_dir / "stdout.log").open("wb") as stdout, (log_dir / "stderr.log").open("wb") as stderr: try: if os.name == "nt": - process, job = _start_windows_process(args, Path(cwd), stdout, stderr, cancel) + process, job = _start_windows_process(args, Path(cwd), stdout, stderr, cancel, env) else: process = subprocess.Popen( args, @@ -194,6 +196,7 @@ def run_engine( stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr, + env=env, ) emit(f"原生引擎已启动,PID={process.pid}") last_heartbeat = started diff --git a/src/dx_productivity/features/pdf_export/exporter.py b/src/dx_productivity/features/pdf_export/exporter.py index d9cc55c..44c94ca 100644 --- a/src/dx_productivity/features/pdf_export/exporter.py +++ b/src/dx_productivity/features/pdf_export/exporter.py @@ -17,6 +17,7 @@ from pypdf import PdfReader, PdfWriter from .engine import discover_engine, run_engine from .models import ExportScope, PdfExportResult, PdfExportSettings +from .native_profile import prepare_environment HEADER_LIMIT = 512 * 1024 @@ -423,6 +424,7 @@ def export_project( ) stage = output_dir / f".{final_path.stem}.{uuid.uuid4().hex[:8]}.partial.pdf" command = build_command(engine, project, stage, settings.scope, block_name) + environment = prepare_environment(run_dir, settings.print_theme) _write_json( run_dir / "request.json", { @@ -433,6 +435,9 @@ def export_project( if settings.scope is ExportScope.CURRENT_PAGE else "", "output": str(final_path), "engine": str(engine), + "print_theme": settings.print_theme, + "native_profile": str(run_dir / "native-profile" / "DxDesigner.xml") + if environment is not None else "", "command": command, }, ) @@ -440,8 +445,9 @@ def export_project( emit("核验当前工程和输出目录") before = _fingerprint(source_root, cancel, database_relative, unverified_native) _write_json(run_dir / "source-before.json", before) - emit("直接调用本机 sch2pdf.exe;读取当前工程配置") - return_code = run_engine(command, source_root, run_dir, cancel, timeout, emit) + palette = "工程参考配色" if settings.print_theme == "reference" else "原生配色" + emit(f"直接调用本机 sch2pdf.exe;使用{palette}") + return_code = run_engine(command, source_root, run_dir, cancel, timeout, emit, env=environment) if return_code != 0: raise RuntimeError(f"原生引擎退出码 {return_code};请检查工程、许可和运行日志") if cancel.is_set(): diff --git a/src/dx_productivity/features/pdf_export/models.py b/src/dx_productivity/features/pdf_export/models.py index 8e3c97d..88521fb 100644 --- a/src/dx_productivity/features/pdf_export/models.py +++ b/src/dx_productivity/features/pdf_export/models.py @@ -19,8 +19,11 @@ class PdfExportSettings: output_dir: Path auto_export: bool = False engine_path: Path | None = None + print_theme: str = "reference" def __post_init__(self) -> None: + if self.print_theme not in {"reference", "original"}: + raise ValueError("不支持的 PDF 配色") values = [str(self.project_path), str(self.output_dir), self.block_name] if self.engine_path is not None: values.append(str(self.engine_path)) diff --git a/src/dx_productivity/features/pdf_export/native_profile.py b/src/dx_productivity/features/pdf_export/native_profile.py new file mode 100644 index 0000000..26eb8ef --- /dev/null +++ b/src/dx_productivity/features/pdf_export/native_profile.py @@ -0,0 +1,47 @@ +"""Provide the reference drawing palette to one native export process.""" +from __future__ import annotations + +import os +from pathlib import Path +import xml.etree.ElementTree as ET + + +# DxDesigner.xml stores RGB values. Explicit colors on drawing objects keep +# their native precedence over these defaults. +REFERENCE_COLORS = { + "NET": "0xff0000", + "COMPONENT": "0x800080", + "PIN": "0x008080", + "LINE": "0x0000ff", + "BOX": "0x800080", + "CIRCLE": "0x008000", + "ARC": "0x0000ff", + "TEXT": "0x0000ff", + "LABEL": "0x008000", + "ATTRIBUTE": "0x388e8e", +} + + +def prepare_environment(run_dir: Path, print_theme: str) -> dict[str, str] | None: + if print_theme == "original": + return None + if print_theme != "reference": + raise ValueError("不支持的 PDF 配色") + directory = Path(run_dir).resolve() / "native-profile" + if ";" in str(directory): + raise ValueError("运行记录路径含分号,无法加入原生配置搜索路径") + directory.mkdir(parents=True, exist_ok=True) + root = ET.Element("DxDesigner_Configuration_file", version="1.2", name="DxDesigner.xml") + designer = ET.SubElement(root, "DxDesigner") + objects = ET.SubElement(designer, "OBJECTS") + for name, color in REFERENCE_COLORS.items(): + item = ET.SubElement(objects, "object", name=name) + ET.SubElement(item, "key", name="COLOR", value=color) + layers = ET.SubElement(designer, "LAYERS") + border = ET.SubElement(layers, "layer", name="BORDER_LAYER") + ET.SubElement(border, "key", name="COLOR", value="0x0000ff") + ET.ElementTree(root).write(directory / "DxDesigner.xml", encoding="utf-8", xml_declaration=True) + environment = dict(os.environ) + inherited = environment.get("WDIR", "") + environment["WDIR"] = str(directory) + (";" + inherited if inherited else "") + return environment diff --git a/src/dx_productivity/features/pdf_export/settings.py b/src/dx_productivity/features/pdf_export/settings.py index 1654ad6..de518ef 100644 --- a/src/dx_productivity/features/pdf_export/settings.py +++ b/src/dx_productivity/features/pdf_export/settings.py @@ -76,6 +76,9 @@ def load_settings( block_name = data.get("block_name", "") output_value = data.get("output_dir", "") engine_value = data.get("engine_path", "") + print_theme = data.get("print_theme", "reference") + if print_theme not in ("reference", "original"): + print_theme = "reference" if not isinstance(block_name, str) or not isinstance(output_value, str): return defaults if not isinstance(engine_value, str): @@ -88,6 +91,7 @@ def load_settings( output_dir=Path(output_value) if output_value else defaults.output_dir, auto_export=data.get("auto_export") is True, engine_path=Path(engine_value) if engine_value else None, + print_theme=print_theme, ) except (OSError, TypeError, ValueError): return defaults @@ -105,6 +109,7 @@ def save_settings( "block_name": settings.block_name, "output_dir": str(settings.output_dir.resolve(strict=False)), "auto_export": bool(settings.auto_export), + "print_theme": settings.print_theme, "engine_path": str(settings.engine_path.resolve(strict=False)) if settings.engine_path else "", diff --git a/src/dx_productivity/ui/app.py b/src/dx_productivity/ui/app.py index 225cd58..4e0f001 100644 --- a/src/dx_productivity/ui/app.py +++ b/src/dx_productivity/ui/app.py @@ -60,7 +60,7 @@ def _load_windows_ui_fonts(application: QApplication) -> None: path = font_root / filename if path.exists(): QFontDatabase.addApplicationFont(str(path)) - application.setFont(QFont("Microsoft YaHei UI", 13)) + application.setFont(QFont("Microsoft YaHei UI", 11)) def build_parser() -> argparse.ArgumentParser: @@ -79,8 +79,8 @@ FEATURE_PAGE_INDEX = { "network": 4, "bom": 5, "history": 6, - "settings": 7, - "pdf-export": 8, + "pdf-export": 7, + "settings": 8, } STATUS_TEXT = { @@ -256,7 +256,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow: settings_page.auto_check_checkbox.isChecked(), ) ) - window.set_page(7, settings_page, "设置") + window.set_page(FEATURE_PAGE_INDEX["settings"], settings_page, "设置") window.settings_controller = settings_controller window.settings_page = settings_page @@ -266,7 +266,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow: tool_root=_tool_root(), ) pdf_export_controller.status_changed.connect(window.operation_status.setText) - window.set_page(8, pdf_export_page, "PDF 导出") + window.set_page(FEATURE_PAGE_INDEX["pdf-export"], pdf_export_page, "PDF 导出") window.pdf_export_controller = pdf_export_controller if settings_controller.auto_check_due(persisted_settings): QTimer.singleShot( @@ -277,6 +277,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow: ) if snapshot is not None: window.project_label.setText(Path(snapshot.design_path).name or snapshot.design_id) + window.project_label.setToolTip(snapshot.design_path) window.bridge_status.setText("桥接已连接") controller.load_snapshot(snapshot) if window.property_change_controller is not None: @@ -380,6 +381,7 @@ class _SnapshotWatcher(QObject): self._window.project_label.setText( Path(snapshot.design_path).name or snapshot.design_id ) + self._window.project_label.setToolTip(snapshot.design_path) self.snapshot_reloaded.emit(snapshot) self._window.operation_status.setText("设计快照已刷新") @@ -474,6 +476,7 @@ def main(argv: Sequence[str] | None = None) -> int: _install_excepthook() app = create_application([sys.argv[0], *arguments]) window = create_main_window(options.request) + window.window_closed.connect(app.quit) window.show() if options.feature is not None: index = FEATURE_PAGE_INDEX[options.feature] diff --git a/src/dx_productivity/ui/bom_page.py b/src/dx_productivity/ui/bom_page.py index 54deb26..ec97fa2 100644 --- a/src/dx_productivity/ui/bom_page.py +++ b/src/dx_productivity/ui/bom_page.py @@ -69,7 +69,7 @@ class BomPage(QWidget): ) self.table = QTableView() self.table.setModel(self.model) - self.table.setMinimumHeight(360) + self.table.setMinimumHeight(200) self.table.setEditTriggers(QTableView.EditTrigger.NoEditTriggers) layout.addWidget(self.table, 1) diff --git a/src/dx_productivity/ui/floating_button.py b/src/dx_productivity/ui/floating_button.py new file mode 100644 index 0000000..a00707a --- /dev/null +++ b/src/dx_productivity/ui/floating_button.py @@ -0,0 +1,87 @@ +"""Small draggable launcher for a hidden, still-running tool window.""" +from __future__ import annotations + +from PySide6.QtCore import QPoint, QSize, Qt, Signal +from PySide6.QtGui import QGuiApplication +from PySide6.QtWidgets import QApplication, QMenu, QPushButton + +from dx_productivity.ui.theme import Theme, theme_tokens, themed_icon + + +class FloatingButton(QPushButton): + open_requested = Signal() + exit_requested = Signal() + + def __init__(self) -> None: + super().__init__() + self.setWindowFlags(Qt.WindowType.Tool | Qt.WindowType.FramelessWindowHint + | Qt.WindowType.WindowStaysOnTopHint) + self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) + self.setWindowTitle("一叶知秋悬浮入口") + self.setObjectName("floatingEntry") + self.setAccessibleName("一叶知秋悬浮入口:点击展开,拖动移动") + self.setToolTip("一叶知秋 · 点击展开\n拖动移动,右键可退出") + self.setFixedSize(56, 56) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self._press_position: QPoint | None = None + self._start_position = QPoint() + self._dragged = False + self.clicked.connect(self.open_requested) + self.refresh_theme(Theme.LIGHT) + + def refresh_theme(self, theme: Theme) -> None: + tokens = theme_tokens(theme) + self.setIcon(themed_icon("fa6s.leaf", theme, color=tokens.accent_text)) + self.setIconSize(QSize(26, 26)) + self.setStyleSheet(f""" + QPushButton#floatingEntry {{ + min-width: 56px; max-width: 56px; min-height: 56px; max-height: 56px; + padding: 0; border-radius: 28px; border: 1px solid {tokens.border}; + background: {tokens.accent}; color: {tokens.accent_text}; + }} + QPushButton#floatingEntry:hover {{ background: {tokens.accent_hover}; }} + """) + + def move_within_screen(self, position: QPoint, screen=None) -> None: + screen = screen or QGuiApplication.screenAt(position) or self.screen() + if screen is None: + self.move(position) + return + bounds = screen.availableGeometry() + self.move(max(bounds.left(), min(position.x(), bounds.right() - self.width() + 1)), + max(bounds.top(), min(position.y(), bounds.bottom() - self.height() + 1))) + + def mousePressEvent(self, event) -> None: + if event.button() == Qt.MouseButton.LeftButton: + self._press_position = event.globalPosition().toPoint() + self._start_position = self.pos() + self._dragged = False + super().mousePressEvent(event) + + def mouseMoveEvent(self, event) -> None: + if self._press_position is not None and event.buttons() & Qt.MouseButton.LeftButton: + delta = event.globalPosition().toPoint() - self._press_position + if self._dragged or delta.manhattanLength() >= QApplication.startDragDistance(): + self._dragged = True + self.setDown(False) + self.move_within_screen(self._start_position + delta, + QGuiApplication.screenAt(event.globalPosition().toPoint())) + event.accept() + return + super().mouseMoveEvent(event) + + def mouseReleaseEvent(self, event) -> None: + self._press_position = None + if event.button() == Qt.MouseButton.LeftButton and self._dragged: + self._dragged = False + self.setDown(False) + event.accept() + return + super().mouseReleaseEvent(event) + + def contextMenuEvent(self, event) -> None: + menu = QMenu(self) + menu.addAction("打开工具", lambda: self.open_requested.emit()) + menu.addAction("退出工具", lambda: self.exit_requested.emit()) + menu.exec(event.globalPos()) diff --git a/src/dx_productivity/ui/inspection_page.py b/src/dx_productivity/ui/inspection_page.py index cce7eb5..567e42c 100644 --- a/src/dx_productivity/ui/inspection_page.py +++ b/src/dx_productivity/ui/inspection_page.py @@ -80,7 +80,7 @@ class InspectionPage(QWidget): self.model.setHorizontalHeaderLabels(("检查项", "名称", "页号", "说明")) self.table = QTableView() self.table.setModel(self.model) - self.table.setMinimumHeight(380) + self.table.setMinimumHeight(200) self.table.setEditTriggers(QTableView.EditTrigger.NoEditTriggers) self.table.doubleClicked.connect(self._on_double_click) layout.addWidget(self.table, 1) diff --git a/src/dx_productivity/ui/main_window.py b/src/dx_productivity/ui/main_window.py index 7bcbcdf..04e2c48 100644 --- a/src/dx_productivity/ui/main_window.py +++ b/src/dx_productivity/ui/main_window.py @@ -2,7 +2,7 @@ from __future__ import annotations -from PySide6.QtCore import QSize, Qt, Signal +from PySide6.QtCore import QEvent, QPoint, QSize, QTimer, Qt, Signal from PySide6.QtWidgets import ( QFrame, QHBoxLayout, @@ -11,6 +11,7 @@ from PySide6.QtWidgets import ( QListWidgetItem, QMainWindow, QPushButton, + QSizePolicy, QApplication, QStackedWidget, QToolButton, @@ -19,6 +20,7 @@ from PySide6.QtWidgets import ( ) from dx_productivity import __version__ +from dx_productivity.ui.floating_button import FloatingButton from dx_productivity.ui.theme import Theme, apply_theme, themed_icon, theme_tokens @@ -30,8 +32,8 @@ NAVIGATION = ( ("网络工具", "fa6s.share-nodes"), ("BOM 工具", "fa6s.table"), ("操作历史", "fa6s.clock-rotate-left"), - ("设置", "fa6s.gear"), ("PDF 导出", "fa6s.file-pdf"), + ("设置", "fa6s.gear"), ) @@ -41,13 +43,21 @@ class MainWindow(QMainWindow): preview_requested = Signal() apply_requested = Signal() page_changed = Signal(int) + window_closed = Signal() def __init__(self, *, theme: Theme = Theme.LIGHT) -> None: super().__init__() + self._closing = False + self._floating_positioned = False + self._expanded_geometry = None + self._was_maximized = False + self.floating_button = FloatingButton() + self.floating_button.open_requested.connect(self.restore_from_floating) + self.floating_button.exit_requested.connect(self.close) self.theme = theme self.setWindowTitle("一叶知秋_重构版") - self.setMinimumSize(1100, 700) - self.resize(1240, 780) + self.setMinimumSize(860, 540) + self.resize(960, 600) self._build_ui() self._refresh_icons() application = QApplication.instance() @@ -77,6 +87,7 @@ class MainWindow(QMainWindow): self.operation_status.setText("正在完成菜单注册,请稍候再关闭") event.ignore() return + self._closing = True for controller in ( getattr(self, "settings_controller", None), getattr(self, "refdes_controller", None), @@ -86,7 +97,44 @@ class MainWindow(QMainWindow): shutdown = getattr(controller, "shutdown", None) if callable(shutdown): shutdown() + self.floating_button.close() super().closeEvent(event) + if event.isAccepted(): + self.window_closed.emit() + + def changeEvent(self, event) -> None: + super().changeEvent(event) + if event.type() == QEvent.Type.WindowStateChange and self.isMinimized() and not self._closing: + QTimer.singleShot(0, self.collapse_to_floating) + + def collapse_to_floating(self) -> None: + if self._closing or self.floating_button.isVisible(): + return + self._expanded_geometry = self.normalGeometry() if self.isMinimized() or self.isMaximized() else self.geometry() + self._was_maximized = self.isMaximized() + if not self._floating_positioned: + screen = self.screen() + if screen is not None: + bounds = screen.availableGeometry() + self.floating_button.move_within_screen(QPoint(bounds.right() - 80, bounds.bottom() - 160), screen) + self._floating_positioned = True + else: + self.floating_button.move_within_screen(self.floating_button.pos()) + self.hide() + self.floating_button.show() + + def restore_from_floating(self) -> None: + if self._closing: + return + self.floating_button.hide() + if self._was_maximized: + self.showMaximized() + else: + self.showNormal() + if self._expanded_geometry is not None: + self.setGeometry(self._expanded_geometry) + self.raise_() + self.activateWindow() def _build_ui(self) -> None: root = QWidget() @@ -109,10 +157,10 @@ class MainWindow(QMainWindow): def _build_title_bar(self) -> QFrame: bar = QFrame() bar.setObjectName("titleBar") - bar.setFixedHeight(52) + bar.setFixedHeight(44) layout = QHBoxLayout(bar) - layout.setContentsMargins(18, 0, 14, 0) - layout.setSpacing(10) + layout.setContentsMargins(12, 0, 12, 0) + layout.setSpacing(8) brand = QLabel("一叶知秋_重构版") self.brand_label = brand @@ -120,8 +168,9 @@ class MainWindow(QMainWindow): layout.addWidget(brand) self.project_label = QLabel("未连接设计") self.project_label.setObjectName("projectLabel") - layout.addWidget(self.project_label) - layout.addStretch(1) + self.project_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) + self.project_label.setMinimumWidth(40) + layout.addWidget(self.project_label, 1) self.start_button = QPushButton("Start") self.start_button.setToolTip("自动加入工具菜单并打开 DxDesigner") @@ -143,12 +192,15 @@ class MainWindow(QMainWindow): self.apply_button.setEnabled(False) self.apply_button.clicked.connect(self.apply_requested) layout.addWidget(self.apply_button) + self.collapse_button = self._tool_button("收起为悬浮窗") + self.collapse_button.clicked.connect(self.collapse_to_floating) + layout.addWidget(self.collapse_button) return bar def _build_navigation(self) -> QFrame: rail = QFrame() rail.setObjectName("navigationRail") - rail.setFixedWidth(218) + rail.setFixedWidth(172) layout = QVBoxLayout(rail) layout.setContentsMargins(8, 10, 8, 10) layout.setSpacing(6) @@ -167,6 +219,7 @@ class MainWindow(QMainWindow): layout.addWidget(self.navigation, 1) version = QLabel(f"DxDesigner 7.9.5 · v{__version__}") version.setObjectName("secondaryLabel") + version.setWordWrap(True) layout.addWidget(version) return rail @@ -178,9 +231,9 @@ class MainWindow(QMainWindow): header = QFrame() header.setObjectName("contentHeader") - header.setFixedHeight(58) + header.setFixedHeight(44) header_layout = QHBoxLayout(header) - header_layout.setContentsMargins(20, 0, 20, 0) + header_layout.setContentsMargins(12, 0, 12, 0) self.page_title = QLabel(NAVIGATION[0][0]) self.page_title.setObjectName("pageTitle") header_layout.addWidget(self.page_title) @@ -199,16 +252,17 @@ class MainWindow(QMainWindow): def _build_status_strip(self) -> QFrame: strip = QFrame() strip.setObjectName("statusStrip") - strip.setFixedHeight(32) + strip.setFixedHeight(28) layout = QHBoxLayout(strip) layout.setContentsMargins(14, 0, 14, 0) self.bridge_status = QLabel("桥接待连接") self.bridge_status.setObjectName("secondaryLabel") layout.addWidget(self.bridge_status) - layout.addStretch(1) self.operation_status = QLabel("就绪") self.operation_status.setObjectName("secondaryLabel") - layout.addWidget(self.operation_status) + self.operation_status.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) + self.operation_status.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + layout.addWidget(self.operation_status, 1) return strip def _tool_button(self, label: str) -> QToolButton: @@ -244,6 +298,8 @@ class MainWindow(QMainWindow): ) self.refresh_button.setIcon(themed_icon("fa6s.arrows-rotate", self.theme)) self.preview_button.setIcon(themed_icon("fa6s.eye", self.theme)) + self.collapse_button.setIcon(themed_icon("fa6s.down-left-and-up-right-to-center", self.theme)) + self.floating_button.refresh_theme(self.theme) self.apply_button.setIcon( themed_icon("fa6s.check", self.theme, color=tokens.accent_text) ) diff --git a/src/dx_productivity/ui/pdf_export_page.py b/src/dx_productivity/ui/pdf_export_page.py index 390f357..60a4218 100644 --- a/src/dx_productivity/ui/pdf_export_page.py +++ b/src/dx_productivity/ui/pdf_export_page.py @@ -2,7 +2,8 @@ from __future__ import annotations from pathlib import Path -from PySide6.QtCore import QSize, Signal +from PySide6.QtCore import QSize, QUrl, Signal +from PySide6.QtGui import QDesktopServices from PySide6.QtWidgets import ( QCheckBox, QComboBox, @@ -36,12 +37,12 @@ class PdfExportPage(QWidget): def _build_ui(self) -> None: layout = QVBoxLayout(self) - layout.setContentsMargins(20, 16, 20, 16) - layout.setSpacing(12) + layout.setContentsMargins(12, 12, 12, 12) + layout.setSpacing(8) form = QFormLayout() form.setHorizontalSpacing(14) - form.setVerticalSpacing(12) + form.setVerticalSpacing(8) self.project_input = QLineEdit() self.project_input.setReadOnly(True) @@ -54,6 +55,11 @@ class PdfExportPage(QWidget): self.scope_combo.addItem("指定原理图或 Block", ExportScope.BLOCK.value) form.addRow("导出范围", self.scope_combo) + self.palette_combo = QComboBox() + self.palette_combo.addItem("工程参考配色(mentor_PDF_output)", "reference") + self.palette_combo.addItem("原生配色", "original") + form.addRow("PDF 配色", self.palette_combo) + block_row = QHBoxLayout() self.block_input = QLineEdit() self.block_input.setPlaceholderText("DxDesigner 原理图或 Block 名称") @@ -68,8 +74,16 @@ class PdfExportPage(QWidget): self.output_button = QPushButton("浏览…") self.output_button.setIconSize(QSize(16, 16)) self.output_button.clicked.connect(self._choose_output) + self.open_output_button = QPushButton("打开输出目录") + self.open_output_button.setIconSize(QSize(16, 16)) + self.open_output_button.setEnabled(False) + self.open_output_button.clicked.connect(self._open_output) output_row.addWidget(self.output_input, 1) output_row.addWidget(self.output_button) + output_row.addWidget(self.open_output_button) + self.output_input.textChanged.connect( + lambda value: self.open_output_button.setEnabled(bool(value.strip())) + ) form.addRow("输出目录", output_row) engine_row = QHBoxLayout() @@ -114,6 +128,7 @@ class PdfExportPage(QWidget): layout.addLayout(actions) self.scope_combo.currentIndexChanged.connect(self._scope_changed) + self.palette_combo.currentIndexChanged.connect(self._emit_settings) self.block_input.editingFinished.connect(self._emit_settings) self.output_input.editingFinished.connect(self._emit_settings) self.engine_input.editingFinished.connect(self._emit_settings) @@ -125,6 +140,7 @@ class PdfExportPage(QWidget): self.project_input.setText(snapshot.design_path if snapshot else "") scope_index = self.scope_combo.findData(settings.scope.value) self.scope_combo.setCurrentIndex(max(scope_index, 0)) + self.palette_combo.setCurrentIndex(max(self.palette_combo.findData(settings.print_theme), 0)) self.block_input.setText( settings.block_name if settings.scope is ExportScope.BLOCK @@ -160,6 +176,7 @@ class PdfExportPage(QWidget): output_dir=Path(output_value), auto_export=self.auto_export_checkbox.isChecked(), engine_path=Path(engine_value) if engine_value else None, + print_theme=self.palette_combo.currentData(), ) def confirm_overwrite(self, path: str) -> bool: @@ -193,6 +210,7 @@ class PdfExportPage(QWidget): self.export_button.setEnabled(not busy and self.snapshot is not None) self.cancel_button.setEnabled(busy) self.scope_combo.setEnabled(not busy) + self.palette_combo.setEnabled(not busy) self.output_input.setEnabled(not busy) self.output_button.setEnabled(not busy) self.engine_input.setEnabled(not busy) @@ -211,6 +229,7 @@ class PdfExportPage(QWidget): def refresh_icons(self, theme: Theme) -> None: self._theme = theme self.output_button.setIcon(themed_icon("fa6s.folder-open", theme)) + self.open_output_button.setIcon(themed_icon("fa6s.folder-open", theme)) self.engine_button.setIcon(themed_icon("fa6s.folder-open", theme)) self.export_button.setIcon(themed_icon("fa6s.file-pdf", theme)) self.cancel_button.setIcon(themed_icon("fa6s.xmark", theme)) @@ -258,3 +277,15 @@ class PdfExportPage(QWidget): if path: self.engine_input.setText(path) self._emit_settings() + + def _open_output(self) -> None: + value = self.output_input.text().strip() + if not value: + return + try: + directory = Path(value).expanduser().resolve() + directory.mkdir(parents=True, exist_ok=True) + if not QDesktopServices.openUrl(QUrl.fromLocalFile(str(directory))): + raise OSError("系统未能打开该目录") + except (OSError, ValueError) as error: + self.set_status(f"无法打开输出目录:{error}") diff --git a/src/dx_productivity/ui/property_change_page.py b/src/dx_productivity/ui/property_change_page.py index 0186acf..8c7b13e 100644 --- a/src/dx_productivity/ui/property_change_page.py +++ b/src/dx_productivity/ui/property_change_page.py @@ -59,7 +59,7 @@ class PropertyChangePage(QWidget): self.model.setHorizontalHeaderLabels(("位号", "当前值", "新值")) self.table = QTableView() self.table.setModel(self.model) - self.table.setMinimumHeight(360) + self.table.setMinimumHeight(200) layout.addWidget(self.table, 1) self.issue_label = QLabel("") diff --git a/src/dx_productivity/ui/property_visibility_page.py b/src/dx_productivity/ui/property_visibility_page.py index 091b75f..9901601 100644 --- a/src/dx_productivity/ui/property_visibility_page.py +++ b/src/dx_productivity/ui/property_visibility_page.py @@ -65,7 +65,7 @@ class PropertyVisibilityPage(QWidget): self.model.setHorizontalHeaderLabels(("位号", "属性值", "当前状态")) self.table = QTableView() self.table.setModel(self.model) - self.table.setMinimumHeight(360) + self.table.setMinimumHeight(200) self.table.setEditTriggers( QTableView.EditTrigger.NoEditTriggers ) diff --git a/src/dx_productivity/ui/refdes_page.py b/src/dx_productivity/ui/refdes_page.py index 3b43462..608e68e 100644 --- a/src/dx_productivity/ui/refdes_page.py +++ b/src/dx_productivity/ui/refdes_page.py @@ -18,6 +18,7 @@ from PySide6.QtWidgets import ( QLineEdit, QPushButton, QSpinBox, + QScrollArea, QTableView, QVBoxLayout, QWidget, @@ -108,18 +109,23 @@ class RefDesPage(QWidget): def _build_ui(self) -> None: root = QHBoxLayout(self) - root.setContentsMargins(20, 18, 20, 18) - root.setSpacing(20) - root.addWidget(self._build_rules_panel()) + root.setContentsMargins(12, 12, 12, 12) + root.setSpacing(12) + rules_scroll = QScrollArea() + rules_scroll.setObjectName("rulesScroll") + rules_scroll.setWidgetResizable(True) + rules_scroll.setFrameShape(QFrame.Shape.NoFrame) + rules_scroll.setFixedWidth(268) + rules_scroll.setWidget(self._build_rules_panel()) + root.addWidget(rules_scroll) root.addWidget(self._build_preview_panel(), 1) def _build_rules_panel(self) -> QFrame: panel = QFrame() panel.setObjectName("rulesPanel") - panel.setFixedWidth(318) layout = QVBoxLayout(panel) - layout.setContentsMargins(0, 0, 20, 0) - layout.setSpacing(10) + layout.setContentsMargins(0, 0, 12, 0) + layout.setSpacing(8) title = QLabel("标注规则") title.setObjectName("pageTitle") layout.addWidget(title) @@ -164,6 +170,8 @@ class RefDesPage(QWidget): layout.addWidget(_labeled_control("页内起始", self.page_start_spin)) self.sort_combo = QComboBox() + self.sort_combo.setMinimumContentsLength(8) + self.sort_combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) self.sort_combo.addItem("从上到下 · 从左到右", SortOrder.TOP_DOWN_LEFT_RIGHT) self.sort_combo.addItem("从上到下 · 从右到左", SortOrder.TOP_DOWN_RIGHT_LEFT) self.sort_combo.addItem("从左到右 · 从上到下", SortOrder.LEFT_RIGHT_TOP_DOWN) @@ -299,7 +307,7 @@ def _labeled_control(text: str, control: QWidget) -> QFrame: layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(8) label = _field_label(text) - label.setMinimumWidth(78) + label.setMinimumWidth(64) layout.addWidget(label) layout.addWidget(control, 1) return frame diff --git a/src/dx_productivity/ui/theme.py b/src/dx_productivity/ui/theme.py index 54c6990..eb7b3a3 100644 --- a/src/dx_productivity/ui/theme.py +++ b/src/dx_productivity/ui/theme.py @@ -121,7 +121,7 @@ def _stylesheet(tokens: ThemeTokens) -> str: return f""" * {{ font-family: "Microsoft YaHei UI"; - font-size: 13pt; + font-size: 11pt; letter-spacing: 0px; }} QMainWindow, QWidget#appRoot {{ @@ -137,8 +137,13 @@ def _stylesheet(tokens: ThemeTokens) -> str: border-right: 1px solid {tokens.border}; }} QFrame#rulesPanel {{ + background: {tokens.canvas}; border-right: 1px solid {tokens.border}; }} + QScrollArea#rulesScroll {{ + background: {tokens.canvas}; + border: none; + }} QFrame#legacyIntro {{ background: {tokens.surface}; border: 1px solid {tokens.border}; @@ -199,22 +204,22 @@ def _stylesheet(tokens: ThemeTokens) -> str: font-size: 10pt; }} QLabel#brandLabel {{ - font-size: 15pt; + font-size: 13pt; font-weight: 600; }} QLabel#pageTitle {{ - font-size: 16pt; + font-size: 14pt; font-weight: 600; }} QListWidget#navigationList {{ background: transparent; border: none; outline: none; - padding: 8px; + padding: 4px; }} QListWidget#navigationList::item {{ - min-height: 36px; - padding: 0 10px; + min-height: 32px; + padding: 0 8px; border-radius: 6px; color: {tokens.text_secondary}; }} @@ -229,12 +234,12 @@ def _stylesheet(tokens: ThemeTokens) -> str: }} QPushButton, QToolButton, QComboBox, QSpinBox, QDoubleSpinBox, QLineEdit {{ - min-height: 30px; + min-height: 26px; border: 1px solid {tokens.border}; border-radius: 6px; background: {tokens.surface}; color: {tokens.text_primary}; - padding: 0 10px; + padding: 0 7px; }} QPushButton:hover, QToolButton:hover, QComboBox:hover {{ background: {tokens.surface_hover}; @@ -260,12 +265,12 @@ def _stylesheet(tokens: ThemeTokens) -> str: background: {tokens.surface}; }} QPushButton#segmentButton {{ - min-height: 30px; + min-height: 26px; border: none; border-right: 1px solid {tokens.border}; border-radius: 0; background: transparent; - padding: 0 8px; + padding: 0 5px; }} QPushButton#segmentButton:checked {{ background: {tokens.accent}; diff --git a/tests/features/test_pdf_export.py b/tests/features/test_pdf_export.py index f3813df..f78525e 100644 --- a/tests/features/test_pdf_export.py +++ b/tests/features/test_pdf_export.py @@ -1,4 +1,5 @@ from pathlib import Path +import os import threading import pytest @@ -82,7 +83,7 @@ def test_current_page_export_publishes_only_selected_sheet(project: Path, tmp_pa engine.touch() settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', tmp_path / 'output', engine_path=engine) - def native_engine(command, *_args): + def native_engine(command, *_args, **_kwargs): assert command[-2:] == ['-schematic', 'Main'] _write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'ANALOG_ONLY'), ('Main Sheet Digital', 'DIGITAL_ONLY'))) return 0 @@ -104,7 +105,7 @@ def test_selection_failure_preserves_previous_export(project: Path, tmp_path: Pa target = exporter.output_path(settings, 'Main', 'Digital') target.write_bytes(b'old-pdf-preserved') - def native_engine(command, *_args): + def native_engine(command, *_args, **_kwargs): _write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'ANALOG_ONLY'),)) return 0 @@ -151,7 +152,7 @@ def test_source_configuration_changes_block_publication(project: Path, tmp_path: engine.touch() settings = PdfExportSettings(project, ExportScope.PROJECT, '', tmp_path / 'output', engine_path=engine) - def native_engine(command, *_args): + def native_engine(command, *_args, **_kwargs): _write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'CONTENT'),)) project.write_text(project.read_text() + 'KEY Unexpected "change"\n') return 0 @@ -196,7 +197,7 @@ def test_native_database_sharing_lock_is_distinguished_from_permission_denial(pr raise error return original_open(path, *args, **kwargs) - def native_engine(command, *_args): + def native_engine(command, *_args, **_kwargs): _write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'CONTENT'),)) return 0 @@ -233,3 +234,27 @@ def test_unreadable_schematic_still_prevents_native_export(project: Path, tmp_pa result = exporter.export_project(settings, threading.Event(), local_app_data=tmp_path / 'state') assert result.state == 'failed' assert not result.output_path.exists() + + +def test_exporter_applies_reference_colors_only_to_child(project, tmp_path, monkeypatch): + engine = tmp_path / 'sch2pdf.exe' + engine.touch() + original_config = project.parent / 'DxDesigner.xml' + original_config.write_bytes(b'original project colors') + monkeypatch.setenv('WDIR', 'D:/Mentor/standard') + before = dict(os.environ) + settings = PdfExportSettings(project, ExportScope.PROJECT, '', tmp_path / 'output', engine_path=engine) + + def native_engine(command, *_args, env=None): + assert env is not None + assert env['WDIR'].endswith(';D:/Mentor/standard') + assert Path(env['WDIR'].split(';')[0], 'DxDesigner.xml').is_file() + assert original_config.read_bytes() == b'original project colors' + _write_pdf(Path(command[command.index('-a') + 1]), (('Main Sheet Analog', 'CONTENT'),)) + return 0 + + monkeypatch.setattr(exporter, 'run_engine', native_engine) + result = exporter.export_project(settings, threading.Event(), local_app_data=tmp_path / 'state') + assert result.state == 'success', result.message + assert dict(os.environ) == before + assert original_config.read_bytes() == b'original project colors' diff --git a/tests/features/test_pdf_export_settings.py b/tests/features/test_pdf_export_settings.py index c4e1c3b..36965d6 100644 --- a/tests/features/test_pdf_export_settings.py +++ b/tests/features/test_pdf_export_settings.py @@ -1,4 +1,5 @@ from pathlib import Path +import json from dx_productivity.features.pdf_export import cli from dx_productivity.features.pdf_export.models import ExportScope, PdfExportResult, PdfExportSettings @@ -39,11 +40,12 @@ def test_save_event_forwards_exact_named_sheet_and_reports_success(tmp_path: Pat project = tmp_path / 'Demo.prj' config = tmp_path / 'config.json' status = tmp_path / 'result.txt' - settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', tmp_path / 'output', True) + settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', tmp_path / 'output', True, print_theme='original') save_settings(settings, config_path=config) observed = {} def export(settings, cancel, **kwargs): + assert settings.print_theme == 'original' observed.update(kwargs) return PdfExportResult(settings.project_path, 'success', 'PDF saved') @@ -52,3 +54,22 @@ def test_save_event_forwards_exact_named_sheet_and_reports_success(tmp_path: Pat assert observed['active_sheet_name'] == 'Digital signal' assert observed['overwrite'] is True assert status.read_text(encoding='utf-8') == 'PDF saved\n' + + +def test_old_settings_use_reference_palette_and_explicit_palette_roundtrips(tmp_path): + config = tmp_path / 'config.json' + settings = PdfExportSettings(tmp_path / 'Demo.prj', ExportScope.PROJECT, '', tmp_path / 'output') + save_settings(settings, config_path=config) + data = json.loads(config.read_text(encoding='utf-8')) + data.pop('print_theme', None) + config.write_text(json.dumps(data), encoding='utf-8') + assert load_settings(settings.project_path, config_path=config).print_theme == 'reference' + data['print_theme'] = 'original' + config.write_text(json.dumps(data), encoding='utf-8') + native = load_settings(settings.project_path, config_path=config) + assert native.print_theme == 'original' + save_settings(native, config_path=config) + assert load_settings(settings.project_path, config_path=config) == native + data['print_theme'] = 'unknown' + config.write_text(json.dumps(data), encoding='utf-8') + assert load_settings(settings.project_path, config_path=config).print_theme == 'reference' diff --git a/tests/features/test_pdf_native_palette.py b/tests/features/test_pdf_native_palette.py new file mode 100644 index 0000000..6de62c7 --- /dev/null +++ b/tests/features/test_pdf_native_palette.py @@ -0,0 +1,49 @@ +import os +from pathlib import Path +import sys +import threading +import xml.etree.ElementTree as ET + +import pytest + +from dx_productivity.features.pdf_export.engine import run_engine + + +def test_reference_palette_preserves_parent_environment_and_native_search_path(tmp_path, monkeypatch): + from dx_productivity.features.pdf_export.native_profile import prepare_environment + + monkeypatch.setenv('WDIR', 'D:/Mentor/standard;D:/Library') + before = dict(os.environ) + environment = prepare_environment(tmp_path / '中文 run', 'reference') + assert dict(os.environ) == before + profile, inherited = environment['WDIR'].split(';', 1) + assert inherited == before['WDIR'] + assert Path(profile).is_relative_to(tmp_path) + tree = ET.parse(Path(profile) / 'DxDesigner.xml') + expected = {'NET': '0xff0000', 'COMPONENT': '0x800080', 'PIN': '0x008080', + 'LINE': '0x0000ff', 'BOX': '0x800080', 'CIRCLE': '0x008000', + 'ARC': '0x0000ff', 'TEXT': '0x0000ff', 'LABEL': '0x008000', + 'ATTRIBUTE': '0x388e8e'} + actual = {item.get('name'): item.find("key[@name='COLOR']").get('value') + for item in tree.findall('./DxDesigner/OBJECTS/object')} + assert actual == expected + assert tree.find("./DxDesigner/LAYERS/layer[@name='BORDER_LAYER']/key").get('value') == '0x0000ff' + assert prepare_environment(tmp_path / 'native', 'original') is None + assert not (tmp_path / 'native').exists() + + +def test_reference_palette_rejects_wdir_separator_in_run_path(tmp_path): + from dx_productivity.features.pdf_export.native_profile import prepare_environment + + with pytest.raises(ValueError, match='分号'): + prepare_environment(tmp_path / 'bad;path', 'reference') + + +def test_engine_uses_child_environment_without_changing_parent(tmp_path, monkeypatch): + monkeypatch.setenv('DXTOOLS_PALETTE_TEST', 'parent') + environment = dict(os.environ, DXTOOLS_PALETTE_TEST='child') + result = run_engine([sys.executable, '-c', "import os; print(os.environ['DXTOOLS_PALETTE_TEST'])"], + tmp_path, tmp_path / 'logs', threading.Event(), 10, env=environment) + assert result == 0 + assert (tmp_path / 'logs/stdout.log').read_text().strip() == 'child' + assert os.environ['DXTOOLS_PALETTE_TEST'] == 'parent' diff --git a/tests/ui/test_compact_floating_window.py b/tests/ui/test_compact_floating_window.py new file mode 100644 index 0000000..05a825e --- /dev/null +++ b/tests/ui/test_compact_floating_window.py @@ -0,0 +1,106 @@ +from PySide6.QtCore import QCoreApplication, QEvent, QPoint, QPointF, QTimer, Qt +from PySide6.QtGui import QMouseEvent +from PySide6.QtWidgets import QAbstractButton + +from dx_productivity.ui.app import FEATURE_PAGE_INDEX, create_main_window +from dx_productivity.ui.pdf_export_page import PdfExportPage +from dx_productivity.ui.settings_page import SettingsPage + + +def make_window(qtbot, monkeypatch, tmp_path): + monkeypatch.setenv("LOCALAPPDATA", str(tmp_path)) + window = create_main_window() + qtbot.addWidget(window) + window.show() + qtbot.waitExposed(window) + return window + + +def test_pdf_is_above_settings_with_matching_page_routing(qtbot, monkeypatch, tmp_path): + window = make_window(qtbot, monkeypatch, tmp_path) + assert window.navigation_items()[-2:] == ["PDF 导出", "设置"] + for feature, page_type in (("pdf-export", PdfExportPage), ("settings", SettingsPage)): + window.set_active_page(FEATURE_PAGE_INDEX[feature]) + assert isinstance(window.pages.currentWidget(), page_type) + + +def test_all_pages_fit_compact_default_window(qtbot, monkeypatch, tmp_path): + window = make_window(qtbot, monkeypatch, tmp_path) + assert window.width() <= 1000 + assert window.height() <= 640 + for index in range(window.pages.count()): + window.set_active_page(index) + qtbot.wait(5) + assert window.width() <= 1000 and window.height() <= 640 + for button in (window.start_button, window.collapse_button, window.apply_button): + assert window.rect().contains(button.mapTo(window, button.rect().bottomRight())) + + +def test_floating_restore_retains_page_form_and_background_work(qtbot, monkeypatch, tmp_path): + window = make_window(qtbot, monkeypatch, tmp_path) + window.set_active_page(FEATURE_PAGE_INDEX["pdf-export"]) + page = window.pages.currentWidget() + page.output_input.setText("pending-user-folder") + ticks = [] + timer = QTimer(window) + timer.setInterval(10) + timer.timeout.connect(lambda: ticks.append(1)) + timer.start() + + qtbot.mouseClick(window.collapse_button, Qt.MouseButton.LeftButton) + + assert not window.isVisible() + assert window.floating_button.isVisible() + assert window.floating_button.windowFlags() & Qt.WindowType.WindowStaysOnTopHint + qtbot.waitUntil(lambda: len(ticks) >= 2) + qtbot.mouseClick(window.floating_button, Qt.MouseButton.LeftButton) + assert window.isVisible() + assert not window.floating_button.isVisible() + assert window.pages.currentWidget() is page + assert page.output_input.text() == "pending-user-folder" + + +def test_minimum_size_keeps_all_page_action_buttons_accessible(qtbot, monkeypatch, tmp_path): + window = make_window(qtbot, monkeypatch, tmp_path) + window.resize(860, 540) + for index in range(window.pages.count()): + window.set_active_page(index) + qtbot.wait(5) + assert window.width() == 860 and window.height() == 540 + for button in window.findChildren(QAbstractButton): + if button.isVisibleTo(window): + assert window.rect().contains(button.mapTo(window, button.rect().bottomRight())), (index, button.text()) + + +def test_native_minimize_becomes_floating_and_can_repeat(qtbot, monkeypatch, tmp_path): + window = make_window(qtbot, monkeypatch, tmp_path) + for _ in range(2): + window.showMinimized() + qtbot.waitUntil(lambda: window.floating_button.isVisible() and not window.isVisible()) + qtbot.mouseClick(window.floating_button, Qt.MouseButton.LeftButton) + assert window.isVisible() and not window.isMinimized() + + +def test_drag_moves_floating_entry_without_opening_main_window(qtbot, monkeypatch, tmp_path): + window = make_window(qtbot, monkeypatch, tmp_path) + window.collapse_to_floating() + floating = window.floating_button + floating.move(40, 40) + start = QPointF(floating.mapToGlobal(QPoint(20, 20))) + for kind, local, global_pos, button, buttons in ( + (QEvent.Type.MouseButtonPress, QPointF(20, 20), start, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton), + (QEvent.Type.MouseMove, QPointF(60, 40), start + QPointF(40, 20), Qt.MouseButton.NoButton, Qt.MouseButton.LeftButton), + (QEvent.Type.MouseButtonRelease, QPointF(20, 20), start + QPointF(40, 20), Qt.MouseButton.LeftButton, Qt.MouseButton.NoButton), + ): + event = QMouseEvent(kind, local, global_pos, button, buttons, Qt.KeyboardModifier.NoModifier) + QCoreApplication.sendEvent(floating, event) + assert floating.pos() == QPoint(80, 60) + assert not window.isVisible() and floating.isVisible() + + +def test_close_while_collapsed_closes_floating_entry(qtbot, monkeypatch, tmp_path): + window = make_window(qtbot, monkeypatch, tmp_path) + window.collapse_to_floating() + with qtbot.waitSignal(window.window_closed): + window.close() + assert not window.floating_button.isVisible() diff --git a/tests/ui/test_main_window.py b/tests/ui/test_main_window.py index 5d57cce..5d204a6 100644 --- a/tests/ui/test_main_window.py +++ b/tests/ui/test_main_window.py @@ -12,8 +12,8 @@ def test_main_window_has_approved_minimum_and_navigation(qtbot): window = MainWindow() qtbot.addWidget(window) - assert window.minimumWidth() == 1100 - assert window.minimumHeight() == 700 + assert window.minimumWidth() == 860 + assert window.minimumHeight() == 540 assert window.navigation_items()[:3] == ["自动位号", "属性批改", "属性显示"] assert window.apply_button.text() == "应用位号" @@ -113,7 +113,7 @@ def test_main_window_wires_settings_page(qtbot): window = create_main_window() qtbot.addWidget(window) - assert isinstance(window.pages.widget(7), SettingsPage) + assert isinstance(window.pages.widget(8), SettingsPage) assert window.settings_page.version_label.text().startswith("当前版本 0.1.0") diff --git a/tests/ui/test_pdf_export_page.py b/tests/ui/test_pdf_export_page.py index cedb0c9..d50dbb6 100644 --- a/tests/ui/test_pdf_export_page.py +++ b/tests/ui/test_pdf_export_page.py @@ -5,6 +5,8 @@ import threading from dx_productivity.features.pdf_export.models import ExportScope, PdfExportResult, PdfExportSettings from dx_productivity.ui import pdf_export_controller from dx_productivity.ui.pdf_export_page import PdfExportPage +from dx_productivity.ui import pdf_export_page +from PySide6.QtCore import Qt def _snapshot(sheet_name: str): @@ -42,3 +44,42 @@ def test_worker_forwards_named_sheet_to_exporter(monkeypatch, tmp_path: Path) -> worker = pdf_export_controller._ExportWorker(settings, 'Main', 'Digital signal', False, threading.Event()) worker.run() assert captured['active_sheet_name'] == 'Digital signal' + + +def test_open_output_directory_uses_current_input_even_during_export(qtbot, tmp_path, monkeypatch): + page = PdfExportPage() + qtbot.addWidget(page) + page.bind(_snapshot('Digital'), PdfExportSettings(Path('C:/Demo.prj'), ExportScope.PROJECT, '', tmp_path)) + destination = tmp_path / '中文 PDF output' + page.output_input.setText(str(destination)) + page.set_busy(True) + opened = [] + monkeypatch.setattr(pdf_export_page.QDesktopServices, 'openUrl', lambda url: opened.append(url.toLocalFile()) or True) + qtbot.mouseClick(page.open_output_button, Qt.MouseButton.LeftButton) + assert destination.is_dir() + assert [Path(value) for value in opened] == [destination.resolve()] + page.output_input.clear() + assert not page.open_output_button.isEnabled() + + +def test_open_output_directory_reports_failure(qtbot, tmp_path, monkeypatch): + page = PdfExportPage() + qtbot.addWidget(page) + page.output_input.setText(str(tmp_path)) + monkeypatch.setattr(pdf_export_page.QDesktopServices, 'openUrl', lambda _url: False) + qtbot.mouseClick(page.open_output_button, Qt.MouseButton.LeftButton) + assert '无法打开' in page.status_label.text() + + +def test_palette_choice_is_bound_and_emitted_with_automatic_settings(qtbot, tmp_path): + page = PdfExportPage() + qtbot.addWidget(page) + settings = PdfExportSettings(Path('C:/Demo.prj'), ExportScope.PROJECT, '', tmp_path, True) + page.bind(_snapshot('Digital'), settings) + assert page.palette_combo.currentData() == 'reference' + with qtbot.waitSignal(page.settings_changed) as signal: + page.palette_combo.setCurrentIndex(page.palette_combo.findData('original')) + assert signal.args[0].print_theme == 'original' + assert signal.args[0].auto_export is True + page.bind(_snapshot('Digital'), signal.args[0]) + assert page.palette_combo.currentData() == 'original' diff --git a/tools/acceptance/compact_window.py b/tools/acceptance/compact_window.py new file mode 100644 index 0000000..f25fe40 --- /dev/null +++ b/tools/acceptance/compact_window.py @@ -0,0 +1,122 @@ +"""Check the packaged floating UI on an already-connected DxDesigner run.""" +from __future__ import annotations + +import argparse +import ctypes +import json +import os +from pathlib import Path +import shlex +import time + +import win32gui +import win32api +import win32process +from pywinauto import Application +from pywinauto import mouse + +from packaged_menu import tools_running, wait_for + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("executable", type=Path) + parser.add_argument("--leave-collapsed", action="store_true") + options = parser.parse_args() + executable = options.executable.resolve() + tool = wait_for(lambda: next((p for p in tools_running() if + Path(p.executable).resolve() == executable and "--request" in p.command_line), None)) + args = shlex.split(tool.command_line, posix=False) + request = Path(args[args.index("--request") + 1].strip('"')) + snapshot = json.loads(request.read_text(encoding="utf-8-sig")) + app = Application(backend="uia").connect(process=tool.pid, timeout=15) + + def floating(): + handles = [] + def inspect(handle, _): + if (win32process.GetWindowThreadProcessId(handle)[1] == tool.pid + and win32gui.GetWindowText(handle) == "一叶知秋悬浮入口" + and win32gui.IsWindowVisible(handle)): + handles.append(handle) + win32gui.EnumWindows(inspect, None) + return handles[0] if handles else None + + collapsed_handle = floating() + if collapsed_handle: + app.window(handle=collapsed_handle).wrapper_object().invoke() + window = app.window(title="一叶知秋_重构版") + window.wait("visible", timeout=15) + main_handle = window.handle + nav = window.descendants(control_type="ListItem") + assert [item.window_text() for item in nav][-2:] == ["PDF 导出", "设置"] + next(item for item in nav if item.window_text() == "PDF 导出").select() + assert [item.window_text() for item in nav if item.is_selected()] == ["PDF 导出"] + assert "桥接已连接" in [item.window_text() for item in window.descendants(control_type="Text")] + bounds = win32gui.GetClientRect(main_handle) + dpi = ctypes.windll.user32.GetDpiForWindow(main_handle) + assert abs(bounds[2] - 960 * dpi / 96) <= 2, (bounds, dpi) + assert abs(bounds[3] - 600 * dpi / 96) <= 2, (bounds, dpi) + progress = request.parent / "apply-progress.json" + + before = progress.stat().st_mtime_ns + window.child_window(title="收起为悬浮窗", control_type="Button").invoke() + handle = wait_for(floating) + assert not win32gui.IsWindowVisible(main_handle) + assert win32gui.GetWindowLong(handle, -20) & 0x8 # WS_EX_TOPMOST + wait_for(lambda: progress.stat().st_mtime_ns > before, 15) + first = win32gui.GetWindowRect(handle) + + # Qt derives global mouse coordinates from the actual Windows pointer. + # Exercise a real drag on the verified, topmost floating button, then + # restore the pointer. SendMessage alone cannot verify this gesture. + width, height = win32gui.GetClientRect(handle)[2:] + x, y = width // 2, height // 2 + pointer = win32gui.GetCursorPos() + start = (first[0] + x, first[1] + y) + finish = (start[0] - 30, start[1] - 20) + try: + mouse.press(coords=start) + mouse.move(coords=finish) + mouse.release(coords=finish) + finally: + mouse.release(coords=win32gui.GetCursorPos()) + win32api.SetCursorPos(pointer) + moved = wait_for(lambda: win32gui.GetWindowRect(handle) if win32gui.GetWindowRect(handle) != first else None) + assert not win32gui.IsWindowVisible(main_handle) + app.window(handle=handle).wrapper_object().invoke() + window.wait("visible", timeout=15) + assert not floating() + assert [item.window_text() for item in window.descendants(control_type="ListItem") if item.is_selected()] == ["PDF 导出"] + + old_snapshot = snapshot["snapshot_id"] + window.child_window(title="刷新设计快照", control_type="Button").invoke() + def refreshed(): + try: + data = json.loads(request.read_text(encoding="utf-8-sig")) + return data if data["snapshot_id"] != old_snapshot else None + except (OSError, ValueError): + return None + fresh = wait_for(refreshed, 15) + assert fresh["design_path"] == snapshot["design_path"] + window.minimize() + handle = wait_for(floating) + assert not win32gui.IsWindowVisible(main_handle) + app.window(handle=handle).wrapper_object().invoke() + window.wait("visible", timeout=15) + if options.leave_collapsed: + window.child_window(title="收起为悬浮窗", control_type="Button").invoke() + wait_for(floating) + result = {"executable": str(executable), "pid": tool.pid, "request": str(request), + "project": snapshot["design_path"], "dpi": dpi, "client_rect": bounds, + "pdf_above_settings": True, "floating_heartbeat_updated": True, + "drag_before": first, "drag_after": moved, "restore_kept_pdf_page": True, + "fresh_snapshot": fresh["snapshot_id"], "native_minimize_restored": True, + "left_collapsed": options.leave_collapsed} + evidence = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/acceptance/compact-floating-20261011" + evidence.mkdir(parents=True, exist_ok=True) + (evidence / "native-ui.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") + print("PASS COMPACT NATIVE FLOATING UI", json.dumps(result, ensure_ascii=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/tools/acceptance/pdf_palette.py b/tools/acceptance/pdf_palette.py new file mode 100644 index 0000000..7f069bc --- /dev/null +++ b/tools/acceptance/pdf_palette.py @@ -0,0 +1,109 @@ +"""Compare native reference colors and check all scopes on explicit copies.""" +from __future__ import annotations + +import argparse +from collections import Counter +from dataclasses import asdict +import json +import os +from pathlib import Path +import sys +import threading + +from pypdf import PdfReader +from pypdf.generic import ContentStream + +from dx_productivity.features.pdf_export.exporter import export_project +from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings +from dx_productivity.features.pdf_export.settings import save_settings + + +def color_operations(path): + reader = PdfReader(path) + colors = Counter() + for page in reader.pages: + def inspect(stream, resources): + for operands, operator in ContentStream(stream, reader).operations: + if operator in (b'RG', b'rg'): + colors[tuple(round(float(value), 4) for value in operands)] += 1 + elif operator == b'Do': + obj = resources['/XObject'][operands[0]].get_object() + if obj.get('/Subtype') == '/Form': + inspect(obj, obj.get('/Resources', resources)) + inspect(page.get_contents(), page['/Resources']) + return colors + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--audio', required=True, type=Path) + parser.add_argument('--pon', required=True, type=Path) + parser.add_argument('--reference-source', required=True, type=Path) + parser.add_argument('--evidence', required=True, type=Path) + parser.add_argument('--resume-scopes', action='store_true') + options = parser.parse_args() + base = options.evidence.resolve() + base.mkdir(parents=True, exist_ok=True) + inherited_wdir = os.environ.get('WDIR') + configs = {str(path): path.read_bytes() for project in (options.audio, options.pon) + for path in project.parent.rglob('*') + if path.is_file() and path.name.casefold() in ('dxdesigner.xml', project.name.casefold(), 'sch2pdf.ini')} + results = [] + for name, project, scope, block, sheet, expected in ( + ('audio', options.audio, ExportScope.PROJECT, '', '', 1), + ('pon-page', options.pon, ExportScope.CURRENT_PAGE, 'PON', '03_FLASH', 1), + ('pon-block', options.pon, ExportScope.BLOCK, 'PON', '', 17), + ('pon-project', options.pon, ExportScope.PROJECT, '', '', 24), + ): + settings = PdfExportSettings(project, scope, block, base / name, True) + if options.resume_scopes: + runs = sorted((base / 'state/DxProductivity/pdf-runs').glob('*/request.json')) + matching = [run for run in runs if Path(json.loads(run.read_text(encoding='utf-8'))['output']).parent == settings.output_dir] + if matching: + run = matching[-1].parent + request = json.loads((run / 'request.json').read_text(encoding='utf-8')) + result = json.loads((run / 'result.json').read_text(encoding='utf-8')) + assert request['print_theme'] == 'reference' and result['state'] == 'success' + assert len(PdfReader(result['output']).pages) == expected + results.append({'output_path': result['output'], 'pages': expected, 'run_dir': str(run), 'state': 'success'}) + print(f'RESUMED VERIFIED SCOPE {name} pages={expected}', flush=True) + continue + result = export_project(settings, threading.Event(), print, active_block_name=block, + active_sheet_name=sheet, local_app_data=base / 'state', overwrite=True) + assert result.state == 'success', result.message + assert result.pages == expected, asdict(result) + results.append(asdict(result)) + save_settings(settings, config_path=base / f'{name}-settings.json') + print(f'PASS REFERENCE SCOPE {name} pages={result.pages}', flush=True) + + sys.path.insert(0, str(options.reference_source)) + from mentor_pdf_export.models import ExportOptions + from mentor_pdf_export.profiles import prepare_native_environment, build_command + from mentor_pdf_export.engine import run_engine + from dx_productivity.features.pdf_export.engine import discover_engine + + reference_run = base / 'original-tool-reference' + reference_run.mkdir(exist_ok=True) + reference_pdf = reference_run / 'reference.pdf' + profile = ExportOptions(print_theme='reference', stop_at='') + command = build_command(discover_engine(), options.audio, reference_pdf, profile) + assert run_engine(command, options.audio.parent, reference_run, threading.Event(), 180, + print, env=prepare_native_environment(reference_run, profile)) == 0 + ours = color_operations(results[0]['output_path']) + reference = color_operations(reference_pdf) + assert ours == reference, (ours, reference) + for rgb in ((1., 0., 0.), (0., 0., 1.), (0., .502, .502), (.502, 0., .502), (0., .502, 0.)): + assert ours[rgb] > 0, (rgb, ours) + assert os.environ.get('WDIR') == inherited_wdir + for path, before in configs.items(): + assert Path(path).read_bytes() == before, f'Source configuration changed: {path}' + report = {'scopes': results, 'reference_pdf': str(reference_pdf), + 'colors_match_reference': True, + 'colors': {str(rgb): count for rgb, count in ours.items()}, + 'source_configuration_unchanged': list(configs), 'parent_wdir_unchanged': True} + (base / 'palette-acceptance.json').write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str), encoding='utf-8') + print('PASS PDF REFERENCE PALETTE AND ALL SCOPES', json.dumps(report['colors']), flush=True) + + +if __name__ == '__main__': + main()