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.
Files changed (219) hide show
  1. main.py +71 -0
  2. molforge/__init__.py +19 -0
  3. molforge/ai/__init__.py +15 -0
  4. molforge/ai/deepseek_harness.py +185 -0
  5. molforge/ai/mcp/desktop_client.py +38 -0
  6. molforge/ai/mcp/desktop_service.py +121 -0
  7. molforge/ai/mcp/mcp_server.py +780 -0
  8. molforge/ai/mcp_bridge.py +945 -0
  9. molforge/ai/observation.py +152 -0
  10. molforge/ai/tools.py +455 -0
  11. molforge/application/__init__.py +22 -0
  12. molforge/application/ai/__init__.py +1 -0
  13. molforge/application/ai/deepseek_client.py +293 -0
  14. molforge/application/ai/observation.py +161 -0
  15. molforge/application/ai/tools.py +200 -0
  16. molforge/application/ai_proposals.py +166 -0
  17. molforge/application/bio_selection.py +143 -0
  18. molforge/application/builtin_commands.py +1445 -0
  19. molforge/application/calculators/__init__.py +10 -0
  20. molforge/application/calculators/base.py +143 -0
  21. molforge/application/calculators/calchem_engine.py +67 -0
  22. molforge/application/calculators/calchem_subprocess_worker.py +109 -0
  23. molforge/application/calculators/gaussian_engine.py +59 -0
  24. molforge/application/calculators/gaussian_job_spec.py +240 -0
  25. molforge/application/calculators/orca_engine.py +92 -0
  26. molforge/application/calculators/qc_input_generator.py +300 -0
  27. molforge/application/calculators/registry.py +29 -0
  28. molforge/application/calculators/rest_engine.py +262 -0
  29. molforge/application/command_bus.py +139 -0
  30. molforge/application/commands.py +55 -0
  31. molforge/application/conformers.py +143 -0
  32. molforge/application/document_session.py +156 -0
  33. molforge/application/events.py +74 -0
  34. molforge/application/fragment_catalog.py +422 -0
  35. molforge/application/fragment_commands.py +268 -0
  36. molforge/application/geometry_commands.py +84 -0
  37. molforge/application/history.py +105 -0
  38. molforge/application/internal_coordinates.py +293 -0
  39. molforge/application/invalidation.py +1174 -0
  40. molforge/application/jobs.py +185 -0
  41. molforge/application/measurement.py +167 -0
  42. molforge/application/measurement_targets.py +264 -0
  43. molforge/application/modeling_commands.py +61 -0
  44. molforge/application/plugins.py +197 -0
  45. molforge/application/ports/editor2d.py +85 -0
  46. molforge/application/reaction.py +75 -0
  47. molforge/application/selection.py +164 -0
  48. molforge/application/selection_commands.py +31 -0
  49. molforge/application/trajectory.py +120 -0
  50. molforge/application/trajectory_analysis.py +231 -0
  51. molforge/application/workspace_registry.py +226 -0
  52. molforge/core/__init__.py +12 -0
  53. molforge/core/conformer.py +45 -0
  54. molforge/core/molecule.py +150 -0
  55. molforge/core/orbital.py +33 -0
  56. molforge/core/properties.py +43 -0
  57. molforge/domain/__init__.py +12 -0
  58. molforge/domain/biomolecule.py +99 -0
  59. molforge/domain/chemical_summary.py +129 -0
  60. molforge/domain/chemistry.py +13 -0
  61. molforge/domain/coordinate_store.py +164 -0
  62. molforge/domain/coordination.py +133 -0
  63. molforge/domain/custom_fragments.py +255 -0
  64. molforge/domain/document.py +469 -0
  65. molforge/domain/element_reference.json +598 -0
  66. molforge/domain/elements.py +188 -0
  67. molforge/domain/ids.py +58 -0
  68. molforge/domain/massive_system.py +246 -0
  69. molforge/domain/periodic.py +116 -0
  70. molforge/domain/provenance.py +115 -0
  71. molforge/domain/topology.py +364 -0
  72. molforge/infrastructure/__init__.py +23 -0
  73. molforge/infrastructure/hpc/cluster_config.py +122 -0
  74. molforge/infrastructure/hpc/remote_executor.py +212 -0
  75. molforge/infrastructure/hpc/slurm_generator.py +93 -0
  76. molforge/io/__init__.py +35 -0
  77. molforge/io/calchem_bridge.py +407 -0
  78. molforge/io/calculators.py +893 -0
  79. molforge/io/cclib_adapter.py +422 -0
  80. molforge/io/conformers.py +183 -0
  81. molforge/io/cube_reader.py +215 -0
  82. molforge/io/custom_fragments.py +79 -0
  83. molforge/io/format_matrix.py +157 -0
  84. molforge/io/gemmi_adapter.py +150 -0
  85. molforge/io/history_skill.py +46 -0
  86. molforge/io/mdanalysis_adapter.py +155 -0
  87. molforge/io/mforge_storage.py +261 -0
  88. molforge/io/multiwfn_driver.py +614 -0
  89. molforge/io/openbabel_adapter.py +265 -0
  90. molforge/io/openbabel_handler.py +33 -0
  91. molforge/io/rdkit_adapter.py +1865 -0
  92. molforge/io/readers/__init__.py +10 -0
  93. molforge/io/readers/cube_reader.py +71 -0
  94. molforge/io/readers/gjf_reader.py +110 -0
  95. molforge/io/readers/glog_reader.py +45 -0
  96. molforge/io/readers/mol2_reader.py +36 -0
  97. molforge/io/readers/mol_reader.py +56 -0
  98. molforge/io/readers/pdb_reader.py +39 -0
  99. molforge/io/readers/smi_reader.py +40 -0
  100. molforge/io/readers/xyz_reader.py +47 -0
  101. molforge/io/registry.py +128 -0
  102. molforge/io/writers/__init__.py +7 -0
  103. molforge/io/writers/gjf_writer.py +68 -0
  104. molforge/io/writers/pdb_writer.py +37 -0
  105. molforge/io/writers/png_writer.py +31 -0
  106. molforge/io/writers/svg_writer.py +111 -0
  107. molforge/io/writers/xyz_writer.py +39 -0
  108. molforge/rendering/__init__.py +21 -0
  109. molforge/rendering/benchmark.py +121 -0
  110. molforge/rendering/bridge.py +60 -0
  111. molforge/rendering/contracts.py +119 -0
  112. molforge/rendering/glyph_scene.py +279 -0
  113. molforge/rendering/ketcher_bridge.py +131 -0
  114. molforge/rendering/ketcher_id_mapping.py +110 -0
  115. molforge/rendering/materials.py +127 -0
  116. molforge/rendering/molstar_backend.py +245 -0
  117. molforge/rendering/native_labels.py +134 -0
  118. molforge/rendering/orbitals.py +139 -0
  119. molforge/rendering/vtk_backend.py +2294 -0
  120. molforge/runtime.py +29 -0
  121. molforge/server/__init__.py +1 -0
  122. molforge/server/api_bridge.py +947 -0
  123. molforge/ui/__init__.py +1 -0
  124. molforge/ui/assets/caffeine_2d.svg +150 -0
  125. molforge/ui/assets/caffeine_3d_preview.svg +209 -0
  126. molforge/ui/assets/caffeine_preview.json +302 -0
  127. molforge/ui/assets/icons/atom.svg +1 -0
  128. molforge/ui/assets/icons/bond.svg +1 -0
  129. molforge/ui/assets/icons/cleanup.svg +1 -0
  130. molforge/ui/assets/icons/export.svg +1 -0
  131. molforge/ui/assets/icons/fragments.svg +1 -0
  132. molforge/ui/assets/icons/history.svg +1 -0
  133. molforge/ui/assets/icons/jobs.svg +1 -0
  134. molforge/ui/assets/icons/measure.svg +1 -0
  135. molforge/ui/assets/icons/molecules.svg +1 -0
  136. molforge/ui/assets/icons/overview.svg +1 -0
  137. molforge/ui/assets/icons/ring.svg +1 -0
  138. molforge/ui/assets/icons/search.svg +1 -0
  139. molforge/ui/assets/icons/select.svg +1 -0
  140. molforge/ui/assets/icons/settings.svg +1 -0
  141. molforge/ui/assets/icons/templates.svg +1 -0
  142. molforge/ui/assets/molforge_logo.ico +0 -0
  143. molforge/ui/assets/molforge_logo.png +0 -0
  144. molforge/ui/atom_labels.py +92 -0
  145. molforge/ui/bio_structure_dialog.py +57 -0
  146. molforge/ui/conformer_dialog.py +151 -0
  147. molforge/ui/dialogs/__init__.py +2 -0
  148. molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
  149. molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
  150. molforge/ui/dialogs/element_fragments.py +130 -0
  151. molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
  152. molforge/ui/dialogs/hpc_job_dialog.py +427 -0
  153. molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
  154. molforge/ui/editor2d_widget.py +1803 -0
  155. molforge/ui/element_picker.py +218 -0
  156. molforge/ui/gmv_window_manager.py +65 -0
  157. molforge/ui/gromacs_job_dialog.py +47 -0
  158. molforge/ui/hotkeys.py +107 -0
  159. molforge/ui/i18n.py +237 -0
  160. molforge/ui/live_llm_dialog.py +135 -0
  161. molforge/ui/llm_config_dialog.py +103 -0
  162. molforge/ui/modeling_actions.py +176 -0
  163. molforge/ui/molstar_widget.py +98 -0
  164. molforge/ui/molstar_window.py +85 -0
  165. molforge/ui/panels.py +2966 -0
  166. molforge/ui/qc_result_dialog.py +1924 -0
  167. molforge/ui/render3d_widget.py +1579 -0
  168. molforge/ui/scrolling.py +52 -0
  169. molforge/ui/settings_panel.py +330 -0
  170. molforge/ui/shells/__init__.py +4 -0
  171. molforge/ui/shells/base_shell.py +72 -0
  172. molforge/ui/shells/document_tabs.py +715 -0
  173. molforge/ui/shells/studio_2d.py +339 -0
  174. molforge/ui/shells/studio_3d.py +401 -0
  175. molforge/ui/shells/studio_split.py +370 -0
  176. molforge/ui/shells/workflow_inputs.py +698 -0
  177. molforge/ui/theme.py +719 -0
  178. molforge/ui/trajectory_window.py +333 -0
  179. molforge/ui/views.py +892 -0
  180. molforge/ui/vtk_multiview_widget.py +141 -0
  181. molforge/ui/welcome_window.py +223 -0
  182. molforge/ui/window.py +3320 -0
  183. molforge/workflows/__init__.py +25 -0
  184. molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
  185. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
  186. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
  187. 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
  188. 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
  189. 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
  190. 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
  191. molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
  192. molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
  193. molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
  194. molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
  195. molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
  196. molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
  197. molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
  198. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
  199. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
  200. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
  201. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
  202. molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
  203. molforge/workflows/dipole_analysis.py +32 -0
  204. molforge/workflows/esp_surface.py +36 -0
  205. molforge/workflows/gromacs_submit.py +167 -0
  206. molforge/workflows/homo_lumo_plot.py +59 -0
  207. molforge/workflows/igmh_interaction.py +111 -0
  208. molforge/workflows/md_rdf_analysis.py +134 -0
  209. molforge/workflows/md_studio.py +255 -0
  210. molforge/workflows/osc_energy_diagram.py +24 -0
  211. molforge/workflows/planarity_analysis.py +66 -0
  212. molforge/workflows/reorganization_energy.py +166 -0
  213. molforge/workflows/scientific_workflows.py +650 -0
  214. molforge_studio-7.4.3.dist-info/METADATA +215 -0
  215. molforge_studio-7.4.3.dist-info/RECORD +219 -0
  216. molforge_studio-7.4.3.dist-info/WHEEL +5 -0
  217. molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
  218. molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
  219. molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
