pycforge 0.15.2__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 (221) hide show
  1. pycforge/__init__.py +8 -0
  2. pycforge/__main__.py +2 -0
  3. pycforge/_version.py +1 -0
  4. pycforge/converter/__init__.py +0 -0
  5. pycforge/converter/analysis/__init__.py +5 -0
  6. pycforge/converter/analysis/functions.py +723 -0
  7. pycforge/converter/analysis/model.py +158 -0
  8. pycforge/converter/analysis/planning.py +464 -0
  9. pycforge/converter/analysis/stage.py +1976 -0
  10. pycforge/converter/analysis/symbols.py +237 -0
  11. pycforge/converter/analysis/validation.py +2166 -0
  12. pycforge/converter/c_output/__init__.py +2 -0
  13. pycforge/converter/c_output/conformance.py +297 -0
  14. pycforge/converter/c_output/renderer.py +220 -0
  15. pycforge/converter/conditional_regions/__init__.py +71 -0
  16. pycforge/converter/conditional_regions/analysis.py +481 -0
  17. pycforge/converter/conditional_regions/lowering.py +579 -0
  18. pycforge/converter/conditional_regions/model.py +243 -0
  19. pycforge/converter/conditional_regions/validation.py +690 -0
  20. pycforge/converter/containers/__init__.py +19 -0
  21. pycforge/converter/containers/analysis.py +542 -0
  22. pycforge/converter/containers/lowering.py +290 -0
  23. pycforge/converter/containers/model.py +146 -0
  24. pycforge/converter/contracts/__init__.py +0 -0
  25. pycforge/converter/contracts/configuration.py +178 -0
  26. pycforge/converter/contracts/identifiers.py +68 -0
  27. pycforge/converter/contracts/versions.py +71 -0
  28. pycforge/converter/core/__init__.py +0 -0
  29. pycforge/converter/core/artifact_io.py +87 -0
  30. pycforge/converter/core/cancellation.py +7 -0
  31. pycforge/converter/core/canonicalization.py +254 -0
  32. pycforge/converter/core/context.py +13 -0
  33. pycforge/converter/core/diagnostics.py +95 -0
  34. pycforge/converter/core/enums.py +23 -0
  35. pycforge/converter/core/fingerprint.py +22 -0
  36. pycforge/converter/core/pipeline.py +8 -0
  37. pycforge/converter/core/progress.py +25 -0
  38. pycforge/converter/core/request.py +50 -0
  39. pycforge/converter/core/resource_policy.py +31 -0
  40. pycforge/converter/core/result.py +23 -0
  41. pycforge/converter/core/serialization.py +36 -0
  42. pycforge/converter/core/stage.py +10 -0
  43. pycforge/converter/core/stage_artifact.py +80 -0
  44. pycforge/converter/core/stage_outcome.py +15 -0
  45. pycforge/converter/decision_trace/__init__.py +0 -0
  46. pycforge/converter/decision_trace/recorder.py +52 -0
  47. pycforge/converter/facade.py +459 -0
  48. pycforge/converter/frontend/__init__.py +4 -0
  49. pycforge/converter/frontend/normalizer.py +59 -0
  50. pycforge/converter/frontend/parser.py +20 -0
  51. pycforge/converter/frontend/source_document.py +93 -0
  52. pycforge/converter/frontend/stages.py +518 -0
  53. pycforge/converter/frontend/validation.py +76 -0
  54. pycforge/converter/io/__init__.py +0 -0
  55. pycforge/converter/io/atomic_writer.py +33 -0
  56. pycforge/converter/ir/__init__.py +1 -0
  57. pycforge/converter/ir/c_ir/__init__.py +4 -0
  58. pycforge/converter/ir/c_ir/builder.py +26 -0
  59. pycforge/converter/ir/c_ir/model.py +318 -0
  60. pycforge/converter/ir/c_ir/serialization.py +88 -0
  61. pycforge/converter/ir/c_ir/validation.py +834 -0
  62. pycforge/converter/ir/python_ir/__init__.py +17 -0
  63. pycforge/converter/ir/python_ir/nodes.py +86 -0
  64. pycforge/converter/keyword_calls/__init__.py +68 -0
  65. pycforge/converter/keyword_calls/analysis.py +458 -0
  66. pycforge/converter/keyword_calls/lowering.py +271 -0
  67. pycforge/converter/keyword_calls/model.py +304 -0
  68. pycforge/converter/keyword_calls/validation.py +802 -0
  69. pycforge/converter/keyword_only_calls/__init__.py +68 -0
  70. pycforge/converter/keyword_only_calls/analysis.py +640 -0
  71. pycforge/converter/keyword_only_calls/lowering.py +376 -0
  72. pycforge/converter/keyword_only_calls/model.py +328 -0
  73. pycforge/converter/keyword_only_calls/validation.py +1357 -0
  74. pycforge/converter/lowering.py +1000 -0
  75. pycforge/converter/modules/__init__.py +13 -0
  76. pycforge/converter/modules/analysis.py +1250 -0
  77. pycforge/converter/modules/lowering.py +200 -0
  78. pycforge/converter/modules/model.py +73 -0
  79. pycforge/converter/modules/stage.py +192 -0
  80. pycforge/converter/numeric_semantics/__init__.py +23 -0
  81. pycforge/converter/numeric_semantics/analysis.py +420 -0
  82. pycforge/converter/numeric_semantics/lowering.py +153 -0
  83. pycforge/converter/numeric_semantics/model.py +123 -0
  84. pycforge/converter/records/__init__.py +34 -0
  85. pycforge/converter/records/analysis.py +1394 -0
  86. pycforge/converter/records/lowering.py +393 -0
  87. pycforge/converter/records/model.py +319 -0
  88. pycforge/converter/rules/__init__.py +3 -0
  89. pycforge/converter/support_templates/__init__.py +49 -0
  90. pycforge/converter/support_templates/assembly.py +106 -0
  91. pycforge/converter/support_templates/factories.py +348 -0
  92. pycforge/converter/support_templates/model.py +159 -0
  93. pycforge/converter/support_templates/registry.py +388 -0
  94. pycforge/converter/telemetry/__init__.py +0 -0
  95. pycforge/converter/telemetry/sink.py +39 -0
  96. pycforge/ide/__init__.py +19 -0
  97. pycforge/ide/__main__.py +5 -0
  98. pycforge/ide/_worker_event_codec.py +276 -0
  99. pycforge/ide/_worker_protocol_json.py +197 -0
  100. pycforge/ide/_worker_protocol_types.py +90 -0
  101. pycforge/ide/_worker_request_codec.py +200 -0
  102. pycforge/ide/_worker_request_data.py +260 -0
  103. pycforge/ide/_worker_result_data.py +343 -0
  104. pycforge/ide/action_contract.py +469 -0
  105. pycforge/ide/action_validation.py +229 -0
  106. pycforge/ide/command_palette.py +223 -0
  107. pycforge/ide/controller.py +904 -0
  108. pycforge/ide/controller_conversion.py +546 -0
  109. pycforge/ide/controller_io.py +205 -0
  110. pycforge/ide/editor.py +951 -0
  111. pycforge/ide/editor_commands_qt.py +274 -0
  112. pycforge/ide/editor_lexical.py +43 -0
  113. pycforge/ide/editor_sidebars.py +236 -0
  114. pycforge/ide/editor_syntax.py +243 -0
  115. pycforge/ide/find_replace.py +535 -0
  116. pycforge/ide/icons.py +91 -0
  117. pycforge/ide/io_service.py +196 -0
  118. pycforge/ide/model.py +164 -0
  119. pycforge/ide/panels.py +903 -0
  120. pycforge/ide/positions.py +220 -0
  121. pycforge/ide/process_worker.py +130 -0
  122. pycforge/ide/qt.py +230 -0
  123. pycforge/ide/qt_actions.py +418 -0
  124. pycforge/ide/qt_close.py +169 -0
  125. pycforge/ide/qt_command_palette.py +297 -0
  126. pycforge/ide/qt_contract.py +220 -0
  127. pycforge/ide/qt_documents.py +590 -0
  128. pycforge/ide/qt_editor_buffers.py +113 -0
  129. pycforge/ide/qt_editor_surfaces.py +112 -0
  130. pycforge/ide/qt_menus.py +324 -0
  131. pycforge/ide/qt_projection.py +500 -0
  132. pycforge/ide/qt_shell.py +348 -0
  133. pycforge/ide/qt_shell_interactions.py +320 -0
  134. pycforge/ide/qt_state.py +393 -0
  135. pycforge/ide/qt_workspace_features.py +398 -0
  136. pycforge/ide/qt_workspace_navigation.py +208 -0
  137. pycforge/ide/qt_workspace_observers.py +173 -0
  138. pycforge/ide/qt_workspace_panels.py +545 -0
  139. pycforge/ide/qt_workspace_widgets.py +228 -0
  140. pycforge/ide/resources/icons/about.svg +1 -0
  141. pycforge/ide/resources/icons/add-document.svg +1 -0
  142. pycforge/ide/resources/icons/brand-mark.svg +1 -0
  143. pycforge/ide/resources/icons/bundle-search.svg +1 -0
  144. pycforge/ide/resources/icons/cancel.svg +1 -0
  145. pycforge/ide/resources/icons/check.svg +1 -0
  146. pycforge/ide/resources/icons/chevron-right.svg +1 -0
  147. pycforge/ide/resources/icons/close.svg +1 -0
  148. pycforge/ide/resources/icons/collapse-all.svg +1 -0
  149. pycforge/ide/resources/icons/command-palette.svg +1 -0
  150. pycforge/ide/resources/icons/convert.svg +1 -0
  151. pycforge/ide/resources/icons/copy.svg +1 -0
  152. pycforge/ide/resources/icons/cut.svg +1 -0
  153. pycforge/ide/resources/icons/decision-trace.svg +1 -0
  154. pycforge/ide/resources/icons/details.svg +1 -0
  155. pycforge/ide/resources/icons/diagnostics.svg +1 -0
  156. pycforge/ide/resources/icons/duplicate-line.svg +1 -0
  157. pycforge/ide/resources/icons/exit.svg +1 -0
  158. pycforge/ide/resources/icons/expand-all.svg +1 -0
  159. pycforge/ide/resources/icons/export.svg +1 -0
  160. pycforge/ide/resources/icons/find.svg +1 -0
  161. pycforge/ide/resources/icons/go-to-line.svg +1 -0
  162. pycforge/ide/resources/icons/go-to-output.svg +1 -0
  163. pycforge/ide/resources/icons/go-to-source.svg +1 -0
  164. pycforge/ide/resources/icons/history.svg +1 -0
  165. pycforge/ide/resources/icons/indent.svg +1 -0
  166. pycforge/ide/resources/icons/link-c.svg +1 -0
  167. pycforge/ide/resources/icons/mappings.svg +1 -0
  168. pycforge/ide/resources/icons/module.svg +1 -0
  169. pycforge/ide/resources/icons/move-down.svg +1 -0
  170. pycforge/ide/resources/icons/move-line-down.svg +1 -0
  171. pycforge/ide/resources/icons/move-line-up.svg +1 -0
  172. pycforge/ide/resources/icons/move-up.svg +1 -0
  173. pycforge/ide/resources/icons/next.svg +1 -0
  174. pycforge/ide/resources/icons/open.svg +1 -0
  175. pycforge/ide/resources/icons/outdent.svg +1 -0
  176. pycforge/ide/resources/icons/outline.svg +1 -0
  177. pycforge/ide/resources/icons/paste.svg +1 -0
  178. pycforge/ide/resources/icons/previous.svg +1 -0
  179. pycforge/ide/resources/icons/primary-module.svg +1 -0
  180. pycforge/ide/resources/icons/redo.svg +1 -0
  181. pycforge/ide/resources/icons/remove-document.svg +1 -0
  182. pycforge/ide/resources/icons/replace.svg +1 -0
  183. pycforge/ide/resources/icons/save-as.svg +1 -0
  184. pycforge/ide/resources/icons/save.svg +1 -0
  185. pycforge/ide/resources/icons/select-all.svg +1 -0
  186. pycforge/ide/resources/icons/settings.svg +1 -0
  187. pycforge/ide/resources/icons/show-c.svg +1 -0
  188. pycforge/ide/resources/icons/split-view.svg +1 -0
  189. pycforge/ide/resources/icons/summary.svg +1 -0
  190. pycforge/ide/resources/icons/telemetry.svg +1 -0
  191. pycforge/ide/resources/icons/toggle-comment.svg +1 -0
  192. pycforge/ide/resources/icons/toggle-fold.svg +1 -0
  193. pycforge/ide/resources/icons/undo.svg +1 -0
  194. pycforge/ide/resources/icons/whitespace.svg +1 -0
  195. pycforge/ide/revisions.py +400 -0
  196. pycforge/ide/search_service.py +280 -0
  197. pycforge/ide/session_history.py +150 -0
  198. pycforge/ide/source_editing.py +417 -0
  199. pycforge/ide/source_structure.py +558 -0
  200. pycforge/ide/source_structure_async.py +191 -0
  201. pycforge/ide/supervisor.py +503 -0
  202. pycforge/ide/theme.py +119 -0
  203. pycforge/ide/theme_stylesheet.py +598 -0
  204. pycforge/ide/theme_workspace_stylesheet.py +155 -0
  205. pycforge/ide/visual_tokens.py +142 -0
  206. pycforge/ide/worker_protocol.py +80 -0
  207. pycforge/ide/workspace_search.py +462 -0
  208. pycforge/ide/workspace_session.py +256 -0
  209. pycforge/laboratory/__init__.py +6 -0
  210. pycforge/laboratory/audits.py +2244 -0
  211. pycforge/laboratory/checkpoint_e.py +2685 -0
  212. pycforge/laboratory/cli.py +119 -0
  213. pycforge/laboratory/exit_codes.py +11 -0
  214. pycforge/laboratory/keyword_audit.py +661 -0
  215. pycforge/laboratory/keyword_only_audit.py +481 -0
  216. pycforge-0.15.2.dist-info/METADATA +209 -0
  217. pycforge-0.15.2.dist-info/RECORD +221 -0
  218. pycforge-0.15.2.dist-info/WHEEL +5 -0
  219. pycforge-0.15.2.dist-info/entry_points.txt +5 -0
  220. pycforge-0.15.2.dist-info/licenses/LICENSE +674 -0
  221. pycforge-0.15.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,418 @@
