molforge-studio 7.4.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- main.py +71 -0
- molforge/__init__.py +19 -0
- molforge/ai/__init__.py +15 -0
- molforge/ai/deepseek_harness.py +185 -0
- molforge/ai/mcp/desktop_client.py +38 -0
- molforge/ai/mcp/desktop_service.py +121 -0
- molforge/ai/mcp/mcp_server.py +780 -0
- molforge/ai/mcp_bridge.py +945 -0
- molforge/ai/observation.py +152 -0
- molforge/ai/tools.py +455 -0
- molforge/application/__init__.py +22 -0
- molforge/application/ai/__init__.py +1 -0
- molforge/application/ai/deepseek_client.py +293 -0
- molforge/application/ai/observation.py +161 -0
- molforge/application/ai/tools.py +200 -0
- molforge/application/ai_proposals.py +166 -0
- molforge/application/bio_selection.py +143 -0
- molforge/application/builtin_commands.py +1445 -0
- molforge/application/calculators/__init__.py +10 -0
- molforge/application/calculators/base.py +143 -0
- molforge/application/calculators/calchem_engine.py +67 -0
- molforge/application/calculators/calchem_subprocess_worker.py +109 -0
- molforge/application/calculators/gaussian_engine.py +59 -0
- molforge/application/calculators/gaussian_job_spec.py +240 -0
- molforge/application/calculators/orca_engine.py +92 -0
- molforge/application/calculators/qc_input_generator.py +300 -0
- molforge/application/calculators/registry.py +29 -0
- molforge/application/calculators/rest_engine.py +262 -0
- molforge/application/command_bus.py +139 -0
- molforge/application/commands.py +55 -0
- molforge/application/conformers.py +143 -0
- molforge/application/document_session.py +156 -0
- molforge/application/events.py +74 -0
- molforge/application/fragment_catalog.py +422 -0
- molforge/application/fragment_commands.py +268 -0
- molforge/application/geometry_commands.py +84 -0
- molforge/application/history.py +105 -0
- molforge/application/internal_coordinates.py +293 -0
- molforge/application/invalidation.py +1174 -0
- molforge/application/jobs.py +185 -0
- molforge/application/measurement.py +167 -0
- molforge/application/measurement_targets.py +264 -0
- molforge/application/modeling_commands.py +61 -0
- molforge/application/plugins.py +197 -0
- molforge/application/ports/editor2d.py +85 -0
- molforge/application/reaction.py +75 -0
- molforge/application/selection.py +164 -0
- molforge/application/selection_commands.py +31 -0
- molforge/application/trajectory.py +120 -0
- molforge/application/trajectory_analysis.py +231 -0
- molforge/application/workspace_registry.py +226 -0
- molforge/core/__init__.py +12 -0
- molforge/core/conformer.py +45 -0
- molforge/core/molecule.py +150 -0
- molforge/core/orbital.py +33 -0
- molforge/core/properties.py +43 -0
- molforge/domain/__init__.py +12 -0
- molforge/domain/biomolecule.py +99 -0
- molforge/domain/chemical_summary.py +129 -0
- molforge/domain/chemistry.py +13 -0
- molforge/domain/coordinate_store.py +164 -0
- molforge/domain/coordination.py +133 -0
- molforge/domain/custom_fragments.py +255 -0
- molforge/domain/document.py +469 -0
- molforge/domain/element_reference.json +598 -0
- molforge/domain/elements.py +188 -0
- molforge/domain/ids.py +58 -0
- molforge/domain/massive_system.py +246 -0
- molforge/domain/periodic.py +116 -0
- molforge/domain/provenance.py +115 -0
- molforge/domain/topology.py +364 -0
- molforge/infrastructure/__init__.py +23 -0
- molforge/infrastructure/hpc/cluster_config.py +122 -0
- molforge/infrastructure/hpc/remote_executor.py +212 -0
- molforge/infrastructure/hpc/slurm_generator.py +93 -0
- molforge/io/__init__.py +35 -0
- molforge/io/calchem_bridge.py +407 -0
- molforge/io/calculators.py +893 -0
- molforge/io/cclib_adapter.py +422 -0
- molforge/io/conformers.py +183 -0
- molforge/io/cube_reader.py +215 -0
- molforge/io/custom_fragments.py +79 -0
- molforge/io/format_matrix.py +157 -0
- molforge/io/gemmi_adapter.py +150 -0
- molforge/io/history_skill.py +46 -0
- molforge/io/mdanalysis_adapter.py +155 -0
- molforge/io/mforge_storage.py +261 -0
- molforge/io/multiwfn_driver.py +614 -0
- molforge/io/openbabel_adapter.py +265 -0
- molforge/io/openbabel_handler.py +33 -0
- molforge/io/rdkit_adapter.py +1865 -0
- molforge/io/readers/__init__.py +10 -0
- molforge/io/readers/cube_reader.py +71 -0
- molforge/io/readers/gjf_reader.py +110 -0
- molforge/io/readers/glog_reader.py +45 -0
- molforge/io/readers/mol2_reader.py +36 -0
- molforge/io/readers/mol_reader.py +56 -0
- molforge/io/readers/pdb_reader.py +39 -0
- molforge/io/readers/smi_reader.py +40 -0
- molforge/io/readers/xyz_reader.py +47 -0
- molforge/io/registry.py +128 -0
- molforge/io/writers/__init__.py +7 -0
- molforge/io/writers/gjf_writer.py +68 -0
- molforge/io/writers/pdb_writer.py +37 -0
- molforge/io/writers/png_writer.py +31 -0
- molforge/io/writers/svg_writer.py +111 -0
- molforge/io/writers/xyz_writer.py +39 -0
- molforge/rendering/__init__.py +21 -0
- molforge/rendering/benchmark.py +121 -0
- molforge/rendering/bridge.py +60 -0
- molforge/rendering/contracts.py +119 -0
- molforge/rendering/glyph_scene.py +279 -0
- molforge/rendering/ketcher_bridge.py +131 -0
- molforge/rendering/ketcher_id_mapping.py +110 -0
- molforge/rendering/materials.py +127 -0
- molforge/rendering/molstar_backend.py +245 -0
- molforge/rendering/native_labels.py +134 -0
- molforge/rendering/orbitals.py +139 -0
- molforge/rendering/vtk_backend.py +2294 -0
- molforge/runtime.py +29 -0
- molforge/server/__init__.py +1 -0
- molforge/server/api_bridge.py +947 -0
- molforge/ui/__init__.py +1 -0
- molforge/ui/assets/caffeine_2d.svg +150 -0
- molforge/ui/assets/caffeine_3d_preview.svg +209 -0
- molforge/ui/assets/caffeine_preview.json +302 -0
- molforge/ui/assets/icons/atom.svg +1 -0
- molforge/ui/assets/icons/bond.svg +1 -0
- molforge/ui/assets/icons/cleanup.svg +1 -0
- molforge/ui/assets/icons/export.svg +1 -0
- molforge/ui/assets/icons/fragments.svg +1 -0
- molforge/ui/assets/icons/history.svg +1 -0
- molforge/ui/assets/icons/jobs.svg +1 -0
- molforge/ui/assets/icons/measure.svg +1 -0
- molforge/ui/assets/icons/molecules.svg +1 -0
- molforge/ui/assets/icons/overview.svg +1 -0
- molforge/ui/assets/icons/ring.svg +1 -0
- molforge/ui/assets/icons/search.svg +1 -0
- molforge/ui/assets/icons/select.svg +1 -0
- molforge/ui/assets/icons/settings.svg +1 -0
- molforge/ui/assets/icons/templates.svg +1 -0
- molforge/ui/assets/molforge_logo.ico +0 -0
- molforge/ui/assets/molforge_logo.png +0 -0
- molforge/ui/atom_labels.py +92 -0
- molforge/ui/bio_structure_dialog.py +57 -0
- molforge/ui/conformer_dialog.py +151 -0
- molforge/ui/dialogs/__init__.py +2 -0
- molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
- molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
- molforge/ui/dialogs/element_fragments.py +130 -0
- molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
- molforge/ui/dialogs/hpc_job_dialog.py +427 -0
- molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
- molforge/ui/editor2d_widget.py +1803 -0
- molforge/ui/element_picker.py +218 -0
- molforge/ui/gmv_window_manager.py +65 -0
- molforge/ui/gromacs_job_dialog.py +47 -0
- molforge/ui/hotkeys.py +107 -0
- molforge/ui/i18n.py +237 -0
- molforge/ui/live_llm_dialog.py +135 -0
- molforge/ui/llm_config_dialog.py +103 -0
- molforge/ui/modeling_actions.py +176 -0
- molforge/ui/molstar_widget.py +98 -0
- molforge/ui/molstar_window.py +85 -0
- molforge/ui/panels.py +2966 -0
- molforge/ui/qc_result_dialog.py +1924 -0
- molforge/ui/render3d_widget.py +1579 -0
- molforge/ui/scrolling.py +52 -0
- molforge/ui/settings_panel.py +330 -0
- molforge/ui/shells/__init__.py +4 -0
- molforge/ui/shells/base_shell.py +72 -0
- molforge/ui/shells/document_tabs.py +715 -0
- molforge/ui/shells/studio_2d.py +339 -0
- molforge/ui/shells/studio_3d.py +401 -0
- molforge/ui/shells/studio_split.py +370 -0
- molforge/ui/shells/workflow_inputs.py +698 -0
- molforge/ui/theme.py +719 -0
- molforge/ui/trajectory_window.py +333 -0
- molforge/ui/views.py +892 -0
- molforge/ui/vtk_multiview_widget.py +141 -0
- molforge/ui/welcome_window.py +223 -0
- molforge/ui/window.py +3320 -0
- molforge/workflows/__init__.py +25 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/03-/342/225/244/320/225/342/225/250/342/226/221/342/225/250/320/246/342/225/244/320/227/342/225/250/342/225/226/342/225/250/342/224/220/342/225/244/320/225/342/225/250/320/247/342/225/250/342/226/221/342/225/244/320/224/321/202/320/245/320/254/342/225/250/320/265/analysis_mol.py +244 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/rms_roughness.py +33 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/xpm_2.py +117 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/09-/342/225/244/320/231/342/225/250/320/240/342/225/250/320/277/342/225/244/320/227/342/225/250/320/256/342/225/250/320/247/marcus_rate.py +60 -0
- molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
- molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
- molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
- molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
- molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
- molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
- molforge/workflows/dipole_analysis.py +32 -0
- molforge/workflows/esp_surface.py +36 -0
- molforge/workflows/gromacs_submit.py +167 -0
- molforge/workflows/homo_lumo_plot.py +59 -0
- molforge/workflows/igmh_interaction.py +111 -0
- molforge/workflows/md_rdf_analysis.py +134 -0
- molforge/workflows/md_studio.py +255 -0
- molforge/workflows/osc_energy_diagram.py +24 -0
- molforge/workflows/planarity_analysis.py +66 -0
- molforge/workflows/reorganization_energy.py +166 -0
- molforge/workflows/scientific_workflows.py +650 -0
- molforge_studio-7.4.3.dist-info/METADATA +215 -0
- molforge_studio-7.4.3.dist-info/RECORD +219 -0
- molforge_studio-7.4.3.dist-info/WHEEL +5 -0
- molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
- molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
- molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
molforge/ui/panels.py
ADDED
|
@@ -0,0 +1,2966 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ui/panels.py - MolForge 现代科学级桌面左右侧边栏与属性面板系统
|
|
3
|
+
===================================================================
|
|
4
|
+
核心重构升级:
|
|
5
|
+
1. 【左侧栏 LeftPanel 全能重构】:
|
|
6
|
+
- Tab 0: 🧱 结构砌块 (OSC 给受体共轭骨架、经典分子、常见芳香/杂环、常用官能团,内置实时模糊过滤搜索)
|
|
7
|
+
- Tab 1: ⚛️ 元素与键 (常用元素 CPK 真实色标网格、化学键级一键设定、自动加氢/去氢/2D美化/3D力场优化/居中)
|
|
8
|
+
- Tab 2: 🌳 结构树 (实时原子列表与化学键列表,支持点击列表行直接在 2D/3D 画布中联动高亮选中,实现全链路响应)
|
|
9
|
+
2. 【彻底消除滚轮卡死与垂直滚动失效】:
|
|
10
|
+
- 彻底移除 CollapsibleCard 标题行多余的 HorizontalWheelScrollArea,消除无谓事件拦截,恢复原生顺滑垂直滚轮!
|
|
11
|
+
- 优化 WheelGuardFilter,未聚焦控件的滚轮事件主动向外冒泡给垂直滚动容器,绝不吃掉滚轮事件!
|
|
12
|
+
3. 【右侧栏 RightPanel 工业级抗截断与模型配置】:
|
|
13
|
+
- 面板最小宽度提至 330px,输入框、按钮预留充裕显示边距,杜绝任何中文字体或 Placeholder 被截断!
|
|
14
|
+
- 模型名采用高可靠 QLineEdit 直接绑定(去除多余下拉覆盖 Bug),新增醒目「💾 保存配置」按键与「✓ 已同步」实时灯。
|
|
15
|
+
- AI 助手就地异步对话,支持模型调用工具时界面确认与分析结果格式化渲染,并提供可选「🗗 独立弹窗」。
|
|
16
|
+
- 属性面板在无选中项时呈现分子全局物化画像(MW、单同位素、电荷、自旋、LogP、TPSA、对称性等)。
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import os
|
|
21
|
+
import sys
|
|
22
|
+
import html
|
|
23
|
+
import json
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from PyQt6.QtCore import Qt, QSize, QSettings, pyqtSignal, QEvent, QTimer
|
|
27
|
+
from PyQt6.QtGui import QIcon, QWheelEvent, QColor, QCursor, QFont
|
|
28
|
+
from PyQt6.QtWidgets import (
|
|
29
|
+
QFrame, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QPushButton,
|
|
30
|
+
QScrollArea, QLineEdit, QStackedWidget, QButtonGroup, QComboBox, QTextEdit,
|
|
31
|
+
QSizePolicy, QDoubleSpinBox, QMessageBox, QTableWidget, QTableWidgetItem,
|
|
32
|
+
QHeaderView, QAbstractItemView, QSlider, QListWidget, QListWidgetItem, QCheckBox, QMenu,
|
|
33
|
+
QApplication, QFileDialog, QFormLayout, QDialog, QInputDialog
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
from .settings_panel import WheelGuardFilter, install_wheel_guard
|
|
37
|
+
from .theme import refresh_button_visual
|
|
38
|
+
from .scrolling import HorizontalWheelScrollArea
|
|
39
|
+
|
|
40
|
+
ICON_DIR = Path(__file__).resolve().parent / "assets" / "icons"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def ic(name: str) -> QIcon:
|
|
44
|
+
p = ICON_DIR / f"{name}.svg"
|
|
45
|
+
return QIcon(str(p)) if p.exists() else QIcon()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def section(text: str) -> QLabel:
|
|
49
|
+
q = QLabel(text.upper())
|
|
50
|
+
q.setProperty("role", "section")
|
|
51
|
+
return q
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def muted(text: str) -> QLabel:
|
|
55
|
+
q = QLabel(text)
|
|
56
|
+
q.setWordWrap(True)
|
|
57
|
+
q.setProperty("role", "muted")
|
|
58
|
+
return q
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def create_smooth_scroll_area(content_widget: QWidget) -> QScrollArea:
|
|
62
|
+
"""创建不截断、无背景补丁、自适应宽度的顺滑纵向滚动区。"""
|
|
63
|
+
content_widget.setObjectName("ScrollPage")
|
|
64
|
+
content_widget.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)
|
|
65
|
+
sa = QScrollArea()
|
|
66
|
+
sa.setWidgetResizable(True)
|
|
67
|
+
sa.setFrameShape(QFrame.Shape.NoFrame)
|
|
68
|
+
sa.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
|
69
|
+
sa.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
|
70
|
+
sa.setWidget(content_widget)
|
|
71
|
+
return sa
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class CollapsibleCard(QFrame):
|
|
75
|
+
"""Blender / DaVinci 风格可折叠属性卡片模块(纯净标题,不截获垂直滚轮事件)。"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, title: str, expanded: bool = True, parent=None):
|
|
78
|
+
super().__init__(parent)
|
|
79
|
+
self.setObjectName("CollapsibleCard")
|
|
80
|
+
self._title = title
|
|
81
|
+
|
|
82
|
+
root = QVBoxLayout(self)
|
|
83
|
+
root.setContentsMargins(0, 0, 0, 0)
|
|
84
|
+
root.setSpacing(0)
|
|
85
|
+
|
|
86
|
+
arrow = "▾" if expanded else "▸"
|
|
87
|
+
self.header_btn = QPushButton(f"{arrow} {title}")
|
|
88
|
+
self.header_btn.setObjectName("CardHeaderBtn")
|
|
89
|
+
self.header_btn.setCheckable(True)
|
|
90
|
+
self.header_btn.setChecked(expanded)
|
|
91
|
+
self.header_btn.clicked.connect(self._on_toggled)
|
|
92
|
+
root.addWidget(self.header_btn)
|
|
93
|
+
|
|
94
|
+
self.body = QWidget()
|
|
95
|
+
self.body.setObjectName("ScrollPage")
|
|
96
|
+
self.body_layout = QVBoxLayout(self.body)
|
|
97
|
+
self.body_layout.setContentsMargins(10, 9, 10, 10)
|
|
98
|
+
self.body_layout.setSpacing(7)
|
|
99
|
+
self.body.setVisible(expanded)
|
|
100
|
+
root.addWidget(self.body)
|
|
101
|
+
|
|
102
|
+
def _on_toggled(self, checked: bool):
|
|
103
|
+
self.body.setVisible(checked)
|
|
104
|
+
arrow = "▾" if checked else "▸"
|
|
105
|
+
self.header_btn.setText(f"{arrow} {self._title}" if self._title else "")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class TopBar(QFrame):
|
|
109
|
+
open_clicked = pyqtSignal()
|
|
110
|
+
export_clicked = pyqtSignal()
|
|
111
|
+
qc_workbench_clicked = pyqtSignal()
|
|
112
|
+
search_submitted = pyqtSignal(str)
|
|
113
|
+
|
|
114
|
+
def __init__(self):
|
|
115
|
+
super().__init__()
|
|
116
|
+
self.setObjectName("TopBar")
|
|
117
|
+
outer = QVBoxLayout(self)
|
|
118
|
+
outer.setContentsMargins(0, 0, 0, 0)
|
|
119
|
+
outer.setSpacing(0)
|
|
120
|
+
|
|
121
|
+
strip = QWidget()
|
|
122
|
+
strip.setObjectName("ToolbarStrip")
|
|
123
|
+
lay = QHBoxLayout(strip)
|
|
124
|
+
lay.setContentsMargins(12, 6, 12, 6)
|
|
125
|
+
lay.setSpacing(8)
|
|
126
|
+
|
|
127
|
+
brand = QLabel("MolForge")
|
|
128
|
+
brand.setProperty("role", "brand")
|
|
129
|
+
self.brand_label = brand
|
|
130
|
+
self._font_size = 14
|
|
131
|
+
self._compact = False
|
|
132
|
+
brand.setStyleSheet("font-size:16px; font-weight:800; color:#66DEC9; margin-right:4px;")
|
|
133
|
+
lay.addWidget(brand)
|
|
134
|
+
|
|
135
|
+
self.project_label = QLabel("未命名分子")
|
|
136
|
+
self.project_label.setStyleSheet("color:#EAF2F6; font-size:13px; font-weight:600;")
|
|
137
|
+
lay.addWidget(self.project_label)
|
|
138
|
+
|
|
139
|
+
self.status_label = QLabel("● 就绪")
|
|
140
|
+
self._status_color = "#66DEC9"
|
|
141
|
+
self.status_label.setStyleSheet("color:#66DEC9; font-weight:700; font-size:12px;")
|
|
142
|
+
lay.addWidget(self.status_label)
|
|
143
|
+
|
|
144
|
+
lay.addStretch(1)
|
|
145
|
+
|
|
146
|
+
self.search_input = QLineEdit()
|
|
147
|
+
self.search_input.setPlaceholderText("🔍 搜分子/SMILES/AI指令 (Ctrl+K)")
|
|
148
|
+
self.search_input.setToolTip(
|
|
149
|
+
"【智能全局检索入口】按 Enter 立即执行:\n"
|
|
150
|
+
"• 分子名:输入 '咖啡因'、'PM6'、'BDT' 快速载入分子\n"
|
|
151
|
+
"• SMILES:输入任意结构式 (如 c1ccccc1) 快速生成\n"
|
|
152
|
+
"• AI 指令:输入提问或修改指令直达 AI 科研助手"
|
|
153
|
+
)
|
|
154
|
+
self.search_input.setMinimumWidth(200)
|
|
155
|
+
self.search_input.setMaximumWidth(280)
|
|
156
|
+
self.search_input.returnPressed.connect(lambda: self.search_submitted.emit(self.search_input.text().strip()))
|
|
157
|
+
lay.addWidget(self.search_input)
|
|
158
|
+
|
|
159
|
+
self.open_btn = QPushButton("📂 打开 / 导入")
|
|
160
|
+
self.open_btn.setMinimumWidth(96)
|
|
161
|
+
self.open_btn.setToolTip("打开分子或量化输出:.log / .out / .gjf / .xyz / .mol / .sdf / .pdb / ctrl.in (Ctrl+O)")
|
|
162
|
+
self.open_btn.clicked.connect(self.open_clicked.emit)
|
|
163
|
+
lay.addWidget(self.open_btn)
|
|
164
|
+
|
|
165
|
+
self.qc_btn = QPushButton("⚛ 量化 / 能级图")
|
|
166
|
+
self.qc_btn.setMinimumWidth(106)
|
|
167
|
+
self.qc_btn.setToolTip("打开 Gaussian、复旦 REST 与 OSC HOMO-LUMO 能级图工作台 (Ctrl+G)")
|
|
168
|
+
self.qc_btn.clicked.connect(self.qc_workbench_clicked.emit)
|
|
169
|
+
lay.addWidget(self.qc_btn)
|
|
170
|
+
|
|
171
|
+
self.export_btn = QPushButton("💾 导出 / 保存")
|
|
172
|
+
self.export_btn.setMinimumWidth(96)
|
|
173
|
+
self.export_btn.setProperty("role", "action")
|
|
174
|
+
self.export_btn.setToolTip("导出 2D 矢量 SVG / PNG / GJF / REST ctrl.in / XYZ / PDB / MOL (Ctrl+S)")
|
|
175
|
+
self.export_btn.clicked.connect(self.export_clicked.emit)
|
|
176
|
+
lay.addWidget(self.export_btn)
|
|
177
|
+
|
|
178
|
+
outer.addWidget(strip)
|
|
179
|
+
self.setFixedHeight(48)
|
|
180
|
+
|
|
181
|
+
def set_project(self, text: str):
|
|
182
|
+
self.project_label.setText(text)
|
|
183
|
+
|
|
184
|
+
def set_status(self, text: str, color: str = "#66DEC9"):
|
|
185
|
+
self._status_color = color
|
|
186
|
+
sz_sm = max(10, getattr(self, "_font_size", 14) - 2)
|
|
187
|
+
self.status_label.setText(f"● {text}")
|
|
188
|
+
self.status_label.setStyleSheet(f"color:{color}; font-weight:700; font-size:{sz_sm}px;")
|
|
189
|
+
|
|
190
|
+
def set_compact(self, compact: bool):
|
|
191
|
+
self._compact = bool(compact)
|
|
192
|
+
self.project_label.setVisible(not compact)
|
|
193
|
+
self.status_label.setVisible(not compact)
|
|
194
|
+
self.open_btn.setText("打开" if compact else "📂 打开 / 导入")
|
|
195
|
+
self.qc_btn.setText("量化" if compact else "⚛ 量化 / 能级图")
|
|
196
|
+
self.export_btn.setText("导出" if compact else "💾 导出 / 保存")
|
|
197
|
+
for button, normal_width in ((self.open_btn, 96), (self.qc_btn, 106), (self.export_btn, 96)):
|
|
198
|
+
button.setMinimumWidth(58 if compact else normal_width)
|
|
199
|
+
button.setMaximumWidth(76 if compact else 200)
|
|
200
|
+
self.search_input.setMinimumWidth(120 if compact else 200)
|
|
201
|
+
self.search_input.setMaximumWidth(190 if compact else 280)
|
|
202
|
+
|
|
203
|
+
def apply_typography(self, family: str, base_size: int):
|
|
204
|
+
sz = max(10, int(base_size))
|
|
205
|
+
self._font_size = sz
|
|
206
|
+
self.setFixedHeight(max(48, sz + 30))
|
|
207
|
+
f = QFont(family)
|
|
208
|
+
f.setPixelSize(sz)
|
|
209
|
+
self.setFont(f)
|
|
210
|
+
self.brand_label.setStyleSheet(f"font-size:{sz + 2}px; font-weight:800; color:#66DEC9; margin-right:4px;")
|
|
211
|
+
self.project_label.setStyleSheet(f"color:#EAF2F6; font-size:{max(11, sz - 1)}px; font-weight:600;")
|
|
212
|
+
self.status_label.setStyleSheet(
|
|
213
|
+
f"color:{getattr(self, '_status_color', '#66DEC9')}; font-weight:700; font-size:{max(10, sz - 2)}px;"
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class NavigationRail(QFrame):
|
|
218
|
+
"""为了兼容性保留的导航条对象(现主要作为内部信号兼容)"""
|
|
219
|
+
rail_selected = pyqtSignal(int)
|
|
220
|
+
|
|
221
|
+
def __init__(self):
|
|
222
|
+
super().__init__()
|
|
223
|
+
self.setObjectName("NavRail")
|
|
224
|
+
self.setFixedWidth(0)
|
|
225
|
+
self.setVisible(False)
|
|
226
|
+
|
|
227
|
+
def set_active_index(self, tab_idx: int):
|
|
228
|
+
pass
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# ==============================================================================
|
|
232
|
+
# 自定义砌块与分子片段保存对话框
|
|
233
|
+
# ==============================================================================
|
|
234
|
+
|
|
235
|
+
class SaveCustomFragmentDialog(QDialog):
|
|
236
|
+
"""保存自定义砌块 / 分子 / 片段的交互对话框,支持设置名称、选择/新建分组、类型与说明。"""
|
|
237
|
+
|
|
238
|
+
def __init__(self, parent=None, default_name: str = "", default_desc: str = "", default_type: str = "fragment"):
|
|
239
|
+
super().__init__(parent)
|
|
240
|
+
self.setWindowTitle("保存到自定义结构库")
|
|
241
|
+
self.setMinimumWidth(400)
|
|
242
|
+
from ..domain.custom_fragments import get_custom_groups, DEFAULT_GROUP
|
|
243
|
+
|
|
244
|
+
lay = QVBoxLayout(self)
|
|
245
|
+
form = QFormLayout()
|
|
246
|
+
form.setSpacing(10)
|
|
247
|
+
|
|
248
|
+
self.name_edit = QLineEdit(default_name)
|
|
249
|
+
self.name_edit.setPlaceholderText("请输入自定义名称...")
|
|
250
|
+
form.addRow("名称 (*):", self.name_edit)
|
|
251
|
+
|
|
252
|
+
# 分组选择与新建
|
|
253
|
+
self.group_combo = QComboBox()
|
|
254
|
+
self.group_combo.setEditable(True)
|
|
255
|
+
groups = get_custom_groups()
|
|
256
|
+
for g in groups:
|
|
257
|
+
self.group_combo.addItem(g)
|
|
258
|
+
self.group_combo.setCurrentText(groups[0] if groups else DEFAULT_GROUP)
|
|
259
|
+
self.group_combo.setToolTip("选择已有分组,或直接输入新分组名称以创建新分组")
|
|
260
|
+
form.addRow("自定义分组:", self.group_combo)
|
|
261
|
+
|
|
262
|
+
# 结构类型
|
|
263
|
+
self.type_combo = QComboBox()
|
|
264
|
+
self.type_combo.addItem("结构片段 / 砌块 (Fragment)", "fragment")
|
|
265
|
+
self.type_combo.addItem("完整分子 (Molecule)", "molecule")
|
|
266
|
+
self.type_combo.addItem("官能团 (Functional Group)", "group")
|
|
267
|
+
if default_type == "molecule":
|
|
268
|
+
self.type_combo.setCurrentIndex(1)
|
|
269
|
+
elif default_type == "group":
|
|
270
|
+
self.type_combo.setCurrentIndex(2)
|
|
271
|
+
else:
|
|
272
|
+
self.type_combo.setCurrentIndex(0)
|
|
273
|
+
form.addRow("结构类别:", self.type_combo)
|
|
274
|
+
|
|
275
|
+
self.desc_edit = QLineEdit(default_desc)
|
|
276
|
+
self.desc_edit.setPlaceholderText("可选:添加性质或用途说明...")
|
|
277
|
+
form.addRow("备注说明:", self.desc_edit)
|
|
278
|
+
|
|
279
|
+
lay.addLayout(form)
|
|
280
|
+
|
|
281
|
+
btns = QHBoxLayout()
|
|
282
|
+
btns.addStretch()
|
|
283
|
+
cancel_btn = QPushButton("取消")
|
|
284
|
+
cancel_btn.clicked.connect(self.reject)
|
|
285
|
+
btns.addWidget(cancel_btn)
|
|
286
|
+
|
|
287
|
+
save_btn = QPushButton("💾 保存到库")
|
|
288
|
+
save_btn.setProperty("role", "action")
|
|
289
|
+
save_btn.clicked.connect(self._on_save)
|
|
290
|
+
btns.addWidget(save_btn)
|
|
291
|
+
lay.addLayout(btns)
|
|
292
|
+
|
|
293
|
+
def _on_save(self):
|
|
294
|
+
name = self.name_edit.text().strip()
|
|
295
|
+
if not name:
|
|
296
|
+
QMessageBox.warning(self, "输入有误", "名称不能为空!")
|
|
297
|
+
return
|
|
298
|
+
self.accept()
|
|
299
|
+
|
|
300
|
+
def get_data(self) -> dict:
|
|
301
|
+
return {
|
|
302
|
+
"name": self.name_edit.text().strip(),
|
|
303
|
+
"group": self.group_combo.currentText().strip() or "🌟 默认分组",
|
|
304
|
+
"type": self.type_combo.currentData() or "fragment",
|
|
305
|
+
"description": self.desc_edit.text().strip(),
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# ==============================================================================
|
|
310
|
+
# 左侧全功能化学工具箱与结构树 (LeftPanel / Sidebar)
|
|
311
|
+
# ==============================================================================
|
|
312
|
+
|
|
313
|
+
class LeftPanel(QFrame):
|
|
314
|
+
"""
|
|
315
|
+
MolForge 现代科学建模工具箱与结构树 (LeftPanel)
|
|
316
|
+
三合一全功能面板:
|
|
317
|
+
Tab 0: 🧱 结构砌块 (共轭砌块、环系模板、官能团取代,带实时搜索)
|
|
318
|
+
Tab 1: ⚛️ 元素与键 (CPK 常用元素调色板、键级设定、结构几何修饰)
|
|
319
|
+
Tab 2: 🌳 结构树 (实时原子列表与化学键列表,支持点击联动 2D/3D 画布选中)
|
|
320
|
+
"""
|
|
321
|
+
|
|
322
|
+
def __init__(self, on_molecule_selected=None, on_ring_insert=None, on_fg_insert=None, parent=None):
|
|
323
|
+
super().__init__(parent)
|
|
324
|
+
self.setObjectName("Sidebar")
|
|
325
|
+
self.setMinimumWidth(210)
|
|
326
|
+
self.setMaximumWidth(380)
|
|
327
|
+
|
|
328
|
+
self.on_molecule_selected = on_molecule_selected
|
|
329
|
+
self.on_ring_insert = on_ring_insert
|
|
330
|
+
self.on_fg_insert = on_fg_insert
|
|
331
|
+
self.on_element_selected = None
|
|
332
|
+
self.on_bond_order_selected = None
|
|
333
|
+
self.on_clean_2d = None
|
|
334
|
+
self.on_clean_3d = None
|
|
335
|
+
self.on_add_h = None
|
|
336
|
+
self.on_remove_h = None
|
|
337
|
+
self.on_center = None
|
|
338
|
+
self.on_atom_selected = None
|
|
339
|
+
self.on_bond_selected = None
|
|
340
|
+
self._current_document = None
|
|
341
|
+
self._font_size = 14
|
|
342
|
+
|
|
343
|
+
self._wheel_guard = WheelGuardFilter(self)
|
|
344
|
+
|
|
345
|
+
outer = QVBoxLayout(self)
|
|
346
|
+
outer.setContentsMargins(6, 8, 6, 8)
|
|
347
|
+
outer.setSpacing(6)
|
|
348
|
+
|
|
349
|
+
# 顶部胶囊导航条
|
|
350
|
+
tab_frame = QFrame()
|
|
351
|
+
tab_frame.setObjectName("TabStripFrame")
|
|
352
|
+
tabs = QHBoxLayout(tab_frame)
|
|
353
|
+
tabs.setContentsMargins(2, 2, 2, 2)
|
|
354
|
+
tabs.setSpacing(2)
|
|
355
|
+
|
|
356
|
+
self.tab_buttons: list[QPushButton] = []
|
|
357
|
+
for i, title in enumerate(("🧱 砌块库", "⚛️ 元素/键", "🌳 结构树")):
|
|
358
|
+
b = QPushButton(title)
|
|
359
|
+
b.setProperty("role", "tab")
|
|
360
|
+
b.setCheckable(True)
|
|
361
|
+
b.clicked.connect(lambda checked=False, idx=i: self.switch_tab(idx))
|
|
362
|
+
tabs.addWidget(b)
|
|
363
|
+
self.tab_buttons.append(b)
|
|
364
|
+
refresh_button_visual(b, active=(i == 0))
|
|
365
|
+
outer.addWidget(tab_frame)
|
|
366
|
+
|
|
367
|
+
self.stack = QStackedWidget()
|
|
368
|
+
outer.addWidget(self.stack, 1)
|
|
369
|
+
|
|
370
|
+
# 1. 砌块与基团页
|
|
371
|
+
self.stack.addWidget(create_smooth_scroll_area(self._build_fragments_page()))
|
|
372
|
+
# 2. 元素与成键页
|
|
373
|
+
self.stack.addWidget(create_smooth_scroll_area(self._build_elements_and_bonds_page()))
|
|
374
|
+
# 3. 结构树与测量页
|
|
375
|
+
self.stack.addWidget(create_smooth_scroll_area(self._build_structure_tree_page()))
|
|
376
|
+
|
|
377
|
+
self.stack.setCurrentIndex(0)
|
|
378
|
+
|
|
379
|
+
def _resolve_active_document(self, document=None):
|
|
380
|
+
doc = document if document is not None else getattr(self, "_current_document", None)
|
|
381
|
+
if doc is None and getattr(self, "_window_ref", None) is not None:
|
|
382
|
+
doc = getattr(self._window_ref, "document", None)
|
|
383
|
+
return doc
|
|
384
|
+
|
|
385
|
+
def set_document(self, document):
|
|
386
|
+
self._current_document = document
|
|
387
|
+
if self.stack.currentIndex() == 2:
|
|
388
|
+
self.refresh_structure_tree(document)
|
|
389
|
+
|
|
390
|
+
def switch_tab(self, index: int):
|
|
391
|
+
if 0 <= index < self.stack.count():
|
|
392
|
+
self.stack.setCurrentIndex(index)
|
|
393
|
+
for i, b in enumerate(self.tab_buttons):
|
|
394
|
+
refresh_button_visual(b, active=(i == index))
|
|
395
|
+
if index == 2:
|
|
396
|
+
doc = self._resolve_active_document()
|
|
397
|
+
if doc is not None:
|
|
398
|
+
self.refresh_structure_tree(doc)
|
|
399
|
+
|
|
400
|
+
# ---------- Tab 0: 结构砌块库 ----------
|
|
401
|
+
def _build_fragments_page(self) -> QWidget:
|
|
402
|
+
w = QWidget()
|
|
403
|
+
lay = QVBoxLayout(w)
|
|
404
|
+
lay.setContentsMargins(4, 4, 4, 8)
|
|
405
|
+
lay.setSpacing(7)
|
|
406
|
+
|
|
407
|
+
# 快速搜索框
|
|
408
|
+
self.filter_edit = QLineEdit()
|
|
409
|
+
self.filter_edit.setPlaceholderText("🔍 快速筛选砌块、分子、环系或基团...")
|
|
410
|
+
self.filter_edit.textChanged.connect(self._apply_filter)
|
|
411
|
+
lay.addWidget(self.filter_edit)
|
|
412
|
+
|
|
413
|
+
# 💡 使用技巧提示(小巧紧凑的 Hover 提示徽标,不挤占竖向空间)
|
|
414
|
+
hint_row = QHBoxLayout()
|
|
415
|
+
lbl_tip = QLabel("💡 砌块与基团使用技巧 ⓘ")
|
|
416
|
+
self.lbl_tip = lbl_tip
|
|
417
|
+
lbl_tip.setCursor(Qt.CursorShape.WhatsThisCursor)
|
|
418
|
+
lbl_tip.setStyleSheet("color: #5EEAD4; font-size: 11px; padding: 1px 4px; font-weight: 600;")
|
|
419
|
+
lbl_tip.setToolTip(
|
|
420
|
+
"【结构砌块与官能团使用指南】\n"
|
|
421
|
+
"• 选中原子时:点击环系/基团,自动在其上精准接枝取代并保持立体构型\n"
|
|
422
|
+
"• 未选原子时:点击环系/基团,在画布中心放置独立新结构\n"
|
|
423
|
+
"• 点击分子库:一键载入标准分子,支持随时另存为自定义砌块\n"
|
|
424
|
+
"• 自定义库:支持存整分子/选中片段,并可按文件夹分组管理"
|
|
425
|
+
)
|
|
426
|
+
hint_row.addWidget(lbl_tip)
|
|
427
|
+
hint_row.addStretch()
|
|
428
|
+
lay.addLayout(hint_row)
|
|
429
|
+
|
|
430
|
+
# ⭐ 我的自定义砌块 (用户保存分子与片段库)
|
|
431
|
+
self.custom_card = CollapsibleCard("⭐ 我的自定义砌块 (CUSTOM)", expanded=True)
|
|
432
|
+
c_lay = self.custom_card.body_layout
|
|
433
|
+
row_c_actions = QHBoxLayout()
|
|
434
|
+
btn_save_cur = QPushButton("➕ 存整分子")
|
|
435
|
+
btn_save_cur.setToolTip("将当前画布中的分子保存为自定义砌块")
|
|
436
|
+
btn_save_cur.setStyleSheet("QPushButton { font-weight:700; }")
|
|
437
|
+
btn_save_cur.clicked.connect(self._on_save_current_as_fragment)
|
|
438
|
+
row_c_actions.addWidget(btn_save_cur)
|
|
439
|
+
|
|
440
|
+
btn_save_sel = QPushButton("✂️ 存选中片段")
|
|
441
|
+
btn_save_sel.setToolTip("将当前画布中选中的原子片段保存为自定义砌块")
|
|
442
|
+
btn_save_sel.setStyleSheet("QPushButton { font-weight:700; }")
|
|
443
|
+
btn_save_sel.clicked.connect(self._on_save_selected_as_fragment)
|
|
444
|
+
row_c_actions.addWidget(btn_save_sel)
|
|
445
|
+
|
|
446
|
+
btn_add_grp = QPushButton("📁+ 新分组")
|
|
447
|
+
btn_add_grp.setToolTip("新建一个自定义分组(空分组也会即时保存并在下方呈现)")
|
|
448
|
+
btn_add_grp.setStyleSheet("QPushButton { font-weight:700; color:#5EEAD4; }")
|
|
449
|
+
btn_add_grp.clicked.connect(self._on_create_new_group)
|
|
450
|
+
row_c_actions.addWidget(btn_add_grp)
|
|
451
|
+
c_lay.addLayout(row_c_actions)
|
|
452
|
+
|
|
453
|
+
self.custom_chips_container = QWidget()
|
|
454
|
+
self.custom_chips_layout = QVBoxLayout(self.custom_chips_container)
|
|
455
|
+
self.custom_chips_layout.setContentsMargins(0, 2, 0, 0)
|
|
456
|
+
self.custom_chips_layout.setSpacing(4)
|
|
457
|
+
c_lay.addWidget(self.custom_chips_container)
|
|
458
|
+
self.custom_fragment_buttons: list[tuple[str, QPushButton]] = []
|
|
459
|
+
self._refresh_custom_fragments_card()
|
|
460
|
+
lay.addWidget(self.custom_card)
|
|
461
|
+
|
|
462
|
+
# 分类分子库
|
|
463
|
+
self.molecule_buttons: list[tuple[str, QPushButton]] = []
|
|
464
|
+
from ..io.rdkit_adapter import SAMPLE_MOLECULES
|
|
465
|
+
|
|
466
|
+
mol_categories = [
|
|
467
|
+
("🌟 光伏与共轭材料 (OSC)", [
|
|
468
|
+
"PM6 核心单元 (BDT-F)", "Y6 受体核心单元", "ITIC 核心单元", "BDT 给体核 (苯并二噻吩)",
|
|
469
|
+
"咔唑 (Carbazole)", "芴 (Fluorene)", "螺芴 (Spiro 核心)", "并五苯 (Pentacene)",
|
|
470
|
+
"碗烯 (Corannulene/C60片段)", "IC 端基 (1,3-茚满酮型)", "2F-IC 端基 (Y6/IT-4F)",
|
|
471
|
+
"2Cl-IC 端基 (BTP-eC9)", "BT 受体核 (苯并噻二唑)", "DTBT 光伏单元", "噻吩-苯-噻吩"
|
|
472
|
+
], True),
|
|
473
|
+
("💊 常用药物与生化单元 (BIO)", [
|
|
474
|
+
"咖啡因", "阿司匹林", "布洛芬", "扑热息痛 (对乙酰氨基酚)",
|
|
475
|
+
"腺嘌呤 (Adenine)", "鸟嘌呤 (Guanine)", "胞嘧啶 (Cytosine)",
|
|
476
|
+
"胸腺嘧啶 (Thymine)", "尿嘧啶 (Uracil)"
|
|
477
|
+
], False),
|
|
478
|
+
("⬡ 经典芳烃与多环稠环", [
|
|
479
|
+
"苯", "萘 (Naphthalene)", "蒽 (Anthracene)", "菲 (Phenanthrene)",
|
|
480
|
+
"芘 (Pyrene)", "三联苯 (p-Terphenyl)"
|
|
481
|
+
], False),
|
|
482
|
+
("⬠ 常见杂环与配体", [
|
|
483
|
+
"吡啶 (Pyridine)", "噻吩 (Thiophene)", "呋喃 (Furan)", "吡咯 (Pyrrole)",
|
|
484
|
+
"吲哚 (Indole)", "喹啉 (Quinoline)", "联吡啶 (2,2-Bipyridine)"
|
|
485
|
+
], False),
|
|
486
|
+
]
|
|
487
|
+
|
|
488
|
+
self.mol_cards = []
|
|
489
|
+
for cat_title, mol_names, is_exp in mol_categories:
|
|
490
|
+
card = CollapsibleCard(cat_title, expanded=is_exp)
|
|
491
|
+
card_lay = card.body_layout
|
|
492
|
+
grid = QGridLayout()
|
|
493
|
+
grid.setSpacing(5)
|
|
494
|
+
col_idx = 0
|
|
495
|
+
for txt in mol_names:
|
|
496
|
+
if txt in SAMPLE_MOLECULES:
|
|
497
|
+
b = QPushButton(txt)
|
|
498
|
+
b.setProperty("role", "chip")
|
|
499
|
+
b.setCheckable(True)
|
|
500
|
+
b.setMinimumHeight(28)
|
|
501
|
+
b.setToolTip(f"点击载入标准分子「{txt}」")
|
|
502
|
+
b.clicked.connect(lambda checked=False, name=txt: self._on_molecule_clicked(name))
|
|
503
|
+
grid.addWidget(b, col_idx // 2, col_idx % 2)
|
|
504
|
+
self.molecule_buttons.append((txt, b))
|
|
505
|
+
col_idx += 1
|
|
506
|
+
card_lay.addLayout(grid)
|
|
507
|
+
lay.addWidget(card)
|
|
508
|
+
self.mol_cards.append(card)
|
|
509
|
+
|
|
510
|
+
# 环系与稠环
|
|
511
|
+
self.ring_card = CollapsibleCard("共轭环与常见环系 (RINGS)", expanded=True)
|
|
512
|
+
self.ring_card.setToolTip("【快捷环模板】选中原子时接枝成环;未选原子时在画布空白处放置独立新环")
|
|
513
|
+
r_lay = self.ring_card.body_layout
|
|
514
|
+
r_grid = QGridLayout()
|
|
515
|
+
r_grid.setSpacing(5)
|
|
516
|
+
self.ring_buttons: list[tuple[str, QPushButton]] = []
|
|
517
|
+
ring_defs = [
|
|
518
|
+
("⬡ 苯环 (6Ar)", 6, True, {}),
|
|
519
|
+
("⬠ 噻吩 (S)", 5, True, {0: 16}),
|
|
520
|
+
("⬡ 吡啶 (N)", 6, True, {0: 7}),
|
|
521
|
+
("⬠ 呋喃 (O)", 5, True, {0: 8}),
|
|
522
|
+
("⬠ 吡咯 (NH)", 5, True, {0: 7}),
|
|
523
|
+
("⬠ 咪唑 (N2)", 5, True, {0: 7, 2: 7}),
|
|
524
|
+
("⬠ 噻唑 (S,N)", 5, True, {0: 16, 2: 7}),
|
|
525
|
+
("⬠ 恶唑 (O,N)", 5, True, {0: 8, 2: 7}),
|
|
526
|
+
("⬡ 环己烷", 6, False, {}),
|
|
527
|
+
("⬠ 环戊烷", 5, False, {}),
|
|
528
|
+
("□ 环丁烷", 4, False, {}),
|
|
529
|
+
("△ 环丙烷", 3, False, {}),
|
|
530
|
+
]
|
|
531
|
+
for idx, (name, size, arom, hetero) in enumerate(ring_defs):
|
|
532
|
+
b = QPushButton(name)
|
|
533
|
+
b.setProperty("role", "chip")
|
|
534
|
+
b.setCheckable(True)
|
|
535
|
+
b.setMinimumHeight(28)
|
|
536
|
+
b.setToolTip(f"向当前选中原子接上 {name};未选时放置独立新环")
|
|
537
|
+
b.clicked.connect(lambda checked=False, btn=b, s=size, a=arom, h=hetero: self._on_ring_clicked(btn, s, a, h))
|
|
538
|
+
r_grid.addWidget(b, idx // 2, idx % 2)
|
|
539
|
+
self.ring_buttons.append((name, b))
|
|
540
|
+
r_lay.addLayout(r_grid)
|
|
541
|
+
lay.addWidget(self.ring_card)
|
|
542
|
+
|
|
543
|
+
# 官能团取代
|
|
544
|
+
self.fg_card = CollapsibleCard("常用官能团取代 (GROUPS)", expanded=True)
|
|
545
|
+
self.fg_card.setToolTip("【官能团取代】先在画布点击选中目标原子,再点击官能团即可自动接枝并优化几何构型")
|
|
546
|
+
f_lay = self.fg_card.body_layout
|
|
547
|
+
f_grid = QGridLayout()
|
|
548
|
+
f_grid.setSpacing(5)
|
|
549
|
+
self.fg_buttons: list[tuple[str, QPushButton]] = []
|
|
550
|
+
fgs = [
|
|
551
|
+
("氟代 -F", "-F"),
|
|
552
|
+
("氯代 -Cl", "-Cl"),
|
|
553
|
+
("溴代 -Br", "-Br"),
|
|
554
|
+
("碘代 -I", "-I"),
|
|
555
|
+
("羟基 -OH", "-OH"),
|
|
556
|
+
("氨基 -NH₂", "-NH2"),
|
|
557
|
+
("硝基 -NO₂", "-NO2"),
|
|
558
|
+
("氰基 -CN", "-CN"),
|
|
559
|
+
("羧基 -COOH", "-COOH"),
|
|
560
|
+
("醛基 -CHO", "-CHO"),
|
|
561
|
+
("甲氧基 -OCH₃", "-OCH3"),
|
|
562
|
+
("甲基 -CH₃", "-CH3"),
|
|
563
|
+
("三氟甲基 -CF₃", "-CF3"),
|
|
564
|
+
]
|
|
565
|
+
for idx, (fg_label, fg_code) in enumerate(fgs):
|
|
566
|
+
b = QPushButton(fg_label)
|
|
567
|
+
b.setProperty("role", "chip")
|
|
568
|
+
b.setCheckable(True)
|
|
569
|
+
b.setMinimumHeight(28)
|
|
570
|
+
b.setToolTip(f"接枝 {fg_label},实时同步 2D/3D")
|
|
571
|
+
b.clicked.connect(lambda checked=False, btn=b, code=fg_code: self._on_fg_clicked(btn, code))
|
|
572
|
+
f_grid.addWidget(b, idx // 2, idx % 2)
|
|
573
|
+
self.fg_buttons.append((fg_label, b))
|
|
574
|
+
f_lay.addLayout(f_grid)
|
|
575
|
+
lay.addWidget(self.fg_card)
|
|
576
|
+
|
|
577
|
+
lay.addStretch(1)
|
|
578
|
+
return w
|
|
579
|
+
|
|
580
|
+
def _apply_filter(self, query: str):
|
|
581
|
+
q = query.strip().lower()
|
|
582
|
+
for name, btn in self.molecule_buttons:
|
|
583
|
+
btn.setVisible(not q or q in name.lower())
|
|
584
|
+
for name, btn in self.ring_buttons:
|
|
585
|
+
btn.setVisible(not q or q in name.lower())
|
|
586
|
+
for name, btn in self.fg_buttons:
|
|
587
|
+
btn.setVisible(not q or q in name.lower())
|
|
588
|
+
for name, btn in getattr(self, "custom_fragment_buttons", []):
|
|
589
|
+
btn.setVisible(not q or q in name.lower())
|
|
590
|
+
|
|
591
|
+
def _refresh_custom_fragments_card(self):
|
|
592
|
+
while self.custom_chips_layout.count() > 0:
|
|
593
|
+
item = self.custom_chips_layout.takeAt(0)
|
|
594
|
+
if item.widget():
|
|
595
|
+
item.widget().deleteLater()
|
|
596
|
+
elif item.layout():
|
|
597
|
+
while item.layout().count() > 0:
|
|
598
|
+
sub = item.layout().takeAt(0)
|
|
599
|
+
if sub.widget():
|
|
600
|
+
sub.widget().deleteLater()
|
|
601
|
+
from ..domain.custom_fragments import (
|
|
602
|
+
get_grouped_custom_fragments, remove_custom_fragment, delete_custom_group, rename_custom_group
|
|
603
|
+
)
|
|
604
|
+
grouped = get_grouped_custom_fragments()
|
|
605
|
+
self.custom_fragment_buttons = []
|
|
606
|
+
if not grouped:
|
|
607
|
+
self.custom_chips_layout.addWidget(muted("暂无自定义分组。点击上方「📁+ 新分组」可创建专属片段库。"))
|
|
608
|
+
return
|
|
609
|
+
|
|
610
|
+
for grp_name, frags in grouped.items():
|
|
611
|
+
grp_box = QFrame()
|
|
612
|
+
grp_box.setStyleSheet(
|
|
613
|
+
"QFrame { background: rgba(19, 36, 54, 0.45); border: 1px solid rgba(36, 62, 86, 0.6); "
|
|
614
|
+
"border-radius: 6px; padding: 2px; margin-bottom: 4px; }"
|
|
615
|
+
)
|
|
616
|
+
g_vlay = QVBoxLayout(grp_box)
|
|
617
|
+
g_vlay.setContentsMargins(4, 4, 4, 4)
|
|
618
|
+
g_vlay.setSpacing(4)
|
|
619
|
+
|
|
620
|
+
# 分组标题行 (名称、重命名、删除)
|
|
621
|
+
sz_xs = max(10, getattr(self, "_font_size", 14) - 3)
|
|
622
|
+
hdr_row = QHBoxLayout()
|
|
623
|
+
lbl_ghdr = QLabel(f"📁 {grp_name} ({len(frags)})")
|
|
624
|
+
lbl_ghdr.setStyleSheet(f"color: #66DEC9; font-weight: 700; font-size: {sz_xs}px;")
|
|
625
|
+
hdr_row.addWidget(lbl_ghdr)
|
|
626
|
+
hdr_row.addStretch()
|
|
627
|
+
|
|
628
|
+
btn_ren_grp = QPushButton("✏️")
|
|
629
|
+
btn_ren_grp.setToolTip(f"重命名分组「{grp_name}」")
|
|
630
|
+
btn_ren_grp.setStyleSheet(
|
|
631
|
+
f"QPushButton {{ background: transparent; border: none; color: #8C9BAE; font-size: {sz_xs}px; padding: 0 2px; }}"
|
|
632
|
+
"QPushButton:hover { color: #5EEAD4; }"
|
|
633
|
+
)
|
|
634
|
+
btn_ren_grp.clicked.connect(lambda checked=False, g=grp_name: self._on_rename_group(g))
|
|
635
|
+
hdr_row.addWidget(btn_ren_grp)
|
|
636
|
+
|
|
637
|
+
btn_del_grp = QPushButton("✕")
|
|
638
|
+
btn_del_grp.setToolTip(f"删除分组「{grp_name}」及其中所有砌块")
|
|
639
|
+
btn_del_grp.setStyleSheet(
|
|
640
|
+
f"QPushButton {{ background: transparent; border: none; color: #8C9BAE; font-size: {sz_xs}px; padding: 0 4px; }}"
|
|
641
|
+
"QPushButton:hover { color: #FF6B6B; }"
|
|
642
|
+
)
|
|
643
|
+
btn_del_grp.clicked.connect(lambda checked=False, g=grp_name: self._on_delete_group(g))
|
|
644
|
+
hdr_row.addWidget(btn_del_grp)
|
|
645
|
+
g_vlay.addLayout(hdr_row)
|
|
646
|
+
|
|
647
|
+
# 分组内砌块 (若为空显示专属添加提示卡,彻底解决自建分组看不到的问题)
|
|
648
|
+
if not frags:
|
|
649
|
+
empty_btn = QPushButton("+ 暂无砌块,点击存入当前分子/片段")
|
|
650
|
+
empty_btn.setToolTip(f"点击快速将当前编辑的分子或选中片段存入「{grp_name}」")
|
|
651
|
+
empty_btn.setStyleSheet(
|
|
652
|
+
"QPushButton { background: rgba(14, 26, 39, 0.5); border: 1px dashed rgba(94, 234, 212, 0.4); "
|
|
653
|
+
f"color: #8BA0B2; font-size: {sz_xs}px; padding: 6px; border-radius: 4px; text-align: center; }}"
|
|
654
|
+
"QPushButton:hover { border-color: #5EEAD4; color: #5EEAD4; background: rgba(20, 45, 65, 0.6); }"
|
|
655
|
+
)
|
|
656
|
+
empty_btn.clicked.connect(lambda checked=False, g=grp_name: self._save_into_group(g))
|
|
657
|
+
g_vlay.addWidget(empty_btn)
|
|
658
|
+
else:
|
|
659
|
+
grid = QGridLayout()
|
|
660
|
+
grid.setSpacing(4)
|
|
661
|
+
for idx, item in enumerate(frags):
|
|
662
|
+
name = item.get("name", "未命名")
|
|
663
|
+
smi = item.get("smiles", "")
|
|
664
|
+
desc = item.get("description", "")
|
|
665
|
+
ftype = item.get("type", "fragment")
|
|
666
|
+
btn = QPushButton(f"★ {name}")
|
|
667
|
+
btn.setProperty("role", "chip")
|
|
668
|
+
btn.setCheckable(True)
|
|
669
|
+
btn.setMinimumHeight(28)
|
|
670
|
+
btn.setToolTip(
|
|
671
|
+
f"【自定义结构】\n"
|
|
672
|
+
f"• 名称: {name}\n"
|
|
673
|
+
f"• 分组: {grp_name}\n"
|
|
674
|
+
f"• 类别: {ftype}\n"
|
|
675
|
+
f"• SMILES: {smi}\n"
|
|
676
|
+
f"• 说明: {desc or '无'}\n"
|
|
677
|
+
f"(左键点击插入画布,右键可移动分组或删除)"
|
|
678
|
+
)
|
|
679
|
+
btn.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
|
680
|
+
btn.customContextMenuRequested.connect(
|
|
681
|
+
lambda pos, n=name, g=grp_name: self._show_custom_fragment_menu(n, g)
|
|
682
|
+
)
|
|
683
|
+
btn.clicked.connect(lambda checked=False, s=smi, n=name: self._on_custom_fragment_clicked(s, n))
|
|
684
|
+
grid.addWidget(btn, idx // 2, idx % 2)
|
|
685
|
+
self.custom_fragment_buttons.append((name, btn))
|
|
686
|
+
g_vlay.addLayout(grid)
|
|
687
|
+
self.custom_chips_layout.addWidget(grp_box)
|
|
688
|
+
|
|
689
|
+
def _on_create_new_group(self):
|
|
690
|
+
from ..domain.custom_fragments import add_custom_group
|
|
691
|
+
name, ok = QInputDialog.getText(self, "新建自定义分组", "请输入新分组名称(如:光伏受体单元、修饰卤素基团):")
|
|
692
|
+
if ok and name.strip():
|
|
693
|
+
add_custom_group(name.strip())
|
|
694
|
+
self._refresh_custom_fragments_card()
|
|
695
|
+
|
|
696
|
+
def _on_rename_group(self, old_name: str):
|
|
697
|
+
from ..domain.custom_fragments import rename_custom_group
|
|
698
|
+
new_name, ok = QInputDialog.getText(self, "重命名分组", f"请输入分组「{old_name}」的新名称:", text=old_name)
|
|
699
|
+
if ok and new_name.strip() and new_name.strip() != old_name:
|
|
700
|
+
if rename_custom_group(old_name, new_name.strip()):
|
|
701
|
+
self._refresh_custom_fragments_card()
|
|
702
|
+
|
|
703
|
+
def _save_into_group(self, group_name: str):
|
|
704
|
+
win = getattr(self, "_window_ref", None)
|
|
705
|
+
if win is None:
|
|
706
|
+
QMessageBox.information(self, "提示", "请在工作台画布中打开分子后再保存。")
|
|
707
|
+
return
|
|
708
|
+
doc = getattr(win, "document", None)
|
|
709
|
+
if doc is None or doc.num_atoms == 0:
|
|
710
|
+
QMessageBox.information(self, "提示", "当前画布为空,请先打开或绘制分子。")
|
|
711
|
+
return
|
|
712
|
+
sel = getattr(win, "selection", None)
|
|
713
|
+
has_sel = sel is not None and bool(sel.selected_atoms)
|
|
714
|
+
dlg = SaveCustomFragmentDialog(
|
|
715
|
+
self,
|
|
716
|
+
default_name=f"片段_{len(sel.selected_atoms)}原子" if has_sel else (doc.name or "我的分子"),
|
|
717
|
+
default_desc=f"{len(sel.selected_atoms)} 原子片段" if has_sel else f"{doc.num_atoms} 原子 · 全分子",
|
|
718
|
+
default_type="fragment" if has_sel else "molecule",
|
|
719
|
+
)
|
|
720
|
+
dlg.group_combo.setCurrentText(group_name)
|
|
721
|
+
if dlg.exec() != QDialog.DialogCode.Accepted:
|
|
722
|
+
return
|
|
723
|
+
data = dlg.get_data()
|
|
724
|
+
from ..io.rdkit_adapter import doc_to_rdkit
|
|
725
|
+
from rdkit import Chem
|
|
726
|
+
try:
|
|
727
|
+
if has_sel:
|
|
728
|
+
from ..domain.document import MoleculeDocument
|
|
729
|
+
sub_doc = MoleculeDocument(name=data["name"])
|
|
730
|
+
old_to_new = {}
|
|
731
|
+
for aid in sel.selected_atoms:
|
|
732
|
+
old_atom = doc.topology.get_atom(aid)
|
|
733
|
+
new_aid = sub_doc.topology.add_atom(old_atom.atomic_num, formal_charge=old_atom.formal_charge, aromatic=old_atom.aromatic)
|
|
734
|
+
old_to_new[aid] = new_aid
|
|
735
|
+
for bid in doc.topology.bond_ids:
|
|
736
|
+
b = doc.topology.get_bond(bid)
|
|
737
|
+
if b.begin in old_to_new and b.end in old_to_new:
|
|
738
|
+
sub_doc.topology.add_bond(old_to_new[b.begin], old_to_new[b.end], b.order, aromatic=b.aromatic)
|
|
739
|
+
rdmol = doc_to_rdkit(sub_doc, sanitize=False)[0]
|
|
740
|
+
else:
|
|
741
|
+
rdmol = doc_to_rdkit(doc)[0]
|
|
742
|
+
smi = Chem.MolToSmiles(rdmol)
|
|
743
|
+
if not smi:
|
|
744
|
+
raise ValueError("未能生成有效的 SMILES")
|
|
745
|
+
from ..domain.custom_fragments import add_custom_fragment
|
|
746
|
+
add_custom_fragment(
|
|
747
|
+
name=data["name"],
|
|
748
|
+
smiles=smi,
|
|
749
|
+
description=data["description"],
|
|
750
|
+
group=data["group"],
|
|
751
|
+
frag_type=data["type"],
|
|
752
|
+
)
|
|
753
|
+
self._refresh_custom_fragments_card()
|
|
754
|
+
QMessageBox.information(self, "保存成功", f"结构「{data['name']}」已成功存入「{data['group']}」!")
|
|
755
|
+
except Exception as e:
|
|
756
|
+
QMessageBox.warning(self, "保存失败", f"无法提取并保存结构: {e}")
|
|
757
|
+
|
|
758
|
+
def _show_custom_fragment_menu(self, name: str, current_group: str = ""):
|
|
759
|
+
menu = QMenu(self)
|
|
760
|
+
move_act = menu.addAction(f"📁 移动「{name}」到其他分组...")
|
|
761
|
+
move_act.triggered.connect(lambda: self._on_move_custom_fragment(name, current_group))
|
|
762
|
+
del_act = menu.addAction(f"🗑️ 删除砌块「{name}」")
|
|
763
|
+
del_act.triggered.connect(lambda: self._on_delete_custom_fragment(name))
|
|
764
|
+
menu.exec(QCursor.pos())
|
|
765
|
+
|
|
766
|
+
def _on_move_custom_fragment(self, name: str, current_group: str):
|
|
767
|
+
from ..domain.custom_fragments import get_custom_groups, load_custom_fragments, save_custom_fragments
|
|
768
|
+
groups = get_custom_groups()
|
|
769
|
+
target_group, ok = QInputDialog.getItem(
|
|
770
|
+
self, "移动分组", f"请选择将砌块「{name}」移动到的目标分组:", groups, 0, True
|
|
771
|
+
)
|
|
772
|
+
if ok and target_group.strip() and target_group.strip() != current_group:
|
|
773
|
+
frags = load_custom_fragments()
|
|
774
|
+
for f in frags:
|
|
775
|
+
if f.get("name") == name:
|
|
776
|
+
f["group"] = target_group.strip()
|
|
777
|
+
break
|
|
778
|
+
save_custom_fragments(frags)
|
|
779
|
+
self._refresh_custom_fragments_card()
|
|
780
|
+
|
|
781
|
+
def _on_delete_group(self, group_name: str):
|
|
782
|
+
from ..domain.custom_fragments import delete_custom_group
|
|
783
|
+
ret = QMessageBox.question(
|
|
784
|
+
self,
|
|
785
|
+
"确认删除分组",
|
|
786
|
+
f"确定要删除分组「{group_name}」及其下的所有自定义结构砌块吗?此操作不可撤销。",
|
|
787
|
+
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
|
788
|
+
QMessageBox.StandardButton.No,
|
|
789
|
+
)
|
|
790
|
+
if ret == QMessageBox.StandardButton.Yes:
|
|
791
|
+
if delete_custom_group(group_name):
|
|
792
|
+
self._refresh_custom_fragments_card()
|
|
793
|
+
|
|
794
|
+
def _on_delete_custom_fragment(self, name: str):
|
|
795
|
+
from ..domain.custom_fragments import remove_custom_fragment
|
|
796
|
+
if remove_custom_fragment(name):
|
|
797
|
+
self._refresh_custom_fragments_card()
|
|
798
|
+
|
|
799
|
+
def _on_custom_fragment_clicked(self, smiles: str, name: str):
|
|
800
|
+
if getattr(self, "on_custom_fragment_insert", None):
|
|
801
|
+
self.on_custom_fragment_insert(smiles, name)
|
|
802
|
+
elif hasattr(self, "_window_ref") and self._window_ref is not None:
|
|
803
|
+
from ..io.rdkit_adapter import create_molecule_from_smiles
|
|
804
|
+
try:
|
|
805
|
+
new_doc = create_molecule_from_smiles(smiles, name=name)
|
|
806
|
+
self._window_ref._merge_document_into_current(new_doc)
|
|
807
|
+
except Exception as e:
|
|
808
|
+
QMessageBox.warning(self, "插入失败", f"无法插入自定义砌块: {e}")
|
|
809
|
+
|
|
810
|
+
def _on_save_current_as_fragment(self):
|
|
811
|
+
win = getattr(self, "_window_ref", None)
|
|
812
|
+
if win is None:
|
|
813
|
+
QMessageBox.information(self, "提示", "请在工作台画布中打开分子后再保存。")
|
|
814
|
+
return
|
|
815
|
+
doc = getattr(win, "document", None)
|
|
816
|
+
if doc is None or doc.num_atoms == 0:
|
|
817
|
+
QMessageBox.information(self, "提示", "当前文档为空,无法保存为砌块。")
|
|
818
|
+
return
|
|
819
|
+
dlg = SaveCustomFragmentDialog(
|
|
820
|
+
self,
|
|
821
|
+
default_name=doc.name or "我的分子",
|
|
822
|
+
default_desc=f"{doc.num_atoms} 原子 · 全分子",
|
|
823
|
+
default_type="molecule",
|
|
824
|
+
)
|
|
825
|
+
if dlg.exec() != QDialog.DialogCode.Accepted:
|
|
826
|
+
return
|
|
827
|
+
data = dlg.get_data()
|
|
828
|
+
from ..io.rdkit_adapter import doc_to_rdkit
|
|
829
|
+
from rdkit import Chem
|
|
830
|
+
try:
|
|
831
|
+
rdmol = doc_to_rdkit(doc)[0]
|
|
832
|
+
smi = Chem.MolToSmiles(rdmol)
|
|
833
|
+
if not smi:
|
|
834
|
+
raise ValueError("未能生成有效的 SMILES")
|
|
835
|
+
from ..domain.custom_fragments import add_custom_fragment
|
|
836
|
+
add_custom_fragment(
|
|
837
|
+
name=data["name"],
|
|
838
|
+
smiles=smi,
|
|
839
|
+
description=data["description"] or f"{doc.num_atoms} 原子 · 全分子",
|
|
840
|
+
group=data["group"],
|
|
841
|
+
frag_type=data["type"],
|
|
842
|
+
)
|
|
843
|
+
self._refresh_custom_fragments_card()
|
|
844
|
+
QMessageBox.information(self, "保存成功", f"分子「{data['name']}」已成功存入「{data['group']}」分组!")
|
|
845
|
+
except Exception as e:
|
|
846
|
+
QMessageBox.warning(self, "保存失败", f"无法将当前分子转换为砌块: {e}")
|
|
847
|
+
|
|
848
|
+
def _on_save_selected_as_fragment(self):
|
|
849
|
+
win = getattr(self, "_window_ref", None)
|
|
850
|
+
if win is None:
|
|
851
|
+
QMessageBox.information(self, "提示", "请在工作台画布中打开分子。")
|
|
852
|
+
return
|
|
853
|
+
doc = getattr(win, "document", None)
|
|
854
|
+
sel = getattr(win, "selection", None)
|
|
855
|
+
if doc is None or sel is None or not sel.selected_atoms:
|
|
856
|
+
QMessageBox.information(self, "提示", "请先在 2D 或 3D 画布中选中要保存为砌块的原子片段。")
|
|
857
|
+
return
|
|
858
|
+
dlg = SaveCustomFragmentDialog(
|
|
859
|
+
self,
|
|
860
|
+
default_name=f"片段_{len(sel.selected_atoms)}原子",
|
|
861
|
+
default_desc=f"{len(sel.selected_atoms)} 原子片段",
|
|
862
|
+
default_type="fragment",
|
|
863
|
+
)
|
|
864
|
+
if dlg.exec() != QDialog.DialogCode.Accepted:
|
|
865
|
+
return
|
|
866
|
+
data = dlg.get_data()
|
|
867
|
+
try:
|
|
868
|
+
from ..domain.document import MoleculeDocument
|
|
869
|
+
sub_doc = MoleculeDocument(name=data["name"])
|
|
870
|
+
old_to_new = {}
|
|
871
|
+
for aid in sel.selected_atoms:
|
|
872
|
+
old_atom = doc.topology.get_atom(aid)
|
|
873
|
+
new_aid = sub_doc.topology.add_atom(old_atom.atomic_num, formal_charge=old_atom.formal_charge, aromatic=old_atom.aromatic)
|
|
874
|
+
old_to_new[aid] = new_aid
|
|
875
|
+
for bid in doc.topology.bond_ids:
|
|
876
|
+
b = doc.topology.get_bond(bid)
|
|
877
|
+
if b.begin in old_to_new and b.end in old_to_new:
|
|
878
|
+
sub_doc.topology.add_bond(old_to_new[b.begin], old_to_new[b.end], b.order, aromatic=b.aromatic)
|
|
879
|
+
from ..io.rdkit_adapter import doc_to_rdkit
|
|
880
|
+
from rdkit import Chem
|
|
881
|
+
rdmol = doc_to_rdkit(sub_doc, sanitize=False)[0]
|
|
882
|
+
smi = Chem.MolToSmiles(rdmol)
|
|
883
|
+
if not smi:
|
|
884
|
+
raise ValueError("未能生成有效 SMILES")
|
|
885
|
+
from ..domain.custom_fragments import add_custom_fragment
|
|
886
|
+
add_custom_fragment(
|
|
887
|
+
name=data["name"],
|
|
888
|
+
smiles=smi,
|
|
889
|
+
description=data["description"] or f"{len(sel.selected_atoms)} 原子片段",
|
|
890
|
+
group=data["group"],
|
|
891
|
+
frag_type=data["type"],
|
|
892
|
+
)
|
|
893
|
+
self._refresh_custom_fragments_card()
|
|
894
|
+
QMessageBox.information(self, "保存成功", f"片段「{data['name']}」已成功存入「{data['group']}」分组!")
|
|
895
|
+
except Exception as e:
|
|
896
|
+
QMessageBox.warning(self, "保存失败", f"无法提取选中片段: {e}")
|
|
897
|
+
|
|
898
|
+
def _on_ring_clicked(self, clicked_btn: QPushButton, size: int, aromatic: bool, hetero: dict):
|
|
899
|
+
for _, b in self.ring_buttons:
|
|
900
|
+
refresh_button_visual(b, active=(b is clicked_btn))
|
|
901
|
+
for _, b in self.fg_buttons:
|
|
902
|
+
refresh_button_visual(b, active=False)
|
|
903
|
+
if self.on_ring_insert is not None:
|
|
904
|
+
self.on_ring_insert(size, aromatic, hetero)
|
|
905
|
+
|
|
906
|
+
def _on_fg_clicked(self, clicked_btn: QPushButton, fg_code: str):
|
|
907
|
+
for _, b in self.fg_buttons:
|
|
908
|
+
refresh_button_visual(b, active=(b is clicked_btn))
|
|
909
|
+
for _, b in self.ring_buttons:
|
|
910
|
+
refresh_button_visual(b, active=False)
|
|
911
|
+
if self.on_fg_insert is not None:
|
|
912
|
+
self.on_fg_insert(fg_code)
|
|
913
|
+
|
|
914
|
+
def _on_molecule_clicked(self, name: str):
|
|
915
|
+
for mol_name, btn in self.molecule_buttons:
|
|
916
|
+
refresh_button_visual(btn, active=(mol_name == name))
|
|
917
|
+
if self.on_molecule_selected:
|
|
918
|
+
self.on_molecule_selected(name)
|
|
919
|
+
|
|
920
|
+
# ---------- Tab 1: 元素调色板与成键设定 ----------
|
|
921
|
+
def _build_elements_and_bonds_page(self) -> QWidget:
|
|
922
|
+
w = QWidget()
|
|
923
|
+
lay = QVBoxLayout(w)
|
|
924
|
+
lay.setContentsMargins(4, 4, 4, 8)
|
|
925
|
+
lay.setSpacing(7)
|
|
926
|
+
|
|
927
|
+
# 元素调色板
|
|
928
|
+
el_card = CollapsibleCard("常用化学元素调色板 (ELEMENTS)", expanded=True)
|
|
929
|
+
e_lay = el_card.body_layout
|
|
930
|
+
e_grid = QGridLayout()
|
|
931
|
+
e_grid.setSpacing(5)
|
|
932
|
+
|
|
933
|
+
elements_data = [
|
|
934
|
+
("C", 6, "#333333", "#EAF2F6", "碳"),
|
|
935
|
+
("H", 1, "#E8E8E8", "#1E293B", "氢"),
|
|
936
|
+
("O", 8, "#EF4444", "#FFFFFF", "氧"),
|
|
937
|
+
("N", 7, "#3B82F6", "#FFFFFF", "氮"),
|
|
938
|
+
("S", 16, "#EAB308", "#1E293B", "硫"),
|
|
939
|
+
("P", 15, "#F97316", "#FFFFFF", "磷"),
|
|
940
|
+
("F", 9, "#84CC16", "#1E293B", "氟"),
|
|
941
|
+
("Cl", 17, "#10B981", "#FFFFFF", "氯"),
|
|
942
|
+
("Br", 35, "#B91C1C", "#FFFFFF", "溴"),
|
|
943
|
+
("I", 53, "#9333EA", "#FFFFFF", "碘"),
|
|
944
|
+
("B", 5, "#F472B6", "#1E293B", "硼"),
|
|
945
|
+
("Si", 14, "#CBD5E1", "#1E293B", "硅"),
|
|
946
|
+
("Fe", 26, "#EA580C", "#FFFFFF", "铁"),
|
|
947
|
+
("Pt", 78, "#6366F1", "#FFFFFF", "铂"),
|
|
948
|
+
]
|
|
949
|
+
|
|
950
|
+
self.element_palette_buttons: list[QPushButton] = []
|
|
951
|
+
for i, (sym, z, bg_col, text_col, name_cn) in enumerate(elements_data):
|
|
952
|
+
b = QPushButton(f"{sym} {name_cn}")
|
|
953
|
+
b.setCheckable(True)
|
|
954
|
+
b.setMinimumHeight(28)
|
|
955
|
+
b.setToolTip(f"{name_cn} (原子序数: {z}) - 点击切换当前绘制元素")
|
|
956
|
+
b.setStyleSheet(
|
|
957
|
+
f"QPushButton {{ background-color: {bg_col}; color: {text_col}; font-weight: bold; border-radius: 4px; border: 1px solid rgba(255,255,255,0.2); }}"
|
|
958
|
+
f"QPushButton:hover {{ border: 2px solid #5EEAD4; }}"
|
|
959
|
+
f"QPushButton:checked {{ border: 2px solid #66DEC9; }}"
|
|
960
|
+
)
|
|
961
|
+
b.clicked.connect(lambda checked=False, btn=b, atomic_z=z: self._on_palette_element_clicked(btn, atomic_z))
|
|
962
|
+
e_grid.addWidget(b, i // 2, i % 2)
|
|
963
|
+
self.element_palette_buttons.append(b)
|
|
964
|
+
if z == 6: # 默认选中碳
|
|
965
|
+
b.setChecked(True)
|
|
966
|
+
e_lay.addLayout(e_grid)
|
|
967
|
+
|
|
968
|
+
more_el_btn = QPushButton("🧪 周期表选择更多元素...")
|
|
969
|
+
more_el_btn.clicked.connect(lambda: getattr(self, "on_open_periodic_table", lambda: None)())
|
|
970
|
+
e_lay.addWidget(more_el_btn)
|
|
971
|
+
lay.addWidget(el_card)
|
|
972
|
+
|
|
973
|
+
# 键级选择
|
|
974
|
+
b_card = CollapsibleCard("化学键型设定 (BOND ORDERS)", expanded=True)
|
|
975
|
+
b_lay = b_card.body_layout
|
|
976
|
+
b_grid = QGridLayout()
|
|
977
|
+
b_grid.setSpacing(5)
|
|
978
|
+
|
|
979
|
+
bonds_data = [
|
|
980
|
+
("— 单键 (Single)", 1),
|
|
981
|
+
("= 双键 (Double)", 2),
|
|
982
|
+
("≡ 叁键 (Triple)", 3),
|
|
983
|
+
(": 芳香键 (Aromatic)", 4),
|
|
984
|
+
("▲ 楔形前向 (Wedge)", 5),
|
|
985
|
+
("▰ 虚线后向 (Dash)", 6),
|
|
986
|
+
]
|
|
987
|
+
self.bond_type_buttons: list[QPushButton] = []
|
|
988
|
+
for idx, (label, order_val) in enumerate(bonds_data):
|
|
989
|
+
b = QPushButton(label)
|
|
990
|
+
b.setCheckable(True)
|
|
991
|
+
b.setMinimumHeight(28)
|
|
992
|
+
b.clicked.connect(lambda checked=False, btn=b, oval=order_val: self._on_palette_bond_clicked(btn, oval))
|
|
993
|
+
b_grid.addWidget(b, idx // 2, idx % 2)
|
|
994
|
+
self.bond_type_buttons.append(b)
|
|
995
|
+
if order_val == 1:
|
|
996
|
+
refresh_button_visual(b, active=True)
|
|
997
|
+
b_lay.addLayout(b_grid)
|
|
998
|
+
lay.addWidget(b_card)
|
|
999
|
+
|
|
1000
|
+
# 结构快捷工具
|
|
1001
|
+
t_card = CollapsibleCard("结构修饰快捷工具 (QUICK ACTIONS)", expanded=True)
|
|
1002
|
+
t_lay = t_card.body_layout
|
|
1003
|
+
for icon_txt, tip, cb_name in [
|
|
1004
|
+
("⚡ 自动补齐氢原子 (Add H)", "为当前结构未满价态的重原子补齐 3D 氢原子", "on_add_h"),
|
|
1005
|
+
("💨 隐藏全部氢原子 (Remove H)", "隐藏或移除所有氢原子以清晰展示分子骨架", "on_remove_h"),
|
|
1006
|
+
("✨ 2D 骨架美化 (Clean 2D)", "按 RDKit 拓扑美学重新排列 2D 平面坐标", "on_clean_2d"),
|
|
1007
|
+
("🔄 3D 快速力场优化 (Clean 3D)", "执行 MMFF94 / UFF 快速力场能量极小化", "on_clean_3d"),
|
|
1008
|
+
("🎯 空间居中归零 (Center)", "将分子几何中心无损平移对齐至三维原点 (0,0,0)", "on_center"),
|
|
1009
|
+
]:
|
|
1010
|
+
btn = QPushButton(icon_txt)
|
|
1011
|
+
btn.setToolTip(tip)
|
|
1012
|
+
btn.clicked.connect(lambda checked=False, name=cb_name: getattr(self, name, lambda: None)() if getattr(self, name, None) else None)
|
|
1013
|
+
t_lay.addWidget(btn)
|
|
1014
|
+
lay.addWidget(t_card)
|
|
1015
|
+
|
|
1016
|
+
lay.addStretch(1)
|
|
1017
|
+
return w
|
|
1018
|
+
|
|
1019
|
+
def _on_palette_element_clicked(self, clicked_btn: QPushButton, atomic_z: int):
|
|
1020
|
+
for b in self.element_palette_buttons:
|
|
1021
|
+
b.setChecked(b is clicked_btn)
|
|
1022
|
+
if self.on_element_selected:
|
|
1023
|
+
self.on_element_selected(atomic_z)
|
|
1024
|
+
|
|
1025
|
+
def _on_palette_bond_clicked(self, clicked_btn: QPushButton, order: int):
|
|
1026
|
+
for b in self.bond_type_buttons:
|
|
1027
|
+
refresh_button_visual(b, active=(b is clicked_btn))
|
|
1028
|
+
if self.on_bond_order_selected:
|
|
1029
|
+
self.on_bond_order_selected(order)
|
|
1030
|
+
|
|
1031
|
+
# ---------- Tab 2: 结构树与测量 ----------
|
|
1032
|
+
def _build_structure_tree_page(self) -> QWidget:
|
|
1033
|
+
w = QWidget()
|
|
1034
|
+
lay = QVBoxLayout(w)
|
|
1035
|
+
lay.setContentsMargins(4, 4, 4, 8)
|
|
1036
|
+
lay.setSpacing(7)
|
|
1037
|
+
|
|
1038
|
+
# 结构统计卡片
|
|
1039
|
+
self.tree_info_label = QLabel("当前分子原子与化学键树:")
|
|
1040
|
+
self.tree_info_label.setStyleSheet("color:#66DEC9; font-weight:700; font-size:12px;")
|
|
1041
|
+
lay.addWidget(self.tree_info_label)
|
|
1042
|
+
|
|
1043
|
+
# 原子表格
|
|
1044
|
+
atom_card = CollapsibleCard("原子列表 (ATOMS - 点击在视口中选中)", expanded=True)
|
|
1045
|
+
a_lay = atom_card.body_layout
|
|
1046
|
+
self.atom_table = QTableWidget(0, 5)
|
|
1047
|
+
self.atom_table.setHorizontalHeaderLabels(["#ID", "元素", "X (Å)", "Y (Å)", "Z (Å)"])
|
|
1048
|
+
atom_hdr = self.atom_table.horizontalHeader()
|
|
1049
|
+
atom_hdr.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
|
|
1050
|
+
atom_hdr.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
|
|
1051
|
+
atom_hdr.setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
|
|
1052
|
+
atom_hdr.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
|
|
1053
|
+
atom_hdr.setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch)
|
|
1054
|
+
self.atom_table.setColumnWidth(0, 44)
|
|
1055
|
+
self.atom_table.setColumnWidth(1, 52)
|
|
1056
|
+
self.atom_table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
|
1057
|
+
self.atom_table.verticalHeader().setVisible(False)
|
|
1058
|
+
self.atom_table.setAlternatingRowColors(True)
|
|
1059
|
+
self.atom_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
|
|
1060
|
+
self.atom_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
|
|
1061
|
+
self.atom_table.setMinimumHeight(170)
|
|
1062
|
+
self.atom_table.cellClicked.connect(self._on_atom_table_clicked)
|
|
1063
|
+
a_lay.addWidget(self.atom_table)
|
|
1064
|
+
|
|
1065
|
+
row_atom_export = QHBoxLayout()
|
|
1066
|
+
btn_copy_coords = QPushButton("📋 复制 XYZ 坐标")
|
|
1067
|
+
btn_copy_coords.setToolTip("复制当前分子所有原子的标准 XYZ 笛卡尔坐标到剪贴板")
|
|
1068
|
+
btn_copy_coords.clicked.connect(self._on_copy_xyz_to_clipboard)
|
|
1069
|
+
row_atom_export.addWidget(btn_copy_coords)
|
|
1070
|
+
|
|
1071
|
+
btn_export_coords = QPushButton("💾 导出原子表...")
|
|
1072
|
+
btn_export_coords.setToolTip("将当前分子原子坐标导出为 .xyz 或 .csv 文件")
|
|
1073
|
+
btn_export_coords.clicked.connect(self._on_export_atoms_to_file)
|
|
1074
|
+
row_atom_export.addWidget(btn_export_coords)
|
|
1075
|
+
a_lay.addLayout(row_atom_export)
|
|
1076
|
+
lay.addWidget(atom_card)
|
|
1077
|
+
|
|
1078
|
+
# 键表格
|
|
1079
|
+
bond_card = CollapsibleCard("化学键列表 (BONDS - 点击在视口中选中)", expanded=True)
|
|
1080
|
+
b_lay = bond_card.body_layout
|
|
1081
|
+
self.bond_table = QTableWidget(0, 4)
|
|
1082
|
+
self.bond_table.setHorizontalHeaderLabels(["#ID", "原子对", "键级", "键长 (Å)"])
|
|
1083
|
+
bond_hdr = self.bond_table.horizontalHeader()
|
|
1084
|
+
bond_hdr.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
|
|
1085
|
+
bond_hdr.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
|
|
1086
|
+
bond_hdr.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)
|
|
1087
|
+
bond_hdr.setSectionResizeMode(3, QHeaderView.ResizeMode.Fixed)
|
|
1088
|
+
self.bond_table.setColumnWidth(0, 44)
|
|
1089
|
+
self.bond_table.setColumnWidth(2, 46)
|
|
1090
|
+
self.bond_table.setColumnWidth(3, 62)
|
|
1091
|
+
self.bond_table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
|
1092
|
+
self.bond_table.verticalHeader().setVisible(False)
|
|
1093
|
+
self.bond_table.setAlternatingRowColors(True)
|
|
1094
|
+
self.bond_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
|
|
1095
|
+
self.bond_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
|
|
1096
|
+
self.bond_table.setMinimumHeight(150)
|
|
1097
|
+
self.bond_table.cellClicked.connect(self._on_bond_table_clicked)
|
|
1098
|
+
b_lay.addWidget(self.bond_table)
|
|
1099
|
+
|
|
1100
|
+
row_bond_export = QHBoxLayout()
|
|
1101
|
+
btn_copy_bonds = QPushButton("📋 复制键表")
|
|
1102
|
+
btn_copy_bonds.setToolTip("复制当前分子的完整化学键列表(序号、原子对、键级、键长)到剪贴板")
|
|
1103
|
+
btn_copy_bonds.clicked.connect(self._on_copy_bonds_to_clipboard)
|
|
1104
|
+
row_bond_export.addWidget(btn_copy_bonds)
|
|
1105
|
+
|
|
1106
|
+
btn_export_bonds = QPushButton("💾 导出键表...")
|
|
1107
|
+
btn_export_bonds.setToolTip("将化学键列表导出为 .csv 表格文件")
|
|
1108
|
+
btn_export_bonds.clicked.connect(self._on_export_bonds_to_file)
|
|
1109
|
+
row_bond_export.addWidget(btn_export_bonds)
|
|
1110
|
+
b_lay.addLayout(row_bond_export)
|
|
1111
|
+
lay.addWidget(bond_card)
|
|
1112
|
+
|
|
1113
|
+
lay.addStretch(1)
|
|
1114
|
+
return w
|
|
1115
|
+
|
|
1116
|
+
def _on_atom_table_clicked(self, row: int, col: int):
|
|
1117
|
+
item = self.atom_table.item(row, 0)
|
|
1118
|
+
if item is not None and self.on_atom_selected:
|
|
1119
|
+
aid = item.data(Qt.ItemDataRole.UserRole)
|
|
1120
|
+
if aid is None:
|
|
1121
|
+
try:
|
|
1122
|
+
from ..domain.ids import AtomId
|
|
1123
|
+
raw_val = int(item.text().lstrip("#")) - 1
|
|
1124
|
+
aid = AtomId(raw_val)
|
|
1125
|
+
except Exception:
|
|
1126
|
+
pass
|
|
1127
|
+
if aid is not None:
|
|
1128
|
+
self.on_atom_selected(aid)
|
|
1129
|
+
|
|
1130
|
+
def _on_bond_table_clicked(self, row: int, col: int):
|
|
1131
|
+
item = self.bond_table.item(row, 0)
|
|
1132
|
+
if item is not None and self.on_bond_selected:
|
|
1133
|
+
bid = item.data(Qt.ItemDataRole.UserRole)
|
|
1134
|
+
if bid is None:
|
|
1135
|
+
try:
|
|
1136
|
+
from ..domain.ids import BondId
|
|
1137
|
+
raw_val = int(item.text().lstrip("#")) - 1
|
|
1138
|
+
bid = BondId(raw_val)
|
|
1139
|
+
except Exception:
|
|
1140
|
+
pass
|
|
1141
|
+
if bid is not None:
|
|
1142
|
+
self.on_bond_selected(bid)
|
|
1143
|
+
|
|
1144
|
+
def refresh_structure_tree(self, document):
|
|
1145
|
+
document = self._resolve_active_document(document)
|
|
1146
|
+
if document is None or not hasattr(document, "topology"):
|
|
1147
|
+
return
|
|
1148
|
+
self._current_document = document
|
|
1149
|
+
top = document.topology
|
|
1150
|
+
coords_arr = (
|
|
1151
|
+
document.coordinates.current.coords
|
|
1152
|
+
if hasattr(document, "coordinates") and document.coordinates and document.coordinates.current is not None
|
|
1153
|
+
else None
|
|
1154
|
+
)
|
|
1155
|
+
|
|
1156
|
+
# 大体系虚拟截断保护:超过 500 个原子/键时仅渲染前 500 项,防止超大盒子导致 GUI 假死
|
|
1157
|
+
max_display = 500
|
|
1158
|
+
atom_ids_all, id_to_idx = top.atom_index_map()
|
|
1159
|
+
bond_ids_all, bond_id_to_idx = top.bond_index_map()
|
|
1160
|
+
total_atoms = len(atom_ids_all)
|
|
1161
|
+
total_bonds = len(bond_ids_all)
|
|
1162
|
+
disp_atom_count = min(total_atoms, max_display)
|
|
1163
|
+
disp_bond_count = min(total_bonds, max_display)
|
|
1164
|
+
|
|
1165
|
+
if total_atoms > max_display:
|
|
1166
|
+
self.tree_info_label.setText(f"{document.name}:共 {total_atoms} 原子 · {total_bonds} 键 (显示前 {disp_atom_count} 个)")
|
|
1167
|
+
else:
|
|
1168
|
+
self.tree_info_label.setText(f"{document.name}:共 {total_atoms} 原子 · {total_bonds} 键")
|
|
1169
|
+
|
|
1170
|
+
import numpy as np
|
|
1171
|
+
n_coords = len(coords_arr) if coords_arr is not None else 0
|
|
1172
|
+
|
|
1173
|
+
self.atom_table.setUpdatesEnabled(False)
|
|
1174
|
+
self.bond_table.setUpdatesEnabled(False)
|
|
1175
|
+
try:
|
|
1176
|
+
# 刷新原子列表(采用全产品统一稳定编号 aid.value + 1 与 O(1) 坐标表读取)
|
|
1177
|
+
self.atom_table.setRowCount(disp_atom_count)
|
|
1178
|
+
for row, aid in enumerate(atom_ids_all[:disp_atom_count]):
|
|
1179
|
+
atom = top.get_atom(aid)
|
|
1180
|
+
disp_id = aid.value + 1
|
|
1181
|
+
it0 = QTableWidgetItem(f"#{disp_id}")
|
|
1182
|
+
it0.setData(Qt.ItemDataRole.UserRole, aid)
|
|
1183
|
+
it0.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
1184
|
+
it0.setToolTip(f"全产品统一稳定编号 #{disp_id} (内部 AtomId={aid.value}, 列表第 {row + 1} 行)")
|
|
1185
|
+
self.atom_table.setItem(row, 0, it0)
|
|
1186
|
+
|
|
1187
|
+
elem_txt = f"{atom.symbol}({atom.atomic_num})"
|
|
1188
|
+
it1 = QTableWidgetItem(elem_txt)
|
|
1189
|
+
it1.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
1190
|
+
it1.setToolTip(f"{atom.symbol} · 原子序数 Z={atom.atomic_num}")
|
|
1191
|
+
self.atom_table.setItem(row, 1, it1)
|
|
1192
|
+
|
|
1193
|
+
if coords_arr is not None and row < n_coords:
|
|
1194
|
+
p3 = coords_arr[row]
|
|
1195
|
+
x_val, y_val, z_val = float(p3[0]), float(p3[1]), float(p3[2])
|
|
1196
|
+
xyz_tip = f"#{disp_id} {atom.symbol}: ({x_val:.5f}, {y_val:.5f}, {z_val:.5f}) Å"
|
|
1197
|
+
it_x = QTableWidgetItem(f"{x_val:.3f}")
|
|
1198
|
+
it_y = QTableWidgetItem(f"{y_val:.3f}")
|
|
1199
|
+
it_z = QTableWidgetItem(f"{z_val:.3f}")
|
|
1200
|
+
else:
|
|
1201
|
+
xyz_tip = f"#{disp_id} {atom.symbol}: (0.000, 0.000, 0.000) Å"
|
|
1202
|
+
it_x = QTableWidgetItem("0.000")
|
|
1203
|
+
it_y = QTableWidgetItem("0.000")
|
|
1204
|
+
it_z = QTableWidgetItem("0.000")
|
|
1205
|
+
|
|
1206
|
+
for it_c in (it_x, it_y, it_z):
|
|
1207
|
+
it_c.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
|
|
1208
|
+
it_c.setToolTip(xyz_tip)
|
|
1209
|
+
self.atom_table.setItem(row, 2, it_x)
|
|
1210
|
+
self.atom_table.setItem(row, 3, it_y)
|
|
1211
|
+
self.atom_table.setItem(row, 4, it_z)
|
|
1212
|
+
|
|
1213
|
+
# 刷新化学键列表
|
|
1214
|
+
self.bond_table.setRowCount(disp_bond_count)
|
|
1215
|
+
order_names = {1: "单键", 2: "双键", 3: "叁键", 4: "芳香"}
|
|
1216
|
+
for row, bid in enumerate(bond_ids_all[:disp_bond_count]):
|
|
1217
|
+
bond = top.get_bond(bid)
|
|
1218
|
+
a1 = top.get_atom(bond.begin)
|
|
1219
|
+
a2 = top.get_atom(bond.end)
|
|
1220
|
+
i1 = id_to_idx.get(bond.begin, -1)
|
|
1221
|
+
i2 = id_to_idx.get(bond.end, -1)
|
|
1222
|
+
idx1 = bond.begin.value + 1
|
|
1223
|
+
idx2 = bond.end.value + 1
|
|
1224
|
+
pair_str = f"#{idx1} {a1.symbol} - #{idx2} {a2.symbol}"
|
|
1225
|
+
b_order_str = "芳香" if bond.aromatic else order_names.get(int(bond.order), f"{bond.order}")
|
|
1226
|
+
|
|
1227
|
+
length_str = "—"
|
|
1228
|
+
if coords_arr is not None and 0 <= i1 < n_coords and 0 <= i2 < n_coords:
|
|
1229
|
+
dist = float(np.linalg.norm(coords_arr[i1] - coords_arr[i2]))
|
|
1230
|
+
length_str = f"{dist:.3f}"
|
|
1231
|
+
|
|
1232
|
+
disp_bid = bid.value + 1
|
|
1233
|
+
it_b0 = QTableWidgetItem(f"#{disp_bid}")
|
|
1234
|
+
it_b0.setData(Qt.ItemDataRole.UserRole, bid)
|
|
1235
|
+
it_b0.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
1236
|
+
it_b0.setToolTip(f"全产品统一化学键编号 #{disp_bid} (内部 BondId={bid.value}, 列表第 {row + 1} 行)")
|
|
1237
|
+
self.bond_table.setItem(row, 0, it_b0)
|
|
1238
|
+
|
|
1239
|
+
|
|
1240
|
+
it_b1 = QTableWidgetItem(pair_str)
|
|
1241
|
+
it_b1.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
1242
|
+
it_b1.setToolTip(f"{pair_str} ({b_order_str}, {length_str} Å)")
|
|
1243
|
+
self.bond_table.setItem(row, 1, it_b1)
|
|
1244
|
+
|
|
1245
|
+
it_b2 = QTableWidgetItem(b_order_str)
|
|
1246
|
+
it_b2.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
1247
|
+
it_b2.setToolTip(f"键级: {b_order_str}")
|
|
1248
|
+
self.bond_table.setItem(row, 2, it_b2)
|
|
1249
|
+
|
|
1250
|
+
it_b3 = QTableWidgetItem(length_str)
|
|
1251
|
+
it_b3.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
|
|
1252
|
+
it_b3.setToolTip(f"键长: {length_str} Å")
|
|
1253
|
+
self.bond_table.setItem(row, 3, it_b3)
|
|
1254
|
+
finally:
|
|
1255
|
+
self.atom_table.setUpdatesEnabled(True)
|
|
1256
|
+
self.bond_table.setUpdatesEnabled(True)
|
|
1257
|
+
|
|
1258
|
+
def _on_copy_xyz_to_clipboard(self):
|
|
1259
|
+
doc = self._resolve_active_document()
|
|
1260
|
+
if doc is None or doc.topology.num_atoms == 0:
|
|
1261
|
+
QMessageBox.information(self, "提示", "当前没有已加载的分子结构。")
|
|
1262
|
+
return
|
|
1263
|
+
top = doc.topology
|
|
1264
|
+
atom_ids_all, _ = top.atom_index_map()
|
|
1265
|
+
coords_arr = doc.coordinates.current.coords if hasattr(doc, "coordinates") and doc.coordinates and doc.coordinates.current is not None else None
|
|
1266
|
+
n_coords = len(coords_arr) if coords_arr is not None else 0
|
|
1267
|
+
lines = [f"{len(atom_ids_all)}", f"{doc.name or 'MolForge'} - Standard XYZ Cartesian Coordinates"]
|
|
1268
|
+
for idx, aid in enumerate(atom_ids_all):
|
|
1269
|
+
atom = top.get_atom(aid)
|
|
1270
|
+
if coords_arr is not None and idx < n_coords:
|
|
1271
|
+
p3 = coords_arr[idx]
|
|
1272
|
+
x, y, z = float(p3[0]), float(p3[1]), float(p3[2])
|
|
1273
|
+
else:
|
|
1274
|
+
x, y, z = 0.0, 0.0, 0.0
|
|
1275
|
+
lines.append(f"{atom.symbol:<4} {x:14.6f} {y:14.6f} {z:14.6f}")
|
|
1276
|
+
xyz_txt = "\n".join(lines)
|
|
1277
|
+
QApplication.clipboard().setText(xyz_txt)
|
|
1278
|
+
QMessageBox.information(self, "复制成功", f"已成功将全部分子 ({top.num_atoms} 原子) 的 XYZ 坐标复制到系统剪贴板!")
|
|
1279
|
+
|
|
1280
|
+
def _on_export_atoms_to_file(self):
|
|
1281
|
+
doc = self._resolve_active_document()
|
|
1282
|
+
if doc is None or doc.topology.num_atoms == 0:
|
|
1283
|
+
QMessageBox.information(self, "提示", "当前没有已加载的分子结构。")
|
|
1284
|
+
return
|
|
1285
|
+
top = doc.topology
|
|
1286
|
+
atom_ids_all, _ = top.atom_index_map()
|
|
1287
|
+
coords_arr = doc.coordinates.current.coords if hasattr(doc, "coordinates") and doc.coordinates and doc.coordinates.current is not None else None
|
|
1288
|
+
n_coords = len(coords_arr) if coords_arr is not None else 0
|
|
1289
|
+
def_name = f"{doc.name or 'molecule'}_atoms.xyz"
|
|
1290
|
+
fpath, sel_filter = QFileDialog.getSaveFileName(
|
|
1291
|
+
self, "导出原子坐标表", def_name, "XYZ 坐标文件 (*.xyz);;CSV 表格文件 (*.csv)"
|
|
1292
|
+
)
|
|
1293
|
+
if not fpath:
|
|
1294
|
+
return
|
|
1295
|
+
try:
|
|
1296
|
+
is_csv = fpath.lower().endswith(".csv") or "csv" in sel_filter.lower()
|
|
1297
|
+
with open(fpath, "w", encoding="utf-8") as f:
|
|
1298
|
+
if is_csv:
|
|
1299
|
+
f.write("Index,Symbol,AtomicNum,X(Angstrom),Y(Angstrom),Z(Angstrom)\n")
|
|
1300
|
+
for idx, aid in enumerate(atom_ids_all):
|
|
1301
|
+
atom = top.get_atom(aid)
|
|
1302
|
+
if coords_arr is not None and idx < n_coords:
|
|
1303
|
+
p3 = coords_arr[idx]
|
|
1304
|
+
x, y, z = float(p3[0]), float(p3[1]), float(p3[2])
|
|
1305
|
+
else:
|
|
1306
|
+
x, y, z = 0.0, 0.0, 0.0
|
|
1307
|
+
f.write(f"{idx + 1},{atom.symbol},{atom.atomic_num},{x:.6f},{y:.6f},{z:.6f}\n")
|
|
1308
|
+
else:
|
|
1309
|
+
f.write(f"{len(atom_ids_all)}\n")
|
|
1310
|
+
f.write(f"{doc.name or 'MolForge'} exported from MolForge Studio\n")
|
|
1311
|
+
for idx, aid in enumerate(atom_ids_all):
|
|
1312
|
+
atom = top.get_atom(aid)
|
|
1313
|
+
if coords_arr is not None and idx < n_coords:
|
|
1314
|
+
p3 = coords_arr[idx]
|
|
1315
|
+
x, y, z = float(p3[0]), float(p3[1]), float(p3[2])
|
|
1316
|
+
else:
|
|
1317
|
+
x, y, z = 0.0, 0.0, 0.0
|
|
1318
|
+
f.write(f"{atom.symbol:<4} {x:14.6f} {y:14.6f} {z:14.6f}\n")
|
|
1319
|
+
QMessageBox.information(self, "导出成功", f"原子列表已成功导出至:\n{fpath}")
|
|
1320
|
+
except Exception as e:
|
|
1321
|
+
QMessageBox.warning(self, "导出失败", f"写入文件失败: {e}")
|
|
1322
|
+
|
|
1323
|
+
def _on_copy_bonds_to_clipboard(self):
|
|
1324
|
+
doc = self._resolve_active_document()
|
|
1325
|
+
if doc is None or doc.topology.num_bonds == 0:
|
|
1326
|
+
QMessageBox.information(self, "提示", "当前分子没有化学键数据。")
|
|
1327
|
+
return
|
|
1328
|
+
top = doc.topology
|
|
1329
|
+
_, id_to_idx = top.atom_index_map()
|
|
1330
|
+
coords_arr = doc.coordinates.current.coords if hasattr(doc, "coordinates") and doc.coordinates and doc.coordinates.current is not None else None
|
|
1331
|
+
n_coords = len(coords_arr) if coords_arr is not None else 0
|
|
1332
|
+
order_names = {1: "单键", 2: "双键", 3: "叁键", 4: "芳香"}
|
|
1333
|
+
lines = ["#ID\tAtom1\tAtom2\tOrder\tLength(Å)"]
|
|
1334
|
+
import numpy as np
|
|
1335
|
+
for b_row, bid in enumerate(top.bond_ids, start=1):
|
|
1336
|
+
bond = top.get_bond(bid)
|
|
1337
|
+
a1 = top.get_atom(bond.begin)
|
|
1338
|
+
a2 = top.get_atom(bond.end)
|
|
1339
|
+
i1 = id_to_idx.get(bond.begin, -1)
|
|
1340
|
+
i2 = id_to_idx.get(bond.end, -1)
|
|
1341
|
+
idx1 = (i1 + 1) if i1 >= 0 else (bond.begin.value + 1)
|
|
1342
|
+
idx2 = (i2 + 1) if i2 >= 0 else (bond.end.value + 1)
|
|
1343
|
+
dist_str = f"{float(np.linalg.norm(coords_arr[i1] - coords_arr[i2])):.3f}" if (coords_arr is not None and 0 <= i1 < n_coords and 0 <= i2 < n_coords) else "—"
|
|
1344
|
+
b_order_str = "芳香" if bond.aromatic else order_names.get(int(bond.order), str(bond.order))
|
|
1345
|
+
lines.append(f"#{b_row}\t#{idx1} {a1.symbol}\t#{idx2} {a2.symbol}\t{b_order_str}\t{dist_str}")
|
|
1346
|
+
QApplication.clipboard().setText("\n".join(lines))
|
|
1347
|
+
QMessageBox.information(self, "复制成功", f"已成功将全部分子 ({top.num_bonds} 条化学键) 的键表复制到系统剪贴板!")
|
|
1348
|
+
|
|
1349
|
+
def _on_export_bonds_to_file(self):
|
|
1350
|
+
doc = self._resolve_active_document()
|
|
1351
|
+
if doc is None or doc.topology.num_bonds == 0:
|
|
1352
|
+
QMessageBox.information(self, "提示", "当前分子没有化学键数据。")
|
|
1353
|
+
return
|
|
1354
|
+
top = doc.topology
|
|
1355
|
+
_, id_to_idx = top.atom_index_map()
|
|
1356
|
+
coords_arr = doc.coordinates.current.coords if hasattr(doc, "coordinates") and doc.coordinates and doc.coordinates.current is not None else None
|
|
1357
|
+
n_coords = len(coords_arr) if coords_arr is not None else 0
|
|
1358
|
+
def_name = f"{doc.name or 'molecule'}_bonds.csv"
|
|
1359
|
+
fpath, _ = QFileDialog.getSaveFileName(self, "导出化学键表", def_name, "CSV 表格文件 (*.csv)")
|
|
1360
|
+
if not fpath:
|
|
1361
|
+
return
|
|
1362
|
+
try:
|
|
1363
|
+
order_names = {1: "单键", 2: "双键", 3: "叁键", 4: "芳香"}
|
|
1364
|
+
import numpy as np
|
|
1365
|
+
with open(fpath, "w", encoding="utf-8") as f:
|
|
1366
|
+
f.write("BondID,Atom1_Index,Atom1_Symbol,Atom2_Index,Atom2_Symbol,BondOrder,Length(Angstrom)\n")
|
|
1367
|
+
for b_row, bid in enumerate(top.bond_ids, start=1):
|
|
1368
|
+
bond = top.get_bond(bid)
|
|
1369
|
+
a1 = top.get_atom(bond.begin)
|
|
1370
|
+
a2 = top.get_atom(bond.end)
|
|
1371
|
+
i1 = id_to_idx.get(bond.begin, -1)
|
|
1372
|
+
i2 = id_to_idx.get(bond.end, -1)
|
|
1373
|
+
idx1 = (i1 + 1) if i1 >= 0 else (bond.begin.value + 1)
|
|
1374
|
+
idx2 = (i2 + 1) if i2 >= 0 else (bond.end.value + 1)
|
|
1375
|
+
dist_str = f"{float(np.linalg.norm(coords_arr[i1] - coords_arr[i2])):.4f}" if (coords_arr is not None and 0 <= i1 < n_coords and 0 <= i2 < n_coords) else ""
|
|
1376
|
+
b_order_str = "芳香" if bond.aromatic else order_names.get(int(bond.order), str(bond.order))
|
|
1377
|
+
f.write(f"{b_row},{idx1},{a1.symbol},{idx2},{a2.symbol},{b_order_str},{dist_str}\n")
|
|
1378
|
+
QMessageBox.information(self, "导出成功", f"化学键列表已成功导出至:\n{fpath}")
|
|
1379
|
+
except Exception as e:
|
|
1380
|
+
QMessageBox.warning(self, "导出失败", f"写入文件失败: {e}")
|
|
1381
|
+
|
|
1382
|
+
|
|
1383
|
+
def apply_typography(self, family: str, base_size: int):
|
|
1384
|
+
"""将全局字体与比例字号同步应用到左侧栏所有卡片、标签、表格与自定义砌块区。"""
|
|
1385
|
+
sz = max(10, int(base_size))
|
|
1386
|
+
self._font_size = sz
|
|
1387
|
+
sz_sm = max(10, sz - 2)
|
|
1388
|
+
f = QFont(family)
|
|
1389
|
+
f.setPixelSize(sz)
|
|
1390
|
+
self.setFont(f)
|
|
1391
|
+
if hasattr(self, "lbl_tip"):
|
|
1392
|
+
self.lbl_tip.setStyleSheet(f"color: #5EEAD4; font-size: {sz_sm}px; padding: 1px 4px; font-weight: 600;")
|
|
1393
|
+
if hasattr(self, "tree_info_label"):
|
|
1394
|
+
self.tree_info_label.setStyleSheet(f"color:#66DEC9; font-weight:700; font-size:{sz_sm}px;")
|
|
1395
|
+
if hasattr(self, "atom_table"):
|
|
1396
|
+
self.atom_table.setFont(f)
|
|
1397
|
+
self.atom_table.horizontalHeader().setFont(f)
|
|
1398
|
+
self.atom_table.verticalHeader().setDefaultSectionSize(sz + 18)
|
|
1399
|
+
if hasattr(self, "bond_table"):
|
|
1400
|
+
self.bond_table.setFont(f)
|
|
1401
|
+
self.bond_table.horizontalHeader().setFont(f)
|
|
1402
|
+
self.bond_table.verticalHeader().setDefaultSectionSize(sz + 18)
|
|
1403
|
+
if hasattr(self, "_refresh_custom_fragments_card"):
|
|
1404
|
+
try:
|
|
1405
|
+
self._refresh_custom_fragments_card()
|
|
1406
|
+
except Exception:
|
|
1407
|
+
pass
|
|
1408
|
+
|
|
1409
|
+
|
|
1410
|
+
# 保持向后兼容别名
|
|
1411
|
+
Sidebar = LeftPanel
|
|
1412
|
+
|
|
1413
|
+
|
|
1414
|
+
class RightPanel(QFrame):
|
|
1415
|
+
def __init__(self):
|
|
1416
|
+
super().__init__()
|
|
1417
|
+
self.setObjectName("RightPanel")
|
|
1418
|
+
self._document_provider = None
|
|
1419
|
+
self._command_bus_provider = None
|
|
1420
|
+
self._selection_provider = None
|
|
1421
|
+
self.ai_action_executor = None
|
|
1422
|
+
self._chat_worker = None
|
|
1423
|
+
self._chat_bridge = None
|
|
1424
|
+
self._wheel_guard = WheelGuardFilter(self)
|
|
1425
|
+
self.setMinimumWidth(260)
|
|
1426
|
+
self.setMaximumWidth(600)
|
|
1427
|
+
|
|
1428
|
+
from ..application.ai.deepseek_client import DeepSeekChemistryAssistant
|
|
1429
|
+
self.settings_store = QSettings("MolForge", "AI_Config")
|
|
1430
|
+
saved_key = self.settings_store.value("deepseek_api_key", "") or os.environ.get("DEEPSEEK_API_KEY", "")
|
|
1431
|
+
self.deepseek = DeepSeekChemistryAssistant(api_key=str(saved_key))
|
|
1432
|
+
|
|
1433
|
+
outer = QVBoxLayout(self)
|
|
1434
|
+
outer.setContentsMargins(9, 10, 9, 9)
|
|
1435
|
+
outer.setSpacing(8)
|
|
1436
|
+
|
|
1437
|
+
# 顶部精致分段胶囊导航条
|
|
1438
|
+
tab_frame = QFrame()
|
|
1439
|
+
tab_frame.setObjectName("TabStripFrame")
|
|
1440
|
+
tabs = QHBoxLayout(tab_frame)
|
|
1441
|
+
tabs.setContentsMargins(3, 3, 3, 3)
|
|
1442
|
+
tabs.setSpacing(3)
|
|
1443
|
+
self.stack = QStackedWidget()
|
|
1444
|
+
|
|
1445
|
+
self._tab_buttons: list[QPushButton] = []
|
|
1446
|
+
for i, title in enumerate(("属性", "AI 助手", "量化", "历史", "设置")):
|
|
1447
|
+
b = QPushButton(title)
|
|
1448
|
+
b.setProperty("role", "tab")
|
|
1449
|
+
b.setCheckable(True)
|
|
1450
|
+
b.clicked.connect(lambda checked=False, index=i: self.switch_tab(index))
|
|
1451
|
+
tabs.addWidget(b)
|
|
1452
|
+
self._tab_buttons.append(b)
|
|
1453
|
+
refresh_button_visual(b, active=(i == 0))
|
|
1454
|
+
outer.addWidget(tab_frame)
|
|
1455
|
+
|
|
1456
|
+
self.inspect_page = self._inspect()
|
|
1457
|
+
self.stack.addWidget(create_smooth_scroll_area(self.inspect_page))
|
|
1458
|
+
|
|
1459
|
+
self.assistant_page = self._assistant()
|
|
1460
|
+
self.stack.addWidget(create_smooth_scroll_area(self.assistant_page))
|
|
1461
|
+
|
|
1462
|
+
self.jobs_page, self.jobs_box = self._page()
|
|
1463
|
+
self.stack.addWidget(create_smooth_scroll_area(self.jobs_page))
|
|
1464
|
+
|
|
1465
|
+
self.history_page, self.history_box = self._page()
|
|
1466
|
+
self.stack.addWidget(create_smooth_scroll_area(self.history_page))
|
|
1467
|
+
|
|
1468
|
+
from .settings_panel import SettingsPanel
|
|
1469
|
+
self.settings_panel = SettingsPanel()
|
|
1470
|
+
self.stack.addWidget(create_smooth_scroll_area(self.settings_panel))
|
|
1471
|
+
|
|
1472
|
+
self.stack.currentChanged.connect(self._on_tab_changed)
|
|
1473
|
+
self.stack.setCurrentIndex(0)
|
|
1474
|
+
outer.addWidget(self.stack, 1)
|
|
1475
|
+
|
|
1476
|
+
def switch_tab(self, index: int):
|
|
1477
|
+
if 0 <= index < self.stack.count():
|
|
1478
|
+
self.stack.setCurrentIndex(index)
|
|
1479
|
+
for i, b in enumerate(self._tab_buttons):
|
|
1480
|
+
refresh_button_visual(b, active=(i == index))
|
|
1481
|
+
|
|
1482
|
+
def _page(self):
|
|
1483
|
+
page = QWidget()
|
|
1484
|
+
page.setObjectName("ScrollPage")
|
|
1485
|
+
box = QVBoxLayout(page)
|
|
1486
|
+
box.setContentsMargins(2, 2, 5, 10)
|
|
1487
|
+
box.setSpacing(9)
|
|
1488
|
+
return page, box
|
|
1489
|
+
|
|
1490
|
+
def _inspect(self):
|
|
1491
|
+
page, box = self._page()
|
|
1492
|
+
|
|
1493
|
+
mol_card = CollapsibleCard("当前分子概览 (MOLECULE)", expanded=True)
|
|
1494
|
+
mc_lay = mol_card.body_layout
|
|
1495
|
+
self.mol_name_label = QLabel("咖啡因 · C₈H₁₀N₄O₂")
|
|
1496
|
+
self.mol_name_label.setWordWrap(True)
|
|
1497
|
+
self.mol_name_label.setStyleSheet("font-size: 14px; font-weight: 700; color: #66DEC9;")
|
|
1498
|
+
mc_lay.addWidget(self.mol_name_label)
|
|
1499
|
+
|
|
1500
|
+
self.inspect_labels = {}
|
|
1501
|
+
for t, v in (
|
|
1502
|
+
("化学式", "C8H10N4O2"),
|
|
1503
|
+
("相对分子质量", "194.19 Da"),
|
|
1504
|
+
("原子 (重/氢)", "24 (14 重 / 10 氢)"),
|
|
1505
|
+
("化学键 (单/双/芳)", "25 键"),
|
|
1506
|
+
("净电荷 / 自旋", "0 / 未指定(默认单重态)"),
|
|
1507
|
+
("环系数量", "2 环 (双环稠合)"),
|
|
1508
|
+
("非环单键 (自定义)", "3 个"),
|
|
1509
|
+
("空间质心 (Å)", "(0.00, 0.00, 0.00)"),
|
|
1510
|
+
("点群 / 几何形态", "未计算"),
|
|
1511
|
+
("3D 渲染器", "VTK Studio Phong"),
|
|
1512
|
+
):
|
|
1513
|
+
row = QHBoxLayout()
|
|
1514
|
+
row.addWidget(muted(t))
|
|
1515
|
+
row.addStretch()
|
|
1516
|
+
value_label = QLabel(v)
|
|
1517
|
+
value_label.setProperty("role", "value")
|
|
1518
|
+
self.inspect_labels[t] = value_label
|
|
1519
|
+
row.addWidget(value_label)
|
|
1520
|
+
mc_lay.addLayout(row)
|
|
1521
|
+
box.addWidget(mol_card)
|
|
1522
|
+
|
|
1523
|
+
box.addWidget(self._atom_editor_card())
|
|
1524
|
+
box.addWidget(self._bond_editor_card())
|
|
1525
|
+
|
|
1526
|
+
meas_card = CollapsibleCard("3D 空间几何测量 (GEOMETRY)", expanded=True)
|
|
1527
|
+
self.measure_label = QLabel("按住 Shift 选中 2 原子测键长(Å),3 原子测键角(°),4 原子测二面角(°)")
|
|
1528
|
+
self.measure_label.setWordWrap(True)
|
|
1529
|
+
self.measure_label.setStyleSheet("color:#9AB0C2;")
|
|
1530
|
+
meas_card.body_layout.addWidget(self.measure_label)
|
|
1531
|
+
mod_ic_btn = QPushButton("📐 精确修改选中内坐标 (键长/键角/二面角)...")
|
|
1532
|
+
mod_ic_btn.clicked.connect(lambda: getattr(self, "on_open_modify_internal", lambda: None)() if getattr(self, "on_open_modify_internal", None) else None)
|
|
1533
|
+
meas_card.body_layout.addWidget(mod_ic_btn)
|
|
1534
|
+
box.addWidget(meas_card)
|
|
1535
|
+
|
|
1536
|
+
box.addWidget(self._visualization_card())
|
|
1537
|
+
|
|
1538
|
+
box.addStretch(1)
|
|
1539
|
+
return page
|
|
1540
|
+
|
|
1541
|
+
def update_measurement(self, text):
|
|
1542
|
+
self.measure_label.setText(text)
|
|
1543
|
+
self.measure_label.setStyleSheet("color:#66DEC9; font-weight:700; font-size:13px;")
|
|
1544
|
+
|
|
1545
|
+
def _visualization_card(self):
|
|
1546
|
+
card = CollapsibleCard("🎨 科学可视化与渲染控制 (VISUALIZATION)", expanded=True)
|
|
1547
|
+
l = card.body_layout
|
|
1548
|
+
|
|
1549
|
+
l.addWidget(muted("3D 分子展示风格 (REPRESENTATION):"))
|
|
1550
|
+
grid_st = QGridLayout()
|
|
1551
|
+
grid_st.setSpacing(5)
|
|
1552
|
+
self.repr_buttons = []
|
|
1553
|
+
for idx, (label, mode_code) in enumerate([
|
|
1554
|
+
("⚽ 球棍模型 (Ball & Stick)", "ball_stick"),
|
|
1555
|
+
("🌐 空间填充 (CPK)", "cpk"),
|
|
1556
|
+
("🥢 棍状模型 (Stick)", "stick"),
|
|
1557
|
+
("🧵 细线框 (Wireframe)", "wireframe"),
|
|
1558
|
+
]):
|
|
1559
|
+
btn = QPushButton(label)
|
|
1560
|
+
btn.setProperty("role", "chip")
|
|
1561
|
+
btn.setCheckable(True)
|
|
1562
|
+
btn.setMinimumHeight(28)
|
|
1563
|
+
btn.clicked.connect(lambda checked=False, m=mode_code, b=btn: self._on_switch_3d_repr(m, b))
|
|
1564
|
+
grid_st.addWidget(btn, idx // 2, idx % 2)
|
|
1565
|
+
self.repr_buttons.append((mode_code, btn))
|
|
1566
|
+
refresh_button_visual(btn, active=(idx == 0))
|
|
1567
|
+
l.addLayout(grid_st)
|
|
1568
|
+
|
|
1569
|
+
l.addWidget(muted("3D 视口标注与参考系统:"))
|
|
1570
|
+
row_chk = QHBoxLayout()
|
|
1571
|
+
self.chk_3d_labels = QCheckBox("显示原子序号 (#ID)")
|
|
1572
|
+
self.chk_3d_labels.toggled.connect(self._on_toggle_3d_labels)
|
|
1573
|
+
row_chk.addWidget(self.chk_3d_labels)
|
|
1574
|
+
|
|
1575
|
+
self.chk_3d_symbols = QCheckBox("显示元素符号")
|
|
1576
|
+
self.chk_3d_symbols.toggled.connect(self._on_toggle_3d_symbols)
|
|
1577
|
+
row_chk.addWidget(self.chk_3d_symbols)
|
|
1578
|
+
l.addLayout(row_chk)
|
|
1579
|
+
|
|
1580
|
+
row_chk2 = QHBoxLayout()
|
|
1581
|
+
self.chk_3d_axes = QCheckBox("显示空间坐标轴")
|
|
1582
|
+
self.chk_3d_axes.setChecked(True)
|
|
1583
|
+
self.chk_3d_axes.toggled.connect(self._on_toggle_3d_axes)
|
|
1584
|
+
row_chk2.addWidget(self.chk_3d_axes)
|
|
1585
|
+
|
|
1586
|
+
self.chk_3d_hs = QCheckBox("显示 3D 氢原子")
|
|
1587
|
+
self.chk_3d_hs.setChecked(True)
|
|
1588
|
+
self.chk_3d_hs.toggled.connect(self._on_toggle_3d_hs)
|
|
1589
|
+
row_chk2.addWidget(self.chk_3d_hs)
|
|
1590
|
+
l.addLayout(row_chk2)
|
|
1591
|
+
|
|
1592
|
+
l.addWidget(muted("3D 视口背景环境预设:"))
|
|
1593
|
+
row_bg = QHBoxLayout()
|
|
1594
|
+
self.combo_3d_bg = QComboBox()
|
|
1595
|
+
self.combo_3d_bg.addItems(["深邃科研黑 (Studio Dark)", "学术纯白 (Paper White)", "蓝灰微光 (Slate #1E293B)"])
|
|
1596
|
+
self.combo_3d_bg.currentIndexChanged.connect(self._on_change_3d_background_preset)
|
|
1597
|
+
row_bg.addWidget(self.combo_3d_bg, 1)
|
|
1598
|
+
l.addLayout(row_bg)
|
|
1599
|
+
|
|
1600
|
+
l.addWidget(muted("2D 绘图视图快速控制:"))
|
|
1601
|
+
row_2d = QHBoxLayout()
|
|
1602
|
+
btn_fit_2d = QPushButton("⛶ 2D 画布居中适配")
|
|
1603
|
+
btn_fit_2d.setToolTip("自动将 2D 分子缩放居中于当前画布")
|
|
1604
|
+
btn_fit_2d.clicked.connect(self._on_fit_2d_view)
|
|
1605
|
+
row_2d.addWidget(btn_fit_2d)
|
|
1606
|
+
|
|
1607
|
+
btn_paper_2d = QPushButton("切换 2D 纸面底色")
|
|
1608
|
+
btn_paper_2d.setToolTip("在 ChemDraw 暖白纸面与暗夜底色间切换")
|
|
1609
|
+
btn_paper_2d.clicked.connect(self._on_toggle_2d_paper)
|
|
1610
|
+
row_2d.addWidget(btn_paper_2d)
|
|
1611
|
+
l.addLayout(row_2d)
|
|
1612
|
+
|
|
1613
|
+
return card
|
|
1614
|
+
|
|
1615
|
+
def _on_switch_3d_repr(self, mode_code: str, clicked_btn: QPushButton):
|
|
1616
|
+
for m, b in getattr(self, "repr_buttons", []):
|
|
1617
|
+
refresh_button_visual(b, active=(b is clicked_btn))
|
|
1618
|
+
win = getattr(self, "_window_ref", None)
|
|
1619
|
+
if win and hasattr(win, "workspace") and win.workspace and hasattr(win.workspace, "view3d_real"):
|
|
1620
|
+
from ..rendering.contracts import RepresentationMode
|
|
1621
|
+
mode_map = {
|
|
1622
|
+
"ball_stick": RepresentationMode.BALL_AND_STICK,
|
|
1623
|
+
"cpk": RepresentationMode.CPK,
|
|
1624
|
+
"stick": RepresentationMode.STICK,
|
|
1625
|
+
"line": RepresentationMode.LINE,
|
|
1626
|
+
"wireframe": RepresentationMode.LINE,
|
|
1627
|
+
}
|
|
1628
|
+
if mode_code in mode_map:
|
|
1629
|
+
win.workspace.view3d_real.set_mode(mode_map[mode_code])
|
|
1630
|
+
|
|
1631
|
+
def _on_toggle_3d_labels(self, checked: bool):
|
|
1632
|
+
win = getattr(self, "_window_ref", None)
|
|
1633
|
+
if win and hasattr(win, "workspace") and win.workspace and hasattr(win.workspace, "view3d_real"):
|
|
1634
|
+
win.workspace.view3d_real.set_view_options(show_labels=checked)
|
|
1635
|
+
|
|
1636
|
+
def _on_toggle_3d_symbols(self, checked: bool):
|
|
1637
|
+
win = getattr(self, "_window_ref", None)
|
|
1638
|
+
if win and hasattr(win, "workspace") and win.workspace and hasattr(win.workspace, "view3d_real"):
|
|
1639
|
+
win.workspace.view3d_real.set_view_options(show_symbols=checked)
|
|
1640
|
+
|
|
1641
|
+
def _on_toggle_3d_axes(self, checked: bool):
|
|
1642
|
+
win = getattr(self, "_window_ref", None)
|
|
1643
|
+
if win and hasattr(win, "workspace") and win.workspace and hasattr(win.workspace, "view3d_real"):
|
|
1644
|
+
win.workspace.view3d_real.set_view_options(show_axes=checked)
|
|
1645
|
+
|
|
1646
|
+
def _on_toggle_3d_hs(self, checked: bool):
|
|
1647
|
+
win = getattr(self, "_window_ref", None)
|
|
1648
|
+
if win and hasattr(win, "workspace") and win.workspace and hasattr(win.workspace, "view3d_real"):
|
|
1649
|
+
win.workspace.view3d_real.set_view_options(show_hydrogens=checked)
|
|
1650
|
+
|
|
1651
|
+
def _on_change_3d_background_preset(self, index: int):
|
|
1652
|
+
win = getattr(self, "_window_ref", None)
|
|
1653
|
+
if win and hasattr(win, "workspace") and win.workspace and hasattr(win.workspace, "view3d_real"):
|
|
1654
|
+
colors = [
|
|
1655
|
+
(0.047, 0.086, 0.133),
|
|
1656
|
+
(0.98, 0.98, 0.98),
|
|
1657
|
+
(0.118, 0.161, 0.231),
|
|
1658
|
+
]
|
|
1659
|
+
if 0 <= index < len(colors):
|
|
1660
|
+
r, g, b = colors[index]
|
|
1661
|
+
win.workspace.view3d_real.set_background_color(r, g, b)
|
|
1662
|
+
|
|
1663
|
+
def _on_fit_2d_view(self):
|
|
1664
|
+
win = getattr(self, "_window_ref", None)
|
|
1665
|
+
if win and hasattr(win, "workspace") and win.workspace and hasattr(win.workspace, "view2d"):
|
|
1666
|
+
win.workspace.view2d.fit_view()
|
|
1667
|
+
|
|
1668
|
+
def _on_toggle_2d_paper(self):
|
|
1669
|
+
win = getattr(self, "_window_ref", None)
|
|
1670
|
+
if win and hasattr(win, "workspace") and win.workspace and hasattr(win.workspace, "view2d"):
|
|
1671
|
+
win.workspace.view2d._toggle_paper_mode()
|
|
1672
|
+
|
|
1673
|
+
def _atom_editor_card(self):
|
|
1674
|
+
from PyQt6.QtWidgets import QSlider, QComboBox
|
|
1675
|
+
card = CollapsibleCard("选中原子属性 (ATOM INSPECTOR)", expanded=True)
|
|
1676
|
+
l = card.body_layout
|
|
1677
|
+
|
|
1678
|
+
# 多选原子片段专属信息卡片
|
|
1679
|
+
self.multi_atom_card = QFrame()
|
|
1680
|
+
self.multi_atom_card.setStyleSheet("background:#13283E; border:1px solid #1F4565; border-radius:6px; padding:6px;")
|
|
1681
|
+
mac_lay = QVBoxLayout(self.multi_atom_card)
|
|
1682
|
+
mac_lay.setContentsMargins(6, 6, 6, 6)
|
|
1683
|
+
mac_lay.setSpacing(5)
|
|
1684
|
+
|
|
1685
|
+
self.multi_atom_ids_label = QLabel("已选中片段原子序号:")
|
|
1686
|
+
self.multi_atom_ids_label.setWordWrap(True)
|
|
1687
|
+
self.multi_atom_ids_label.setStyleSheet("color:#66DEC9; font-weight:700; font-size:12px;")
|
|
1688
|
+
mac_lay.addWidget(self.multi_atom_ids_label)
|
|
1689
|
+
|
|
1690
|
+
self.multi_atom_pos_label = QLabel("片段几何质心:—")
|
|
1691
|
+
self.multi_atom_pos_label.setStyleSheet("color:#9AB0C2; font-size:11px;")
|
|
1692
|
+
mac_lay.addWidget(self.multi_atom_pos_label)
|
|
1693
|
+
|
|
1694
|
+
row_mac_btns = QHBoxLayout()
|
|
1695
|
+
btn_frag_save = QPushButton("💾 存为砌块...")
|
|
1696
|
+
btn_frag_save.setToolTip("将当前选中的原子片段保存到左侧砌块库")
|
|
1697
|
+
btn_frag_save.clicked.connect(self._save_selected_fragment_to_library)
|
|
1698
|
+
row_mac_btns.addWidget(btn_frag_save)
|
|
1699
|
+
|
|
1700
|
+
btn_frag_clear = QPushButton("取消多选")
|
|
1701
|
+
btn_frag_clear.clicked.connect(self._clear_selection)
|
|
1702
|
+
row_mac_btns.addWidget(btn_frag_clear)
|
|
1703
|
+
mac_lay.addLayout(row_mac_btns)
|
|
1704
|
+
|
|
1705
|
+
l.addWidget(self.multi_atom_card)
|
|
1706
|
+
self.multi_atom_card.setVisible(False)
|
|
1707
|
+
|
|
1708
|
+
self.atom_info_label = QLabel("未选中原子(点击 2D/3D 原子即可选中)")
|
|
1709
|
+
self.atom_info_label.setWordWrap(True)
|
|
1710
|
+
self.atom_info_label.setStyleSheet("color:#9AB0C2; font-weight:600;")
|
|
1711
|
+
l.addWidget(self.atom_info_label)
|
|
1712
|
+
|
|
1713
|
+
row_el = QHBoxLayout()
|
|
1714
|
+
row_el.addWidget(muted("元素种类"))
|
|
1715
|
+
row_el.addStretch()
|
|
1716
|
+
self.atom_element_label = QLabel("—")
|
|
1717
|
+
self.atom_element_label.setProperty("role", "value")
|
|
1718
|
+
row_el.addWidget(self.atom_element_label)
|
|
1719
|
+
change_btn = QPushButton("周期表替换...")
|
|
1720
|
+
change_btn.clicked.connect(self._change_selected_atom_element)
|
|
1721
|
+
row_el.addWidget(change_btn)
|
|
1722
|
+
l.addLayout(row_el)
|
|
1723
|
+
|
|
1724
|
+
row_sc_hdr = QHBoxLayout()
|
|
1725
|
+
row_sc_hdr.addWidget(muted("选中原子大小(只调这个)"))
|
|
1726
|
+
row_sc_hdr.addStretch()
|
|
1727
|
+
self.atom_scale_val_lbl = QLabel("100%")
|
|
1728
|
+
self.atom_scale_val_lbl.setProperty("role", "value")
|
|
1729
|
+
row_sc_hdr.addWidget(self.atom_scale_val_lbl)
|
|
1730
|
+
l.addLayout(row_sc_hdr)
|
|
1731
|
+
|
|
1732
|
+
self.atom_scale_slider = QSlider(Qt.Orientation.Horizontal)
|
|
1733
|
+
self.atom_scale_slider.setRange(40, 300)
|
|
1734
|
+
self.atom_scale_slider.setValue(100)
|
|
1735
|
+
install_wheel_guard(self.atom_scale_slider, self._wheel_guard)
|
|
1736
|
+
self.atom_scale_slider.valueChanged.connect(self._on_selected_atom_scale_changed)
|
|
1737
|
+
l.addWidget(self.atom_scale_slider)
|
|
1738
|
+
|
|
1739
|
+
row_ch = QHBoxLayout()
|
|
1740
|
+
row_ch.addWidget(muted("形式电荷"))
|
|
1741
|
+
row_ch.addStretch()
|
|
1742
|
+
self.atom_charge_combo = QComboBox()
|
|
1743
|
+
for c in (-2, -1, 0, 1, 2):
|
|
1744
|
+
self.atom_charge_combo.addItem(("+" if c > 0 else "") + str(c) if c != 0 else "0", c)
|
|
1745
|
+
self.atom_charge_combo.setCurrentIndex(2)
|
|
1746
|
+
install_wheel_guard(self.atom_charge_combo, self._wheel_guard)
|
|
1747
|
+
self.atom_charge_combo.currentIndexChanged.connect(self._on_charge_changed)
|
|
1748
|
+
row_ch.addWidget(self.atom_charge_combo)
|
|
1749
|
+
|
|
1750
|
+
color_btn = QPushButton("自定义颜色...")
|
|
1751
|
+
color_btn.clicked.connect(self._on_pick_atom_color)
|
|
1752
|
+
row_ch.addWidget(color_btn)
|
|
1753
|
+
l.addLayout(row_ch)
|
|
1754
|
+
|
|
1755
|
+
# 杂化方式 + 相连成键邻居原子
|
|
1756
|
+
row_hyb = QHBoxLayout()
|
|
1757
|
+
row_hyb.addWidget(muted("配位与杂化方式"))
|
|
1758
|
+
row_hyb.addStretch()
|
|
1759
|
+
self.atom_hyb_label = QLabel("—")
|
|
1760
|
+
self.atom_hyb_label.setProperty("role", "value")
|
|
1761
|
+
row_hyb.addWidget(self.atom_hyb_label)
|
|
1762
|
+
l.addLayout(row_hyb)
|
|
1763
|
+
|
|
1764
|
+
self.atom_neighbors_label = QLabel("相连成键邻居: —")
|
|
1765
|
+
self.atom_neighbors_label.setWordWrap(True)
|
|
1766
|
+
self.atom_neighbors_label.setStyleSheet("color:#7DAEFA; font-size:11px; padding:2px 0;")
|
|
1767
|
+
l.addWidget(self.atom_neighbors_label)
|
|
1768
|
+
|
|
1769
|
+
self.atom_vdw_label = QLabel("vdW 半径 / 质量: —")
|
|
1770
|
+
self.atom_vdw_label.setStyleSheet("color:#9AB0C2; font-size:11px;")
|
|
1771
|
+
l.addWidget(self.atom_vdw_label)
|
|
1772
|
+
|
|
1773
|
+
self.atom_partial_charge_label = QLabel("量化部分电荷: 暂未计算 (可由 REST 产出)")
|
|
1774
|
+
self.atom_partial_charge_label.setStyleSheet("color:#66DEC9; font-size:11px; font-weight:600;")
|
|
1775
|
+
l.addWidget(self.atom_partial_charge_label)
|
|
1776
|
+
|
|
1777
|
+
row_xyz_lbl = QHBoxLayout()
|
|
1778
|
+
row_xyz_lbl.addWidget(muted("空间几何绝对坐标 (Å):"))
|
|
1779
|
+
l.addLayout(row_xyz_lbl)
|
|
1780
|
+
|
|
1781
|
+
row_xyz = QHBoxLayout()
|
|
1782
|
+
row_xyz.setSpacing(4)
|
|
1783
|
+
self.atom_x_spin = QDoubleSpinBox()
|
|
1784
|
+
self.atom_y_spin = QDoubleSpinBox()
|
|
1785
|
+
self.atom_z_spin = QDoubleSpinBox()
|
|
1786
|
+
for prefix, sp in (("X:", self.atom_x_spin), ("Y:", self.atom_y_spin), ("Z:", self.atom_z_spin)):
|
|
1787
|
+
sp.setPrefix(prefix)
|
|
1788
|
+
sp.setRange(-999.0, 999.0)
|
|
1789
|
+
sp.setDecimals(3)
|
|
1790
|
+
sp.setSingleStep(0.05)
|
|
1791
|
+
install_wheel_guard(sp, self._wheel_guard)
|
|
1792
|
+
sp.editingFinished.connect(self._on_atom_xyz_changed)
|
|
1793
|
+
row_xyz.addWidget(sp, 1)
|
|
1794
|
+
l.addLayout(row_xyz)
|
|
1795
|
+
|
|
1796
|
+
self.atom_editor_card_widget = card
|
|
1797
|
+
return card
|
|
1798
|
+
|
|
1799
|
+
def _bond_editor_card(self):
|
|
1800
|
+
from PyQt6.QtWidgets import QSlider, QComboBox
|
|
1801
|
+
card = CollapsibleCard("选中化学键属性 (BOND INSPECTOR)", expanded=True)
|
|
1802
|
+
l = card.body_layout
|
|
1803
|
+
|
|
1804
|
+
self.bond_info_label = QLabel("未选中化学键(点击 2D/3D 键即可选中)")
|
|
1805
|
+
self.bond_info_label.setWordWrap(True)
|
|
1806
|
+
self.bond_info_label.setStyleSheet("color:#9AB0C2; font-weight:600;")
|
|
1807
|
+
l.addWidget(self.bond_info_label)
|
|
1808
|
+
|
|
1809
|
+
row_bo = QHBoxLayout()
|
|
1810
|
+
row_bo.addWidget(muted("键级类型"))
|
|
1811
|
+
self.bond_order_combo = QComboBox()
|
|
1812
|
+
for order, label in ((1, "单键 (Single)"), (2, "双键 (Double)"), (3, "三键 (Triple)"), (4, "芳香键 (Aromatic)")):
|
|
1813
|
+
self.bond_order_combo.addItem(label, order)
|
|
1814
|
+
install_wheel_guard(self.bond_order_combo, self._wheel_guard)
|
|
1815
|
+
self.bond_order_combo.currentIndexChanged.connect(self._on_bond_order_changed)
|
|
1816
|
+
row_bo.addWidget(self.bond_order_combo, 1)
|
|
1817
|
+
l.addLayout(row_bo)
|
|
1818
|
+
|
|
1819
|
+
row_bw_hdr = QHBoxLayout()
|
|
1820
|
+
row_bw_hdr.addWidget(muted("选中键粗细(只调选中键)"))
|
|
1821
|
+
row_bw_hdr.addStretch()
|
|
1822
|
+
self.bond_width_val_lbl = QLabel("100%")
|
|
1823
|
+
self.bond_width_val_lbl.setProperty("role", "value")
|
|
1824
|
+
row_bw_hdr.addWidget(self.bond_width_val_lbl)
|
|
1825
|
+
l.addLayout(row_bw_hdr)
|
|
1826
|
+
|
|
1827
|
+
self.bond_width_slider = QSlider(Qt.Orientation.Horizontal)
|
|
1828
|
+
self.selected_bond_width_slider = self.bond_width_slider
|
|
1829
|
+
self.bond_width_slider.setRange(40, 220)
|
|
1830
|
+
self.bond_width_slider.setValue(100)
|
|
1831
|
+
install_wheel_guard(self.bond_width_slider, self._wheel_guard)
|
|
1832
|
+
self.bond_width_slider.valueChanged.connect(self._on_selected_bond_width_changed)
|
|
1833
|
+
l.addWidget(self.bond_width_slider)
|
|
1834
|
+
l.addWidget(muted("↑ 仅缩放当前选中化学键粗细(全局粗细在[设置]页)"))
|
|
1835
|
+
|
|
1836
|
+
row_bl = QHBoxLayout()
|
|
1837
|
+
row_bl.addWidget(muted("精确键长 (Å)"))
|
|
1838
|
+
self.bond_length_spin = QDoubleSpinBox()
|
|
1839
|
+
self.bond_length_spin.setRange(0.45, 4.50)
|
|
1840
|
+
self.bond_length_spin.setDecimals(3)
|
|
1841
|
+
self.bond_length_spin.setSingleStep(0.02)
|
|
1842
|
+
self.bond_length_spin.setValue(1.45)
|
|
1843
|
+
self.bond_length_spin.setToolTip("选中键后显示真实键长;改数值或点[应用]即沿键方向移动基团并支持 Ctrl+Z 撤销")
|
|
1844
|
+
install_wheel_guard(self.bond_length_spin, self._wheel_guard)
|
|
1845
|
+
self.bond_length_spin.editingFinished.connect(self._on_bond_length_changed)
|
|
1846
|
+
row_bl.addWidget(self.bond_length_spin, 1)
|
|
1847
|
+
apply_bl_btn = QPushButton("应用")
|
|
1848
|
+
apply_bl_btn.setMinimumWidth(48)
|
|
1849
|
+
apply_bl_btn.clicked.connect(self._on_bond_length_changed)
|
|
1850
|
+
row_bl.addWidget(apply_bl_btn)
|
|
1851
|
+
l.addLayout(row_bl)
|
|
1852
|
+
|
|
1853
|
+
self.bond_angle_dih_label = QLabel("相邻键角 / 二面角:选中化学键后自动计算")
|
|
1854
|
+
self.bond_angle_dih_label.setWordWrap(True)
|
|
1855
|
+
self.bond_angle_dih_label.setStyleSheet("color:#7DAEFA; font-size:12px; font-weight:600;")
|
|
1856
|
+
l.addWidget(self.bond_angle_dih_label)
|
|
1857
|
+
|
|
1858
|
+
self.bond_ring_label = QLabel("环系归属: —")
|
|
1859
|
+
self.bond_ring_label.setStyleSheet("color:#9AB0C2; font-size:11px;")
|
|
1860
|
+
l.addWidget(self.bond_ring_label)
|
|
1861
|
+
|
|
1862
|
+
# 精确修改键角/二面角按钮
|
|
1863
|
+
row_ang = QHBoxLayout()
|
|
1864
|
+
mod_ang_btn = QPushButton("📐 精确修改键角...")
|
|
1865
|
+
mod_ang_btn.setToolTip("选中 3 个相邻原子后,精确修改中间键角(°)")
|
|
1866
|
+
mod_ang_btn.clicked.connect(self._on_modify_angle)
|
|
1867
|
+
row_ang.addWidget(mod_ang_btn)
|
|
1868
|
+
mod_dih_btn = QPushButton("🔄 精确修改二面角...")
|
|
1869
|
+
mod_dih_btn.setToolTip("选中 4 个相邻原子后,精确修改二面角扭转角(°)")
|
|
1870
|
+
mod_dih_btn.clicked.connect(self._on_modify_dihedral)
|
|
1871
|
+
row_ang.addWidget(mod_dih_btn)
|
|
1872
|
+
l.addLayout(row_ang)
|
|
1873
|
+
|
|
1874
|
+
row_bc = QHBoxLayout()
|
|
1875
|
+
row_bc.addWidget(muted("键色定制"))
|
|
1876
|
+
row_bc.addStretch()
|
|
1877
|
+
bond_color_btn = QPushButton("自定义键色...")
|
|
1878
|
+
bond_color_btn.clicked.connect(self._on_pick_bond_color)
|
|
1879
|
+
row_bc.addWidget(bond_color_btn)
|
|
1880
|
+
l.addLayout(row_bc)
|
|
1881
|
+
return card
|
|
1882
|
+
|
|
1883
|
+
def _on_bond_length_changed(self):
|
|
1884
|
+
if hasattr(self, "on_bond_length") and self.on_bond_length:
|
|
1885
|
+
self.on_bond_length(float(self.bond_length_spin.value()))
|
|
1886
|
+
|
|
1887
|
+
def _on_bond_order_changed(self, idx):
|
|
1888
|
+
if hasattr(self, "on_bond_order") and self.on_bond_order:
|
|
1889
|
+
self.on_bond_order(self.bond_order_combo.itemData(idx))
|
|
1890
|
+
|
|
1891
|
+
def _on_bond_width_changed(self, v: int):
|
|
1892
|
+
self.bond_width_val_lbl.setText(f"{v}%")
|
|
1893
|
+
if hasattr(self, "on_bond_width") and self.on_bond_width:
|
|
1894
|
+
self.on_bond_width(v / 100.0)
|
|
1895
|
+
|
|
1896
|
+
def _on_modify_angle(self):
|
|
1897
|
+
"""弹出精确修改键角对话框(支持显式回调与 _window_ref 双路径)。"""
|
|
1898
|
+
if hasattr(self, "on_modify_angle") and callable(self.on_modify_angle):
|
|
1899
|
+
self.on_modify_angle()
|
|
1900
|
+
return
|
|
1901
|
+
from .views import ModifyInternalCoordDialog
|
|
1902
|
+
win = getattr(self, "_window_ref", None) or self.window()
|
|
1903
|
+
if win is not None:
|
|
1904
|
+
ModifyInternalCoordDialog(win, "angle").exec()
|
|
1905
|
+
|
|
1906
|
+
def _on_modify_dihedral(self):
|
|
1907
|
+
"""弹出精确修改二面角对话框(支持显式回调与 _window_ref 双路径)。"""
|
|
1908
|
+
if hasattr(self, "on_modify_dihedral") and callable(self.on_modify_dihedral):
|
|
1909
|
+
self.on_modify_dihedral()
|
|
1910
|
+
return
|
|
1911
|
+
from .views import ModifyInternalCoordDialog
|
|
1912
|
+
win = getattr(self, "_window_ref", None) or self.window()
|
|
1913
|
+
if win is not None:
|
|
1914
|
+
ModifyInternalCoordDialog(win, "dihedral").exec()
|
|
1915
|
+
|
|
1916
|
+
def _on_selected_bond_width_changed(self, v: int):
|
|
1917
|
+
self.bond_width_val_lbl.setText(f"{v}%")
|
|
1918
|
+
if hasattr(self, "on_selected_bond_width") and self.on_selected_bond_width:
|
|
1919
|
+
self.on_selected_bond_width(v / 100.0)
|
|
1920
|
+
|
|
1921
|
+
def _on_pick_bond_color(self):
|
|
1922
|
+
if hasattr(self, "on_pick_bond_color") and self.on_pick_bond_color:
|
|
1923
|
+
self.on_pick_bond_color()
|
|
1924
|
+
|
|
1925
|
+
def update_selected_bond(self, bond):
|
|
1926
|
+
if bond is None:
|
|
1927
|
+
self.bond_info_label.setText("未选中化学键(点击 2D/3D 键即可选中)")
|
|
1928
|
+
return
|
|
1929
|
+
names = {1: "单键", 2: "双键", 3: "三键", 4: "芳香键"}
|
|
1930
|
+
self.bond_info_label.setText(
|
|
1931
|
+
f"✓ 已选中键 #{bond.id.value + 1} (#{bond.begin.value + 1}–#{bond.end.value + 1}) · {names.get(bond.order, str(bond.order))}"
|
|
1932
|
+
)
|
|
1933
|
+
self.bond_order_combo.blockSignals(True)
|
|
1934
|
+
for i in range(self.bond_order_combo.count()):
|
|
1935
|
+
if self.bond_order_combo.itemData(i) == bond.order:
|
|
1936
|
+
self.bond_order_combo.setCurrentIndex(i)
|
|
1937
|
+
self.bond_order_combo.blockSignals(False)
|
|
1938
|
+
w_pct = int(round(float(getattr(bond, "width_scale", 1.0)) * 100))
|
|
1939
|
+
self.bond_width_slider.blockSignals(True)
|
|
1940
|
+
self.bond_width_slider.setValue(max(40, min(220, w_pct)))
|
|
1941
|
+
self.bond_width_val_lbl.setText(f"{w_pct}%")
|
|
1942
|
+
self.bond_width_slider.blockSignals(False)
|
|
1943
|
+
# 填入当前真实键长(从 3D 坐标算)
|
|
1944
|
+
try:
|
|
1945
|
+
doc = self._document_provider() if self._document_provider else None
|
|
1946
|
+
if doc is not None and getattr(doc, "has_3d", False) and doc.coordinates.current is not None:
|
|
1947
|
+
_, id2idx = doc.topology.atom_index_map()
|
|
1948
|
+
coords = doc.coordinates.current.coords
|
|
1949
|
+
a, b = bond.begin, bond.end
|
|
1950
|
+
if a in id2idx and b in id2idx:
|
|
1951
|
+
import numpy as np
|
|
1952
|
+
from ..application import measurement as mm
|
|
1953
|
+
from ..domain.periodic import cell_from_document
|
|
1954
|
+
cell = cell_from_document(doc)
|
|
1955
|
+
ia, ib = id2idx[a], id2idx[b]
|
|
1956
|
+
d = mm.distance(coords, ia, ib, cell)
|
|
1957
|
+
self.bond_length_spin.blockSignals(True)
|
|
1958
|
+
self.bond_length_spin.setValue(round(d, 3))
|
|
1959
|
+
self.bond_length_spin.blockSignals(False)
|
|
1960
|
+
# 计算相邻键角与二面角
|
|
1961
|
+
nbrs_a = [n for n in doc.topology.neighbors_of(a) if n != b and n in id2idx]
|
|
1962
|
+
nbrs_b = [n for n in doc.topology.neighbors_of(b) if n != a and n in id2idx]
|
|
1963
|
+
extra_parts = [f"键长: {d:.3f} Å"]
|
|
1964
|
+
if nbrs_a:
|
|
1965
|
+
ang_v, ok_a, _ = mm.angle(coords, id2idx[nbrs_a[0]], ia, ib, cell)
|
|
1966
|
+
if ok_a:
|
|
1967
|
+
extra_parts.append(f"邻角: {ang_v:.1f}°")
|
|
1968
|
+
from ..application.measurement_targets import MeasurementTargetResolver
|
|
1969
|
+
canon_dih = MeasurementTargetResolver.find_canonical_dihedral_for_bond(doc, bond.id)
|
|
1970
|
+
if canon_dih:
|
|
1971
|
+
i, j, k, l = canon_dih
|
|
1972
|
+
if i in id2idx and j in id2idx and k in id2idx and l in id2idx:
|
|
1973
|
+
dih_v, ok_d, _ = mm.dihedral(coords, id2idx[i], id2idx[j], id2idx[k], id2idx[l], cell)
|
|
1974
|
+
if ok_d:
|
|
1975
|
+
extra_parts.append(f"主二面角(#{i.value+1}-#{j.value+1}-#{k.value+1}-#{l.value+1}): {dih_v:.1f}°")
|
|
1976
|
+
elif nbrs_a and nbrs_b:
|
|
1977
|
+
dih_v, ok_d, _ = mm.dihedral(coords, id2idx[nbrs_a[0]], ia, ib, id2idx[nbrs_b[0]], cell)
|
|
1978
|
+
if ok_d:
|
|
1979
|
+
extra_parts.append(f"二面角: {dih_v:.1f}°")
|
|
1980
|
+
self.bond_angle_dih_label.setText(" · ".join(extra_parts))
|
|
1981
|
+
is_ring = doc.topology.is_bond_in_ring(bond.id) if hasattr(doc.topology, "is_bond_in_ring") else False
|
|
1982
|
+
self.bond_ring_label.setText(f"环系归属:{'环内化学键 (In Ring)' if is_ring else '链状可旋转单键 (Chain / Rotatable)'}")
|
|
1983
|
+
except Exception:
|
|
1984
|
+
pass
|
|
1985
|
+
|
|
1986
|
+
def _on_atom_xyz_changed(self):
|
|
1987
|
+
if hasattr(self, "on_atom_xyz_edited") and self.on_atom_xyz_edited:
|
|
1988
|
+
self.on_atom_xyz_edited(
|
|
1989
|
+
float(self.atom_x_spin.value()),
|
|
1990
|
+
float(self.atom_y_spin.value()),
|
|
1991
|
+
float(self.atom_z_spin.value()),
|
|
1992
|
+
)
|
|
1993
|
+
|
|
1994
|
+
def _change_selected_atom_element(self):
|
|
1995
|
+
if hasattr(self, "on_change_element") and self.on_change_element:
|
|
1996
|
+
self.on_change_element()
|
|
1997
|
+
|
|
1998
|
+
def _on_atom_scale_changed(self, v: int):
|
|
1999
|
+
self.atom_scale_val_lbl.setText(f"{v}%")
|
|
2000
|
+
if hasattr(self, "on_atom_scale") and self.on_atom_scale:
|
|
2001
|
+
self.on_atom_scale(v / 100.0)
|
|
2002
|
+
|
|
2003
|
+
def _on_selected_atom_scale_changed(self, v: int):
|
|
2004
|
+
self.atom_scale_val_lbl.setText(f"{v}%")
|
|
2005
|
+
if hasattr(self, "on_selected_atom_scale") and self.on_selected_atom_scale:
|
|
2006
|
+
self.on_selected_atom_scale(v / 100.0)
|
|
2007
|
+
|
|
2008
|
+
def _on_charge_changed(self, idx):
|
|
2009
|
+
if hasattr(self, "on_charge") and self.on_charge:
|
|
2010
|
+
self.on_charge(self.atom_charge_combo.itemData(idx))
|
|
2011
|
+
|
|
2012
|
+
def _on_pick_atom_color(self):
|
|
2013
|
+
if hasattr(self, "on_pick_color") and self.on_pick_color:
|
|
2014
|
+
self.on_pick_color()
|
|
2015
|
+
|
|
2016
|
+
def _save_selected_fragment_to_library(self):
|
|
2017
|
+
win = getattr(self, "_window_ref", None)
|
|
2018
|
+
if win and hasattr(win, "sidebar"):
|
|
2019
|
+
win.sidebar._on_save_selected_as_fragment()
|
|
2020
|
+
|
|
2021
|
+
def _clear_selection(self):
|
|
2022
|
+
win = getattr(self, "_window_ref", None)
|
|
2023
|
+
if win and hasattr(win, "selection") and win.selection:
|
|
2024
|
+
win.selection.clear()
|
|
2025
|
+
|
|
2026
|
+
def update_selected_atoms_summary(self, atom_ids: list, doc=None):
|
|
2027
|
+
if not hasattr(self, "multi_atom_card"):
|
|
2028
|
+
return
|
|
2029
|
+
if not atom_ids or len(atom_ids) <= 1:
|
|
2030
|
+
self.multi_atom_card.setVisible(False)
|
|
2031
|
+
return
|
|
2032
|
+
self.multi_atom_card.setVisible(True)
|
|
2033
|
+
sorted_ids = sorted(atom_ids, key=lambda a: a.value if hasattr(a, "value") else int(a))
|
|
2034
|
+
id_numbers = [a.value + 1 if hasattr(a, "value") else int(a) + 1 for a in sorted_ids]
|
|
2035
|
+
id_str = ", ".join(f"#{i}" for i in id_numbers[:12])
|
|
2036
|
+
if len(id_numbers) > 12:
|
|
2037
|
+
id_str += f" ... 等共 {len(id_numbers)} 个原子"
|
|
2038
|
+
self.multi_atom_ids_label.setText(f"✓ 已选中 {len(id_numbers)} 个原子序号:\n{id_str}")
|
|
2039
|
+
self.atom_info_label.setText(f"✓ 当前多选:{len(id_numbers)} 个原子(可一键存为砌块或拖拽平移)")
|
|
2040
|
+
if doc and doc.has_3d and doc.coordinates.current is not None:
|
|
2041
|
+
import numpy as np
|
|
2042
|
+
coords = [p for a in sorted_ids if (p := doc.get_atom_3d_pos(a)) is not None]
|
|
2043
|
+
if coords:
|
|
2044
|
+
mean_pos = np.mean(coords, axis=0)
|
|
2045
|
+
self.multi_atom_pos_label.setText(f"选中片段质心: ({mean_pos[0]:.3f}, {mean_pos[1]:.3f}, {mean_pos[2]:.3f}) Å")
|
|
2046
|
+
|
|
2047
|
+
def update_selected_atom(
|
|
2048
|
+
self,
|
|
2049
|
+
elem,
|
|
2050
|
+
charge=0,
|
|
2051
|
+
atom_scale: float = 1.0,
|
|
2052
|
+
atom_id=None,
|
|
2053
|
+
xyz: tuple[float, float, float] | None = None,
|
|
2054
|
+
hybridization: str = "—",
|
|
2055
|
+
frozen: bool = False,
|
|
2056
|
+
):
|
|
2057
|
+
if elem is None:
|
|
2058
|
+
self.atom_info_label.setText("未选中原子(点击 2D/3D 原子即可选中)")
|
|
2059
|
+
self.atom_element_label.setText("—")
|
|
2060
|
+
self.atom_hyb_label.setText("—")
|
|
2061
|
+
return
|
|
2062
|
+
w_val = getattr(elem, "atomic_weight", getattr(elem, "atomic_mass", 12.011))
|
|
2063
|
+
id_str = f"#{atom_id.value+1} " if hasattr(atom_id, "value") else ""
|
|
2064
|
+
self.atom_info_label.setText(f"✓ 已选中原子 {id_str}:{elem.name_cn} · {elem.symbol} ({w_val:.3f} u)")
|
|
2065
|
+
self.atom_element_label.setText(f"{elem.symbol} (Z={elem.atomic_number})" + (" · 坐标已冻结" if frozen else ""))
|
|
2066
|
+
self.atom_hyb_label.setText(hybridization)
|
|
2067
|
+
vdw_r = getattr(elem, "vdw_radius", getattr(elem, "radius_vdw", 1.70))
|
|
2068
|
+
self.atom_vdw_label.setText(f"vdW 半径: {vdw_r:.2f} Å · 原子量: {w_val:.3f} u")
|
|
2069
|
+
nbr_strs = []
|
|
2070
|
+
if atom_id is not None and self._document_provider:
|
|
2071
|
+
doc = self._document_provider()
|
|
2072
|
+
if doc:
|
|
2073
|
+
atom = doc.topology.get_atom(atom_id)
|
|
2074
|
+
m_ch = atom.properties.get("mulliken_charge", None)
|
|
2075
|
+
if m_ch is not None:
|
|
2076
|
+
self.atom_partial_charge_label.setText(f"Mulliken 电荷: {float(m_ch):+.4f} e")
|
|
2077
|
+
else:
|
|
2078
|
+
self.atom_partial_charge_label.setText("量化部分电荷: 暂未计算 (可由 REST 产出)")
|
|
2079
|
+
for nbr_id in doc.topology.neighbors_of(atom_id):
|
|
2080
|
+
nbr_atom = doc.topology.get_atom(nbr_id)
|
|
2081
|
+
nbr_strs.append(f"{nbr_atom.symbol}#{nbr_id.value+1}")
|
|
2082
|
+
self.atom_neighbors_label.setText("相连成键邻居: " + (", ".join(nbr_strs) if nbr_strs else "孤立原子"))
|
|
2083
|
+
if xyz is not None:
|
|
2084
|
+
for sp, val in ((self.atom_x_spin, xyz[0]), (self.atom_y_spin, xyz[1]), (self.atom_z_spin, xyz[2])):
|
|
2085
|
+
sp.blockSignals(True)
|
|
2086
|
+
sp.setValue(round(float(val), 3))
|
|
2087
|
+
sp.blockSignals(False)
|
|
2088
|
+
self.atom_charge_combo.blockSignals(True)
|
|
2089
|
+
for i in range(self.atom_charge_combo.count()):
|
|
2090
|
+
if self.atom_charge_combo.itemData(i) == charge:
|
|
2091
|
+
self.atom_charge_combo.setCurrentIndex(i)
|
|
2092
|
+
self.atom_charge_combo.blockSignals(False)
|
|
2093
|
+
sc_pct = int(round(float(atom_scale) * 100))
|
|
2094
|
+
self.atom_scale_slider.blockSignals(True)
|
|
2095
|
+
self.atom_scale_slider.setValue(max(40, min(300, sc_pct)))
|
|
2096
|
+
self.atom_scale_val_lbl.setText(f"{sc_pct}%")
|
|
2097
|
+
self.atom_scale_slider.blockSignals(False)
|
|
2098
|
+
|
|
2099
|
+
def update_molecule_info(self, name: str, formula: str, num_atoms: int, num_bonds: int,
|
|
2100
|
+
molecular_weight: float = 0.0, heavy_atoms: int = 0, hydrogens: int = 0,
|
|
2101
|
+
charge: int = 0, spin_mult: int = 1, spin_label: str = "Singlet",
|
|
2102
|
+
rings_count: int = 0, rotatable_bonds: int = 0,
|
|
2103
|
+
centroid_str: str = "(0.00, 0.00, 0.00)", point_group: str = "C1", **kwargs):
|
|
2104
|
+
self.mol_name_label.setText(f"{name} · {formula}")
|
|
2105
|
+
if "化学式" in self.inspect_labels:
|
|
2106
|
+
self.inspect_labels["化学式"].setText(formula)
|
|
2107
|
+
if "相对分子质量" in self.inspect_labels:
|
|
2108
|
+
self.inspect_labels["相对分子质量"].setText(f"{molecular_weight:.2f} Da")
|
|
2109
|
+
if "原子 (重/氢)" in self.inspect_labels:
|
|
2110
|
+
self.inspect_labels["原子 (重/氢)"].setText(f"{num_atoms} ({heavy_atoms} 重 / {hydrogens} 氢)")
|
|
2111
|
+
if "化学键 (单/双/芳)" in self.inspect_labels:
|
|
2112
|
+
self.inspect_labels["化学键 (单/双/芳)"].setText(f"{num_bonds} 键")
|
|
2113
|
+
if "净电荷 / 自旋" in self.inspect_labels:
|
|
2114
|
+
self.inspect_labels["净电荷 / 自旋"].setText(f"{charge:+d} / {spin_label} (M={spin_mult})")
|
|
2115
|
+
if "环系数量" in self.inspect_labels:
|
|
2116
|
+
self.inspect_labels["环系数量"].setText(f"{rings_count} 环")
|
|
2117
|
+
if "非环单键 (自定义)" in self.inspect_labels:
|
|
2118
|
+
self.inspect_labels["非环单键 (自定义)"].setText(f"{rotatable_bonds} 个")
|
|
2119
|
+
if "空间质心 (Å)" in self.inspect_labels:
|
|
2120
|
+
self.inspect_labels["空间质心 (Å)"].setText(centroid_str)
|
|
2121
|
+
if "点群 / 几何形态" in self.inspect_labels:
|
|
2122
|
+
self.inspect_labels["点群 / 几何形态"].setText(point_group)
|
|
2123
|
+
|
|
2124
|
+
# ---------- DeepSeek AI 助手页 ----------
|
|
2125
|
+
|
|
2126
|
+
def _assistant(self):
|
|
2127
|
+
page, box = self._page()
|
|
2128
|
+
|
|
2129
|
+
self.assistant_context_label = QLabel("尚未加载分子")
|
|
2130
|
+
self.assistant_context_label.setWordWrap(True)
|
|
2131
|
+
self.assistant_context_label.setStyleSheet(
|
|
2132
|
+
"color:#EAF2F6; background:#132436; border:1px solid #243E56;"
|
|
2133
|
+
"border-radius:7px; padding:8px 10px; font-size:12px;"
|
|
2134
|
+
)
|
|
2135
|
+
box.addWidget(self.assistant_context_label)
|
|
2136
|
+
|
|
2137
|
+
cfg_card = CollapsibleCard("AI 助手与大模型配置 (LLM / MCP CONFIG)", expanded=True)
|
|
2138
|
+
cfg_lay = cfg_card.body_layout
|
|
2139
|
+
|
|
2140
|
+
from ..ai.mcp_bridge import get_llm_config, set_llm_config
|
|
2141
|
+
cfg = get_llm_config()
|
|
2142
|
+
|
|
2143
|
+
# 平台预设
|
|
2144
|
+
row_prov = QHBoxLayout()
|
|
2145
|
+
row_prov.addWidget(muted("服务商:"))
|
|
2146
|
+
self.provider_combo = QComboBox()
|
|
2147
|
+
self.providers_data = {
|
|
2148
|
+
"DeepSeek (官方)": {
|
|
2149
|
+
"url": "https://api.deepseek.com/v1",
|
|
2150
|
+
"models": ["deepseek-chat", "deepseek-reasoner"],
|
|
2151
|
+
},
|
|
2152
|
+
"OpenAI / ChatGPT": {
|
|
2153
|
+
"url": "https://api.openai.com/v1",
|
|
2154
|
+
"models": ["gpt-4o", "gpt-4o-mini", "o1", "gpt-4.5-preview"],
|
|
2155
|
+
},
|
|
2156
|
+
"通义千问 (Qwen / 阿里百炼)": {
|
|
2157
|
+
"url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
2158
|
+
"models": ["qwen-plus", "qwen-max", "qwen-turbo"],
|
|
2159
|
+
},
|
|
2160
|
+
"月之暗面 (Kimi / Moonshot)": {
|
|
2161
|
+
"url": "https://api.moonshot.cn/v1",
|
|
2162
|
+
"models": ["moonshot-v1-8k", "moonshot-v1-32k"],
|
|
2163
|
+
},
|
|
2164
|
+
"智谱清言 (GLM-4 / Zhipu)": {
|
|
2165
|
+
"url": "https://open.bigmodel.cn/api/paas/v4",
|
|
2166
|
+
"models": ["glm-4-plus", "glm-4-flash"],
|
|
2167
|
+
},
|
|
2168
|
+
"Ollama 本地大模型": {
|
|
2169
|
+
"url": "http://localhost:11434/v1",
|
|
2170
|
+
"models": ["deepseek-r1:14b", "qwen2.5:14b", "llama3.3"],
|
|
2171
|
+
},
|
|
2172
|
+
"Antigravity MCP / 本地端点": {
|
|
2173
|
+
"url": "http://127.0.0.1:8045/v1",
|
|
2174
|
+
"models": ["gemini-3.8-flash", "claude-sonnet-5-5", "claude-opus-5-5"],
|
|
2175
|
+
},
|
|
2176
|
+
"自定义端点 (Custom URL)": {
|
|
2177
|
+
"url": "http://127.0.0.1:8045/v1",
|
|
2178
|
+
"models": ["gemini-3.8-flash"],
|
|
2179
|
+
},
|
|
2180
|
+
}
|
|
2181
|
+
for p_name in self.providers_data:
|
|
2182
|
+
self.provider_combo.addItem(p_name)
|
|
2183
|
+
install_wheel_guard(self.provider_combo, self._wheel_guard)
|
|
2184
|
+
row_prov.addWidget(self.provider_combo, 1)
|
|
2185
|
+
cfg_lay.addLayout(row_prov)
|
|
2186
|
+
|
|
2187
|
+
# Base URL
|
|
2188
|
+
row_url = QHBoxLayout()
|
|
2189
|
+
row_url.addWidget(muted("Base URL:"))
|
|
2190
|
+
self.ds_url_input = QLineEdit()
|
|
2191
|
+
self.ds_url_input.setText(cfg["base_url"])
|
|
2192
|
+
self.ds_url_input.editingFinished.connect(self._on_ds_config_changed)
|
|
2193
|
+
row_url.addWidget(self.ds_url_input, 1)
|
|
2194
|
+
cfg_lay.addLayout(row_url)
|
|
2195
|
+
|
|
2196
|
+
# Model Name (editable QComboBox + 获取模型按钮)
|
|
2197
|
+
row_m = QHBoxLayout()
|
|
2198
|
+
row_m.addWidget(muted("模型名:"))
|
|
2199
|
+
self.ds_model_combo = QComboBox()
|
|
2200
|
+
self.ds_model_combo.setEditable(True)
|
|
2201
|
+
self.ds_model_combo.setToolTip("输入或从端点下拉选择可用模型")
|
|
2202
|
+
self.ds_model_combo.lineEdit().setPlaceholderText("如 gemini-3.8-flash / deepseek-chat")
|
|
2203
|
+
self.ds_model_combo.setMinimumWidth(150)
|
|
2204
|
+
cur_m = cfg["model"] if cfg["model"] not in ("default-model", "antigravity") else "gemini-3.8-flash"
|
|
2205
|
+
self.ds_model_combo.addItem(cur_m)
|
|
2206
|
+
self.ds_model_combo.setCurrentText(cur_m)
|
|
2207
|
+
self.ds_model_input = self.ds_model_combo.lineEdit()
|
|
2208
|
+
self.ds_model_combo.activated.connect(self._on_ds_config_changed)
|
|
2209
|
+
if self.ds_model_input is not None:
|
|
2210
|
+
self.ds_model_input.editingFinished.connect(self._on_ds_config_changed)
|
|
2211
|
+
install_wheel_guard(self.ds_model_combo, self._wheel_guard)
|
|
2212
|
+
row_m.addWidget(self.ds_model_combo, 1)
|
|
2213
|
+
|
|
2214
|
+
self.btn_fetch_models = QPushButton("🔄 获取模型")
|
|
2215
|
+
self.btn_fetch_models.setToolTip("请求所填 Base URL 的 /v1/models 接口,自动拉取当前端点所有可用模型并填充下拉列表")
|
|
2216
|
+
self.btn_fetch_models.clicked.connect(self._fetch_remote_models_action)
|
|
2217
|
+
row_m.addWidget(self.btn_fetch_models)
|
|
2218
|
+
cfg_lay.addLayout(row_m)
|
|
2219
|
+
|
|
2220
|
+
# Match provider with cfg["base_url"]
|
|
2221
|
+
matched_provider = None
|
|
2222
|
+
for p_name, p_info in self.providers_data.items():
|
|
2223
|
+
if p_info["url"].rstrip("/") == cfg["base_url"].rstrip("/"):
|
|
2224
|
+
matched_provider = p_name
|
|
2225
|
+
break
|
|
2226
|
+
if matched_provider is None:
|
|
2227
|
+
matched_provider = "自定义端点 (Custom URL)"
|
|
2228
|
+
|
|
2229
|
+
self.provider_combo.blockSignals(True)
|
|
2230
|
+
self.provider_combo.setCurrentText(matched_provider)
|
|
2231
|
+
self.provider_combo.blockSignals(False)
|
|
2232
|
+
self.provider_combo.currentIndexChanged.connect(self._on_provider_changed)
|
|
2233
|
+
|
|
2234
|
+
# API Key
|
|
2235
|
+
self.ds_key_input = QLineEdit()
|
|
2236
|
+
self.ds_key_input.setEchoMode(QLineEdit.EchoMode.Password)
|
|
2237
|
+
self.ds_key_input.setPlaceholderText("填入 API Key (如 sk-...),留空自动使用内置化学规则引擎")
|
|
2238
|
+
if cfg["api_key"] and cfg["api_key"] != "EMPTY":
|
|
2239
|
+
self.ds_key_input.setText(cfg["api_key"])
|
|
2240
|
+
else:
|
|
2241
|
+
self.ds_key_input.setText("")
|
|
2242
|
+
self.ds_key_input.editingFinished.connect(self._on_ds_config_changed)
|
|
2243
|
+
cfg_lay.addWidget(self.ds_key_input)
|
|
2244
|
+
|
|
2245
|
+
# Temperature (温度调节)
|
|
2246
|
+
row_temp = QHBoxLayout()
|
|
2247
|
+
row_temp.addWidget(muted("温度 (Temp):"))
|
|
2248
|
+
self.temp_slider = QSlider(Qt.Orientation.Horizontal)
|
|
2249
|
+
self.temp_slider.setRange(0, 100)
|
|
2250
|
+
self.temp_slider.setValue(int(cfg.get("temperature", 0.3) * 100))
|
|
2251
|
+
self.temp_val_lbl = QLabel(f"{cfg.get('temperature', 0.3):.2f}")
|
|
2252
|
+
self.temp_val_lbl.setMinimumWidth(35)
|
|
2253
|
+
self.temp_val_lbl.setStyleSheet("color:#5EEAD4; font-weight:700;")
|
|
2254
|
+
self.temp_slider.valueChanged.connect(lambda v: self.temp_val_lbl.setText(f"{v / 100.0:.2f}"))
|
|
2255
|
+
self.temp_slider.valueChanged.connect(self._on_ds_config_changed)
|
|
2256
|
+
install_wheel_guard(self.temp_slider, self._wheel_guard)
|
|
2257
|
+
row_temp.addWidget(self.temp_slider, 1)
|
|
2258
|
+
row_temp.addWidget(self.temp_val_lbl)
|
|
2259
|
+
cfg_lay.addLayout(row_temp)
|
|
2260
|
+
|
|
2261
|
+
# Max Tokens & Reasoning Effort (深度思考/推理等级)
|
|
2262
|
+
row_params = QHBoxLayout()
|
|
2263
|
+
row_params.addWidget(muted("最大输出:"))
|
|
2264
|
+
self.max_tokens_spin = QDoubleSpinBox()
|
|
2265
|
+
self.max_tokens_spin.setRange(256, 131072)
|
|
2266
|
+
self.max_tokens_spin.setDecimals(0)
|
|
2267
|
+
self.max_tokens_spin.setSingleStep(1024)
|
|
2268
|
+
self.max_tokens_spin.setValue(float(cfg.get("max_tokens", 4096)))
|
|
2269
|
+
self.max_tokens_spin.setSuffix(" tokens")
|
|
2270
|
+
self.max_tokens_spin.valueChanged.connect(self._on_ds_config_changed)
|
|
2271
|
+
install_wheel_guard(self.max_tokens_spin, self._wheel_guard)
|
|
2272
|
+
row_params.addWidget(self.max_tokens_spin)
|
|
2273
|
+
|
|
2274
|
+
row_params.addWidget(muted("思考等级:"))
|
|
2275
|
+
self.reasoning_combo = QComboBox()
|
|
2276
|
+
self.reasoning_combo.addItem("关闭 (none)", "none")
|
|
2277
|
+
self.reasoning_combo.addItem("低 (low)", "low")
|
|
2278
|
+
self.reasoning_combo.addItem("中 (medium)", "medium")
|
|
2279
|
+
self.reasoning_combo.addItem("高 (high)", "high")
|
|
2280
|
+
cur_re = str(cfg.get("reasoning_effort", "none")).lower()
|
|
2281
|
+
re_idx = 0
|
|
2282
|
+
if cur_re in ("low", "低"): re_idx = 1
|
|
2283
|
+
elif cur_re in ("medium", "中"): re_idx = 2
|
|
2284
|
+
elif cur_re in ("high", "高"): re_idx = 3
|
|
2285
|
+
self.reasoning_combo.setCurrentIndex(re_idx)
|
|
2286
|
+
self.reasoning_combo.currentIndexChanged.connect(self._on_ds_config_changed)
|
|
2287
|
+
install_wheel_guard(self.reasoning_combo, self._wheel_guard)
|
|
2288
|
+
row_params.addWidget(self.reasoning_combo, 1)
|
|
2289
|
+
cfg_lay.addLayout(row_params)
|
|
2290
|
+
|
|
2291
|
+
row_save = QHBoxLayout()
|
|
2292
|
+
self.save_cfg_btn = QPushButton("💾 保存配置")
|
|
2293
|
+
self.save_cfg_btn.setStyleSheet("font-weight:700; padding:4px 14px;")
|
|
2294
|
+
self.save_cfg_btn.clicked.connect(self._save_and_confirm_config)
|
|
2295
|
+
row_save.addWidget(self.save_cfg_btn)
|
|
2296
|
+
|
|
2297
|
+
self.save_feedback_lbl = QLabel("")
|
|
2298
|
+
self.save_feedback_lbl.setStyleSheet("color:#66DEC9; font-size:12px; font-weight:700;")
|
|
2299
|
+
row_save.addWidget(self.save_feedback_lbl, 1)
|
|
2300
|
+
cfg_lay.addLayout(row_save)
|
|
2301
|
+
|
|
2302
|
+
lbl_sync = QLabel("✓ 此处配置已全局持久化,独立对话窗口与 MCP 工具链自动实时继承。")
|
|
2303
|
+
lbl_sync.setStyleSheet("color: #5EEAD4; font-size: 11px; padding: 2px 0;")
|
|
2304
|
+
cfg_lay.addWidget(lbl_sync)
|
|
2305
|
+
|
|
2306
|
+
box.addWidget(cfg_card)
|
|
2307
|
+
|
|
2308
|
+
tools_card = CollapsibleCard("一键量化与结构分析 (QUICK TOOLS)", expanded=True)
|
|
2309
|
+
t_lay = tools_card.body_layout
|
|
2310
|
+
for txt, callback in (
|
|
2311
|
+
("🔍 检查当前分子官能团 (RDKit SMARTS)", self._check_functional_groups),
|
|
2312
|
+
("🧬 生成 3D 多构象系综 (ETKDGv3 + MMFF94)", self._generate_conformer),
|
|
2313
|
+
("⚛ 打开 Gaussian / 复旦 REST / 能级图工作台", self._prepare_dft),
|
|
2314
|
+
):
|
|
2315
|
+
b = QPushButton(txt)
|
|
2316
|
+
b.clicked.connect(callback)
|
|
2317
|
+
t_lay.addWidget(b)
|
|
2318
|
+
box.addWidget(tools_card)
|
|
2319
|
+
|
|
2320
|
+
chat_card = CollapsibleCard("AI 科研助手对话 (AI SCIENTIST / MCP)", expanded=True)
|
|
2321
|
+
c_lay = chat_card.body_layout
|
|
2322
|
+
|
|
2323
|
+
self.chat_history = QTextEdit()
|
|
2324
|
+
self.chat_history.setReadOnly(True)
|
|
2325
|
+
self.chat_history.setMinimumHeight(210)
|
|
2326
|
+
self.chat_history.setHtml(
|
|
2327
|
+
"<div style='color:#9AB0C2; font-size:12px; line-height:1.45;'>"
|
|
2328
|
+
"<b style='color:#66DEC9'>🤖 MolForge AI 智能科研助手就绪</b><br>"
|
|
2329
|
+
"支持自然语言对话、分子结构修改、3D构象优化与量化计算卡生成。<br>"
|
|
2330
|
+
"(可点击下方「💡 常用指令示例 ▾」快速调用)"
|
|
2331
|
+
"</div>"
|
|
2332
|
+
)
|
|
2333
|
+
c_lay.addWidget(self.chat_history)
|
|
2334
|
+
|
|
2335
|
+
input_row = QHBoxLayout()
|
|
2336
|
+
self.ai_prompt_input = QLineEdit()
|
|
2337
|
+
self.ai_prompt_input.setPlaceholderText("输入问题或建模/计算指令回车发送...")
|
|
2338
|
+
self.ai_prompt_input.returnPressed.connect(self._on_ask_question)
|
|
2339
|
+
input_row.addWidget(self.ai_prompt_input, 1)
|
|
2340
|
+
|
|
2341
|
+
self.ai_prompt_send_btn = QPushButton("发送")
|
|
2342
|
+
self.ai_prompt_send_btn.setProperty("role", "action")
|
|
2343
|
+
self.ai_prompt_send_btn.clicked.connect(self._on_ask_question)
|
|
2344
|
+
input_row.addWidget(self.ai_prompt_send_btn)
|
|
2345
|
+
|
|
2346
|
+
btn_examples = QPushButton("💡 示例 ▾")
|
|
2347
|
+
btn_examples.setToolTip("点击展开常用 AI 建模与量子化学计算指令示例")
|
|
2348
|
+
btn_examples.clicked.connect(self._show_prompt_examples_menu)
|
|
2349
|
+
input_row.addWidget(btn_examples)
|
|
2350
|
+
|
|
2351
|
+
standalone_btn = QPushButton("🗗 独立弹窗")
|
|
2352
|
+
standalone_btn.setToolTip("在独立弹出窗口中打开全功能 LLM / MCP 工具对话")
|
|
2353
|
+
standalone_btn.clicked.connect(self._open_standalone_dialog)
|
|
2354
|
+
input_row.addWidget(standalone_btn)
|
|
2355
|
+
|
|
2356
|
+
c_lay.addLayout(input_row)
|
|
2357
|
+
|
|
2358
|
+
dsh_row = QHBoxLayout()
|
|
2359
|
+
self.dsh_launch_btn = QPushButton("🚀 在 DeepSeek Harness 中打开 (联动当前分子)")
|
|
2360
|
+
self.dsh_launch_btn.setToolTip(
|
|
2361
|
+
"自动开启桌面 MCP 服务并写入 MolForge 专属 Skill 与自定义图标快捷方式,\n"
|
|
2362
|
+
"启动 DeepSeek Harness 直接读取与搭建/修改当前工作台分子"
|
|
2363
|
+
)
|
|
2364
|
+
from ..ai.deepseek_harness import get_custom_icon_path
|
|
2365
|
+
_dsh_icon = get_custom_icon_path()
|
|
2366
|
+
if _dsh_icon is not None:
|
|
2367
|
+
from PyQt6.QtGui import QIcon
|
|
2368
|
+
self.dsh_launch_btn.setIcon(QIcon(str(_dsh_icon)))
|
|
2369
|
+
self.dsh_launch_btn.clicked.connect(self._launch_deepseek_harness)
|
|
2370
|
+
dsh_row.addWidget(self.dsh_launch_btn)
|
|
2371
|
+
c_lay.addLayout(dsh_row)
|
|
2372
|
+
box.addWidget(chat_card)
|
|
2373
|
+
|
|
2374
|
+
box.addStretch(1)
|
|
2375
|
+
return page
|
|
2376
|
+
|
|
2377
|
+
def _launch_deepseek_harness(self):
|
|
2378
|
+
from ..ai.deepseek_harness import launch_deepseek_harness
|
|
2379
|
+
win = getattr(self, "_window_ref", None)
|
|
2380
|
+
if win is not None and hasattr(win, "_toggle_desktop_mcp"):
|
|
2381
|
+
svc_cur = getattr(win, "mcp_service", None)
|
|
2382
|
+
if svc_cur is None or not getattr(svc_cur, "is_active", False):
|
|
2383
|
+
if getattr(win, "mcp_action", None) is not None:
|
|
2384
|
+
win.mcp_action.setChecked(True)
|
|
2385
|
+
win._toggle_desktop_mcp(True)
|
|
2386
|
+
svc = getattr(win, "mcp_service", None) if win is not None else None
|
|
2387
|
+
res = launch_deepseek_harness(desktop_mcp_service=svc)
|
|
2388
|
+
if res.get("ok"):
|
|
2389
|
+
self.chat_history.append(
|
|
2390
|
+
"<div style='color:#66DEC9; font-size:12px; margin-top:4px;'>"
|
|
2391
|
+
"<b>🚀 已启动 DeepSeek Harness 并开启 MolForge 桌面 MCP 联动</b><br>"
|
|
2392
|
+
f"Skill 已同步: <code>{res.get('skill_path', '')}</code><br>"
|
|
2393
|
+
f"MCP 配置: <code>{res.get('mcp_config_path', '')}</code>"
|
|
2394
|
+
"</div>"
|
|
2395
|
+
)
|
|
2396
|
+
if win is not None and hasattr(win, "statusBar"):
|
|
2397
|
+
win.statusBar().showMessage("已启动 DeepSeek Harness(已开启桌面 MCP 当前分子联动)", 8000)
|
|
2398
|
+
else:
|
|
2399
|
+
QMessageBox.warning(self, "DeepSeek Harness 联动提示", str(res.get("error", "启动失败")))
|
|
2400
|
+
|
|
2401
|
+
def _show_prompt_examples_menu(self):
|
|
2402
|
+
menu = QMenu(self)
|
|
2403
|
+
examples = [
|
|
2404
|
+
("帮我画一个水分子", "帮我画一个水分子"),
|
|
2405
|
+
("加一个噻吩环", "在当前选中的位置加一个噻吩环"),
|
|
2406
|
+
("引入氰基 -CN 取代基", "在当前选中的原子上引入氰基 -CN"),
|
|
2407
|
+
("计算重原子最佳拟合平面度 (RMSD)", "计算当前分子所有重原子的最佳拟合平面度 RMSD"),
|
|
2408
|
+
("生成复旦 REST 的 XYG3 计算卡", "帮我生成复旦 REST 的 XYG3 双杂化 DFT 输入卡"),
|
|
2409
|
+
("生成 Gaussian CAM-B3LYP TD-DFT 输入", "生成 Gaussian 16 的 CAM-B3LYP/def2-SVP TD-DFT 激发态计算输入文件"),
|
|
2410
|
+
("生成超算 Slurm 提交脚本", "生成可直接提交至远程超算集群的 Slurm 运行脚本"),
|
|
2411
|
+
]
|
|
2412
|
+
for title, prompt in examples:
|
|
2413
|
+
act = menu.addAction(title)
|
|
2414
|
+
act.triggered.connect(lambda checked=False, p=prompt: self.ai_prompt_input.setText(p))
|
|
2415
|
+
menu.exec(QCursor.pos())
|
|
2416
|
+
|
|
2417
|
+
def _fetch_remote_models_action(self):
|
|
2418
|
+
url = self.ds_url_input.text().strip()
|
|
2419
|
+
key = self.ds_key_input.text().strip()
|
|
2420
|
+
if not url:
|
|
2421
|
+
QMessageBox.warning(self, "提示", "请先输入 Base URL")
|
|
2422
|
+
return
|
|
2423
|
+
self.save_feedback_lbl.setText("⏳ 正在拉取可用模型列表...")
|
|
2424
|
+
from ..ai.mcp_bridge import fetch_remote_models
|
|
2425
|
+
try:
|
|
2426
|
+
models = fetch_remote_models(url, key)
|
|
2427
|
+
if not models:
|
|
2428
|
+
self.save_feedback_lbl.setText("⚠️ 未获取到模型")
|
|
2429
|
+
QMessageBox.information(self, "获取模型结果", f"成功连接到端点 {url},但未返回模型列表。您可以手动在输入框中填入模型名称。")
|
|
2430
|
+
return
|
|
2431
|
+
self.ds_model_combo.blockSignals(True)
|
|
2432
|
+
self.ds_model_combo.clear()
|
|
2433
|
+
for m in models:
|
|
2434
|
+
self.ds_model_combo.addItem(m)
|
|
2435
|
+
self.ds_model_combo.blockSignals(False)
|
|
2436
|
+
|
|
2437
|
+
preferred = ["gemini-3.8-flash", "claude-sonnet-5-5", "deepseek-chat", "gpt-4o-mini"]
|
|
2438
|
+
chosen = None
|
|
2439
|
+
for p in preferred:
|
|
2440
|
+
if p in models:
|
|
2441
|
+
chosen = p
|
|
2442
|
+
break
|
|
2443
|
+
if chosen:
|
|
2444
|
+
self.ds_model_combo.setCurrentText(chosen)
|
|
2445
|
+
else:
|
|
2446
|
+
self.ds_model_combo.setCurrentIndex(0)
|
|
2447
|
+
self._save_and_confirm_config()
|
|
2448
|
+
self.save_feedback_lbl.setText(f"✓ 成功获取 {len(models)} 个可用模型!")
|
|
2449
|
+
QMessageBox.information(
|
|
2450
|
+
self, "获取模型成功",
|
|
2451
|
+
f"成功从端点获取到 {len(models)} 个可用模型!\n\n已为您自动选中:{self.ds_model_combo.currentText()}"
|
|
2452
|
+
)
|
|
2453
|
+
except Exception as e:
|
|
2454
|
+
self.save_feedback_lbl.setText(f"❌ 获取失败")
|
|
2455
|
+
QMessageBox.warning(
|
|
2456
|
+
self, "获取模型失败",
|
|
2457
|
+
f"无法连接端点 {url} 获取模型列表:\n{e}\n\n请检查服务是否启动及网络配置。"
|
|
2458
|
+
)
|
|
2459
|
+
|
|
2460
|
+
def _on_provider_changed(self, idx: int):
|
|
2461
|
+
p_name = self.provider_combo.currentText()
|
|
2462
|
+
data = self.providers_data.get(p_name)
|
|
2463
|
+
if data:
|
|
2464
|
+
self.ds_url_input.setText(data["url"])
|
|
2465
|
+
if hasattr(self, "ds_model_combo") and data.get("models"):
|
|
2466
|
+
if p_name != "自定义端点 (Custom URL)":
|
|
2467
|
+
self.ds_model_combo.setCurrentText(data["models"][0])
|
|
2468
|
+
self._on_ds_config_changed()
|
|
2469
|
+
|
|
2470
|
+
def _on_ds_config_changed(self):
|
|
2471
|
+
key = self.ds_key_input.text().strip()
|
|
2472
|
+
model = self.ds_model_combo.currentText().strip() if hasattr(self, "ds_model_combo") else "gemini-3.8-flash"
|
|
2473
|
+
if not model:
|
|
2474
|
+
return
|
|
2475
|
+
url = self.ds_url_input.text().strip() or "http://127.0.0.1:8045/v1"
|
|
2476
|
+
temp = float(self.temp_slider.value()) / 100.0 if hasattr(self, "temp_slider") else 0.3
|
|
2477
|
+
mt = int(self.max_tokens_spin.value()) if hasattr(self, "max_tokens_spin") else 4096
|
|
2478
|
+
re_eff = self.reasoning_combo.currentData() if hasattr(self, "reasoning_combo") else "none"
|
|
2479
|
+
|
|
2480
|
+
self.deepseek.api_key = key
|
|
2481
|
+
self.deepseek.model = model
|
|
2482
|
+
self.deepseek.base_url = url
|
|
2483
|
+
from ..ai.mcp_bridge import set_llm_config
|
|
2484
|
+
set_llm_config(url, key or "EMPTY", model, temperature=temp, max_tokens=mt, reasoning_effort=re_eff)
|
|
2485
|
+
if self._chat_bridge is not None:
|
|
2486
|
+
self._chat_bridge.config = {
|
|
2487
|
+
"base_url": url, "api_key": key or "EMPTY", "model": model,
|
|
2488
|
+
"temperature": temp, "max_tokens": mt, "reasoning_effort": re_eff
|
|
2489
|
+
}
|
|
2490
|
+
|
|
2491
|
+
def _save_and_confirm_config(self):
|
|
2492
|
+
url = self.ds_url_input.text().strip() or "http://127.0.0.1:8045/v1"
|
|
2493
|
+
model = self.ds_model_combo.currentText().strip() if hasattr(self, "ds_model_combo") else "gemini-3.8-flash"
|
|
2494
|
+
key = self.ds_key_input.text().strip() or "EMPTY"
|
|
2495
|
+
temp = float(self.temp_slider.value()) / 100.0 if hasattr(self, "temp_slider") else 0.3
|
|
2496
|
+
mt = int(self.max_tokens_spin.value()) if hasattr(self, "max_tokens_spin") else 4096
|
|
2497
|
+
re_eff = self.reasoning_combo.currentData() if hasattr(self, "reasoning_combo") else "none"
|
|
2498
|
+
|
|
2499
|
+
from ..ai.mcp_bridge import set_llm_config
|
|
2500
|
+
set_llm_config(url, key, model, temperature=temp, max_tokens=mt, reasoning_effort=re_eff)
|
|
2501
|
+
if self._chat_bridge is not None:
|
|
2502
|
+
self._chat_bridge.config = {
|
|
2503
|
+
"base_url": url, "api_key": key, "model": model,
|
|
2504
|
+
"temperature": temp, "max_tokens": mt, "reasoning_effort": re_eff
|
|
2505
|
+
}
|
|
2506
|
+
if hasattr(self, "save_feedback_lbl"):
|
|
2507
|
+
self.save_feedback_lbl.setText(f"✓ 已保存: {model}")
|
|
2508
|
+
QTimer.singleShot(3000, lambda: self.save_feedback_lbl.setText(""))
|
|
2509
|
+
|
|
2510
|
+
def _sync_ai_config_from_global(self):
|
|
2511
|
+
from ..ai.mcp_bridge import get_llm_config
|
|
2512
|
+
cfg = get_llm_config()
|
|
2513
|
+
cur_url = cfg["base_url"]
|
|
2514
|
+
matched_provider = None
|
|
2515
|
+
for p_name, p_info in self.providers_data.items():
|
|
2516
|
+
if p_info["url"].rstrip("/") == cur_url.rstrip("/"):
|
|
2517
|
+
matched_provider = p_name
|
|
2518
|
+
break
|
|
2519
|
+
if matched_provider is None:
|
|
2520
|
+
matched_provider = "自定义端点 (Custom URL)"
|
|
2521
|
+
self.provider_combo.blockSignals(True)
|
|
2522
|
+
self.provider_combo.setCurrentText(matched_provider)
|
|
2523
|
+
self.provider_combo.blockSignals(False)
|
|
2524
|
+
|
|
2525
|
+
self.ds_url_input.setText(cur_url)
|
|
2526
|
+
if hasattr(self, "ds_model_combo"):
|
|
2527
|
+
self.ds_model_combo.setCurrentText(cfg["model"])
|
|
2528
|
+
if hasattr(self, "temp_slider") and "temperature" in cfg:
|
|
2529
|
+
self.temp_slider.setValue(int(float(cfg["temperature"]) * 100))
|
|
2530
|
+
if hasattr(self, "max_tokens_spin") and "max_tokens" in cfg:
|
|
2531
|
+
self.max_tokens_spin.setValue(float(cfg["max_tokens"]))
|
|
2532
|
+
if hasattr(self, "reasoning_combo") and "reasoning_effort" in cfg:
|
|
2533
|
+
cur_re = str(cfg["reasoning_effort"]).lower()
|
|
2534
|
+
re_idx = 0
|
|
2535
|
+
if cur_re in ("low", "低"): re_idx = 1
|
|
2536
|
+
elif cur_re in ("medium", "中"): re_idx = 2
|
|
2537
|
+
elif cur_re in ("high", "高"): re_idx = 3
|
|
2538
|
+
self.reasoning_combo.setCurrentIndex(re_idx)
|
|
2539
|
+
|
|
2540
|
+
if cfg["api_key"] and cfg["api_key"] != "EMPTY":
|
|
2541
|
+
self.ds_key_input.setText(cfg["api_key"])
|
|
2542
|
+
else:
|
|
2543
|
+
self.ds_key_input.setText("")
|
|
2544
|
+
|
|
2545
|
+
def _open_standalone_dialog(self):
|
|
2546
|
+
from .live_llm_dialog import LiveLlmDialog
|
|
2547
|
+
owner = self.window()
|
|
2548
|
+
dialog = LiveLlmDialog(owner, self._document_provider)
|
|
2549
|
+
dialog.exec()
|
|
2550
|
+
self._sync_ai_config_from_global()
|
|
2551
|
+
|
|
2552
|
+
def update_molecule_context(self, name: str, formula: str, num_atoms: int, num_bonds: int,
|
|
2553
|
+
molecular_weight: float = 0.0):
|
|
2554
|
+
if not hasattr(self, "assistant_context_label"):
|
|
2555
|
+
return
|
|
2556
|
+
mw_txt = f" · {molecular_weight:.2f} Da" if molecular_weight > 0 else ""
|
|
2557
|
+
self.assistant_context_label.setText(
|
|
2558
|
+
f"当前分子上下文:{name} • {formula}\n{num_atoms} 原子 · {num_bonds} 键{mw_txt}"
|
|
2559
|
+
)
|
|
2560
|
+
|
|
2561
|
+
def set_document_provider(self, provider):
|
|
2562
|
+
self._document_provider = provider
|
|
2563
|
+
|
|
2564
|
+
def set_command_bus_provider(self, provider):
|
|
2565
|
+
self._command_bus_provider = provider
|
|
2566
|
+
|
|
2567
|
+
def set_selection_provider(self, provider):
|
|
2568
|
+
self._selection_provider = provider
|
|
2569
|
+
|
|
2570
|
+
def _check_functional_groups(self):
|
|
2571
|
+
if self._document_provider is None:
|
|
2572
|
+
return
|
|
2573
|
+
doc = self._document_provider()
|
|
2574
|
+
found = []
|
|
2575
|
+
try:
|
|
2576
|
+
from ..io.rdkit_adapter import doc_to_rdkit
|
|
2577
|
+
from rdkit import Chem
|
|
2578
|
+
rdmol, _, _ = doc_to_rdkit(doc, sanitize=True)
|
|
2579
|
+
patterns = [
|
|
2580
|
+
("噻吩环 (Thiophene)", Chem.MolFromSmarts("c1ccsc1")),
|
|
2581
|
+
("苯环/芳香六元环", Chem.MolFromSmarts("c1ccccc1")),
|
|
2582
|
+
("氰基 (-C≡N)", Chem.MolFromSmarts("[CX2]#[NX1]")),
|
|
2583
|
+
("氟代 (-F)", Chem.MolFromSmarts("[#6][F]")),
|
|
2584
|
+
("氯代 (-Cl)", Chem.MolFromSmarts("[#6][Cl]")),
|
|
2585
|
+
("羰基 (C=O)", Chem.MolFromSmarts("[CX3]=[OX1]")),
|
|
2586
|
+
("羧基 (-COOH)", Chem.MolFromSmarts("[CX3](=O)[OX2H1]")),
|
|
2587
|
+
("酯基 (-COO-)", Chem.MolFromSmarts("[CX3](=O)[OX2][#6]")),
|
|
2588
|
+
("羟基 (-OH)", Chem.MolFromSmarts("[OX2H1]")),
|
|
2589
|
+
("酰胺 (-CON-)", Chem.MolFromSmarts("[NX3][CX3](=[OX1])")),
|
|
2590
|
+
("氨基 (-NH₂)", Chem.MolFromSmarts("[NX3H2]")),
|
|
2591
|
+
("甲基 (-CH₃)", Chem.MolFromSmarts("[CH3]")),
|
|
2592
|
+
]
|
|
2593
|
+
for name, patt in patterns:
|
|
2594
|
+
if patt is not None:
|
|
2595
|
+
hits = len(rdmol.GetSubstructMatches(patt))
|
|
2596
|
+
if hits > 0:
|
|
2597
|
+
found.append(f"• {name}: {hits} 处")
|
|
2598
|
+
except Exception as e:
|
|
2599
|
+
found.append(f"• 拓扑统计: {doc.num_atoms} 原子, {doc.num_bonds} 键 ({e})")
|
|
2600
|
+
if not found:
|
|
2601
|
+
found = ["• 未匹配到预设特征官能团"]
|
|
2602
|
+
msg = f"分子:{doc.name}\n" + "\n".join(found)
|
|
2603
|
+
self.switch_tab(1)
|
|
2604
|
+
self.chat_history.append(f"<hr><b style='color:#66DEC9'>[官能团分析]</b><br><pre>{msg}</pre>")
|
|
2605
|
+
|
|
2606
|
+
def _generate_conformer(self):
|
|
2607
|
+
if getattr(self, "on_generate_conformers", None):
|
|
2608
|
+
self.on_generate_conformers()
|
|
2609
|
+
|
|
2610
|
+
def _prepare_dft(self):
|
|
2611
|
+
if getattr(self, "on_open_qc_log", None):
|
|
2612
|
+
self.on_open_qc_log()
|
|
2613
|
+
|
|
2614
|
+
def _on_ask_question(self):
|
|
2615
|
+
text = self.ai_prompt_input.text().strip()
|
|
2616
|
+
if not text:
|
|
2617
|
+
return
|
|
2618
|
+
if self._chat_worker and self._chat_worker.isRunning():
|
|
2619
|
+
QMessageBox.information(self, "请求处理中", "当前已有 AI 请求正在运行,请等待回复完成。")
|
|
2620
|
+
return
|
|
2621
|
+
if self._document_provider is None:
|
|
2622
|
+
self.chat_history.append("<div style='color:#E06C75;'>⚠️ 未检测到分子文档。</div>")
|
|
2623
|
+
return
|
|
2624
|
+
doc = self._document_provider()
|
|
2625
|
+
if doc is None:
|
|
2626
|
+
self.chat_history.append("<div style='color:#E06C75;'>⚠️ 当前没有打开的分子文档,请先在画布中打开或创建分子。</div>")
|
|
2627
|
+
return
|
|
2628
|
+
bus = self._command_bus_provider() if self._command_bus_provider else getattr(self.window(), 'command_bus', None)
|
|
2629
|
+
if bus is None or bus.document is not doc:
|
|
2630
|
+
self.chat_history.append("<div style='color:#E06C75;'>⚠️ 当前窗口命令总线与文档不一致,无法执行操作。</div>")
|
|
2631
|
+
return
|
|
2632
|
+
|
|
2633
|
+
url = self.ds_url_input.text().strip() if hasattr(self, "ds_url_input") and self.ds_url_input.text().strip() else "http://127.0.0.1:8045/v1"
|
|
2634
|
+
model = self.ds_model_combo.currentText().strip() if hasattr(self, "ds_model_combo") else "gemini-3.8-flash"
|
|
2635
|
+
if not model or model in ("default-model", "antigravity"):
|
|
2636
|
+
model = "gemini-3.8-flash"
|
|
2637
|
+
key = self.ds_key_input.text().strip() if hasattr(self, "ds_key_input") and self.ds_key_input.text().strip() else "EMPTY"
|
|
2638
|
+
|
|
2639
|
+
temp = float(self.temp_slider.value()) / 100.0 if hasattr(self, "temp_slider") else 0.3
|
|
2640
|
+
mt = int(self.max_tokens_spin.value()) if hasattr(self, "max_tokens_spin") else 4096
|
|
2641
|
+
re_eff = self.reasoning_combo.currentData() if hasattr(self, "reasoning_combo") else "none"
|
|
2642
|
+
|
|
2643
|
+
from ..ai.mcp_bridge import MolForgeMCPBridge, set_llm_config
|
|
2644
|
+
set_llm_config(url, key, model, temperature=temp, max_tokens=mt, reasoning_effort=re_eff)
|
|
2645
|
+
|
|
2646
|
+
if self._chat_bridge is None or self._chat_bridge.document is not doc:
|
|
2647
|
+
self._chat_bridge = MolForgeMCPBridge(doc, bus)
|
|
2648
|
+
self._chat_bridge.config = {
|
|
2649
|
+
"base_url": url, "api_key": key, "model": model,
|
|
2650
|
+
"temperature": temp, "max_tokens": mt, "reasoning_effort": re_eff
|
|
2651
|
+
}
|
|
2652
|
+
|
|
2653
|
+
self.ai_prompt_input.clear()
|
|
2654
|
+
self.chat_history.append(
|
|
2655
|
+
f"<div style='margin-top:8px; margin-bottom:4px;'>"
|
|
2656
|
+
f"<b style='color:#7DAEFA;'>🧑 你:</b> {html.escape(text)}"
|
|
2657
|
+
f"</div>"
|
|
2658
|
+
)
|
|
2659
|
+
self.chat_history.append(
|
|
2660
|
+
"<div style='color:#66DEC9; font-size:12px; margin-bottom:6px;'>"
|
|
2661
|
+
"⏳ 正在连接 AI 端点并分析分子结构...</div>"
|
|
2662
|
+
)
|
|
2663
|
+
self.ai_prompt_send_btn.setEnabled(False)
|
|
2664
|
+
self.ai_prompt_send_btn.setText("思考中...")
|
|
2665
|
+
|
|
2666
|
+
from .live_llm_dialog import _ChatWorker
|
|
2667
|
+
self._chat_worker = _ChatWorker(self._chat_bridge, text, self)
|
|
2668
|
+
self._chat_worker.tool_requested.connect(self._on_panel_tool_requested)
|
|
2669
|
+
self._chat_worker.reply.connect(self._on_panel_chat_reply)
|
|
2670
|
+
self._chat_worker.finished.connect(self._on_panel_chat_finished)
|
|
2671
|
+
self._chat_worker.start()
|
|
2672
|
+
|
|
2673
|
+
def _on_panel_tool_requested(self, name, args, packet):
|
|
2674
|
+
try:
|
|
2675
|
+
if name in {'add_atom', 'delete_atom', 'add_bond'}:
|
|
2676
|
+
allowed = QMessageBox.question(
|
|
2677
|
+
self,
|
|
2678
|
+
"确认分子修改",
|
|
2679
|
+
f"模型请求执行工具:{name}\n参数:{args}\n\n是否应用到当前分子画布?",
|
|
2680
|
+
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
|
2681
|
+
QMessageBox.StandardButton.Yes,
|
|
2682
|
+
)
|
|
2683
|
+
if allowed != QMessageBox.StandardButton.Yes:
|
|
2684
|
+
packet['result'] = {'ok': False, 'error': '用户取消了本次结构修改'}
|
|
2685
|
+
self.chat_history.append(
|
|
2686
|
+
f"<div style='color:#E06C75; font-size:11px;'>❌ <b>工具 {html.escape(name)}</b>:用户取消执行</div>"
|
|
2687
|
+
)
|
|
2688
|
+
return
|
|
2689
|
+
packet['result'] = self._chat_bridge.dispatch(name, args)
|
|
2690
|
+
self.chat_history.append(
|
|
2691
|
+
f"<div style='color:#E5C07B; font-size:11px;'>🔧 <b>执行工具 {html.escape(name)}</b>:{html.escape(str(packet['result'])[:140])}</div>"
|
|
2692
|
+
)
|
|
2693
|
+
except Exception as exc:
|
|
2694
|
+
packet['result'] = {'ok': False, 'error': str(exc)}
|
|
2695
|
+
self.chat_history.append(
|
|
2696
|
+
f"<div style='color:#E06C75; font-size:11px;'>⚠️ <b>工具错误</b>:{html.escape(str(exc))}</div>"
|
|
2697
|
+
)
|
|
2698
|
+
finally:
|
|
2699
|
+
packet['event'].set()
|
|
2700
|
+
|
|
2701
|
+
def _on_panel_chat_reply(self, reply_text):
|
|
2702
|
+
formatted = html.escape(reply_text).replace('\n', '<br>')
|
|
2703
|
+
self.chat_history.append(
|
|
2704
|
+
f"<div style='margin-top:6px; margin-bottom:8px; line-height:1.45;'>"
|
|
2705
|
+
f"<b style='color:#66DEC9;'>🤖 MolForge AI:</b><br>{formatted}"
|
|
2706
|
+
f"</div>"
|
|
2707
|
+
)
|
|
2708
|
+
QTimer.singleShot(60, self._scroll_chat_to_bottom)
|
|
2709
|
+
|
|
2710
|
+
def _scroll_chat_to_bottom(self):
|
|
2711
|
+
sb = self.chat_history.verticalScrollBar()
|
|
2712
|
+
if sb:
|
|
2713
|
+
sb.setValue(sb.maximum())
|
|
2714
|
+
|
|
2715
|
+
def _on_panel_chat_finished(self):
|
|
2716
|
+
if hasattr(self, 'ai_prompt_send_btn'):
|
|
2717
|
+
self.ai_prompt_send_btn.setEnabled(True)
|
|
2718
|
+
self.ai_prompt_send_btn.setText("发送")
|
|
2719
|
+
|
|
2720
|
+
def _on_tab_changed(self, index):
|
|
2721
|
+
if index == 2:
|
|
2722
|
+
self._refresh_jobs()
|
|
2723
|
+
elif index == 3:
|
|
2724
|
+
self._refresh_history()
|
|
2725
|
+
|
|
2726
|
+
def _clear_box(self, box):
|
|
2727
|
+
while box.count():
|
|
2728
|
+
item = box.takeAt(0)
|
|
2729
|
+
w = item.widget()
|
|
2730
|
+
if w is not None:
|
|
2731
|
+
w.hide()
|
|
2732
|
+
w.deleteLater()
|
|
2733
|
+
|
|
2734
|
+
def _refresh_jobs(self):
|
|
2735
|
+
self._clear_box(self.jobs_box)
|
|
2736
|
+
box = self.jobs_box
|
|
2737
|
+
|
|
2738
|
+
eng_card = CollapsibleCard("量化计算引擎状态 (ENGINES)", expanded=True)
|
|
2739
|
+
e_lay = eng_card.body_layout
|
|
2740
|
+
from ..application.calculators.registry import _all_engines
|
|
2741
|
+
for eng in _all_engines():
|
|
2742
|
+
ok = eng.probe()
|
|
2743
|
+
st = "本地可执行已就绪" if ok else "输入卡生成就绪"
|
|
2744
|
+
col = "#22C55E" if ok else "#66DEC9"
|
|
2745
|
+
lbl = QLabel(f"• <b>{eng.name}</b>: <span style='color:{col}'>{st}</span>")
|
|
2746
|
+
e_lay.addWidget(lbl)
|
|
2747
|
+
|
|
2748
|
+
open_qc_btn = QPushButton("⚛ 打开 Gaussian / 复旦 REST / 能级图工作台...")
|
|
2749
|
+
open_qc_btn.setProperty("role", "action")
|
|
2750
|
+
open_qc_btn.clicked.connect(self._prepare_dft)
|
|
2751
|
+
e_lay.addWidget(open_qc_btn)
|
|
2752
|
+
box.addWidget(eng_card)
|
|
2753
|
+
|
|
2754
|
+
cmd_card = CollapsibleCard("最近执行的建模与计算操作", expanded=True)
|
|
2755
|
+
c_lay = cmd_card.body_layout
|
|
2756
|
+
cmds = []
|
|
2757
|
+
if self._command_bus_provider is not None:
|
|
2758
|
+
cmds = self._command_bus_provider().history.executed_commands
|
|
2759
|
+
if not cmds:
|
|
2760
|
+
c_lay.addWidget(muted("暂无编辑命令记录。"))
|
|
2761
|
+
else:
|
|
2762
|
+
for cmd in cmds[-12:]:
|
|
2763
|
+
row = QHBoxLayout()
|
|
2764
|
+
row.addWidget(muted(f"• {cmd.description}"))
|
|
2765
|
+
row.addStretch()
|
|
2766
|
+
done = QLabel("已生效")
|
|
2767
|
+
done.setStyleSheet("color: #66DEC9; font-size: 11px;")
|
|
2768
|
+
row.addWidget(done)
|
|
2769
|
+
c_lay.addLayout(row)
|
|
2770
|
+
box.addWidget(cmd_card)
|
|
2771
|
+
box.addStretch(1)
|
|
2772
|
+
|
|
2773
|
+
def _refresh_history(self):
|
|
2774
|
+
bus = self._command_bus_provider() if self._command_bus_provider else None
|
|
2775
|
+
can_undo = bool(bus and bus.history.can_undo)
|
|
2776
|
+
can_redo = bool(bus and bus.history.can_redo)
|
|
2777
|
+
undo_cmds = list(bus.history._undo_stack) if bus else []
|
|
2778
|
+
redo_cmds = list(reversed(bus.history._redo_stack)) if bus else []
|
|
2779
|
+
|
|
2780
|
+
# 若历史面板控件已存在,原地平滑刷新列表内容,绝不销毁重构,防止事件循环重入假死!
|
|
2781
|
+
if hasattr(self, "btn_undo") and hasattr(self, "history_list"):
|
|
2782
|
+
self.btn_undo.setEnabled(can_undo)
|
|
2783
|
+
self.btn_redo.setEnabled(can_redo)
|
|
2784
|
+
self.history_list.blockSignals(True)
|
|
2785
|
+
self.history_list.clear()
|
|
2786
|
+
|
|
2787
|
+
item0 = QListWidgetItem("🏁 0. 初始结构 (起点)")
|
|
2788
|
+
self.history_list.addItem(item0)
|
|
2789
|
+
for idx, cmd in enumerate(undo_cmds, 1):
|
|
2790
|
+
desc = getattr(cmd, "description", type(cmd).__name__)
|
|
2791
|
+
it = QListWidgetItem(f"✓ {idx}. {desc}")
|
|
2792
|
+
self.history_list.addItem(it)
|
|
2793
|
+
|
|
2794
|
+
active_row = len(undo_cmds)
|
|
2795
|
+
self.history_list.setCurrentRow(active_row)
|
|
2796
|
+
cur_item = self.history_list.item(active_row)
|
|
2797
|
+
if cur_item:
|
|
2798
|
+
cur_item.setText(cur_item.text() + " ◀ [当前状态]")
|
|
2799
|
+
cur_item.setForeground(QColor("#5EEAD4"))
|
|
2800
|
+
|
|
2801
|
+
for idx, cmd in enumerate(redo_cmds, len(undo_cmds) + 1):
|
|
2802
|
+
desc = getattr(cmd, "description", type(cmd).__name__)
|
|
2803
|
+
it = QListWidgetItem(f"↷ {idx}. {desc} (可重做)")
|
|
2804
|
+
it.setForeground(QColor("#688094"))
|
|
2805
|
+
self.history_list.addItem(it)
|
|
2806
|
+
|
|
2807
|
+
self.history_list.blockSignals(False)
|
|
2808
|
+
if hasattr(self, "history_export_btn"):
|
|
2809
|
+
self.history_export_btn.setEnabled(bool(undo_cmds or (bus and bus.history.audit_events)))
|
|
2810
|
+
return
|
|
2811
|
+
|
|
2812
|
+
self._clear_box(self.history_box)
|
|
2813
|
+
box = self.history_box
|
|
2814
|
+
h_card = CollapsibleCard("操作历史与时间线跳转 (HISTORY TIMELINE)", expanded=True)
|
|
2815
|
+
h_lay = h_card.body_layout
|
|
2816
|
+
|
|
2817
|
+
row_act = QHBoxLayout()
|
|
2818
|
+
self.btn_undo = QPushButton("⏪ 撤销 (Ctrl+Z)")
|
|
2819
|
+
self.btn_undo.setEnabled(can_undo)
|
|
2820
|
+
self.btn_undo.setMinimumHeight(30)
|
|
2821
|
+
self.btn_undo.setStyleSheet("QPushButton { font-weight:700; }")
|
|
2822
|
+
self.btn_undo.clicked.connect(self._history_do_undo)
|
|
2823
|
+
row_act.addWidget(self.btn_undo)
|
|
2824
|
+
|
|
2825
|
+
self.btn_redo = QPushButton("⏩ 重做 (Ctrl+Y)")
|
|
2826
|
+
self.btn_redo.setEnabled(can_redo)
|
|
2827
|
+
self.btn_redo.setMinimumHeight(30)
|
|
2828
|
+
self.btn_redo.setStyleSheet("QPushButton { font-weight:700; }")
|
|
2829
|
+
self.btn_redo.clicked.connect(self._history_do_redo)
|
|
2830
|
+
row_act.addWidget(self.btn_redo)
|
|
2831
|
+
|
|
2832
|
+
btn_clear = QPushButton("🗑️ 清空")
|
|
2833
|
+
btn_clear.setToolTip("清空当前撤销与重做历史栈")
|
|
2834
|
+
btn_clear.setMinimumHeight(30)
|
|
2835
|
+
btn_clear.clicked.connect(self._history_do_clear)
|
|
2836
|
+
row_act.addWidget(btn_clear)
|
|
2837
|
+
h_lay.addLayout(row_act)
|
|
2838
|
+
|
|
2839
|
+
h_lay.addWidget(muted("点击下方任意历史记录,可直接时空跳转至该步分子构型:"))
|
|
2840
|
+
|
|
2841
|
+
self.history_list = QListWidget()
|
|
2842
|
+
self.history_list.setMinimumHeight(240)
|
|
2843
|
+
self.history_list.setStyleSheet(
|
|
2844
|
+
"QListWidget { background:#0F1B29; border:1px solid #243B52; border-radius:6px; color:#EAF2F6; padding:4px; }"
|
|
2845
|
+
"QListWidget::item { padding:7px 10px; border-bottom:1px solid #17283B; border-radius:4px; }"
|
|
2846
|
+
"QListWidget::item:hover { background:#1C2E42; }"
|
|
2847
|
+
"QListWidget::item:selected { background:#0D9488; color:#FFFFFF; font-weight:bold; }"
|
|
2848
|
+
)
|
|
2849
|
+
|
|
2850
|
+
item0 = QListWidgetItem("🏁 0. 初始结构 (起点)")
|
|
2851
|
+
self.history_list.addItem(item0)
|
|
2852
|
+
for idx, cmd in enumerate(undo_cmds, 1):
|
|
2853
|
+
desc = getattr(cmd, "description", type(cmd).__name__)
|
|
2854
|
+
it = QListWidgetItem(f"✓ {idx}. {desc}")
|
|
2855
|
+
self.history_list.addItem(it)
|
|
2856
|
+
|
|
2857
|
+
active_row = len(undo_cmds)
|
|
2858
|
+
self.history_list.setCurrentRow(active_row)
|
|
2859
|
+
cur_item = self.history_list.item(active_row)
|
|
2860
|
+
if cur_item:
|
|
2861
|
+
cur_item.setText(cur_item.text() + " ◀ [当前状态]")
|
|
2862
|
+
cur_item.setForeground(QColor("#5EEAD4"))
|
|
2863
|
+
|
|
2864
|
+
for idx, cmd in enumerate(redo_cmds, len(undo_cmds) + 1):
|
|
2865
|
+
desc = getattr(cmd, "description", type(cmd).__name__)
|
|
2866
|
+
it = QListWidgetItem(f"↷ {idx}. {desc} (可重做)")
|
|
2867
|
+
it.setForeground(QColor("#688094"))
|
|
2868
|
+
self.history_list.addItem(it)
|
|
2869
|
+
|
|
2870
|
+
self.history_list.itemClicked.connect(self._on_history_item_clicked)
|
|
2871
|
+
h_lay.addWidget(self.history_list)
|
|
2872
|
+
|
|
2873
|
+
self.history_export_btn = QPushButton("📦 导出本次操作为技能 (Export Skill)...")
|
|
2874
|
+
self.history_export_btn.setEnabled(bool(undo_cmds or (bus and bus.history.audit_events)))
|
|
2875
|
+
self.history_export_btn.setMinimumHeight(32)
|
|
2876
|
+
self.history_export_btn.clicked.connect(self._export_history_skill)
|
|
2877
|
+
h_lay.addWidget(self.history_export_btn)
|
|
2878
|
+
|
|
2879
|
+
h_lay.addWidget(muted("快捷键提示:Ctrl+Z 撤销,Ctrl+Y 重做。点击列表行可直接回退或前进。"))
|
|
2880
|
+
box.addWidget(h_card)
|
|
2881
|
+
box.addStretch(1)
|
|
2882
|
+
box.addStretch(1)
|
|
2883
|
+
|
|
2884
|
+
def _history_do_undo(self):
|
|
2885
|
+
bus = self._command_bus_provider() if self._command_bus_provider else None
|
|
2886
|
+
if bus and bus.history.can_undo:
|
|
2887
|
+
bus.undo()
|
|
2888
|
+
self._refresh_history()
|
|
2889
|
+
|
|
2890
|
+
def _history_do_redo(self):
|
|
2891
|
+
bus = self._command_bus_provider() if self._command_bus_provider else None
|
|
2892
|
+
if bus and bus.history.can_redo:
|
|
2893
|
+
bus.redo()
|
|
2894
|
+
self._refresh_history()
|
|
2895
|
+
|
|
2896
|
+
def _history_do_clear(self):
|
|
2897
|
+
bus = self._command_bus_provider() if self._command_bus_provider else None
|
|
2898
|
+
if bus:
|
|
2899
|
+
bus.history.clear()
|
|
2900
|
+
self._refresh_history()
|
|
2901
|
+
|
|
2902
|
+
def _on_history_item_clicked(self, item: QListWidgetItem):
|
|
2903
|
+
row = self.history_list.row(item)
|
|
2904
|
+
bus = self._command_bus_provider() if self._command_bus_provider else None
|
|
2905
|
+
if not bus:
|
|
2906
|
+
return
|
|
2907
|
+
current_active = len(bus.history._undo_stack)
|
|
2908
|
+
if row < current_active:
|
|
2909
|
+
# 需要 Undo 的步数
|
|
2910
|
+
steps = current_active - row
|
|
2911
|
+
for _ in range(steps):
|
|
2912
|
+
bus.undo()
|
|
2913
|
+
self._refresh_history()
|
|
2914
|
+
elif row > current_active:
|
|
2915
|
+
# 需要 Redo 的步数
|
|
2916
|
+
steps = row - current_active
|
|
2917
|
+
for _ in range(steps):
|
|
2918
|
+
bus.redo()
|
|
2919
|
+
self._refresh_history()
|
|
2920
|
+
|
|
2921
|
+
def _export_history_skill(self):
|
|
2922
|
+
from PyQt6.QtWidgets import QFileDialog, QMessageBox
|
|
2923
|
+
from ..runtime import data_dir
|
|
2924
|
+
from ..io.history_skill import export_history_skill
|
|
2925
|
+
folder = QFileDialog.getExistingDirectory(self, "选择 D/E 盘技能保存目录", str(data_dir()))
|
|
2926
|
+
if not folder:
|
|
2927
|
+
return
|
|
2928
|
+
try:
|
|
2929
|
+
bus = self._command_bus_provider()
|
|
2930
|
+
result = export_history_skill(bus.document, bus.history.audit_events, Path(folder))
|
|
2931
|
+
except Exception as exc:
|
|
2932
|
+
QMessageBox.warning(self, "导出失败", str(exc))
|
|
2933
|
+
return
|
|
2934
|
+
QMessageBox.information(self, "技能已导出", str(result / "SKILL.md"))
|
|
2935
|
+
|
|
2936
|
+
def apply_typography(self, family: str, base_size: int):
|
|
2937
|
+
"""将全局字体与比例字号同步应用到右侧属性面板、AI 助手与历史面板。"""
|
|
2938
|
+
sz = max(10, int(base_size))
|
|
2939
|
+
self._font_size = sz
|
|
2940
|
+
for button, full_text in zip(self._tab_buttons, ("属性", "AI 助手", "量化", "历史", "设置")):
|
|
2941
|
+
button.setText(full_text if sz < 18 else ("属性", "AI", "量化", "历史", "设置")[self._tab_buttons.index(button)])
|
|
2942
|
+
sz_xs = max(10, sz - 3)
|
|
2943
|
+
sz_sm = max(10, sz - 2)
|
|
2944
|
+
f = QFont(family)
|
|
2945
|
+
f.setPixelSize(sz)
|
|
2946
|
+
self.setFont(f)
|
|
2947
|
+
if hasattr(self, "mol_name_label"):
|
|
2948
|
+
self.mol_name_label.setStyleSheet(f"font-size: {sz}px; font-weight: 700; color: #66DEC9;")
|
|
2949
|
+
if hasattr(self, "measure_label") and "●" in self.measure_label.text():
|
|
2950
|
+
self.measure_label.setStyleSheet(f"color:#66DEC9; font-weight:700; font-size:{max(11, sz - 1)}px;")
|
|
2951
|
+
if hasattr(self, "multi_atom_ids_label"):
|
|
2952
|
+
self.multi_atom_ids_label.setStyleSheet(f"color:#66DEC9; font-weight:700; font-size:{sz_sm}px;")
|
|
2953
|
+
if hasattr(self, "multi_atom_pos_label"):
|
|
2954
|
+
self.multi_atom_pos_label.setStyleSheet(f"color:#9AB0C2; font-size:{sz_xs}px;")
|
|
2955
|
+
for attr, color, bold in (
|
|
2956
|
+
("atom_neighbors_label", "#7DAEFA", False),
|
|
2957
|
+
("atom_vdw_label", "#9AB0C2", False),
|
|
2958
|
+
("atom_partial_charge_label", "#66DEC9", True),
|
|
2959
|
+
("bond_angle_dih_label", "#7DAEFA", True),
|
|
2960
|
+
("bond_ring_label", "#9AB0C2", False),
|
|
2961
|
+
("save_feedback_lbl", "#66DEC9", True),
|
|
2962
|
+
):
|
|
2963
|
+
lbl = getattr(self, attr, None)
|
|
2964
|
+
if lbl is not None:
|
|
2965
|
+
fw = "font-weight:700;" if bold else ""
|
|
2966
|
+
lbl.setStyleSheet(f"color:{color}; font-size:{sz_sm}px; {fw}")
|