@@ -0,0 +1,1803 @@
1
+ """
2
+ ui/editor2d_widget.py - 零偏差坐标映射的 ChemDraw 级 2D 分子编辑器
3
+ ====================================================================
4
+ 核心修复(彻底解决 Issue 8/9/10/11):
5
+ 1. 严格区分「分子 2D 世界坐标 (Å, 原点 0,0, C-C 键长 1.50 Å)」与「屏幕像素坐标 (px)」:
6
+ - `world_to_screen(wx, wy)` 与 `screen_to_world(sx, sy)` 互为严格代数逆变换
7
+ - 窗口缩放或 Splitter 调整大小时,绝不污染 `doc.coords_2d`,鼠标点哪里原子就精确落在哪里!
8
+ 2. 顺滑拖拽与精准画键:
9
+ - 选择模式下按住原子拖动:实时更新 `doc.coords_2d[aid]`,释放时同步提交 `MoveAtom3DCommand`
10
+ - 键/原子模式下从原子 A 拖向原子 B:目标原子显示磁吸高亮圈,释放即准确建键;拖向空白则在释放点新建原子并连键
11
+ - 在选择模式下双击空白处也可直接快速添加原子
12
+ 3. 键盘快捷键状态同步信号:
13
+ - 按 V/B/A/E 或 C/N/O/S/F/P/I/H 时发射 `tool_changed_signal` 与 `element_changed_signal`,主工具栏与 3D 视口同步切换!
14
+ """
15
+ from __future__ import annotations
16
+ from .scrolling import HorizontalWheelScrollArea
17
+
18
+ import math
19
+ import numpy as np
20
+ from PyQt6.QtCore import Qt, QPointF, QRectF, pyqtSignal, QTimer
21
+ from PyQt6.QtGui import (
22
+ QPainter, QPen, QBrush, QColor, QMouseEvent, QWheelEvent, QFont, QFontMetricsF
23
+ )
24
+ from PyQt6.QtWidgets import (
25
+ QWidget, QVBoxLayout, QHBoxLayout, QFrame, QLabel, QPushButton, QMenu, QMessageBox
26
+ )
27
+
28
+ from ..domain.document import MoleculeDocument
29
+ from ..domain.ids import AtomId, BondId
30
+ from ..domain.elements import get_element
31
+ from ..io.rdkit_adapter import doc_to_rdkit
32
+
33
+ STANDARD_VALENCE: dict[int, int] = {
34
+ 1: 1, 5: 3, 6: 4, 7: 3, 8: 2, 9: 1, 14: 4, 15: 3, 16: 2, 17: 1, 35: 1, 53: 1
35
+ }
36
+ SUBSCRIPT_DIGITS = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
37
+
38
+
39
+ def point_to_segment_dist(px: float, py: float, x1: float, y1: float, x2: float, y2: float) -> float:
40
+ dx, dy = x2 - x1, y2 - y1
41
+ l2 = dx * dx + dy * dy
42
+ if l2 < 1e-6:
43
+ return math.hypot(px - x1, py - y1)
44
+ t = ((px - x1) * dx + (py - y1) * dy) / l2
45
+ t = max(0.18, min(0.82, t))
46
+ proj_x = x1 + t * dx
47
+ proj_y = y1 + t * dy
48
+ return math.hypot(px - proj_x, py - proj_y)
49
+
50
+
51
+ class Editor2DWidget(QWidget):
52
+ """
53
+ ChemDraw 级可交互 2D 分子编辑器(世界坐标 Å <-> 屏幕像素精确双射)。
54
+ """
55
+
56
+ atom_clicked = pyqtSignal(AtomId)
57
+ atom_double_clicked = pyqtSignal(AtomId)
58
+ tool_changed_signal = pyqtSignal(str)
59
+ element_changed_signal = pyqtSignal(int)
60
+
61
+ HEADER_HEIGHT = 36.0
62
+ BASE_PX_PER_ANGSTROM = 36.0 # 1 Å = 36 px (1.5 Å 标准化学键 = 54 px)
63
+
64
+ COLORS_PAPER = {
65
+ "bg": "#F4F3EE",
66
+ "grid": "#E2DFD7",
67
+ "bond": "#1F2D3A",
68
+ "text_c": "#1F2D3A",
69
+ 1: (90, 105, 120),
70
+ 6: (31, 45, 58),
71
+ 7: (32, 96, 216),
72
+ 8: (218, 42, 46),
73
+ 9: (24, 152, 82),
74
+ 15: (212, 108, 16),
75
+ 16: (196, 142, 12),
76
+ 17: (24, 152, 82),
77
+ 35: (156, 48, 32),
78
+ 53: (128, 36, 156),
79
+ }
80
+
81
+ COLORS_DARK = {
82
+ "bg": "#0C1622",
83
+ "grid": "#192A3C",
84
+ "bond": "#D4E1EC",
85
+ "text_c": "#EAF2F6",
86
+ 1: (200, 212, 224),
87
+ 6: (212, 225, 236),
88
+ 7: (90, 162, 255),
89
+ 8: (255, 98, 102),
90
+ 9: (92, 224, 146),
91
+ 15: (255, 168, 76),
92
+ 16: (248, 208, 88),
93
+ 17: (82, 218, 138),
94
+ 35: (224, 112, 92),
95
+ 53: (192, 112, 232),
96
+ }
97
+
98
+ def __init__(self, parent=None, chromeless: bool = False):
99
+ super().__init__(parent)
100
+ self._chromeless = bool(chromeless)
101
+ if self._chromeless:
102
+ self.HEADER_HEIGHT = 0.0
103
+ self._document: MoleculeDocument | None = None
104
+ self._selection = None
105
+ self._command_bus = None
106
+ self._current_element = 6
107
+ self._current_tool = "选择"
108
+ self._last_doc_id: str | None = None
109
+
110
+ self._paper_mode: bool = True
111
+ self._hide_explicit_hydrogens: bool = True
112
+ # 原子编号开关:开启后在每个可见原子旁显示基于稳定 AtomId 的唯一编号(与 3D 视图一致)
113
+ self._show_atom_numbers: bool = False
114
+
115
+ # 视图相机变换参数:s = center + pan + w * (BASE_PX_PER_ANGSTROM * zoom)
116
+ self._zoom: float = 1.0
117
+ self._pan_x: float = 0.0
118
+ self._pan_y: float = 0.0
119
+
120
+ # 交互状态
121
+ self._drag_atom: AtomId | None = None
122
+ self._drag_start_wpos: tuple[float, float] | None = None
123
+ self._bond_start: AtomId | None = None
124
+ self._dragging_bond: bool = False
125
+ self._hover_atom: AtomId | None = None
126
+ self._hover_bond: BondId | None = None
127
+ self._press_pos = QPointF()
128
+ self._mouse_pos = QPointF()
129
+ self._panning: bool = False
130
+ self._pan_start = QPointF()
131
+ self._pending_ring: tuple[int, bool, dict[int, int] | None] | None = None
132
+ self._marquee_start: QPointF | None = None
133
+ self._marquee_rect: QRectF | None = None
134
+ # 批量拖动多个选中的原子
135
+ self._batch_dragging: bool = False
136
+ self._batch_drag_start_screen: QPointF | None = None
137
+ self._batch_drag_start_world: dict = {}
138
+
139
+ # 性能缓存:环成员(静态拓扑属性,只在拓扑变化时重算)与网格预渲染
140
+ self._ring_cache_key: tuple | None = None
141
+ self._ring_atom_lists: list[list[AtomId]] = []
142
+ self._bond_rings: dict[BondId, list[int]] = {}
143
+ self._grid_pixmap = None
144
+ self._grid_cache_key: tuple | None = None
145
+ # 复用画笔/颜色/字体,避免每帧成百上千次对象构造
146
+ self._pen_cache: dict = {}
147
+ self._color_cache: dict = {}
148
+ self._label_font = None
149
+
150
+ self.setMinimumSize(400, 400)
151
+ self.setMouseTracking(True)
152
+ self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
153
+ self.setAutoFillBackground(True)
154
+
155
+ self._build_header_overlay()
156
+ self._apply_canvas_palette()
157
+
158
+ def _build_header_overlay(self):
159
+ lay = QVBoxLayout(self)
160
+ lay.setContentsMargins(0, 0, 0, 0)
161
+ lay.setSpacing(0)
162
+
163
+ header = QFrame(self)
164
+ header.setObjectName("Canvas2DHeader")
165
+ header.setMinimumHeight(36)
166
+ header.setStyleSheet(
167
+ "QFrame#Canvas2DHeader { background-color: #0E1926; border-bottom: 1px solid #1E3246; }"
168
+ )
169
+ h_lay = QHBoxLayout(header)
170
+ h_lay.setContentsMargins(10, 3, 10, 3)
171
+ h_lay.setSpacing(6)
172
+
173
+ title = QLabel("2D 画布")
174
+ title.setStyleSheet(
175
+ "color: #66DEC9; background: #132A38; border: 1px solid #265264; "
176
+ "border-radius: 4px; padding: 2px 6px; font-size: 11px; font-weight: 700;"
177
+ )
178
+ h_lay.addWidget(title)
179
+
180
+ self.tool_hint_label = QLabel("[选择] · 元素 C")
181
+ self.tool_hint_label.setMinimumWidth(40)
182
+ self.tool_hint_label.setStyleSheet("color: #EAF2F6; font-size: 12px; font-weight: 600; background: transparent;")
183
+ h_lay.addWidget(self.tool_hint_label, 1)
184
+
185
+ self.btn_toggle_h = QPushButton("隐式氢")
186
+ self.btn_toggle_h.setCheckable(True)
187
+ self.btn_toggle_h.setChecked(True)
188
+ self.btn_toggle_h.setMinimumWidth(62)
189
+ self.btn_toggle_h.setToolTip("切换:ChemDraw 骨架隐式氢 / 显示全部显式 H")
190
+ self.btn_toggle_h.setStyleSheet(
191
+ "QPushButton { background:#152435; color:#95A9B8; border:1px solid #243B50; "
192
+ "border-radius:6px; padding:3px 8px; font-size:12px; font-weight:600; }"
193
+ "QPushButton:checked { background:#0D9488; color:#FFFFFF; border:1px solid #5EEAD4; font-weight:800; }"
194
+ )
195
+ self.btn_toggle_h.clicked.connect(self._toggle_explicit_h)
196
+ h_lay.addWidget(self.btn_toggle_h)
197
+
198
+ self.btn_toggle_num = QPushButton("原子编号")
199
+ self.btn_toggle_num.setCheckable(True)
200
+ self.btn_toggle_num.setChecked(False)
201
+ self.btn_toggle_num.setMinimumWidth(72)
202
+ self.btn_toggle_num.setToolTip("显示/隐藏每个原子的稳定唯一编号(与 3D 视图一致)")
203
+ self.btn_toggle_num.setStyleSheet(
204
+ "QPushButton { background:#152435; color:#95A9B8; border:1px solid #243B50; "
205
+ "border-radius:6px; padding:3px 8px; font-size:12px; font-weight:600; }"
206
+ "QPushButton:checked { background:#0D9488; color:#FFFFFF; border:1px solid #5EEAD4; font-weight:800; }"
207
+ )
208
+ self.btn_toggle_num.toggled.connect(self.set_show_atom_numbers)
209
+ h_lay.addWidget(self.btn_toggle_num)
210
+
211
+ self.btn_bg_mode = QPushButton("暖白纸面")
212
+ self.btn_bg_mode.setCheckable(True)
213
+ self.btn_bg_mode.setChecked(True)
214
+ self.btn_bg_mode.setMinimumWidth(68)
215
+ self.btn_bg_mode.setToolTip("在 ChemDraw 暖白出版画布与深色蓝图画布之间切换")
216
+ self.btn_bg_mode.setStyleSheet(
217
+ "QPushButton { background:#152435; color:#95A9B8; border:1px solid #243B50; "
218
+ "border-radius:6px; padding:3px 8px; font-size:12px; font-weight:600; }"
219
+ "QPushButton:checked { background:#0D9488; color:#FFFFFF; border:1px solid #5EEAD4; font-weight:800; }"
220
+ "QPushButton:hover { background:#1F354C; color:#EAF2F6; }"
221
+ )
222
+ self.btn_bg_mode.clicked.connect(self._toggle_paper_mode)
223
+ h_lay.addWidget(self.btn_bg_mode)
224
+
225
+ # 缩放控制组:[-] 100% [+] [⛶ 居中]
226
+ btn_zoom_out = QPushButton("-")
227
+ btn_zoom_out.setFixedSize(26, 26)
228
+ btn_zoom_out.setToolTip("缩小 2D 画布 (滚轮下滚)")
229
+ btn_zoom_out.setStyleSheet(
230
+ "QPushButton { background:#152435; color:#95A9B8; border:1px solid #243B50; border-radius:4px; font-weight:bold; }"
231
+ "QPushButton:hover { background:#0D9488; color:#FFFFFF; }"
232
+ )
233
+ btn_zoom_out.clicked.connect(self.zoom_out)
234
+ h_lay.addWidget(btn_zoom_out)
235
+
236
+ self.lbl_zoom = QLabel("100%")
237
+ self.lbl_zoom.setStyleSheet("color:#66DEC9; font-weight:700; font-size:12px; padding:0 4px;")
238
+ h_lay.addWidget(self.lbl_zoom)
239
+
240
+ btn_zoom_in = QPushButton("+")
241
+ btn_zoom_in.setFixedSize(26, 26)
242
+ btn_zoom_in.setToolTip("放大 2D 画布 (滚轮上滚)")
243
+ btn_zoom_in.setStyleSheet(
244
+ "QPushButton { background:#152435; color:#95A9B8; border:1px solid #243B50; border-radius:4px; font-weight:bold; }"
245
+ "QPushButton:hover { background:#0D9488; color:#FFFFFF; }"
246
+ )
247
+ btn_zoom_in.clicked.connect(self.zoom_in)
248
+ h_lay.addWidget(btn_zoom_in)
249
+
250
+ reset_2d_btn = QPushButton("⛶ 居中适配")
251
+ reset_2d_btn.setMinimumWidth(72)
252
+ reset_2d_btn.setToolTip("自动缩放居中分子以完美契合当前画布 (快捷键: 0)")
253
+ reset_2d_btn.setStyleSheet(
254
+ "QPushButton { background:#152435; color:#95A9B8; border:1px solid #243B50; "
255
+ "border-radius:6px; padding:3px 8px; font-size:12px; font-weight:600; }"
256
+ "QPushButton:hover { background:#0D9488; color:#FFFFFF; border:1px solid #5EEAD4; }"
257
+ )
258
+ reset_2d_btn.clicked.connect(self.fit_view)
259
+ h_lay.addWidget(reset_2d_btn)
260
+
261
+ self._header_frame = HorizontalWheelScrollArea(header, height=36)
262
+ self._header_frame.height_changed.connect(self._on_header_height)
263
+ lay.addWidget(self._header_frame)
264
+ self.HEADER_HEIGHT = 0.0 if self._chromeless else float(self._header_frame.height())
265
+ lay.addStretch(1)
266
+ if getattr(self, "_chromeless", False):
267
+ self._header_frame.hide()
268
+
269
+ def _on_header_height(self, height):
270
+ self.HEADER_HEIGHT = 0.0 if self._header_frame.isHidden() else float(height)
271
+ self.update()
272
+
273
+ def set_header_visible(self, visible: bool) -> None:
274
+ self.HEADER_HEIGHT = float(self._header_frame.height()) if visible else 0.0
275
+ if hasattr(self, "_header_frame") and self._header_frame is not None:
276
+ self._header_frame.setVisible(visible)
277
+ self.update()
278
+
279
+ # ---------- 严格可逆的 2D 世界坐标 (Å) <-> 屏幕像素坐标 (px) 变换 ----------
280
+
281
+ @property
282
+ def _scale(self) -> float:
283
+ return self.BASE_PX_PER_ANGSTROM * self._zoom
284
+
285
+ def world_to_screen(self, wx: float, wy: float) -> tuple[float, float]:
286
+ """将 2D 世界坐标 (wx, wy, 单位 Å) 转换为当前画布像素坐标 (sx, sy)。"""
287
+ cx = self.width() * 0.5 + self._pan_x
288
+ cy = (self.height() + self.HEADER_HEIGHT) * 0.5 + self._pan_y
289
+ s = self._scale
290
+ return (cx + wx * s, cy - wy * s)
291
+
292
+ def screen_to_world(self, sx: float, sy: float) -> tuple[float, float]:
293
+ """将当前画布像素坐标 (sx, sy) 逆变换为 2D 世界坐标 (wx, wy, 单位 Å)。"""
294
+ cx = self.width() * 0.5 + self._pan_x
295
+ cy = (self.height() + self.HEADER_HEIGHT) * 0.5 + self._pan_y
296
+ s = max(1e-6, self._scale)
297
+ return ((sx - cx) / s, -(sy - cy) / s)
298
+
299
+ def _ensure_world_coords_2d(self) -> dict[AtomId, tuple[float, float]]:
300
+ """确保 doc.coords_2d 中存储的是以 (0,0) 为中心、键长 ~1.50 Å 的世界坐标。"""
301
+ if self._document is None or self._document.topology.num_atoms == 0:
302
+ return {}
303
+ # 对 > 1500 原子的动力学盒子与超大体系,严格禁止生成 2D 坐标以防止内存暴涨和卡死
304
+ if self._document.topology.num_atoms > 1500:
305
+ return {}
306
+
307
+ doc = self._document
308
+ atom_ids = list(doc.topology.atom_ids)
309
+
310
+ # 若全部原子已有 2D 世界坐标,先检查是否误存了旧版屏幕像素坐标,若是则自动归一化
311
+ if doc.coords_2d and all(aid in doc.coords_2d for aid in atom_ids):
312
+ doc.sync_2d_coords_from_3d()
313
+ return doc.coords_2d
314
+
315
+ # 若部分新原子缺失 2D 坐标(例如刚在 3D 里点了加原子),调用增量同步而不打乱已有布局!
316
+ if doc.coords_2d and any(aid in doc.coords_2d for aid in atom_ids):
317
+ doc.sync_2d_coords_from_3d()
318
+ return doc.coords_2d
319
+
320
+ # 首次加载或重排:若已有 3D 坐标且原子数较大(>45),优先走 0.1ms SVD 主平面投影;中小分子走 RDKit 2D
321
+ coords_w: dict[AtomId, tuple[float, float]] = {}
322
+ if doc.has_3d and doc.coordinates.current is not None and len(doc.coordinates.current.coords) == len(atom_ids) and len(atom_ids) > 45:
323
+ from ..io.rdkit_adapter import compute_2d_coords_from_3d_svd
324
+ _, id_to_idx = doc.topology.atom_index_map()
325
+ b_list = [
326
+ (id_to_idx[doc.topology.get_bond(bid).begin], id_to_idx[doc.topology.get_bond(bid).end], 1)
327
+ for bid in doc.topology.bond_ids
328
+ if doc.topology.get_bond(bid).begin in id_to_idx and doc.topology.get_bond(bid).end in id_to_idx
329
+ ]
330
+ doc.coords_2d = compute_2d_coords_from_3d_svd(atom_ids, doc.coordinates.current.coords, b_list)
331
+ return doc.coords_2d
332
+
333
+ try:
334
+ rdmol, atom_rdkit_idx_map, _ = doc_to_rdkit(doc, sanitize=True)
335
+ from rdkit.Chem import AllChem
336
+ AllChem.Compute2DCoords(rdmol)
337
+ if rdmol.GetNumConformers() > 0:
338
+ conf = rdmol.GetConformer()
339
+ raw = np.array([[conf.GetAtomPosition(i).x, conf.GetAtomPosition(i).y] for i in range(rdmol.GetNumAtoms())])
340
+ center = raw.mean(axis=0) if len(raw) > 0 else np.zeros(2)
341
+ rdkit_to_aid = {v: k for k, v in atom_rdkit_idx_map.items()}
342
+ for i in range(rdmol.GetNumAtoms()):
343
+ aid = rdkit_to_aid.get(i)
344
+ if aid is not None:
345
+ coords_w[aid] = (float(raw[i, 0] - center[0]), float(raw[i, 1] - center[1]))
346
+ except Exception:
347
+ pass
348
+
349
+ if not coords_w:
350
+ if doc.has_3d and doc.coordinates.current is not None and len(doc.coordinates.current.coords) == len(atom_ids):
351
+ from ..io.rdkit_adapter import compute_2d_coords_from_3d_svd
352
+ coords_w = compute_2d_coords_from_3d_svd(atom_ids, doc.coordinates.current.coords)
353
+ else:
354
+ for i, aid in enumerate(atom_ids):
355
+ coords_w[aid] = (float(i) * 1.50, 0.0)
356
+
357
+ doc.coords_2d = coords_w
358
+ return doc.coords_2d
359
+
360
+ def _get_screen_coords(self) -> dict[AtomId, tuple[float, float]]:
361
+ """获取所有原子在当前屏幕上的像素坐标 (sx, sy);变换用 NumPy 向量化。"""
362
+ world_map = self._ensure_world_coords_2d()
363
+ if not world_map:
364
+ return {}
365
+ aids = list(world_map.keys())
366
+ w = np.array([world_map[a] for a in aids], dtype=np.float64)
367
+ cx = self.width() * 0.5 + self._pan_x
368
+ cy = (self.height() + self.HEADER_HEIGHT) * 0.5 + self._pan_y
369
+ s = self._scale
370
+ sx = cx + w[:, 0] * s
371
+ sy = cy - w[:, 1] * s
372
+ return {a: (float(sx[i]), float(sy[i])) for i, a in enumerate(aids)}
373
+
374
+ # ---------- 视图与工具切换 ----------
375
+
376
+ def _toggle_explicit_h(self, checked: bool):
377
+ self._hide_explicit_hydrogens = checked
378
+ self.btn_toggle_h.setText("隐式氢" if checked else "全显氢")
379
+ self.update()
380
+
381
+ def _toggle_paper_mode(self):
382
+ self._paper_mode = not self._paper_mode
383
+ self.btn_bg_mode.setText("暖白纸面" if self._paper_mode else "深色蓝图")
384
+ self._apply_canvas_palette()
385
+ self.update()
386
+
387
+ def _apply_canvas_palette(self):
388
+ scheme = self.COLORS_PAPER if self._paper_mode else self.COLORS_DARK
389
+ palette = self.palette()
390
+ palette.setColor(self.backgroundRole(), QColor(scheme["bg"]))
391
+ self.setPalette(palette)
392
+
393
+ def recompute_2d_layout(self):
394
+ if self._document is not None:
395
+ if self._document.topology.num_atoms > 1500:
396
+ return
397
+ self._document.coords_2d.clear()
398
+ self._ensure_world_coords_2d()
399
+ self._zoom = 1.0
400
+ self._pan_x = 0.0
401
+ self._pan_y = 0.0
402
+ self.update()
403
+
404
+ def _update_tool_hint(self):
405
+ elem = get_element(self._current_element)
406
+ sym = elem.symbol if elem else "C"
407
+ if self._pending_ring is not None:
408
+ size, arom, _ = self._pending_ring
409
+ kind = "芳香" if arom else "饱和"
410
+ self.tool_hint_label.setText(f"放置模式:{kind} {size} 元环(点击空白放置或点原子接环)")
411
+ else:
412
+ self.tool_hint_label.setText(f"[{self._current_tool}] · 元素 {sym}")
413
+
414
+ def set_document(self, doc: MoleculeDocument):
415
+ is_new_doc = (self._last_doc_id != doc.document_id)
416
+ self._document = doc
417
+ self._last_doc_id = doc.document_id
418
+ if is_new_doc:
419
+ self._zoom = 1.0
420
+ self._pan_x = 0.0
421
+ self._pan_y = 0.0
422
+ self._ensure_world_coords_2d()
423
+ if is_new_doc and doc.num_atoms > 1:
424
+ from PyQt6.QtCore import QTimer
425
+ QTimer.singleShot(30, self.fit_view)
426
+ self.update()
427
+
428
+ def fit_view(self):
429
+ """自动调整缩放和平移,让整个分子完整显示在画布中间"""
430
+ if self._document is None or self._document.topology.num_atoms == 0:
431
+ return
432
+ coords = self._ensure_world_coords_2d()
433
+ if not coords:
434
+ return
435
+ # 计算所有原子的坐标范围
436
+ xs = [x for x, y in coords.values()]
437
+ ys = [y for x, y in coords.values()]
438
+ min_x, max_x = min(xs), max(xs)
439
+ min_y, max_y = min(ys), max(ys)
440
+ mol_width = max(max_x - min_x + 1.2, 2.0)
441
+ mol_height = max(max_y - min_y + 1.2, 2.0)
442
+ # 画布大小(减去顶部标题栏)
443
+ canvas_w = max(50.0, float(self.width()))
444
+ canvas_h = max(50.0, float(self.height() - self.HEADER_HEIGHT))
445
+ if canvas_w <= 80 or canvas_h <= 80:
446
+ return
447
+ # 计算缩放比例:保留 ~25% 优雅边距,确保分子舒展居中显示
448
+ zoom_x = (canvas_w * 0.72) / (mol_width * self.BASE_PX_PER_ANGSTROM)
449
+ zoom_y = (canvas_h * 0.72) / (mol_height * self.BASE_PX_PER_ANGSTROM)
450
+ # 无界自适应缩放:支持超大分子网络(最低 0.5%)与单原子局部(最高 250%),兼顾大体系全景与微观细节
451
+ self._zoom = max(0.005, min(2.5, min(zoom_x, zoom_y)))
452
+ # 计算平移,让分子质心对齐画布中心
453
+ center_x = (min_x + max_x) / 2.0
454
+ center_y = (min_y + max_y) / 2.0
455
+ self._pan_x = -center_x * self.BASE_PX_PER_ANGSTROM * self._zoom
456
+ self._pan_y = center_y * self.BASE_PX_PER_ANGSTROM * self._zoom
457
+ if hasattr(self, "lbl_zoom"):
458
+ self.lbl_zoom.setText(self._format_zoom_str())
459
+ self.update()
460
+
461
+ def _format_zoom_str(self) -> str:
462
+ pct = self._zoom * 100.0
463
+ if pct < 1.0:
464
+ return f"{pct:.1f}%"
465
+ return f"{int(pct)}%"
466
+
467
+ def zoom_in(self):
468
+ self._zoom = min(50.0, self._zoom * 1.25)
469
+ if hasattr(self, "lbl_zoom"):
470
+ self.lbl_zoom.setText(self._format_zoom_str())
471
+ self.update()
472
+
473
+ def zoom_out(self):
474
+ self._zoom = max(0.005, self._zoom / 1.25)
475
+ if hasattr(self, "lbl_zoom"):
476
+ self.lbl_zoom.setText(self._format_zoom_str())
477
+ self.update()
478
+
479
+ def resizeEvent(self, event):
480
+ super().resizeEvent(event)
481
+ if not getattr(self, "_initial_fit_done", False) and self.width() > 180 and self.height() > 180:
482
+ self._initial_fit_done = True
483
+ QTimer.singleShot(60, self.fit_view)
484
+
485
+ def set_selection_service(self, selection):
486
+ if getattr(self, "_selection", None) is selection and getattr(self, "_selection_callback", None) is not None:
487
+ return
488
+ previous = getattr(self, "_selection", None)
489
+ callback = getattr(self, "_selection_callback", None)
490
+ if previous is not None and callback is not None:
491
+ previous.remove_listener(callback)
492
+ self._selection = selection
493
+ self._selection_callback = lambda origin: self.update()
494
+ selection.add_listener(self._selection_callback)
495
+ self.destroyed.connect(lambda _=None, service=selection, cb=self._selection_callback: service.remove_listener(cb))
496
+
497
+ def set_command_bus(self, bus):
498
+ if getattr(self, "_command_bus", None) is bus and getattr(self, "_bus_callback", None) is not None:
499
+ return
500
+ previous = getattr(self, "_command_bus", None)
501
+ callback = getattr(self, "_bus_callback", None)
502
+ if previous is not None and callback is not None:
503
+ previous.remove_listener(callback)
504
+ self._command_bus = bus
505
+ self._bus_callback = lambda _doc: self.update()
506
+ bus.add_listener(self._bus_callback)
507
+ self.destroyed.connect(lambda _=None, service=bus, cb=self._bus_callback: service.remove_listener(cb))
508
+
509
+ def set_ring_template(self, size: int, aromatic: bool = False, hetero_atoms: dict[int, int] | None = None):
510
+ self._pending_ring = (size, aromatic, hetero_atoms)
511
+ self._update_tool_hint()
512
+
513
+ def set_current_tool(self, tool: str):
514
+ self._current_tool = tool
515
+ self._update_tool_hint()
516
+ self.update()
517
+
518
+ def set_current_element(self, atomic_num: int) -> None:
519
+ self._current_element = int(atomic_num)
520
+ self._update_tool_hint()
521
+ self.update()
522
+
523
+ # ---------- 骨架氢折叠与环内双键检测 ----------
524
+
525
+ def _is_hidden_hydrogen(self, aid: AtomId) -> bool:
526
+ if not self._hide_explicit_hydrogens or self._document is None:
527
+ return False
528
+ if aid not in self._document.topology._atoms:
529
+ return False
530
+ atom = self._document.topology.get_atom(aid)
531
+ if atom.atomic_num != 1:
532
+ return False
533
+ nbrs = self._document.topology.neighbors_of(aid)
534
+ if len(nbrs) != 1:
535
+ return False
536
+ parent = self._document.topology.get_atom(nbrs[0])
537
+ return parent.atomic_num in (6, 7, 8, 15, 16)
538
+
539
+ def _should_show_atom_label(self, aid: AtomId) -> tuple[bool, str]:
540
+ doc = self._document
541
+ atom = doc.topology.get_atom(aid)
542
+ z = atom.atomic_num
543
+ elem = get_element(z)
544
+ sym = elem.symbol if elem else "?"
545
+
546
+ all_nbrs = doc.topology.neighbors_of(aid)
547
+ visible_nbrs = [n for n in all_nbrs if not self._is_hidden_hydrogen(n)]
548
+ folded_h = len(all_nbrs) - len(visible_nbrs)
549
+
550
+ bond_order_sum = 0
551
+ for bid in doc.topology._adjacency.get(aid, []):
552
+ b = doc.topology.get_bond(bid)
553
+ other = b.end if b.begin == aid else b.begin
554
+ if not self._is_hidden_hydrogen(other):
555
+ bond_order_sum += (2 if b.aromatic else b.order)
556
+
557
+ if z == 6 and atom.formal_charge == 0 and len(visible_nbrs) >= 1:
558
+ return False, ""
559
+
560
+ if folded_h > 0:
561
+ h_count = folded_h
562
+ else:
563
+ std_v = STANDARD_VALENCE.get(z, 0)
564
+ h_count = max(0, std_v - bond_order_sum + atom.formal_charge) if z in (6, 7, 8, 16) else 0
565
+
566
+ h_str = "H" if h_count == 1 else (("H" + str(h_count).translate(SUBSCRIPT_DIGITS)) if h_count > 1 else "")
567
+ charge_str = ""
568
+ if atom.formal_charge > 0:
569
+ charge_str = "⁺" if atom.formal_charge == 1 else f"{atom.formal_charge}⁺"
570
+ elif atom.formal_charge < 0:
571
+ charge_str = "⁻" if atom.formal_charge == -1 else f"{abs(atom.formal_charge)}⁻"
572
+
573
+ return True, f"{sym}{h_str}{charge_str}"
574
+
575
+ def _get_color(self, key):
576
+ col = self._color_cache.get(key)
577
+ if col is None:
578
+ if isinstance(key, (tuple, list)):
579
+ col = QColor(*key)
580
+ else:
581
+ col = QColor(key)
582
+ self._color_cache[key] = col
583
+ return col
584
+
585
+ def _get_pen(self, color_key, width, style=Qt.PenStyle.SolidLine, cap=Qt.PenCapStyle.RoundCap):
586
+ key = (color_key, width, style, cap)
587
+ pen = self._pen_cache.get(key)
588
+ if pen is None:
589
+ pen = QPen(self._get_color(color_key), width, style, cap)
590
+ self._pen_cache[key] = pen
591
+ return pen
592
+
593
+ def _get_label_font(self):
594
+ font = QFont("Segoe UI", 11, QFont.Weight.DemiBold)
595
+ font.setPointSizeF(max(1.0, 11.0 * self._zoom))
596
+ return font
597
+
598
+ def _ensure_grid_pixmap(self, scheme: dict):
599
+ """网格只在尺寸/配色变化时绘制一次到 QPixmap,paintEvent 直接 drawPixmap。"""
600
+ key = (self.width(), self.height(), int(self.HEADER_HEIGHT), scheme["grid"])
601
+ if key == self._grid_cache_key and self._grid_pixmap is not None:
602
+ return self._grid_pixmap
603
+ from PyQt6.QtGui import QPixmap
604
+ pixmap = QPixmap(self.size())
605
+ pixmap.fill(QColor(scheme["bg"]))
606
+ gp = QPainter(pixmap)
607
+ gp.setPen(QPen(QColor(scheme["grid"]), 1.2))
608
+ for y in range(int(self.HEADER_HEIGHT) + 18, self.height() - 12, 24):
609
+ for x in range(20, self.width() - 12, 24):
610
+ gp.drawPoint(x, y)
611
+ gp.end()
612
+ self._grid_pixmap = pixmap
613
+ self._grid_cache_key = key
614
+ return pixmap
615
+
616
+ def _ensure_ring_cache(self) -> None:
617
+ """环是分子拓扑的静态属性:用 RDKit SSSR 计算一次并缓存,只在拓扑变化时重算。"""
618
+ if self._document is None:
619
+ return
620
+ doc = self._document
621
+ key = (doc.document_id, doc.topology_hash())
622
+ if key == self._ring_cache_key:
623
+ return
624
+ self._ring_atom_lists = []
625
+ self._bond_rings = {}
626
+ try:
627
+ rdmol, atom_rdkit_idx_map, _ = doc_to_rdkit(doc, sanitize=False)
628
+ aid_by_rdkit = {v: k for k, v in atom_rdkit_idx_map.items()}
629
+ ring_info = rdmol.GetRingInfo()
630
+ for r_atoms in ring_info.AtomRings():
631
+ aids = [aid_by_rdkit[i] for i in r_atoms if i in aid_by_rdkit]
632
+ if len(aids) >= 3:
633
+ ring_idx = len(self._ring_atom_lists)
634
+ self._ring_atom_lists.append(aids)
635
+ # 建立 键 -> 所属环 索引:环内相邻原子对(含首尾)对应一条键
636
+ idx_to_aid = aid_by_rdkit
637
+ for ring_idx, r_atoms in enumerate(ring_info.AtomRings()):
638
+ seq = list(r_atoms)
639
+ for a, b in zip(seq, seq[1:] + seq[:1]):
640
+ bid = doc.topology.bond_between(idx_to_aid[a], idx_to_aid[b])
641
+ if bid is not None:
642
+ self._bond_rings.setdefault(bid, []).append(ring_idx)
643
+ except Exception:
644
+ self._ring_atom_lists = []
645
+ self._bond_rings = {}
646
+ self._ring_cache_key = key
647
+
648
+ def _find_ring_centroids(self, screen_coords: dict[AtomId, tuple[float, float]]) -> dict[BondId, tuple[float, float]]:
649
+ """基于缓存的环成员直接计算每个环中心,并映射到环内各键(不再每帧 BFS)。"""
650
+ centroids: dict[BondId, tuple[float, float]] = {}
651
+ if self._document is None:
652
+ return centroids
653
+ self._ensure_ring_cache()
654
+ # 先一次性算出每个环的中心
655
+ ring_centers: dict[int, tuple[float, float]] = {}
656
+ for ring_idx, aids in enumerate(self._ring_atom_lists):
657
+ pts = [screen_coords[a] for a in aids if a in screen_coords]
658
+ if len(pts) < 3:
659
+ continue
660
+ arr = np.array(pts, dtype=np.float64)
661
+ ring_centers[ring_idx] = (float(arr[:, 0].mean()), float(arr[:, 1].mean()))
662
+ # 再单次遍历 键->环 映射查表
663
+ for bid, ring_ids in self._bond_rings.items():
664
+ for r in ring_ids:
665
+ if r in ring_centers:
666
+ centroids[bid] = ring_centers[r]
667
+ break
668
+ return centroids
669
+
670
+ # ---------- 渲染绘制 ----------
671
+
672
+ def paintEvent(self, event):
673
+ p = QPainter(self)
674
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
675
+ p.setRenderHint(QPainter.RenderHint.TextAntialiasing)
676
+
677
+ scheme = self.COLORS_PAPER if self._paper_mode else self.COLORS_DARK
678
+ # 背景+网格走预渲染缓存,避免每帧数千次 drawPoint
679
+ p.drawPixmap(0, 0, self._ensure_grid_pixmap(scheme))
680
+
681
+ if self._document is None or self._document.topology.num_atoms == 0:
682
+ p.setPen(QColor("#7D93A6"))
683
+ p.setFont(QFont("Segoe UI", 12))
684
+ p.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "点击或双击画布添加原子,或从左侧选择共轭环模板")
685
+ p.end()
686
+ return
687
+
688
+ doc = self._document
689
+ if doc.topology.num_atoms > 1500:
690
+ # 严格禁止在 2D 画布中渲染超大体系/动力学盒子,免除内存暴涨与卡死!
691
+ p.setPen(Qt.PenStyle.NoPen)
692
+ p.setBrush(QColor(18, 28, 38, 235) if not self._paper_mode else QColor(245, 247, 250, 240))
693
+ card_w = max(360, min(620, self.width() - 40))
694
+ card_h = 210
695
+ cx = (self.width() - card_w) / 2
696
+ cy = (self.height() - card_h) / 2 + self.HEADER_HEIGHT / 2
697
+ p.drawRoundedRect(int(cx), int(cy), int(card_w), int(card_h), 12, 12)
698
+
699
+ p.setPen(QPen(QColor("#00E5FF" if not self._paper_mode else "#0052CC"), 1.8))
700
+ p.setBrush(Qt.BrushStyle.NoBrush)
701
+ p.drawRoundedRect(int(cx), int(cy), int(card_w), int(card_h), 12, 12)
702
+
703
+ p.setPen(QColor("#00E5FF" if not self._paper_mode else "#0052CC"))
704
+ p.setFont(QFont("Segoe UI", 13, QFont.Weight.Bold))
705
+ p.drawText(int(cx + 24), int(cy + 40), f"📦 宏观体系 / 动力学盒子 ({doc.num_atoms:,} 原子 · {doc.num_bonds:,} 键)")
706
+
707
+ p.setPen(QColor("#E2E8F0" if not self._paper_mode else "#172B4D"))
708
+ p.setFont(QFont("Segoe UI", 10))
709
+ desc_text = (
710
+ "为保障极速流畅度并彻底防止系统内存耗尽,>1,500 原子的宏观体系已自动转入\n"
711
+ "【3D GPU 高性能视口】进行 3D 渲染与漫游交互。\n\n"
712
+ "💡 2D 结构草图画布针对经典化学分子设计,已安全休眠以保护内存。\n"
713
+ "您可以在右侧 3D 视口中以 60 FPS 自由旋转、平移和缩放观察该体系。"
714
+ )
715
+ from PyQt6.QtCore import QRect
716
+ p.drawText(QRect(int(cx + 24), int(cy + 62), int(card_w - 48), 135), Qt.TextFlag.TextWordWrap, desc_text)
717
+ self._draw_header(p)
718
+ p.end()
719
+ return
720
+ # 一次性计算隐藏氢集合,避免每帧对每个原子/键反复查拓扑
721
+ hidden_h = {aid for aid in doc.topology.atom_ids if self._is_hidden_hydrogen(aid)}
722
+ coords_2d = self._get_screen_coords()
723
+ ring_centroids = self._find_ring_centroids(coords_2d)
724
+
725
+ selected_atoms = self._selection.selected_atoms if self._selection is not None else set()
726
+ selected_bonds = self._selection.selected_bonds if self._selection is not None else set()
727
+
728
+ atom_labels: dict[AtomId, tuple[bool, str]] = {}
729
+ for aid in list(doc.topology.atom_ids):
730
+ if aid not in hidden_h:
731
+ atom_labels[aid] = self._should_show_atom_label(aid)
732
+
733
+ # 计算视口裁剪范围(保留 80px 宽裕缓冲带),开启高速视口剔除 (Viewport Frustum Culling)
734
+ pad = 80.0
735
+ vw_l, vw_t = -pad, float(self.HEADER_HEIGHT) - pad
736
+ vw_r, vw_b = float(self.width()) + pad, float(self.height()) + pad
737
+
738
+ def in_view(x: float, y: float) -> bool:
739
+ return vw_l <= x <= vw_r and vw_t <= y <= vw_b
740
+
741
+ def bond_in_view(x1: float, y1: float, x2: float, y2: float) -> bool:
742
+ return in_view(x1, y1) or in_view(x2, y2) or (min(x1, x2) <= vw_r and max(x1, x2) >= vw_l and min(y1, y2) <= vw_b and max(y1, y2) >= vw_t)
743
+
744
+ # 1. 绘制化学键(视口裁剪过滤)
745
+ for bid in list(doc.topology.bond_ids):
746
+ bond = doc.topology.get_bond(bid)
747
+ if bond.begin in hidden_h or bond.end in hidden_h:
748
+ continue
749
+ if bond.begin in coords_2d and bond.end in coords_2d:
750
+ x1, y1 = coords_2d[bond.begin]
751
+ x2, y2 = coords_2d[bond.end]
752
+ if not bond_in_view(x1, y1, x2, y2):
753
+ continue
754
+ clip_start = 11.5 * self._zoom if atom_labels.get(bond.begin, (False, ""))[0] else 0.0
755
+ clip_end = 11.5 * self._zoom if atom_labels.get(bond.end, (False, ""))[0] else 0.0
756
+ is_sel = (bid in selected_bonds) or (bid == self._hover_bond)
757
+ self._draw_bond(
758
+ p, x1, y1, x2, y2, bond.order, bond.aromatic,
759
+ clip_start=clip_start, clip_end=clip_end,
760
+ ring_center=ring_centroids.get(bid), highlighted=is_sel, scheme=scheme
761
+ )
762
+
763
+ # 2. 绘制选中与悬停光晕
764
+ for aid in selected_atoms:
765
+ if aid in coords_2d and aid not in hidden_h:
766
+ x, y = coords_2d[aid]
767
+ if in_view(x, y):
768
+ self._draw_selection_ring(p, x, y, is_hover=False)
769
+ if self._hover_atom is not None and self._hover_atom in coords_2d and self._hover_atom not in selected_atoms:
770
+ if self._hover_atom not in hidden_h:
771
+ hx, hy = coords_2d[self._hover_atom]
772
+ if in_view(hx, hy):
773
+ self._draw_selection_ring(p, hx, hy, is_hover=True)
774
+
775
+ # 3. 绘制原子标签(结合 2D LOD 与视口剔除)
776
+ is_lod_far_view = (self._zoom < 0.20)
777
+ for aid in list(doc.topology.atom_ids):
778
+ if aid not in coords_2d or aid in hidden_h:
779
+ continue
780
+ x, y = coords_2d[aid]
781
+ if not in_view(x, y):
782
+ continue
783
+ atom = doc.topology.get_atom(aid)
784
+ show_lbl, lbl_text = atom_labels.get(aid, (False, ""))
785
+ if is_lod_far_view:
786
+ # LOD 极远视口模式:绘制极速 CPK 彩色原子骨架点,跳过昂贵的 QFontMetrics 排版运算
787
+ elem = get_element(atom.atomic_num)
788
+ dot_color = self._get_color(tuple(int(c * 255) for c in elem.cpk_color)) if elem else self._get_color(scheme["text_c"])
789
+ p.setPen(Qt.PenStyle.NoPen)
790
+ p.setBrush(QBrush(dot_color))
791
+ dot_r = max(1.5, 4.0 * self._zoom)
792
+ p.drawEllipse(QPointF(x, y), dot_r, dot_r)
793
+ elif show_lbl:
794
+ self._draw_atom_label(p, x, y, atom.atomic_num, lbl_text, scheme)
795
+
796
+ # 3.5 绘制原子编号(独立角标,基于稳定 AtomId,与 3D 视图编号一致,仅在中近景且视野内绘制)
797
+ if self._show_atom_numbers and not is_lod_far_view:
798
+ for aid in list(doc.topology.atom_ids):
799
+ if aid not in coords_2d or aid in hidden_h:
800
+ continue
801
+ nx, ny = coords_2d[aid]
802
+ if in_view(nx, ny):
803
+ self._draw_atom_number(p, nx, ny, aid.value)
804
+
805
+ # 3.6 绘制选中原子的专属高亮序号徽标 (Badge)!
806
+ for aid in selected_atoms:
807
+ if aid in coords_2d and aid not in hidden_h:
808
+ nx, ny = coords_2d[aid]
809
+ if in_view(nx, ny):
810
+ self._draw_selected_atom_badge(p, nx, ny, aid.value + 1)
811
+
812
+ # 4. 绘制拖拽建键预览线(若悬停在目标原子上,自动吸附到目标原子中心!)
813
+ if self._dragging_bond and self._bond_start in coords_2d:
814
+ sx, sy = coords_2d[self._bond_start]
815
+ if self._hover_atom is not None and self._hover_atom in coords_2d and self._hover_atom != self._bond_start:
816
+ ex, ey = coords_2d[self._hover_atom]
817
+ else:
818
+ ex, ey = self._mouse_pos.x(), self._mouse_pos.y()
819
+ pen = QPen(QColor("#14A38C" if self._paper_mode else "#66DEC9"), 2.4, Qt.PenStyle.DashLine)
820
+ p.setPen(pen)
821
+ p.drawLine(QPointF(sx, sy), QPointF(ex, ey))
822
+
823
+ # 5. 框选矩形
824
+ if self._marquee_rect is not None:
825
+ pen = QPen(QColor(20, 163, 140), 1.5, Qt.PenStyle.DashLine)
826
+ p.setPen(pen)
827
+ p.setBrush(QBrush(QColor(102, 222, 201, 38)))
828
+ p.drawRect(self._marquee_rect.normalized())
829
+
830
+ p.setPen(QColor("#788998" if self._paper_mode else "#627788"))
831
+ p.setFont(QFont("Segoe UI", 9))
832
+ vis_count = sum(1 for a in doc.topology.atom_ids if a not in hidden_h)
833
+ h_folded = max(0, doc.num_atoms - vis_count)
834
+ atom_stat = (
835
+ f"共 {doc.num_atoms} 原子 ({vis_count} 骨架 · {h_folded} 隐式 H)"
836
+ if h_folded > 0
837
+ else f"共 {doc.num_atoms} 原子 (全原子显式)"
838
+ )
839
+ p.drawText(
840
+ 14, self.height() - 10,
841
+ f"缩放 {self._format_zoom_str()} · {atom_stat}"
842
+ )
843
+ p.end()
844
+
845
+ def _draw_bond(
846
+ self, p: QPainter, x1: float, y1: float, x2: float, y2: float,
847
+ order: int, aromatic: bool = False,
848
+ clip_start: float = 0.0, clip_end: float = 0.0,
849
+ ring_center: tuple[float, float] | None = None,
850
+ highlighted: bool = False,
851
+ scheme: dict = COLORS_PAPER,
852
+ ):
853
+ dx, dy = x2 - x1, y2 - y1
854
+ length = math.hypot(dx, dy)
855
+ if length < 1e-3:
856
+ return
857
+ ux, uy = dx / length, dy / length
858
+ nx, ny = -uy, ux
859
+
860
+ if highlighted:
861
+ hl_pen = self._get_pen((102, 222, 201, 130), max(2.,8.0*self._zoom))
862
+ p.setPen(hl_pen)
863
+ p.drawLine(QPointF(x1, y1), QPointF(x2, y2))
864
+
865
+ sx1, sy1 = x1 + ux * min(clip_start, length * 0.35), y1 + uy * min(clip_start, length * 0.35)
866
+ sx2, sy2 = x2 - ux * min(clip_end, length * 0.35), y2 - uy * min(clip_end, length * 0.35)
867
+
868
+ p.setPen(self._get_pen(scheme["bond"], max(.45,2.2*self._zoom)))
869
+
870
+ inward_sign = 1.0
871
+ if ring_center is not None:
872
+ mx, my = (x1 + x2) * 0.5, (y1 + y2) * 0.5
873
+ if ((ring_center[0] - mx) * nx + (ring_center[1] - my) * ny) < 0:
874
+ inward_sign = -1.0
875
+
876
+ if order == 1 and not aromatic:
877
+ p.drawLine(QPointF(sx1, sy1), QPointF(sx2, sy2))
878
+ elif order == 2 or aromatic:
879
+ if ring_center is not None:
880
+ p.drawLine(QPointF(sx1, sy1), QPointF(sx2, sy2))
881
+ offset = 4.8 * self._zoom * inward_sign
882
+ shrink = min(6.5*self._zoom, length * 0.18)
883
+ ix1 = sx1 + ux * shrink + nx * offset
884
+ iy1 = sy1 + uy * shrink + ny * offset
885
+ ix2 = sx2 - ux * shrink + nx * offset
886
+ iy2 = sy2 - uy * shrink + ny * offset
887
+ if aromatic and order == 1:
888
+ p.setPen(self._get_pen(scheme["bond"], max(.4,1.8*self._zoom), Qt.PenStyle.DashLine))
889
+ p.drawLine(QPointF(ix1, iy1), QPointF(ix2, iy2))
890
+ else:
891
+ off = 2.8*self._zoom
892
+ p.drawLine(QPointF(sx1 + nx * off, sy1 + ny * off), QPointF(sx2 + nx * off, sy2 + ny * off))
893
+ p.drawLine(QPointF(sx1 - nx * off, sy1 - ny * off), QPointF(sx2 - nx * off, sy2 - ny * off))
894
+ elif order == 3:
895
+ off = 4.2*self._zoom
896
+ p.drawLine(QPointF(sx1, sy1), QPointF(sx2, sy2))
897
+ p.drawLine(QPointF(sx1 + nx * off, sy1 + ny * off), QPointF(sx2 + nx * off, sy2 + ny * off))
898
+ p.drawLine(QPointF(sx1 - nx * off, sy1 - ny * off), QPointF(sx2 - nx * off, sy2 - ny * off))
899
+ else:
900
+ p.drawLine(QPointF(sx1, sy1), QPointF(sx2, sy2))
901
+
902
+ def _draw_selection_ring(self, p: QPainter, x: float, y: float, is_hover: bool = False):
903
+ if is_hover:
904
+ p.setPen(QPen(QColor(20, 163, 140, 160), 2.0))
905
+ p.setBrush(QBrush(QColor(102, 222, 201, 55)))
906
+ p.drawEllipse(QPointF(x, y), max(4.,13*self._zoom), max(4.,13*self._zoom))
907
+ else:
908
+ p.setPen(QPen(QColor(20, 163, 140, 95), max(1.5,5.*self._zoom)))
909
+ p.setBrush(Qt.BrushStyle.NoBrush)
910
+ p.drawEllipse(QPointF(x, y), max(5.,15*self._zoom), max(5.,15*self._zoom))
911
+ p.setPen(QPen(QColor(20, 163, 140), 2.0))
912
+ p.drawEllipse(QPointF(x, y), max(4.,13*self._zoom), max(4.,13*self._zoom))
913
+
914
+ def _draw_atom_label(self, p: QPainter, x: float, y: float, atomic_num: int, text: str, scheme: dict):
915
+ if atomic_num in scheme:
916
+ color = self._get_color(tuple(scheme[atomic_num]))
917
+ else:
918
+ elem = get_element(atomic_num)
919
+ color = self._get_color(tuple(int(c * 255) for c in elem.cpk_color)) if elem else self._get_color(scheme["text_c"])
920
+
921
+ font = self._get_label_font()
922
+ p.setFont(font)
923
+ fm = QFontMetricsF(font)
924
+ tw = fm.horizontalAdvance(text) + 4.0 * self._zoom
925
+ th = fm.height() + 1.5 * self._zoom
926
+
927
+ bg_rect = QRectF(x - tw * 0.5, y - th * 0.5, tw, th)
928
+ p.setPen(Qt.PenStyle.NoPen)
929
+ p.setBrush(QBrush(self._get_color(scheme["bg"])))
930
+ p.drawRoundedRect(bg_rect, 5.0, 5.0)
931
+ p.setPen(color)
932
+ p.drawText(bg_rect, Qt.AlignmentFlag.AlignCenter, text)
933
+
934
+ def _draw_atom_number(self, p: QPainter, x: float, y: float, number: int):
935
+ """在原子右上角绘制随图缩放的轻量稳定编号。
936
+
937
+ 内部 AtomId 为 0-based,展示时统一 +1 为化学家习惯的 1-based,且与 3D 视图口径一致。
938
+ """
939
+ font = self._get_label_font()
940
+ small = QFont(font)
941
+ small.setPointSizeF(max(1.0, font.pointSizeF() * 0.72))
942
+ small.setBold(True)
943
+ p.setFont(small)
944
+ fm = QFontMetricsF(small)
945
+ txt = str(number + 1)
946
+ tw = fm.horizontalAdvance(txt) + 5.0
947
+ th = fm.height() + 1.0
948
+ # 角标定位在原子右上方,避免与中心元素标签重叠
949
+ bx = x + 11.0 * self._zoom
950
+ by = y - 13.0 * self._zoom
951
+ rect = QRectF(bx, by, tw, th)
952
+ p.setPen(self._get_color("#637587" if self._paper_mode else "#B5C4D2"))
953
+ p.drawText(rect, Qt.AlignmentFlag.AlignCenter, txt)
954
+
955
+ def _draw_selected_atom_badge(self, p: QPainter, x: float, y: float, number: int):
956
+ """为选中的原子绘制高对比度荧光青色编号徽标,即使未开启全局编号也能醒目标记出选中的原子序号。"""
957
+ txt = f"#{number}"
958
+ font = QFont("Microsoft YaHei UI", max(8, int(9.5 * self._zoom)), QFont.Weight.Bold)
959
+ p.setFont(font)
960
+ fm = QFontMetricsF(font)
961
+ tw = fm.horizontalAdvance(txt) + 6.0
962
+ th = fm.height() + 2.0
963
+ bx = x + 10.0 * self._zoom
964
+ by = y - 14.0 * self._zoom
965
+ rect = QRectF(bx, by, tw, th)
966
+
967
+ p.setPen(QPen(QColor("#5EEAD4"), 1.2))
968
+ p.setBrush(QBrush(QColor("#0D9488")))
969
+ p.drawRoundedRect(rect, 4.0, 4.0)
970
+
971
+ p.setPen(QColor("#FFFFFF"))
972
+ p.drawText(rect, Qt.AlignmentFlag.AlignCenter, txt)
973
+
974
+ def set_show_atom_numbers(self, on: bool):
975
+ """切换 2D 原子编号显示,并触发重绘。"""
976
+ self._show_atom_numbers = bool(on)
977
+ self.btn_toggle_num.blockSignals(True)
978
+ self.btn_toggle_num.setChecked(bool(on))
979
+ self.btn_toggle_num.blockSignals(False)
980
+ self.update()
981
+
982
+ # ---------- 拾取与生长辅助 ----------
983
+
984
+ def _find_atom_at(self, pos: QPointF, radius: float = 22.0) -> AtomId | None:
985
+ if self._document is None:
986
+ return None
987
+ coords = self._get_screen_coords()
988
+ if not coords:
989
+ return None
990
+ px, py = pos.x(), pos.y()
991
+ best_aid = None
992
+ best_dist = float("inf")
993
+ dyn_radius = max(radius, 16.0 * self._zoom)
994
+ font = self._get_label_font()
995
+ fm = QFontMetricsF(font)
996
+
997
+ for aid, (x, y) in coords.items():
998
+ if self._is_hidden_hydrogen(aid):
999
+ continue
1000
+ # 1. 如果原子有文本标签(如 CH4, OH, NH2 等),优先检测标签文字矩形包围盒
1001
+ atom = self._document.topology.get_atom(aid) if aid in self._document.topology._atoms else None
1002
+ if atom is not None:
1003
+ show_lbl, lbl_text = self._should_show_atom_label(aid)
1004
+ if show_lbl and lbl_text:
1005
+ tw = fm.horizontalAdvance(lbl_text) + 8.0 * self._zoom
1006
+ th = fm.height() + 4.0 * self._zoom
1007
+ l_rect = QRectF(x - tw * 0.5, y - th * 0.5, tw, th).adjusted(-6.0, -6.0, 6.0, 6.0)
1008
+ if l_rect.contains(pos):
1009
+ d = math.hypot(px - x, py - y)
1010
+ if d < best_dist:
1011
+ best_dist = d
1012
+ best_aid = aid
1013
+ continue
1014
+
1015
+ # 2. 距离圆检测(随视口缩放动态放大)
1016
+ d = math.hypot(px - x, py - y)
1017
+ if d <= dyn_radius and d < best_dist:
1018
+ best_dist = d
1019
+ best_aid = aid
1020
+ return best_aid
1021
+
1022
+ def _find_bond_at(self, pos: QPointF, tol: float = 9.0) -> BondId | None:
1023
+ if self._document is None:
1024
+ return None
1025
+ coords = self._get_screen_coords()
1026
+ best_bid = None
1027
+ best_d = tol
1028
+ for bid in list(self._document.topology.bond_ids):
1029
+ bond = self._document.topology.get_bond(bid)
1030
+ if self._is_hidden_hydrogen(bond.begin) or self._is_hidden_hydrogen(bond.end):
1031
+ continue
1032
+ if bond.begin in coords and bond.end in coords:
1033
+ x1, y1 = coords[bond.begin]
1034
+ x2, y2 = coords[bond.end]
1035
+ d = point_to_segment_dist(pos.x(), pos.y(), x1, y1, x2, y2)
1036
+ if d < best_d:
1037
+ best_d = d
1038
+ best_bid = bid
1039
+ return best_bid
1040
+
1041
+ def _suggest_2d_sprout_world_pos(self, anchor_id: AtomId, bond_len_a: float = 1.50) -> tuple[float, float]:
1042
+ """在 2D 世界坐标系 (Å) 中计算 120° 链生长点。"""
1043
+ wmap = self._ensure_world_coords_2d()
1044
+ if anchor_id not in wmap or self._document is None:
1045
+ return (0.0, 0.0)
1046
+ x0, y0 = wmap[anchor_id]
1047
+ nbrs = [
1048
+ n for n in self._document.topology.neighbors_of(anchor_id)
1049
+ if n in wmap and not self._is_hidden_hydrogen(n)
1050
+ ]
1051
+ if not nbrs:
1052
+ return (x0 + bond_len_a * math.cos(math.pi / 6), y0 + bond_len_a * math.sin(math.pi / 6))
1053
+ if len(nbrs) == 1:
1054
+ nx, ny = wmap[nbrs[0]]
1055
+ ang = math.atan2(y0 - ny, x0 - nx)
1056
+ turn = math.pi / 3 if (anchor_id.value % 2 == 0) else -math.pi / 3
1057
+ return (x0 + bond_len_a * math.cos(ang + turn), y0 + bond_len_a * math.sin(ang + turn))
1058
+ vx = sum(wmap[n][0] - x0 for n in nbrs)
1059
+ vy = sum(wmap[n][1] - y0 for n in nbrs)
1060
+ norm = math.hypot(vx, vy)
1061
+ if norm > 1e-4:
1062
+ return (x0 - (vx / norm) * bond_len_a, y0 - (vy / norm) * bond_len_a)
1063
+ return (x0 + bond_len_a, y0)
1064
+
1065
+ # ---------- 鼠标与滚轮交互 ----------
1066
+
1067
+ def wheelEvent(self, event: QWheelEvent):
1068
+ delta = event.angleDelta().y()
1069
+ factor = 1.12 if delta > 0 else (1.0 / 1.12)
1070
+ # 超宽无界缩放:0.5% ~ 5000% (10,000 倍动态范围),从超大纳米片/聚合物到单键局部自由缩放
1071
+ self._zoom = max(0.005, min(50.0, self._zoom * factor))
1072
+ if hasattr(self, "lbl_zoom"):
1073
+ self.lbl_zoom.setText(self._format_zoom_str())
1074
+ self.update()
1075
+
1076
+ def mousePressEvent(self, event: QMouseEvent):
1077
+ self.setFocus()
1078
+ if self._document is None:
1079
+ return
1080
+ if self._document.topology.num_atoms > 1500:
1081
+ if event.button() in (Qt.MouseButton.MiddleButton, Qt.MouseButton.LeftButton):
1082
+ self._panning = True
1083
+ self._pan_start = event.position()
1084
+ return
1085
+ pos = event.position()
1086
+ if pos.y() <= self.HEADER_HEIGHT:
1087
+ super().mousePressEvent(event)
1088
+ return
1089
+
1090
+ if event.button() == Qt.MouseButton.MiddleButton:
1091
+ self._panning = True
1092
+ self._pan_start = pos
1093
+ return
1094
+
1095
+ is_left = (event.button() == Qt.MouseButton.LeftButton)
1096
+ is_right = (event.button() == Qt.MouseButton.RightButton)
1097
+ add_mode = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
1098
+ space_pan = bool(event.modifiers() & Qt.KeyboardModifier.AltModifier) # Alt/空格+左键平移
1099
+
1100
+ # Alt+左键 或 中键 都可以平移画布
1101
+ if is_left and space_pan:
1102
+ self._panning = True
1103
+ self._pan_start = pos
1104
+ return
1105
+
1106
+ # 待放置环模板优先处理
1107
+ if is_left and self._pending_ring is not None:
1108
+ hit_a = self._find_atom_at(pos)
1109
+ wpos = self.screen_to_world(pos.x(), pos.y())
1110
+ self._add_ring_at(wpos, attach_to=hit_a)
1111
+ return
1112
+
1113
+ hit_atom = self._find_atom_at(pos)
1114
+ if hit_atom is not None:
1115
+ if is_left:
1116
+ if self._current_tool == "擦除":
1117
+ self._delete_atom(hit_atom)
1118
+ return
1119
+ already_in_multi = (
1120
+ not add_mode
1121
+ and self._current_tool == "选择"
1122
+ and self._selection is not None
1123
+ and len(self._selection.selected_atoms) > 1
1124
+ and hit_atom in self._selection.selected_atoms
1125
+ )
1126
+ self._keep_multi_on_press = already_in_multi
1127
+ self._batch_drag_hit_atom = hit_atom if already_in_multi else None
1128
+ if self._selection is not None and not already_in_multi:
1129
+ if add_mode:
1130
+ self._selection.toggle_atom(hit_atom, origin="2d")
1131
+ else:
1132
+ self._selection.select_atom(hit_atom, add=False, origin="2d")
1133
+ if self._current_tool == "选择" and self._document.topology.get_atom(hit_atom).properties.get("frozen"):
1134
+ self.atom_clicked.emit(hit_atom)
1135
+ return
1136
+ self._press_pos = QPointF(pos)
1137
+ self._dragging_bond = False
1138
+ if self._current_tool in ("键", "原子"):
1139
+ self._bond_start = hit_atom
1140
+ else:
1141
+ # 如果点中的原子已经在选中集合里,并且选中了多个原子,就批量拖动整个片段/分子
1142
+ if (self._selection is not None
1143
+ and len(self._selection.selected_atoms) > 1
1144
+ and hit_atom in self._selection.selected_atoms):
1145
+ self._batch_dragging = True
1146
+ self._batch_drag_start_screen = QPointF(pos)
1147
+ self._batch_drag_start_world = {
1148
+ aid: self._document.coords_2d.get(aid, (0, 0))
1149
+ for aid in self._selection.selected_atoms if not self._document.topology.get_atom(aid).properties.get("frozen")
1150
+ }
1151
+ else:
1152
+ self._drag_atom = hit_atom
1153
+ self._drag_start_wpos = self._document.coords_2d.get(hit_atom)
1154
+ self.atom_clicked.emit(hit_atom)
1155
+ elif is_right:
1156
+ self._show_atom_context_menu(pos, hit_atom)
1157
+ return
1158
+
1159
+ hit_bond = self._find_bond_at(pos)
1160
+ if hit_bond is not None:
1161
+ if is_left:
1162
+ if self._current_tool == "擦除":
1163
+ self._delete_bond(hit_bond)
1164
+ return
1165
+ if self._selection is not None:
1166
+ self._selection.select_bond(hit_bond, add=add_mode, origin="2d")
1167
+ # 只有在"键"工具模式下,点击键才改变键级
1168
+ if self._current_tool == "键":
1169
+ bond = self._document.topology.get_bond(hit_bond)
1170
+ next_order = (bond.order % 3) + 1
1171
+ if self._command_bus is not None:
1172
+ from ..application.builtin_commands import ChangeBondOrderCommand
1173
+ self._command_bus.execute(ChangeBondOrderCommand(hit_bond, next_order))
1174
+ elif is_right:
1175
+ self._show_bond_context_menu(pos, hit_bond)
1176
+ return
1177
+
1178
+ if is_left:
1179
+ self._marquee_start = QPointF(pos)
1180
+ self._marquee_rect = QRectF(pos, pos)
1181
+ elif is_right:
1182
+ self._show_canvas_context_menu(pos)
1183
+
1184
+ def mouseMoveEvent(self, event: QMouseEvent):
1185
+ pos = event.position()
1186
+ self._mouse_pos = pos
1187
+
1188
+ if self._panning:
1189
+ delta = pos - self._pan_start
1190
+ self._pan_x += delta.x()
1191
+ self._pan_y += delta.y()
1192
+ self._pan_start = pos
1193
+ self.update()
1194
+ return
1195
+
1196
+ if self._document is not None and self._document.topology.num_atoms > 1500:
1197
+ return
1198
+
1199
+ if self._marquee_start is not None:
1200
+ self._marquee_rect = QRectF(self._marquee_start, pos)
1201
+ self.update()
1202
+ return
1203
+
1204
+ # 批量拖动多个选中的原子
1205
+ if self._batch_dragging and self._document is not None:
1206
+ delta_screen = pos - self._batch_drag_start_screen
1207
+ # 屏幕 delta 转世界 delta
1208
+ scale = self.BASE_PX_PER_ANGSTROM * self._zoom
1209
+ dx_world = delta_screen.x() / scale
1210
+ dy_world = delta_screen.y() / scale
1211
+ for aid, (x0, y0) in self._batch_drag_start_world.items():
1212
+ if aid in self._document.coords_2d:
1213
+ self._document.coords_2d[aid] = (x0 + dx_world, y0 + dy_world)
1214
+ self.update()
1215
+ return
1216
+
1217
+ # 选择工具下拖动原子:实时更新 2D 世界坐标,丝滑无跳变
1218
+ if self._drag_atom is not None and self._document is not None:
1219
+ wpos = self.screen_to_world(pos.x(), pos.y())
1220
+ self._document.coords_2d[self._drag_atom] = wpos
1221
+ self.update()
1222
+ return
1223
+
1224
+ # 键/原子工具下拖动拉键:检测磁吸目标原子
1225
+ if self._bond_start is not None:
1226
+ if not self._dragging_bond and (pos - self._press_pos).manhattanLength() > 5:
1227
+ self._dragging_bond = True
1228
+ if self._dragging_bond:
1229
+ self._hover_atom = self._find_atom_at(pos, radius=22.0)
1230
+ self.update()
1231
+ return
1232
+
1233
+ old_ha, old_hb = self._hover_atom, self._hover_bond
1234
+ self._hover_atom = self._find_atom_at(pos)
1235
+ self._hover_bond = None if self._hover_atom is not None else self._find_bond_at(pos)
1236
+ if (self._hover_atom != old_ha) or (self._hover_bond != old_hb):
1237
+ self.update()
1238
+
1239
+ def mouseDoubleClickEvent(self, event: QMouseEvent):
1240
+ if self._document is None or self._selection is None or self._document.topology.num_atoms > 1500:
1241
+ return super().mouseDoubleClickEvent(event)
1242
+ if event.button() == Qt.MouseButton.LeftButton:
1243
+ hit_atom = self._find_atom_at(event.position())
1244
+ if hit_atom is not None:
1245
+ from collections import deque
1246
+ visited = {hit_atom}
1247
+ q = deque([hit_atom])
1248
+ while q:
1249
+ cur = q.popleft()
1250
+ for nb in self._document.topology.neighbors_of(cur):
1251
+ if nb not in visited:
1252
+ visited.add(nb)
1253
+ q.append(nb)
1254
+ add_mode = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
1255
+ final_aids = list(self._selection.selected_atoms | visited) if add_mode else list(visited)
1256
+ self._selection.select_atoms(final_aids, origin="2d")
1257
+ self.update()
1258
+ return
1259
+ super().mouseDoubleClickEvent(event)
1260
+
1261
+ def mouseReleaseEvent(self, event: QMouseEvent):
1262
+ if event.button() == Qt.MouseButton.MiddleButton:
1263
+ self._panning = False
1264
+ return
1265
+
1266
+ pos = event.position()
1267
+
1268
+ # 1. 空白处点击或框选释放
1269
+ if self._marquee_start is not None:
1270
+ rect = QRectF(self._marquee_start, pos).normalized()
1271
+ add_mode = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
1272
+ if rect.width() < 6 and rect.height() < 6:
1273
+ if self._current_tool in ("原子", "键") or (self._document is not None and self._document.num_atoms == 0):
1274
+ wpos = self.screen_to_world(pos.x(), pos.y())
1275
+ if self._current_tool == "键":
1276
+ # ChemDraw 标准:键工具点击空白画布,直接生成标准 C-C 键
1277
+ self._add_standard_bond_at_world(wpos)
1278
+ else:
1279
+ if self._current_tool == "选择":
1280
+ self._current_tool = "原子"
1281
+ self._update_tool_hint()
1282
+ self.tool_changed_signal.emit("原子")
1283
+ self._add_atom_at_world(wpos)
1284
+ elif not add_mode and self._selection is not None:
1285
+ self._selection.clear(origin="2d")
1286
+ else:
1287
+ self._apply_marquee(rect, add_mode)
1288
+ self._marquee_start = None
1289
+ self._marquee_rect = None
1290
+ self.update()
1291
+ return
1292
+
1293
+ # 2. 批量拖动多个原子释放 -> 同步更新 3D 坐标并提交单步 MoveMultiAtoms3DCommand
1294
+ if getattr(self, "_batch_dragging", False):
1295
+ self._batch_dragging = False
1296
+ keep_multi = getattr(self, "_keep_multi_on_press", False)
1297
+ hit_multi_aid = getattr(self, "_batch_drag_hit_atom", None)
1298
+ self._keep_multi_on_press = False
1299
+ self._batch_drag_hit_atom = None
1300
+ moved_dist = (pos - self._press_pos).manhattanLength()
1301
+ if moved_dist < 4 and keep_multi and hit_multi_aid is not None and self._selection is not None:
1302
+ # 仅点击未拖动:恢复坐标并把多选收敛到所点原子
1303
+ for aid, xy in (getattr(self, "_batch_drag_start_world", None) or {}).items():
1304
+ if self._document is not None and aid in self._document.coords_2d:
1305
+ self._document.coords_2d[aid] = xy
1306
+ self._selection.select_atom(hit_multi_aid, add=False, origin="2d")
1307
+ self.update()
1308
+ return
1309
+ if moved_dist >= 4 and self._document is not None and self._command_bus is not None and getattr(self, "_batch_drag_start_world", None):
1310
+ from ..application.builtin_commands import MoveMultiAtoms3DCommand
1311
+ old_3d_map = {}
1312
+ new_3d_map = {}
1313
+ for aid, (ox, oy) in self._batch_drag_start_world.items():
1314
+ if aid in self._document.topology._atoms:
1315
+ nx, ny = self._document.coords_2d.get(aid, (ox, oy))
1316
+ p3 = self._document.get_atom_3d_pos(aid)
1317
+ cz = float(p3[2]) if p3 is not None else 0.0
1318
+ old_3d_map[aid] = p3 if p3 is not None else np.array([ox, oy, cz], dtype=np.float32)
1319
+ new_3d_map[aid] = np.array([nx, ny, cz], dtype=np.float32)
1320
+ if old_3d_map:
1321
+ new_2d_map = {
1322
+ aid: self._document.coords_2d[aid]
1323
+ for aid in self._batch_drag_start_world
1324
+ if aid in self._document.coords_2d
1325
+ }
1326
+ self._command_bus.execute(
1327
+ MoveMultiAtoms3DCommand(
1328
+ old_3d_map,
1329
+ new_3d_map,
1330
+ description="批量平移选中原子",
1331
+ old_coords_2d=self._batch_drag_start_world,
1332
+ new_coords_2d=new_2d_map,
1333
+ )
1334
+ )
1335
+ self.update()
1336
+ return
1337
+
1338
+ # 3. 拖动原子释放 -> 同步更新 3D 坐标并入撤销栈
1339
+ if self._drag_atom is not None:
1340
+ aid = self._drag_atom
1341
+ old_2d = self._drag_start_wpos
1342
+ self._drag_atom = None
1343
+ self._drag_start_wpos = None
1344
+ if (pos - self._press_pos).manhattanLength() >= 3 and self._document is not None:
1345
+ wx, wy = self.screen_to_world(pos.x(), pos.y())
1346
+ old_3d = self._document.get_atom_3d_pos(aid)
1347
+ cur_z = float(old_3d[2]) if old_3d is not None else 0.0
1348
+ if self._command_bus is not None and old_3d is not None:
1349
+ from ..application.builtin_commands import MoveAtom3DCommand
1350
+ self._command_bus.execute(
1351
+ MoveAtom3DCommand(aid, (wx, wy, cur_z), old_pos=old_3d, new_pos_2d=(wx, wy), old_pos_2d=old_2d)
1352
+ )
1353
+ self.update()
1354
+ return
1355
+
1356
+ # 3. 画键或生长新键释放
1357
+ if self._bond_start is not None:
1358
+ start_aid = self._bond_start
1359
+ was_dragging = self._dragging_bond
1360
+ self._bond_start = None
1361
+ self._dragging_bond = False
1362
+ if was_dragging:
1363
+ target = self._find_atom_at(pos, radius=22.0)
1364
+ if target is not None and target != start_aid:
1365
+ self._add_bond(start_aid, target)
1366
+ elif target is None:
1367
+ wpos = self.screen_to_world(pos.x(), pos.y())
1368
+ # ChemDraw 标准:拖出化学键时,对角度按 30° 吸附,对键长按标准 1.50 Å 吸附
1369
+ wmap = self._ensure_world_coords_2d()
1370
+ if start_aid in wmap:
1371
+ sx_w, sy_w = wmap[start_aid]
1372
+ dx, dy = wpos[0] - sx_w, wpos[1] - sy_w
1373
+ dist = math.hypot(dx, dy)
1374
+ if dist > 0.3:
1375
+ ang = math.atan2(dy, dx)
1376
+ # 吸附到最接近的 30° 倍数 (k * pi / 6)
1377
+ snap_ang = round(ang / (math.pi / 6.0)) * (math.pi / 6.0)
1378
+ snap_len = 1.50 if (0.75 <= dist <= 2.25) else dist
1379
+ wpos = (sx_w + snap_len * math.cos(snap_ang), sy_w + snap_len * math.sin(snap_ang))
1380
+ self._add_atom_at_world(wpos, bond_to=start_aid)
1381
+ else:
1382
+ atom = self._document.topology.get_atom(start_aid)
1383
+ if self._current_tool == "原子":
1384
+ # 原子工具点击原子:如果元素不同则切换元素;若相同则仅选中,绝不无故发芽!
1385
+ if atom.atomic_num != self._current_element:
1386
+ from ..application.builtin_commands import ChangeElementCommand
1387
+ if self._command_bus is not None:
1388
+ self._command_bus.execute(ChangeElementCommand(start_aid, self._current_element))
1389
+ elif self._selection is not None:
1390
+ self._selection.select_atom(start_aid, add=False, origin="2d")
1391
+ elif self._current_tool == "键":
1392
+ # 键工具点击原子:ChemDraw 标准发芽生长!
1393
+ sprout_wpos = self._suggest_2d_sprout_world_pos(start_aid)
1394
+ self._add_atom_at_world(sprout_wpos, bond_to=start_aid)
1395
+ self.update()
1396
+
1397
+ # ---------- 命令执行 ----------
1398
+
1399
+ def _add_ring_at(self, center_wpos: tuple[float, float], attach_to: AtomId | None = None):
1400
+ if self._command_bus is None or self._pending_ring is None:
1401
+ return
1402
+ from ..application.builtin_commands import AddRingCommand
1403
+ size, aromatic, hetero = self._pending_ring
1404
+ self._pending_ring = None
1405
+ self._update_tool_hint()
1406
+ self._command_bus.execute(
1407
+ AddRingCommand(
1408
+ size=size, aromatic=aromatic, hetero_atoms=hetero,
1409
+ center_2d=center_wpos, center_3d=(center_wpos[0], center_wpos[1], 0.0),
1410
+ attach_to=attach_to,
1411
+ )
1412
+ )
1413
+ self.update()
1414
+
1415
+ def _add_atom_at_world(self, wpos: tuple[float, float], bond_to: AtomId | None = None) -> AtomId | None:
1416
+ if self._command_bus is None:
1417
+ return None
1418
+ from ..application.builtin_commands import AddAtomCommand
1419
+ wx, wy = float(wpos[0]), float(wpos[1])
1420
+
1421
+ # 保护:若未指定成键目标,且点击位置距离已有可见原子极其接近 (< 0.70 Å),避免重叠生成孤立原子
1422
+ if bond_to is None and self._document is not None and self._document.coords_2d:
1423
+ for aid, (ox, oy) in self._document.coords_2d.items():
1424
+ if aid in self._document.topology._atoms and not self._is_hidden_hydrogen(aid):
1425
+ if math.hypot(wx - ox, wy - oy) < 0.70:
1426
+ return aid
1427
+ z_val = 0.0
1428
+ if bond_to is not None and self._document is not None:
1429
+ p3 = self._document.get_atom_3d_pos(bond_to)
1430
+ if p3 is not None:
1431
+ z_val = float(p3[2])
1432
+ cmd = AddAtomCommand(
1433
+ self._current_element, x=wx, y=wy, z=z_val, bond_to=bond_to, pos_2d=(wx, wy)
1434
+ )
1435
+ result = self._command_bus.execute(cmd)
1436
+ if result.success:
1437
+ aid = AtomId(result.data["atom_id"])
1438
+ if self._document is not None:
1439
+ self._document.coords_2d[aid] = (wx, wy)
1440
+ self.update()
1441
+ return aid
1442
+ return None
1443
+
1444
+ def _add_standard_bond_at_world(self, wpos: tuple[float, float]) -> tuple[AtomId | None, AtomId | None]:
1445
+ """在空白处按 ChemDraw 标准创建一条标准 C-C 单键(乙烷式基元:30° 角,键长 1.50 Å)。"""
1446
+ if self._command_bus is None or self._document is None:
1447
+ return None, None
1448
+ wx, wy = float(wpos[0]), float(wpos[1])
1449
+ bond_len = 1.50
1450
+ angle = math.pi / 6.0 # 30°
1451
+ wpos2 = (wx + bond_len * math.cos(angle), wy + bond_len * math.sin(angle))
1452
+
1453
+ a1 = self._add_atom_at_world((wx, wy))
1454
+ if a1 is not None:
1455
+ a2 = self._add_atom_at_world(wpos2, bond_to=a1)
1456
+ return a1, a2
1457
+ return None, None
1458
+
1459
+ def _add_bond(self, a: AtomId, b: AtomId):
1460
+ if self._command_bus is None or self._document is None:
1461
+ return
1462
+ from ..application.builtin_commands import AddBondCommand, ChangeBondOrderCommand
1463
+ existing = self._document.topology.bond_between(a, b)
1464
+ if existing is not None:
1465
+ cur_order = self._document.topology.get_bond(existing).order
1466
+ self._command_bus.execute(ChangeBondOrderCommand(existing, (cur_order % 3) + 1))
1467
+ else:
1468
+ self._command_bus.execute(AddBondCommand(a, b, 1))
1469
+ self.update()
1470
+
1471
+ def _delete_atom(self, aid: AtomId):
1472
+ if self._command_bus is None:
1473
+ return
1474
+ from ..application.builtin_commands import DeleteAtomCommand
1475
+ self._command_bus.execute(DeleteAtomCommand(aid))
1476
+ self.update()
1477
+
1478
+ def _delete_bond(self, bid: BondId):
1479
+ if self._command_bus is None:
1480
+ return
1481
+ from ..application.builtin_commands import DeleteBondCommand
1482
+ self._command_bus.execute(DeleteBondCommand(bid))
1483
+ self.update()
1484
+
1485
+ def _apply_marquee(self, rect: QRectF, add: bool):
1486
+ """
1487
+ 框选原子:在隐式氢模式下,框选骨架重原子时自动连带选中其挂接的所有隐式氢原子(修复 P0 Bug 3)!
1488
+ 同时自动选中两端原子均在选中集内的化学键。
1489
+ """
1490
+ if self._selection is None or self._document is None:
1491
+ return
1492
+ coords = self._get_screen_coords()
1493
+ hits: set[AtomId] = {
1494
+ aid for aid, (x, y) in coords.items()
1495
+ if rect.contains(QPointF(x, y))
1496
+ }
1497
+ # 连带纳入所有已命中重原子相连的氢原子(即便在隐式氢模式下未单独绘制)
1498
+ attached_h: set[AtomId] = set()
1499
+ for aid in list(hits):
1500
+ for nb in self._document.topology.neighbors_of(aid):
1501
+ if nb in self._document.topology._atoms and self._document.topology.get_atom(nb).atomic_num == 1:
1502
+ attached_h.add(nb)
1503
+ hits |= attached_h
1504
+
1505
+ if not add:
1506
+ self._selection.clear(origin="2d")
1507
+ if hits:
1508
+ self._selection.select_atoms(hits | (self._selection.selected_atoms if add else set()), origin="2d")
1509
+ # 同步选中两端原子均被选中的化学键
1510
+ all_sel = self._selection.selected_atoms
1511
+ for bid in self._document.topology.bond_ids:
1512
+ b = self._document.topology.get_bond(bid)
1513
+ if b.begin in all_sel and b.end in all_sel:
1514
+ self._selection.select_bond(bid, add=True, origin="2d")
1515
+ self.update()
1516
+
1517
+ def delete_selected(self) -> int:
1518
+ """删除当前选中的所有化学键与原子(连带相连氢原子),完美解决 P0 Bug 2 & Bug 4。"""
1519
+ if self._selection is None or self._document is None or self._command_bus is None:
1520
+ return 0
1521
+ sel_bonds = list(self._selection.selected_bonds)
1522
+ sel_atoms = list(self._selection.selected_atoms)
1523
+ if not sel_bonds and not sel_atoms:
1524
+ return 0
1525
+ from ..application.selection_commands import DeleteSelectionCommand
1526
+ result = self._command_bus.execute(DeleteSelectionCommand(sel_atoms, sel_bonds))
1527
+ count = len(sel_atoms) + len(sel_bonds) if result.success else 0
1528
+ self._selection.clear(origin="2d")
1529
+ self.update()
1530
+ return count
1531
+
1532
+ def _show_atom_context_menu(self, pos: QPointF, atom_id: AtomId):
1533
+ """原子右键上下文菜单(支持单原子操作与多选批量删除)。"""
1534
+ from PyQt6.QtWidgets import QMenu
1535
+ menu = QMenu(self)
1536
+ menu.setStyleSheet("QMenu { font-size: 13px; padding: 4px; } QMenu::item { padding: 6px 24px; }")
1537
+
1538
+ atom = self._document.topology.get_atom(atom_id)
1539
+ elem = get_element(atom.atomic_num)
1540
+ sym = elem.symbol if elem else "C"
1541
+
1542
+ title = menu.addAction(f"原子 #{atom_id.value+1} ({sym})")
1543
+ title.setEnabled(False)
1544
+ menu.addSeparator()
1545
+
1546
+ if self._selection is not None and len(self._selection.selected_atoms) > 1:
1547
+ n_sel = len(self._selection.selected_atoms)
1548
+ menu.addAction(f"🗑️ 删除选中的 {n_sel} 个原子 (Delete)", self.delete_selected)
1549
+ menu.addSeparator()
1550
+
1551
+ menu.addAction("删除该原子", lambda: self._delete_atom(atom_id))
1552
+ menu.addAction("删除连通基团", lambda: self._delete_connected_fragment(atom_id))
1553
+ menu.addSeparator()
1554
+
1555
+ elem_menu = menu.addMenu("改为元素")
1556
+ for s_lbl, z in [("C", 6), ("N", 7), ("O", 8), ("S", 16), ("F", 9), ("Cl", 17), ("Br", 35), ("P", 15), ("H", 1)]:
1557
+ elem_menu.addAction(s_lbl, lambda _=False, zv=z, aid=atom_id: self._change_element(aid, zv))
1558
+ menu.addSeparator()
1559
+
1560
+ elem_menu.addSeparator()
1561
+ elem_menu.addAction("完整118元素周期表…", lambda: self._pick_context_element(atom_id))
1562
+ from .modeling_actions import add_modeling_actions
1563
+ add_modeling_actions(self, menu, atom_id)
1564
+ menu.addAction("复制坐标到剪贴板", lambda: self._copy_atom_coord(atom_id))
1565
+ menu.exec(self.mapToGlobal(pos.toPoint()))
1566
+
1567
+ def _pick_context_element(self, atom_id):
1568
+ from .element_picker import ElementPickerDialog
1569
+ dialog = ElementPickerDialog(self, compact=True)
1570
+ if dialog.exec() and dialog.selected_element:
1571
+ self._change_element(atom_id, dialog.selected_element.atomic_number)
1572
+
1573
+ def _show_bond_context_menu(self, pos: QPointF, bond_id: BondId):
1574
+ """化学键右键上下文菜单"""
1575
+ from PyQt6.QtWidgets import QMenu
1576
+ menu = QMenu(self)
1577
+ menu.setStyleSheet("QMenu { font-size: 13px; padding: 4px; } QMenu::item { padding: 6px 24px; }")
1578
+
1579
+ bond = self._document.topology.get_bond(bond_id)
1580
+ order_names = {1: "单键", 2: "双键", 3: "三键", 4: "芳香键"}
1581
+
1582
+ title = menu.addAction(f"键 #{bond_id.value} ({order_names.get(bond.order, '未知')})")
1583
+ title.setEnabled(False)
1584
+ menu.addSeparator()
1585
+
1586
+ if self._selection is not None and len(self._selection.selected_atoms) > 0:
1587
+ menu.addAction(f"🗑️ 删除选中项 (Delete)", self.delete_selected)
1588
+ menu.addSeparator()
1589
+
1590
+ menu.addAction("删除该化学键", lambda: self._delete_bond(bond_id))
1591
+ menu.addSeparator()
1592
+
1593
+ order_menu = menu.addMenu("切换键级")
1594
+ for order, name in [(1, "单键"), (2, "双键"), (3, "三键"), (4, "芳香")]:
1595
+ order_menu.addAction(name, lambda _=False, o=order, bid=bond_id: self._set_bond_order(bid, o))
1596
+ from .modeling_actions import add_modeling_actions
1597
+ add_modeling_actions(self, menu, bond_id=bond_id)
1598
+
1599
+ menu.exec(self.mapToGlobal(pos.toPoint()))
1600
+
1601
+ def _show_canvas_context_menu(self, pos: QPointF):
1602
+ """空白处右键上下文菜单(含框选后“删除选中原子”项,修复 P0 Bug 2)。"""
1603
+ from PyQt6.QtWidgets import QMenu
1604
+ menu = QMenu(self)
1605
+ menu.setStyleSheet("QMenu { font-size: 13px; padding: 4px; } QMenu::item { padding: 6px 24px; }")
1606
+
1607
+ # 若当前有框选或点选的原子/化学键,第一项直接提供「删除选中原子/键」
1608
+ if self._selection is not None and (len(self._selection.selected_atoms) > 0 or len(self._selection.selected_bonds) > 0):
1609
+ n_a = len(self._selection.selected_atoms)
1610
+ n_b = len(self._selection.selected_bonds)
1611
+ del_act = menu.addAction(f"🗑️ 删除选中 ({n_a} 个原子, {n_b} 条键) [Delete]")
1612
+ del_act.triggered.connect(self.delete_selected)
1613
+ menu.addSeparator()
1614
+
1615
+ if self._command_bus is not None:
1616
+ undo_action = menu.addAction("撤销 (Ctrl+Z)")
1617
+ undo_action.triggered.connect(self._command_bus.undo)
1618
+ redo_action = menu.addAction("重做 (Ctrl+Y)")
1619
+ redo_action.triggered.connect(self._command_bus.redo)
1620
+ menu.addSeparator()
1621
+
1622
+ menu.addAction("在此处添加当前元素原子", lambda: self._add_atom_at_world(self.screen_to_world(pos.x(), pos.y())))
1623
+ menu.addAction("清洁 2D 结构布局", self._clean_structure)
1624
+ menu.addAction("居中适配视图", self._center_view)
1625
+ menu.addSeparator()
1626
+
1627
+ menu.addAction("全选所有原子(含隐式氢) (Ctrl+A)", self._select_all)
1628
+ menu.addAction("取消全选", self._deselect_all)
1629
+
1630
+ menu.exec(self.mapToGlobal(pos.toPoint()))
1631
+
1632
+ def _change_element(self, atom_id: AtomId, new_z: int):
1633
+ """修改原子元素类型(通过 ChangeElementCommand 支持 Undo/Redo)。"""
1634
+ if self._document is None or atom_id not in self._document.topology._atoms:
1635
+ return
1636
+ atom = self._document.topology.get_atom(atom_id)
1637
+ if atom.atomic_num == new_z:
1638
+ return
1639
+ if self._command_bus is not None:
1640
+ from ..application.builtin_commands import ChangeElementCommand
1641
+ self._command_bus.execute(ChangeElementCommand(atom_id, new_z))
1642
+ else:
1643
+ atom.atomic_num = new_z
1644
+ self.update()
1645
+
1646
+ def _set_bond_order(self, bond_id: BondId, order: int):
1647
+ """设置键级"""
1648
+ if self._document is None or bond_id not in self._document.topology._bonds:
1649
+ return
1650
+ bond = self._document.topology.get_bond(bond_id)
1651
+ if bond.order == order:
1652
+ return
1653
+ if self._command_bus is not None:
1654
+ from ..application.builtin_commands import ChangeBondOrderCommand
1655
+ self._command_bus.execute(ChangeBondOrderCommand(bond_id, order))
1656
+ self.update()
1657
+
1658
+ def _delete_connected_fragment(self, seed_atom: AtomId):
1659
+ """删除从 seed_atom 开始的连通基团"""
1660
+ if self._document is None:
1661
+ return
1662
+ from PyQt6.QtWidgets import QMessageBox
1663
+ visited: set[AtomId] = set()
1664
+ stack = [seed_atom]
1665
+ while stack:
1666
+ aid = stack.pop()
1667
+ if aid in visited:
1668
+ continue
1669
+ visited.add(aid)
1670
+ for neighbor in self._document.topology.neighbors_of(aid):
1671
+ if neighbor not in visited:
1672
+ stack.append(neighbor)
1673
+
1674
+ reply = QMessageBox.question(
1675
+ self, "删除基团",
1676
+ f"将删除 {len(visited)} 个原子组成的连通基团,确认?",
1677
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
1678
+ )
1679
+ if reply != QMessageBox.StandardButton.Yes:
1680
+ return
1681
+
1682
+ for aid in sorted(visited, key=lambda a: a.value, reverse=True):
1683
+ if aid in self._document.topology._atoms:
1684
+ self._delete_atom(aid)
1685
+ self.update()
1686
+
1687
+ def _copy_atom_coord(self, atom_id: AtomId):
1688
+ """复制原子坐标到剪贴板"""
1689
+ if self._document is None:
1690
+ return
1691
+ coord = self._document.coords_2d.get(atom_id)
1692
+ if coord:
1693
+ from PyQt6.QtWidgets import QApplication
1694
+ QApplication.clipboard().setText(f"{coord[0]:.4f}, {coord[1]:.4f}")
1695
+
1696
+ def _clean_structure(self):
1697
+ self.recompute_2d_layout()
1698
+
1699
+ def _center_view(self):
1700
+ self.fit_view()
1701
+
1702
+ def _select_all(self):
1703
+ """全选所有原子(包含隐式氢与全部化学键,修复 P0 Bug 3)。"""
1704
+ if self._selection is not None and self._document is not None:
1705
+ all_aids = set(self._document.topology.atom_ids)
1706
+ self._selection.select_atoms(all_aids, origin="2d")
1707
+ for bid in self._document.topology.bond_ids:
1708
+ self._selection.select_bond(bid, add=True, origin="2d")
1709
+ self.update()
1710
+
1711
+ def _deselect_all(self):
1712
+ """取消全选"""
1713
+ if self._selection is not None:
1714
+ self._selection.clear(origin="2d")
1715
+ self.update()
1716
+
1717
+ def doubleClickEvent(self, event):
1718
+ pos = event.position()
1719
+ if pos.y() <= self.HEADER_HEIGHT:
1720
+ return
1721
+ hit = self._find_atom_at(pos)
1722
+ if hit is not None and self._selection is not None:
1723
+ self._selection.select_atom(hit, origin="2d")
1724
+ self.atom_double_clicked.emit(hit)
1725
+ elif hit is None:
1726
+ wpos = self.screen_to_world(pos.x(), pos.y())
1727
+ self._add_atom_at_world(wpos)
1728
+
1729
+ _ELEMENT_KEYS = {
1730
+ "c": 6, "n": 7, "o": 8, "s": 16, "p": 15,
1731
+ "f": 9, "i": 53, "h": 1,
1732
+ }
1733
+
1734
+ def keyPressEvent(self, event):
1735
+ key = event.key()
1736
+ text = event.text().lower()
1737
+
1738
+ if event.modifiers() & Qt.KeyboardModifier.ControlModifier:
1739
+ if key == Qt.Key.Key_A:
1740
+ self._select_all()
1741
+ event.accept()
1742
+ return
1743
+ if key == Qt.Key.Key_Z:
1744
+ if self._command_bus is not None:
1745
+ if event.modifiers() & Qt.KeyboardModifier.ShiftModifier:
1746
+ self._command_bus.redo()
1747
+ else:
1748
+ self._command_bus.undo()
1749
+ event.accept()
1750
+ self.update()
1751
+ return
1752
+ if key == Qt.Key.Key_Y:
1753
+ if self._command_bus is not None:
1754
+ self._command_bus.redo()
1755
+ event.accept()
1756
+ self.update()
1757
+ return
1758
+ super().keyPressEvent(event)
1759
+ return
1760
+
1761
+ if key in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace):
1762
+ self.delete_selected()
1763
+ event.accept()
1764
+ return
1765
+
1766
+ if text == "0" or key == Qt.Key.Key_Space:
1767
+ self.fit_view()
1768
+ event.accept()
1769
+ return
1770
+
1771
+ if text in self._ELEMENT_KEYS:
1772
+ z = self._ELEMENT_KEYS[text]
1773
+ # ChemDraw 标准:光标悬停在原子上或已选中原子时,按快捷键直接修改该原子的元素!
1774
+ target_aids = []
1775
+ if self._hover_atom is not None:
1776
+ target_aids = [self._hover_atom]
1777
+ elif self._selection is not None and self._selection.selected_atoms:
1778
+ target_aids = list(self._selection.selected_atoms)
1779
+
1780
+ if target_aids and self._command_bus is not None:
1781
+ from ..application.builtin_commands import ChangeElementCommand
1782
+ for target_aid in target_aids:
1783
+ self._command_bus.execute(ChangeElementCommand(target_aid, z))
1784
+ self.update()
1785
+ return
1786
+
1787
+ self._current_element = z
1788
+ self._current_tool = "原子"
1789
+ self._update_tool_hint()
1790
+ self.element_changed_signal.emit(z)
1791
+ self.tool_changed_signal.emit("原子")
1792
+ self.update()
1793
+ return
1794
+
1795
+ for k_char, t_name in (("v", "选择"), ("b", "键"), ("a", "原子"), ("e", "擦除")):
1796
+ if text == k_char:
1797
+ self._current_tool = t_name
1798
+ self._update_tool_hint()
1799
+ self.tool_changed_signal.emit(t_name)
1800
+ self.update()
1801
+ return
1802
+
1803
+ super().keyPressEvent(event)