1
+ """Optional Qt materialization of the declared PyCForge action contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from typing import Any
7
+
8
+ from .action_contract import (
9
+ ACTION_SPECS,
10
+ DYNAMIC_ACTION_GROUPS,
11
+ ActionSpec,
12
+ ActionState,
13
+ DynamicActionEntry,
14
+ validated_dynamic_entries,
15
+ )
16
+
17
+
18
+ try:
19
+ from PyQt5.QtCore import QObject, QSignalBlocker, Qt
20
+ from PyQt5.QtGui import QIcon, QKeySequence
21
+ from PyQt5.QtWidgets import QAction, QToolButton, QWidget
22
+ except (ImportError, ModuleNotFoundError) as exc:
23
+ QT_ACTIONS_AVAILABLE = False
24
+ _QT_ERROR = exc
25
+ else:
26
+ QT_ACTIONS_AVAILABLE = True
27
+ _QT_ERROR = None
28
+
29
+
30
+ ActionHandler = Callable[..., Any]
31
+ ActionStateProvider = Callable[
32
+ [str | None, object | None],
33
+ Mapping[str, ActionState],
34
+ ]
35
+
36
+
37
+ if QT_ACTIONS_AVAILABLE:
38
+ from .icons import pycforge_icon_path
39
+
40
+ _STANDARD_KEYS = {
41
+ "Open": QKeySequence.Open,
42
+ "New": QKeySequence.New,
43
+ "Save": QKeySequence.Save,
44
+ "SaveAs": QKeySequence.SaveAs,
45
+ "Undo": QKeySequence.Undo,
46
+ "Redo": QKeySequence.Redo,
47
+ "Cut": QKeySequence.Cut,
48
+ "Copy": QKeySequence.Copy,
49
+ "Paste": QKeySequence.Paste,
50
+ "SelectAll": QKeySequence.SelectAll,
51
+ "Find": QKeySequence.Find,
52
+ "Replace": QKeySequence.Replace,
53
+ "FindNext": QKeySequence.FindNext,
54
+ }
55
+
56
+ class QtActionRegistry(QObject):
57
+ """Own exactly one QAction per declared non-parameterized action."""
58
+
59
+ def __init__(
60
+ self,
61
+ owner: QWidget,
62
+ handlers: Mapping[str, ActionHandler] | None = None,
63
+ *,
64
+ state_provider: ActionStateProvider | None = None,
65
+ action_specs: Mapping[str, ActionSpec] = ACTION_SPECS,
66
+ ) -> None:
67
+ if owner is None:
68
+ raise TypeError("owner must be a QWidget")
69
+ super().__init__(owner)
70
+ self._owner = owner
71
+ self._specs = dict(action_specs)
72
+ self._handlers = dict(handlers or {})
73
+ self._state_provider = state_provider
74
+ self._actions: dict[str, QAction] = {}
75
+ self._dynamic_actions: dict[str, tuple[QAction, ...]] = {}
76
+ self._last_states: dict[str, ActionState] = {}
77
+ self._active_surface_id: str | None = None
78
+ self._active_target: object | None = None
79
+ for action_id, spec in self._specs.items():
80
+ if spec.dynamic:
81
+ continue
82
+ action = self._materialize(spec)
83
+ self._actions[action_id] = action
84
+ if spec.shortcut_context == "window":
85
+ owner.addAction(action)
86
+ self.refresh()
87
+
88
+ @property
89
+ def active_surface_id(self) -> str | None:
90
+ return self._active_surface_id
91
+
92
+ @property
93
+ def active_target(self) -> object | None:
94
+ return self._active_target
95
+
96
+ def action(self, action_id: str) -> QAction:
97
+ """Return the sole QAction for a declared static action."""
98
+
99
+ try:
100
+ return self._actions[action_id]
101
+ except KeyError as exc:
102
+ if action_id in self._specs:
103
+ raise KeyError(
104
+ f"dynamic action has no static instance: {action_id}"
105
+ ) from exc
106
+ raise KeyError(f"unknown PyCForge action: {action_id}") from exc
107
+
108
+ def spec(self, action_id: str) -> ActionSpec:
109
+ try:
110
+ return self._specs[action_id]
111
+ except KeyError as exc:
112
+ raise KeyError(
113
+ f"unknown PyCForge action: {action_id}"
114
+ ) from exc
115
+
116
+ def static_action_ids(self) -> tuple[str, ...]:
117
+ return tuple(self._actions)
118
+
119
+ def is_disabled_window_shortcut(
120
+ self,
121
+ key: int,
122
+ modifiers: int,
123
+ ) -> bool:
124
+ """Return whether a reserved disabled shortcut must be consumed."""
125
+
126
+ sequence = QKeySequence(int(modifiers) | int(key))
127
+ for action_id, action in self._actions.items():
128
+ shortcut = action.shortcut()
129
+ if (
130
+ self._specs[action_id].shortcut_context == "window"
131
+ and not action.isEnabled()
132
+ and not shortcut.isEmpty()
133
+ and sequence.matches(shortcut)
134
+ == QKeySequence.ExactMatch
135
+ ):
136
+ return True
137
+ return False
138
+
139
+ def register_handler(
140
+ self, action_id: str, handler: ActionHandler
141
+ ) -> None:
142
+ if action_id not in self._actions:
143
+ raise KeyError(f"unknown static action: {action_id}")
144
+ if not callable(handler):
145
+ raise TypeError("action handler must be callable")
146
+ self._handlers[action_id] = handler
147
+ self.refresh()
148
+
149
+ def unregister_handler(self, action_id: str) -> None:
150
+ self._handlers.pop(action_id, None)
151
+ self.refresh()
152
+
153
+ def set_state_provider(
154
+ self, provider: ActionStateProvider | None
155
+ ) -> None:
156
+ if provider is not None and not callable(provider):
157
+ raise TypeError("state provider must be callable")
158
+ self._state_provider = provider
159
+ self.refresh()
160
+
161
+ def set_active_context(
162
+ self, surface_id: str | None, target: object | None
163
+ ) -> None:
164
+ self._active_surface_id = surface_id
165
+ self._active_target = target
166
+ self.refresh()
167
+
168
+ def clear_active_context(self) -> None:
169
+ self.set_active_context(None, None)
170
+
171
+ def refresh(
172
+ self,
173
+ states: Mapping[str, ActionState] | None = None,
174
+ ) -> None:
175
+ """Project bounded application state onto every static action."""
176
+
177
+ if states is None and self._state_provider is not None:
178
+ states = self._state_provider(
179
+ self._active_surface_id,
180
+ self._active_target,
181
+ )
182
+ if states is not None:
183
+ unknown = set(states).difference(self._actions)
184
+ if unknown:
185
+ raise KeyError(
186
+ f"state supplied for unknown actions: {sorted(unknown)}"
187
+ )
188
+ if any(
189
+ not isinstance(value, ActionState)
190
+ for value in states.values()
191
+ ):
192
+ raise TypeError("action states must be ActionState values")
193
+ self._last_states = dict(states)
194
+ for action_id, action in self._actions.items():
195
+ state = self._last_states.get(action_id, ActionState())
196
+ enabled = state.enabled and action_id in self._handlers
197
+ action.setEnabled(enabled)
198
+ action.setVisible(state.visible)
199
+ if action.isCheckable() and state.checked is not None:
200
+ blocker = QSignalBlocker(action)
201
+ action.setChecked(bool(state.checked))
202
+ del blocker
203
+
204
+ def set_enabled(self, action_id: str, enabled: bool) -> None:
205
+ current = self._last_states.get(action_id, ActionState())
206
+ self._last_states[action_id] = ActionState(
207
+ enabled=bool(enabled),
208
+ checked=current.checked,
209
+ visible=current.visible,
210
+ )
211
+ self.refresh(self._last_states)
212
+
213
+ def set_checked(self, action_id: str, checked: bool) -> None:
214
+ action = self.action(action_id)
215
+ if not action.isCheckable():
216
+ raise ValueError(f"action is not checkable: {action_id}")
217
+ current = self._last_states.get(action_id, ActionState())
218
+ self._last_states[action_id] = ActionState(
219
+ enabled=current.enabled,
220
+ checked=bool(checked),
221
+ visible=current.visible,
222
+ )
223
+ self.refresh(self._last_states)
224
+
225
+ def attach_to_widget(
226
+ self, action_id: str, widget: QWidget
227
+ ) -> QAction:
228
+ """Attach a widget-scoped shortcut to its intended owner."""
229
+
230
+ action = self.action(action_id)
231
+ if self.spec(action_id).shortcut_context != "widget":
232
+ raise ValueError(
233
+ f"action is not widget-scoped: {action_id}"
234
+ )
235
+ widget.addAction(action)
236
+ return action
237
+
238
+ def bind_tool_button(
239
+ self,
240
+ action_id: str,
241
+ button: QToolButton,
242
+ *,
243
+ accessible_description: str | None = None,
244
+ ) -> None:
245
+ """Bind a button without duplicating labels, icons, or callbacks."""
246
+
247
+ if not isinstance(button, QToolButton):
248
+ raise TypeError("button must be a QToolButton")
249
+ spec = self.spec(action_id)
250
+ button.setDefaultAction(self.action(action_id))
251
+ button.setAccessibleName(spec.accessible_name)
252
+ if accessible_description:
253
+ button.setAccessibleDescription(accessible_description)
254
+
255
+ def replace_dynamic(
256
+ self,
257
+ group_id: str,
258
+ entries: tuple[DynamicActionEntry, ...] | list[DynamicActionEntry],
259
+ handler: Callable[[str], Any],
260
+ ) -> tuple[QAction, ...]:
261
+ """Replace a bounded parameterized group owned by this registry."""
262
+
263
+ if group_id not in DYNAMIC_ACTION_GROUPS:
264
+ raise KeyError(f"unknown dynamic action group: {group_id}")
265
+ if not callable(handler):
266
+ raise TypeError("dynamic action handler must be callable")
267
+ records = validated_dynamic_entries(entries)
268
+ if not records:
269
+ records = (
270
+ DynamicActionEntry(
271
+ key="empty",
272
+ label="No recent Python documents",
273
+ tooltip="No recent Python documents are available",
274
+ accessible_name="No recent Python documents",
275
+ payload="",
276
+ enabled=False,
277
+ ),
278
+ )
279
+ for action in self._dynamic_actions.get(group_id, ()):
280
+ action.setParent(None)
281
+ action.deleteLater()
282
+ template = self.spec(DYNAMIC_ACTION_GROUPS[group_id])
283
+ actions = tuple(
284
+ self._materialize_dynamic(
285
+ group_id, template, entry, handler, index
286
+ )
287
+ for index, entry in enumerate(records)
288
+ )
289
+ self._dynamic_actions[group_id] = actions
290
+ return actions
291
+
292
+ def dynamic_actions(self, group_id: str) -> tuple[QAction, ...]:
293
+ if group_id not in DYNAMIC_ACTION_GROUPS:
294
+ raise KeyError(f"unknown dynamic action group: {group_id}")
295
+ return self._dynamic_actions.get(group_id, ())
296
+
297
+ def _materialize(self, spec: ActionSpec) -> QAction:
298
+ icon = (
299
+ QIcon(str(pycforge_icon_path(spec.icon_name)))
300
+ if spec.icon_name else QIcon()
301
+ )
302
+ action = QAction(icon, spec.menu_text, self._owner)
303
+ action.setObjectName(
304
+ "pycforgeAction__" + spec.action_id.replace(".", "__")
305
+ )
306
+ action.setData(spec.action_id)
307
+ action.setIconText(spec.toolbar_text)
308
+ action.setCheckable(spec.checkable)
309
+ action.setAutoRepeat(False)
310
+ action.setProperty("pycforgeActionId", spec.action_id)
311
+ action.setProperty("pycforgeTone", spec.tone)
312
+ action.setProperty(
313
+ "pycforgeAccessibleName", spec.accessible_name
314
+ )
315
+ sequence = self._shortcut(spec)
316
+ if sequence is not None:
317
+ action.setShortcut(sequence)
318
+ context = (
319
+ Qt.WidgetWithChildrenShortcut
320
+ if spec.shortcut_context == "widget"
321
+ else Qt.WindowShortcut
322
+ )
323
+ action.setShortcutContext(context)
324
+ tooltip = self._tooltip(spec.tooltip, sequence)
325
+ action.setToolTip(tooltip)
326
+ action.setStatusTip(spec.tooltip)
327
+ action.setWhatsThis(spec.tooltip)
328
+ action.triggered.connect(
329
+ lambda checked=False, action_id=spec.action_id:
330
+ self._invoke(action_id, checked)
331
+ )
332
+ return action
333
+
334
+ def _materialize_dynamic(
335
+ self,
336
+ group_id: str,
337
+ template: ActionSpec,
338
+ entry: DynamicActionEntry,
339
+ handler: Callable[[str], Any],
340
+ index: int,
341
+ ) -> QAction:
342
+ icon = (
343
+ QIcon(str(pycforge_icon_path(template.icon_name)))
344
+ if template.icon_name else QIcon()
345
+ )
346
+ action = QAction(
347
+ icon, entry.label.replace("&", "&&"), self._owner
348
+ )
349
+ action.setObjectName(
350
+ f"pycforgeDynamic__{group_id}__{index}"
351
+ )
352
+ action.setData((group_id, entry.key))
353
+ action.setEnabled(entry.enabled)
354
+ action.setToolTip(entry.tooltip)
355
+ action.setStatusTip(entry.tooltip)
356
+ action.setProperty("pycforgeActionId", template.action_id)
357
+ action.setProperty("pycforgeTone", template.tone)
358
+ action.setProperty(
359
+ "pycforgeAccessibleName", entry.accessible_name
360
+ )
361
+ if entry.enabled:
362
+ action.triggered.connect(
363
+ lambda checked=False, payload=entry.payload:
364
+ handler(payload)
365
+ )
366
+ return action
367
+
368
+ def _invoke(self, action_id: str, checked: bool) -> None:
369
+ handler = self._handlers.get(action_id)
370
+ if handler is None:
371
+ return
372
+ if self._specs[action_id].checkable:
373
+ handler(bool(checked))
374
+ else:
375
+ handler()
376
+
377
+ @staticmethod
378
+ def _shortcut(spec: ActionSpec) -> QKeySequence | None:
379
+ if spec.standard_shortcut:
380
+ try:
381
+ return QKeySequence(
382
+ _STANDARD_KEYS[spec.standard_shortcut]
383
+ )
384
+ except KeyError as exc:
385
+ raise ValueError(
386
+ "unknown standard shortcut: "
387
+ f"{spec.standard_shortcut}"
388
+ ) from exc
389
+ if spec.shortcut:
390
+ return QKeySequence(spec.shortcut)
391
+ return None
392
+
393
+ @staticmethod
394
+ def _tooltip(
395
+ tooltip: str, sequence: QKeySequence | None
396
+ ) -> str:
397
+ if sequence is None or sequence.isEmpty():
398
+ return tooltip
399
+ rendered = sequence.toString(QKeySequence.NativeText)
400
+ return f"{tooltip} ({rendered})" if rendered else tooltip
401
+
402
+
403
+ else:
404
+ class QtActionRegistry:
405
+ """Import-safe placeholder for a damaged installation without PyQt5."""
406
+
407
+ def __init__(self, *_args, **_kwargs) -> None:
408
+ raise RuntimeError(
409
+ "PyQt5 is required for the PyCForge action registry"
410
+ ) from _QT_ERROR
411
+
412
+
413
+ __all__ = [
414
+ "ActionHandler",
415
+ "ActionStateProvider",
416
+ "QT_ACTIONS_AVAILABLE",
417
+ "QtActionRegistry",
418
+ ]
@@ -0,0 +1,169 @@
1
+ """Guarded modal choices and non-blocking close flow for the Qt workspace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from concurrent.futures import Future
6
+ from typing import Any
7
+
8
+ from PyQt5.QtCore import Qt, QTimer
9
+ from PyQt5.QtWidgets import (
10
+ QDialog,
11
+ QDialogButtonBox,
12
+ QLabel,
13
+ QVBoxLayout,
14
+ )
15
+
16
+
17
+ class QtCloseMixin:
18
+ """Keep destructive choices explicit and shutdown off the event loop."""
19
+
20
+ def _confirm_discard(self, logical_name: str) -> bool:
21
+ dialog = QDialog(self)
22
+ dialog.setWindowTitle("Discard unsaved module?")
23
+ dialog.setModal(True)
24
+ layout = QVBoxLayout(dialog)
25
+ label = QLabel(
26
+ f"{logical_name} has unsaved changes. "
27
+ "Removing it discards those changes."
28
+ )
29
+ label.setWordWrap(True)
30
+ layout.addWidget(label)
31
+ buttons = QDialogButtonBox()
32
+ discard = buttons.addButton(
33
+ "Discard Module", QDialogButtonBox.DestructiveRole
34
+ )
35
+ cancel = buttons.addButton(QDialogButtonBox.Cancel)
36
+ discard.clicked.connect(lambda: dialog.done(1))
37
+ cancel.clicked.connect(lambda: dialog.done(0))
38
+ layout.addWidget(buttons)
39
+ return dialog.exec_() == 1
40
+
41
+ def _confirm_reload(self, logical_name: str) -> bool:
42
+ dialog = QDialog(self)
43
+ dialog.setWindowTitle("Reload linked Python file?")
44
+ dialog.setModal(True)
45
+ layout = QVBoxLayout(dialog)
46
+ label = QLabel(
47
+ f"{logical_name} has unsaved changes. Reloading replaces "
48
+ "them with the explicitly selected disk version."
49
+ )
50
+ label.setWordWrap(True)
51
+ layout.addWidget(label)
52
+ buttons = QDialogButtonBox()
53
+ reload_button = buttons.addButton(
54
+ "Reload from Disk", QDialogButtonBox.DestructiveRole
55
+ )
56
+ cancel = buttons.addButton(QDialogButtonBox.Cancel)
57
+ reload_button.clicked.connect(lambda: dialog.done(1))
58
+ cancel.clicked.connect(lambda: dialog.done(0))
59
+ layout.addWidget(buttons)
60
+ return dialog.exec_() == 1
61
+
62
+ def _unsaved_choice(self, documents: tuple[Any, ...]) -> str:
63
+ dialog = QDialog(self)
64
+ dialog.setWindowTitle("Unsaved Python documents")
65
+ dialog.setModal(True)
66
+ layout = QVBoxLayout(dialog)
67
+ names = "\n".join(
68
+ f"• {item.logical_name}" for item in documents[:8]
69
+ )
70
+ if len(documents) > 8:
71
+ names += f"\n• and {len(documents) - 8} more"
72
+ label = QLabel(
73
+ "Save modified Python documents before closing?\n\n"
74
+ + names
75
+ )
76
+ label.setTextInteractionFlags(Qt.TextSelectableByMouse)
77
+ layout.addWidget(label)
78
+ buttons = QDialogButtonBox()
79
+ save = buttons.addButton(
80
+ "Save All", QDialogButtonBox.AcceptRole
81
+ )
82
+ discard = buttons.addButton(
83
+ "Discard", QDialogButtonBox.DestructiveRole
84
+ )
85
+ cancel = buttons.addButton(QDialogButtonBox.Cancel)
86
+ save.clicked.connect(lambda: dialog.done(1))
87
+ discard.clicked.connect(lambda: dialog.done(2))
88
+ cancel.clicked.connect(lambda: dialog.done(0))
89
+ layout.addWidget(buttons)
90
+ result = dialog.exec_()
91
+ return {1: "save", 2: "discard"}.get(result, "cancel")
92
+
93
+ def closeEvent(self, event) -> None: # noqa: N802 - Qt API
94
+ if self._closing:
95
+ self._close_workspace_features()
96
+ event.accept()
97
+ return
98
+ if self._close_save_pending:
99
+ event.ignore()
100
+ return
101
+ if not self._flush_pending_source_sync():
102
+ event.ignore()
103
+ return
104
+ dirty = tuple(
105
+ item for item in self.controller.snapshot.documents
106
+ if item.dirty
107
+ )
108
+ if dirty:
109
+ choice = self._unsaved_choice(dirty)
110
+ if choice == "cancel":
111
+ event.ignore()
112
+ return
113
+ if choice == "save":
114
+ futures: list[Future] = []
115
+ for document in dirty:
116
+ future = self._save_document(
117
+ document.document_id
118
+ )
119
+ if future is None:
120
+ event.ignore()
121
+ return
122
+ futures.append(future)
123
+ self._close_save_pending = len(futures)
124
+ self._close_save_failed = False
125
+ for future in futures:
126
+ self._dispatch_io(
127
+ future,
128
+ self._close_save_completed,
129
+ )
130
+ event.ignore()
131
+ return
132
+ self._closing = True
133
+ self._persist_workspace_state()
134
+ self.controller.unsubscribe(self._snapshot_listener)
135
+ self._close_workspace_features()
136
+ self.controller.close(wait=False)
137
+ event.accept()
138
+
139
+ def _close_save_completed(self, future: Future) -> None:
140
+ try:
141
+ future.result()
142
+ except Exception:
143
+ self._close_save_failed = True
144
+ self._close_save_pending = max(
145
+ 0, self._close_save_pending - 1
146
+ )
147
+ if self._close_save_pending:
148
+ return
149
+ if self._close_save_failed:
150
+ self.toast.show_message(
151
+ "Close paused because at least one Python file "
152
+ "was not saved.",
153
+ "warning",
154
+ )
155
+ return
156
+ if any(
157
+ item.dirty
158
+ for item in self.controller.snapshot.documents
159
+ ):
160
+ self.toast.show_message(
161
+ "Close paused because source changed while "
162
+ "files were saving.",
163
+ "warning",
164
+ )
165
+ return
166
+ QTimer.singleShot(0, self.close)
167
+
168
+
169
+ __all__ = ["QtCloseMixin"]