lightfall 0.1.1__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 (388) hide show
  1. lightfall/__init__.py +8 -0
  2. lightfall/__main__.py +10 -0
  3. lightfall/_version.py +24 -0
  4. lightfall/acquire/__init__.py +74 -0
  5. lightfall/acquire/buffer.py +363 -0
  6. lightfall/acquire/device_wrapper.py +416 -0
  7. lightfall/acquire/engine/__init__.py +155 -0
  8. lightfall/acquire/engine/base.py +587 -0
  9. lightfall/acquire/engine/bluesky.py +358 -0
  10. lightfall/acquire/engine/mock.py +165 -0
  11. lightfall/acquire/engine/plugins/__init__.py +9 -0
  12. lightfall/acquire/engine/plugins/bluesky_plugin.py +56 -0
  13. lightfall/acquire/engine/plugins/mock_plugin.py +55 -0
  14. lightfall/acquire/engine/protocol.py +145 -0
  15. lightfall/acquire/engine/registry.py +152 -0
  16. lightfall/acquire/engine/state.py +32 -0
  17. lightfall/acquire/engine/waiting_hook.py +225 -0
  18. lightfall/acquire/nats_bridge.py +62 -0
  19. lightfall/acquire/plan_ui.py +78 -0
  20. lightfall/acquire/plans/__init__.py +38 -0
  21. lightfall/acquire/plans/adaptive.py +288 -0
  22. lightfall/acquire/plans/example_plans.py +995 -0
  23. lightfall/acquire/plans/lightfall_plans.py +587 -0
  24. lightfall/acquire/plans/registry.py +543 -0
  25. lightfall/acquire/plans/standard_plans.py +186 -0
  26. lightfall/acquire/plans/user_plans.py +470 -0
  27. lightfall/acquire/runengine.py +36 -0
  28. lightfall/acquire/signals.py +452 -0
  29. lightfall/acquire/triggers/__init__.py +16 -0
  30. lightfall/acquire/triggers/base.py +25 -0
  31. lightfall/acquire/triggers/filter.py +37 -0
  32. lightfall/acquire/triggers/manager.py +73 -0
  33. lightfall/acquire/triggers/manual.py +36 -0
  34. lightfall/acquire/triggers/run_end.py +74 -0
  35. lightfall/acquire/triggers/run_start.py +52 -0
  36. lightfall/auth/__init__.py +38 -0
  37. lightfall/auth/policy.py +518 -0
  38. lightfall/auth/providers/__init__.py +30 -0
  39. lightfall/auth/providers/base.py +124 -0
  40. lightfall/auth/providers/keycloak.py +1017 -0
  41. lightfall/auth/providers/local.py +319 -0
  42. lightfall/auth/providers/pam.py +250 -0
  43. lightfall/auth/service_key.py +173 -0
  44. lightfall/auth/service_key_auth.py +79 -0
  45. lightfall/auth/session.py +656 -0
  46. lightfall/claude/__init__.py +52 -0
  47. lightfall/claude/_internal/__init__.py +1 -0
  48. lightfall/claude/_internal/serialization.py +195 -0
  49. lightfall/claude/_internal/threading.py +61 -0
  50. lightfall/claude/_internal/worker.py +757 -0
  51. lightfall/claude/_session_assembly.py +124 -0
  52. lightfall/claude/agent.py +596 -0
  53. lightfall/claude/lightfall_core_tools.py +410 -0
  54. lightfall/claude/markdown.py +103 -0
  55. lightfall/claude/permission_manager.py +588 -0
  56. lightfall/claude/tools/__init__.py +45 -0
  57. lightfall/claude/tools/controller.py +143 -0
  58. lightfall/claude/tools/interaction.py +177 -0
  59. lightfall/claude/tools/introspection.py +127 -0
  60. lightfall/claude/tools/logs.py +155 -0
  61. lightfall/claude/tools/screenshot.py +87 -0
  62. lightfall/claude/widget.py +851 -0
  63. lightfall/claude/widgets/__init__.py +5 -0
  64. lightfall/claude/widgets/permission_request.py +282 -0
  65. lightfall/claude/widgets/question_request.py +227 -0
  66. lightfall/claude/widgets/task_card.py +223 -0
  67. lightfall/config/__init__.py +23 -0
  68. lightfall/config/layers.py +317 -0
  69. lightfall/config/manager.py +244 -0
  70. lightfall/config/schema.py +154 -0
  71. lightfall/core/__init__.py +23 -0
  72. lightfall/core/application.py +727 -0
  73. lightfall/core/services.py +235 -0
  74. lightfall/devices/__init__.py +53 -0
  75. lightfall/devices/backends/__init__.py +17 -0
  76. lightfall/devices/backends/bcs.py +448 -0
  77. lightfall/devices/backends/happi.py +986 -0
  78. lightfall/devices/backends/mock.py +646 -0
  79. lightfall/devices/base.py +338 -0
  80. lightfall/devices/catalog.py +1039 -0
  81. lightfall/devices/connection_manager.py +676 -0
  82. lightfall/devices/model.py +290 -0
  83. lightfall/devices/monitoring.py +442 -0
  84. lightfall/devices/sim/__init__.py +26 -0
  85. lightfall/devices/sim/areadetector.py +436 -0
  86. lightfall/devices/sim/generators.py +223 -0
  87. lightfall/devices/sim/plugins.py +116 -0
  88. lightfall/epics/__init__.py +28 -0
  89. lightfall/epics/ca/__init__.py +10 -0
  90. lightfall/epics/ca/context.py +100 -0
  91. lightfall/epics/ca/pv.py +303 -0
  92. lightfall/epics/widgets/__init__.py +49 -0
  93. lightfall/epics/widgets/areadetector/__init__.py +16 -0
  94. lightfall/epics/widgets/areadetector/areadetector.py +281 -0
  95. lightfall/epics/widgets/areadetector/controls.py +478 -0
  96. lightfall/epics/widgets/areadetector/image_view.py +447 -0
  97. lightfall/epics/widgets/auto.py +319 -0
  98. lightfall/epics/widgets/base.py +404 -0
  99. lightfall/epics/widgets/checkbox.py +239 -0
  100. lightfall/epics/widgets/combobox.py +202 -0
  101. lightfall/epics/widgets/label.py +176 -0
  102. lightfall/epics/widgets/lineedit.py +253 -0
  103. lightfall/epics/widgets/motor.py +694 -0
  104. lightfall/epics/widgets/ophyd_base.py +469 -0
  105. lightfall/epics/widgets/ophyd_combobox.py +86 -0
  106. lightfall/epics/widgets/ophyd_label.py +54 -0
  107. lightfall/epics/widgets/ophyd_lineedit.py +170 -0
  108. lightfall/epics/widgets/ophyd_spinbox.py +79 -0
  109. lightfall/epics/widgets/slider.py +272 -0
  110. lightfall/epics/widgets/status_indicator.py +98 -0
  111. lightfall/epics/widgets/style.py +188 -0
  112. lightfall/exporter/__init__.py +1 -0
  113. lightfall/exporter/cli.py +67 -0
  114. lightfall/exporter/converters/__init__.py +26 -0
  115. lightfall/exporter/converters/base.py +39 -0
  116. lightfall/exporter/converters/noop.py +39 -0
  117. lightfall/exporter/converters/nxsas.py +73 -0
  118. lightfall/exporter/service.py +200 -0
  119. lightfall/exporter/tiled_utils.py +92 -0
  120. lightfall/ipc/__init__.py +6 -0
  121. lightfall/ipc/service.py +701 -0
  122. lightfall/ipc/trust.py +144 -0
  123. lightfall/logbook/__init__.py +46 -0
  124. lightfall/logbook/action_dialog.py +207 -0
  125. lightfall/logbook/action_logger.py +432 -0
  126. lightfall/logbook/block_mapper.py +562 -0
  127. lightfall/logbook/client.py +799 -0
  128. lightfall/logbook/converter.py +273 -0
  129. lightfall/logbook/editors/__init__.py +19 -0
  130. lightfall/logbook/editors/highlighter.py +305 -0
  131. lightfall/logbook/editors/markdown_editor.py +319 -0
  132. lightfall/logbook/editors/richtext_editor.py +1397 -0
  133. lightfall/logbook/entry_widget.py +1065 -0
  134. lightfall/logbook/event_listener.py +221 -0
  135. lightfall/logbook/fragment_widgets.py +925 -0
  136. lightfall/logbook/position_mapper.py +320 -0
  137. lightfall/logbook/protection.py +402 -0
  138. lightfall/logbook/style.py +394 -0
  139. lightfall/logbook/url.py +29 -0
  140. lightfall/logbook/visual_protection.py +330 -0
  141. lightfall/logbook/widget.py +680 -0
  142. lightfall/main.py +1091 -0
  143. lightfall/pipelines/__init__.py +4 -0
  144. lightfall/pipelines/client.py +148 -0
  145. lightfall/plugins/__init__.py +119 -0
  146. lightfall/plugins/agent_plugin.py +106 -0
  147. lightfall/plugins/agents/__init__.py +10 -0
  148. lightfall/plugins/agents/_mcp_helpers.py +52 -0
  149. lightfall/plugins/agents/alignment.py +94 -0
  150. lightfall/plugins/agents/autonomous_experiment/__init__.py +12 -0
  151. lightfall/plugins/agents/autonomous_experiment/nats_tools.py +210 -0
  152. lightfall/plugins/agents/autonomous_experiment/plugin.py +60 -0
  153. lightfall/plugins/agents/autonomous_experiment/prompts.py +164 -0
  154. lightfall/plugins/agents/current_esaf.py +435 -0
  155. lightfall/plugins/agents/device_tools.py +1043 -0
  156. lightfall/plugins/agents/engine_tools.py +720 -0
  157. lightfall/plugins/agents/ipython_tools.py +444 -0
  158. lightfall/plugins/agents/panel_builder.py +637 -0
  159. lightfall/plugins/agents/panel_design/references/cross_panel_patterns.md +95 -0
  160. lightfall/plugins/agents/panel_design/references/panel_design.md +680 -0
  161. lightfall/plugins/agents/panel_design.py +94 -0
  162. lightfall/plugins/agents/plan_design/references/plan_design.md +398 -0
  163. lightfall/plugins/agents/plan_design.py +90 -0
  164. lightfall/plugins/agents/plan_tools.py +878 -0
  165. lightfall/plugins/agents/scan_planning.py +101 -0
  166. lightfall/plugins/builtin_manifest.py +348 -0
  167. lightfall/plugins/controller_plugin.py +162 -0
  168. lightfall/plugins/engine_plugin.py +124 -0
  169. lightfall/plugins/errors.py +104 -0
  170. lightfall/plugins/info.py +112 -0
  171. lightfall/plugins/loader.py +878 -0
  172. lightfall/plugins/manifest.py +150 -0
  173. lightfall/plugins/panel_plugin.py +119 -0
  174. lightfall/plugins/plan_plugin.py +163 -0
  175. lightfall/plugins/registry.py +309 -0
  176. lightfall/plugins/settings_plugin.py +226 -0
  177. lightfall/plugins/statusbar_plugin.py +289 -0
  178. lightfall/plugins/theme_plugin.py +165 -0
  179. lightfall/plugins/types.py +136 -0
  180. lightfall/plugins/user_plugins.py +764 -0
  181. lightfall/project/__init__.py +37 -0
  182. lightfall/project/model.py +375 -0
  183. lightfall/project/service.py +427 -0
  184. lightfall/project/welcome.py +106 -0
  185. lightfall/resources/__init__.py +126 -0
  186. lightfall/resources/images/__init__.py +1 -0
  187. lightfall/resources/images/icon.ico +0 -0
  188. lightfall/resources/images/icon.png +0 -0
  189. lightfall/resources/images/logo.png +0 -0
  190. lightfall/services/__init__.py +33 -0
  191. lightfall/services/_alshub_client.py +73 -0
  192. lightfall/services/access_stamper.py +240 -0
  193. lightfall/services/als_beam_status.py +347 -0
  194. lightfall/services/ca_tunnel.py +325 -0
  195. lightfall/services/threaded_tiled_writer.py +174 -0
  196. lightfall/services/tiled_auth.py +21 -0
  197. lightfall/services/tiled_service.py +971 -0
  198. lightfall/services/tiled_writer_patch.py +301 -0
  199. lightfall/settings/__init__.py +1 -0
  200. lightfall/settings/image_helpers.py +30 -0
  201. lightfall/settings/user_settings_client.py +232 -0
  202. lightfall/ui/__init__.py +28 -0
  203. lightfall/ui/annotations.py +208 -0
  204. lightfall/ui/common/__init__.py +7 -0
  205. lightfall/ui/dialogs/__init__.py +26 -0
  206. lightfall/ui/dialogs/about_dialog.py +131 -0
  207. lightfall/ui/dialogs/add_trigger_dialog.py +152 -0
  208. lightfall/ui/dialogs/base.py +44 -0
  209. lightfall/ui/dialogs/bug_report_dialog.py +353 -0
  210. lightfall/ui/dialogs/create_plan_dialog.py +189 -0
  211. lightfall/ui/dialogs/device_edit_dialog.py +183 -0
  212. lightfall/ui/dialogs/export_dialog.py +565 -0
  213. lightfall/ui/dialogs/go_to_position_dialog.py +192 -0
  214. lightfall/ui/dialogs/login_dialog.py +756 -0
  215. lightfall/ui/dialogs/oauth_browser_dialog.py +305 -0
  216. lightfall/ui/dialogs/run_pipeline_dialog.py +131 -0
  217. lightfall/ui/dialogs/sample_metadata_dialog.py +316 -0
  218. lightfall/ui/docking/__init__.py +22 -0
  219. lightfall/ui/docking/icon_sidebar.py +806 -0
  220. lightfall/ui/docking/manager.py +682 -0
  221. lightfall/ui/docking/state.py +113 -0
  222. lightfall/ui/docking/theme.py +399 -0
  223. lightfall/ui/docking/widget.py +214 -0
  224. lightfall/ui/events.py +75 -0
  225. lightfall/ui/mainwindow.py +1006 -0
  226. lightfall/ui/models/__init__.py +49 -0
  227. lightfall/ui/models/device_selection.py +389 -0
  228. lightfall/ui/models/device_tree.py +1095 -0
  229. lightfall/ui/models/thread_model.py +667 -0
  230. lightfall/ui/models/tiled_model.py +384 -0
  231. lightfall/ui/panels/__init__.py +28 -0
  232. lightfall/ui/panels/base.py +525 -0
  233. lightfall/ui/panels/bluesky_panel.py +619 -0
  234. lightfall/ui/panels/claude/__init__.py +9 -0
  235. lightfall/ui/panels/claude/agent_registry.py +168 -0
  236. lightfall/ui/panels/claude_panel.py +887 -0
  237. lightfall/ui/panels/device_panel.py +370 -0
  238. lightfall/ui/panels/documents_panel.py +166 -0
  239. lightfall/ui/panels/ipython_panel.py +580 -0
  240. lightfall/ui/panels/logbook_entries_panel.py +84 -0
  241. lightfall/ui/panels/logbook_panel.py +627 -0
  242. lightfall/ui/panels/logging_panel.py +587 -0
  243. lightfall/ui/panels/pipeline_jobs_panel.py +160 -0
  244. lightfall/ui/panels/pipeline_triggers_panel.py +170 -0
  245. lightfall/ui/panels/plugins/__init__.py +34 -0
  246. lightfall/ui/panels/plugins/bluesky_plugin.py +27 -0
  247. lightfall/ui/panels/plugins/claude_plugin.py +29 -0
  248. lightfall/ui/panels/plugins/device_plugin.py +27 -0
  249. lightfall/ui/panels/plugins/documents_plugin.py +26 -0
  250. lightfall/ui/panels/plugins/ipython_plugin.py +27 -0
  251. lightfall/ui/panels/plugins/logbook_entries_plugin.py +23 -0
  252. lightfall/ui/panels/plugins/logbook_plugin.py +27 -0
  253. lightfall/ui/panels/plugins/logging_plugin.py +27 -0
  254. lightfall/ui/panels/plugins/pipeline_jobs_plugin.py +23 -0
  255. lightfall/ui/panels/plugins/pipeline_triggers_plugin.py +25 -0
  256. lightfall/ui/panels/plugins/queue_plugin.py +29 -0
  257. lightfall/ui/panels/plugins/synoptic_plugin.py +38 -0
  258. lightfall/ui/panels/plugins/threads_plugin.py +27 -0
  259. lightfall/ui/panels/plugins/tiled_browser_plugin.py +27 -0
  260. lightfall/ui/panels/plugins/visualization_plugin.py +27 -0
  261. lightfall/ui/panels/queue.py +754 -0
  262. lightfall/ui/panels/registry.py +483 -0
  263. lightfall/ui/panels/synoptic/__init__.py +27 -0
  264. lightfall/ui/panels/synoptic/editors.py +481 -0
  265. lightfall/ui/panels/synoptic/items.py +556 -0
  266. lightfall/ui/panels/synoptic/models.py +336 -0
  267. lightfall/ui/panels/synoptic/panel.py +889 -0
  268. lightfall/ui/panels/synoptic/serialization.py +300 -0
  269. lightfall/ui/panels/synoptic/view.py +504 -0
  270. lightfall/ui/panels/threads_panel.py +621 -0
  271. lightfall/ui/panels/tiled_browser_panel.py +854 -0
  272. lightfall/ui/panels/visualization_panel.py +508 -0
  273. lightfall/ui/preferences/__init__.py +24 -0
  274. lightfall/ui/preferences/backend.py +148 -0
  275. lightfall/ui/preferences/builtin.py +220 -0
  276. lightfall/ui/preferences/claude_settings.py +762 -0
  277. lightfall/ui/preferences/device_settings.py +461 -0
  278. lightfall/ui/preferences/dialog.py +234 -0
  279. lightfall/ui/preferences/editor_settings.py +227 -0
  280. lightfall/ui/preferences/ipc_settings.py +226 -0
  281. lightfall/ui/preferences/logbook_settings.py +232 -0
  282. lightfall/ui/preferences/login_settings.py +183 -0
  283. lightfall/ui/preferences/manager.py +562 -0
  284. lightfall/ui/preferences/plugin_settings.py +392 -0
  285. lightfall/ui/preferences/proxy_settings.py +561 -0
  286. lightfall/ui/preferences/skill_settings.py +28 -0
  287. lightfall/ui/preferences/tiled_settings.py +469 -0
  288. lightfall/ui/preferences/tool_settings.py +393 -0
  289. lightfall/ui/preferences/user_portable_backend.py +131 -0
  290. lightfall/ui/preferences/user_profile_settings.py +316 -0
  291. lightfall/ui/preferences/visualization_settings.py +159 -0
  292. lightfall/ui/resources/__init__.py +1 -0
  293. lightfall/ui/resources/logo.png +0 -0
  294. lightfall/ui/statusbar/__init__.py +11 -0
  295. lightfall/ui/statusbar/manager.py +379 -0
  296. lightfall/ui/statusbar/plugins/__init__.py +28 -0
  297. lightfall/ui/statusbar/plugins/als_beam_status.py +218 -0
  298. lightfall/ui/statusbar/plugins/auth_status.py +116 -0
  299. lightfall/ui/statusbar/plugins/connection_status.py +100 -0
  300. lightfall/ui/statusbar/plugins/thread_status.py +556 -0
  301. lightfall/ui/statusbar/plugins/tiled_status.py +179 -0
  302. lightfall/ui/statusbar/plugins/user_status.py +84 -0
  303. lightfall/ui/theater/__init__.py +28 -0
  304. lightfall/ui/theater/manager.py +124 -0
  305. lightfall/ui/theater/overlay.py +279 -0
  306. lightfall/ui/theater/proxy.py +111 -0
  307. lightfall/ui/theme/__init__.py +18 -0
  308. lightfall/ui/theme/builtin.py +1015 -0
  309. lightfall/ui/theme/manager.py +875 -0
  310. lightfall/ui/theme/registry.py +195 -0
  311. lightfall/ui/toast.py +221 -0
  312. lightfall/ui/tutorial.py +1100 -0
  313. lightfall/ui/widgets/__init__.py +110 -0
  314. lightfall/ui/widgets/base_control.py +259 -0
  315. lightfall/ui/widgets/camera/__init__.py +36 -0
  316. lightfall/ui/widgets/camera/base.py +815 -0
  317. lightfall/ui/widgets/camera/dark_frames.py +213 -0
  318. lightfall/ui/widgets/camera/image_view.py +649 -0
  319. lightfall/ui/widgets/camera/panels/__init__.py +14 -0
  320. lightfall/ui/widgets/camera/panels/cooler.py +320 -0
  321. lightfall/ui/widgets/camera/panels/temperature.py +192 -0
  322. lightfall/ui/widgets/camera/plan_based.py +202 -0
  323. lightfall/ui/widgets/compact_motor.py +522 -0
  324. lightfall/ui/widgets/controller_matcher.py +278 -0
  325. lightfall/ui/widgets/controller_registry.py +144 -0
  326. lightfall/ui/widgets/device_control.py +411 -0
  327. lightfall/ui/widgets/device_selector.py +438 -0
  328. lightfall/ui/widgets/device_tree_tab.py +461 -0
  329. lightfall/ui/widgets/document_stream.py +1028 -0
  330. lightfall/ui/widgets/favorites_tab.py +191 -0
  331. lightfall/ui/widgets/motor_control.py +1120 -0
  332. lightfall/ui/widgets/observers/__init__.py +8 -0
  333. lightfall/ui/widgets/observers/camera.py +48 -0
  334. lightfall/ui/widgets/observers/image_view.py +130 -0
  335. lightfall/ui/widgets/plan_config.py +954 -0
  336. lightfall/ui/widgets/plan_edit_dialog.py +294 -0
  337. lightfall/ui/widgets/plan_selector.py +452 -0
  338. lightfall/ui/widgets/profile_avatar.py +128 -0
  339. lightfall/ui/widgets/queue_view.py +647 -0
  340. lightfall/ui/widgets/runengine_control.py +549 -0
  341. lightfall/ui/widgets/signal_control.py +793 -0
  342. lightfall/ui/widgets/skill_trigger_button.py +183 -0
  343. lightfall/ui/widgets/tiled_filter_widget.py +314 -0
  344. lightfall/ui/widgets/tiled_status.py +149 -0
  345. lightfall/ui/widgets/warning_banner.py +185 -0
  346. lightfall/utils/__init__.py +53 -0
  347. lightfall/utils/crash_diagnostics.py +454 -0
  348. lightfall/utils/data_migration.py +22 -0
  349. lightfall/utils/editor_launcher.py +594 -0
  350. lightfall/utils/error_collector.py +245 -0
  351. lightfall/utils/git_tracker.py +197 -0
  352. lightfall/utils/log_buffer.py +233 -0
  353. lightfall/utils/logging.py +229 -0
  354. lightfall/utils/module_resolver.py +70 -0
  355. lightfall/utils/sentry.py +722 -0
  356. lightfall/utils/threads.py +991 -0
  357. lightfall/utils/tiled_helpers.py +96 -0
  358. lightfall/visualization/__init__.py +50 -0
  359. lightfall/visualization/base.py +5 -0
  360. lightfall/visualization/base_visualization.py +74 -0
  361. lightfall/visualization/fitting/__init__.py +24 -0
  362. lightfall/visualization/fitting/base.py +267 -0
  363. lightfall/visualization/fitting/fitters.py +325 -0
  364. lightfall/visualization/fitting/panel.py +265 -0
  365. lightfall/visualization/memory.py +392 -0
  366. lightfall/visualization/motor_mixin.py +524 -0
  367. lightfall/visualization/pg.py +156 -0
  368. lightfall/visualization/registry.py +144 -0
  369. lightfall/visualization/spec.py +79 -0
  370. lightfall/visualization/theme.py +266 -0
  371. lightfall/visualization/widgets/__init__.py +28 -0
  372. lightfall/visualization/widgets/adaptive/__init__.py +1 -0
  373. lightfall/visualization/widgets/adaptive/heatmap.py +655 -0
  374. lightfall/visualization/widgets/adaptive/plot.py +233 -0
  375. lightfall/visualization/widgets/heatmap.py +264 -0
  376. lightfall/visualization/widgets/image_stack.py +316 -0
  377. lightfall/visualization/widgets/image_view_toolbar.py +227 -0
  378. lightfall/visualization/widgets/lazy_image_view.py +590 -0
  379. lightfall/visualization/widgets/plot_1d.py +262 -0
  380. lightfall/visualization/widgets/scatter.py +247 -0
  381. lightfall/visualization/widgets/table.py +221 -0
  382. lightfall/visualization/widgets/time_axis.py +93 -0
  383. lightfall-0.1.1.dist-info/METADATA +223 -0
  384. lightfall-0.1.1.dist-info/RECORD +388 -0
  385. lightfall-0.1.1.dist-info/WHEEL +4 -0
  386. lightfall-0.1.1.dist-info/entry_points.txt +6 -0
  387. lightfall-0.1.1.dist-info/licenses/LEGAL.md +13 -0
  388. lightfall-0.1.1.dist-info/licenses/LICENSE.md +33 -0
@@ -0,0 +1,991 @@
1
+ """Threading utilities for NCS.
2
+
3
+ Provides Qt-integrated threading with global thread management, flexible decorators,
4
+ and proper interruption/cancellation support.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ import threading
11
+ import time
12
+ from collections.abc import Callable, Generator
13
+ from functools import wraps
14
+ from typing import TYPE_CHECKING, Any, TypeVar
15
+
16
+ from PySide6.QtCore import QCoreApplication, QEvent, QObject, QThread, QTimer, Signal
17
+ from PySide6.QtWidgets import QApplication
18
+
19
+ from lightfall.utils.logging import logger
20
+
21
+ if TYPE_CHECKING:
22
+ from collections.abc import Callable
23
+
24
+ __all__ = [
25
+ "ThreadManager",
26
+ "ManagedThreadPool",
27
+ "get_thread_manager",
28
+ "thread_manager",
29
+ "QThreadFuture",
30
+ "QThreadFutureIterator",
31
+ "method",
32
+ "iterator",
33
+ "invoke_in_main_thread",
34
+ "invoke_as_event",
35
+ "is_main_thread",
36
+ "initialize_main_thread_invoker",
37
+ ]
38
+
39
+ T = TypeVar("T")
40
+
41
+ # -----------------------------------------------------------------------------
42
+ # Coverage workaround for QThread tracing
43
+ # -----------------------------------------------------------------------------
44
+ _running_coverage = "coverage" in sys.modules
45
+
46
+
47
+ def _coverage_resolve_trace(fn: Callable[..., T]) -> Callable[..., T]:
48
+ """Decorator to fix coverage tracing inside QThread.run() methods."""
49
+ if not _running_coverage:
50
+ return fn
51
+
52
+ @wraps(fn)
53
+ def wrapped(*args: Any, **kwargs: Any) -> T:
54
+ sys.settrace(threading._trace_hook)
55
+ return fn(*args, **kwargs)
56
+
57
+ return wrapped
58
+
59
+
60
+ # -----------------------------------------------------------------------------
61
+ # Thread Manager (Singleton)
62
+ # -----------------------------------------------------------------------------
63
+ class _ThreadManagerSignals(QObject):
64
+ """Helper QObject to hold signals for ThreadManager (which is not a QObject)."""
65
+
66
+ sigProgress = Signal(object, object, object, object) # (thread, current, minimum, maximum)
67
+ sigFinished = Signal(object) # (thread,)
68
+
69
+
70
+ class ThreadManager:
71
+ """Global registry for tracking and managing QThreadFuture instances.
72
+
73
+ Access via get_thread_manager() or the module-level thread_manager variable.
74
+
75
+ Signals (via .signals attribute):
76
+ sigProgress: Relayed from all registered threads.
77
+ """
78
+
79
+ _instance: ThreadManager | None = None
80
+ _lock = threading.Lock()
81
+
82
+ def __new__(cls) -> ThreadManager:
83
+ if cls._instance is None:
84
+ with cls._lock:
85
+ if cls._instance is None:
86
+ cls._instance = super().__new__(cls)
87
+ cls._instance._initialized = False
88
+ return cls._instance
89
+
90
+ def __init__(self) -> None:
91
+ if self._initialized:
92
+ return
93
+ self._initialized = True
94
+ self._signals = _ThreadManagerSignals()
95
+ # Strong references to prevent GC before thread completion.
96
+ # Threads unregister themselves in finally block when done.
97
+ self._threads: dict[int, QThreadFuture] = {}
98
+ self._keys: dict[str, int] = {} # key -> thread id mapping
99
+ self._registry_lock = threading.Lock()
100
+ self._shutdown_connected = False
101
+ self._connect_app_shutdown()
102
+
103
+ @property
104
+ def sigProgress(self) -> Signal:
105
+ """Progress signal relayed from all registered threads."""
106
+ return self._signals.sigProgress
107
+
108
+ @property
109
+ def sigFinished(self) -> Signal:
110
+ """Emitted with the thread object when a registered thread finishes."""
111
+ return self._signals.sigFinished
112
+
113
+ def _connect_app_shutdown(self) -> None:
114
+ """Connect to application shutdown signal if app exists."""
115
+ if self._shutdown_connected:
116
+ return
117
+ app = QApplication.instance()
118
+ if app:
119
+ app.aboutToQuit.connect(self.shutdown)
120
+ self._shutdown_connected = True
121
+
122
+ def register(self, thread: QThreadFuture, key: str | None = None) -> None:
123
+ """Register a thread for tracking.
124
+
125
+ Holds a strong reference to prevent GC before thread completion.
126
+ Threads must call unregister() when done (handled automatically
127
+ in QThreadFuture.run() finally block).
128
+
129
+ Args:
130
+ thread: The QThreadFuture to track.
131
+ key: Optional unique key for later retrieval. If a thread with
132
+ this key already exists, the old one is cancelled first.
133
+ """
134
+ # Ensure shutdown is connected (in case app was created after ThreadManager)
135
+ self._connect_app_shutdown()
136
+
137
+ thread_id = id(thread)
138
+
139
+ with self._registry_lock:
140
+ # Cancel existing thread with same key
141
+ if key and key in self._keys:
142
+ old_id = self._keys[key]
143
+ old_thread = self._threads.get(old_id)
144
+ if old_thread and old_thread.isRunning():
145
+ logger.debug(f"Cancelling existing thread with key '{key}'")
146
+ old_thread.cancel()
147
+
148
+ self._threads[thread_id] = thread
149
+ if key:
150
+ self._keys[key] = thread_id
151
+ thread._manager_key = key
152
+
153
+ # Relay thread progress through the manager's signal
154
+ thread.sigProgress.connect(self._signals.sigProgress)
155
+
156
+ logger.trace(f"Registered thread {thread_id}" + (f" with key '{key}'" if key else ""))
157
+
158
+ def unregister(self, thread: QThreadFuture) -> None:
159
+ """Unregister a thread from tracking."""
160
+ thread_id = id(thread)
161
+ with self._registry_lock:
162
+ self._threads.pop(thread_id, None)
163
+ key = getattr(thread, "_manager_key", None)
164
+ if key and key in self._keys:
165
+ del self._keys[key]
166
+
167
+ # Disconnect progress relay
168
+ try:
169
+ thread.sigProgress.disconnect(self._signals.sigProgress)
170
+ except RuntimeError:
171
+ pass # Already disconnected
172
+
173
+ self._signals.sigFinished.emit(thread)
174
+ logger.trace(f"Unregistered thread {thread_id}")
175
+
176
+ def get_active(self) -> list[QThreadFuture]:
177
+ """Get all currently active (running) threads."""
178
+ active = []
179
+ with self._registry_lock:
180
+ for thread in list(self._threads.values()):
181
+ if thread.isRunning():
182
+ active.append(thread)
183
+ return active
184
+
185
+ def get_by_key(self, key: str) -> QThreadFuture | None:
186
+ """Get a thread by its key."""
187
+ with self._registry_lock:
188
+ thread_id = self._keys.get(key)
189
+ if thread_id is None:
190
+ return None
191
+ return self._threads.get(thread_id)
192
+
193
+ def cancel(self, key: str, timeout_ms: int = 5000) -> bool:
194
+ """Cancel a thread by key.
195
+
196
+ Args:
197
+ key: The thread key.
198
+ timeout_ms: Time to wait for graceful shutdown before force-terminating.
199
+
200
+ Returns:
201
+ True if thread was found and cancelled, False if not found.
202
+ """
203
+ thread = self.get_by_key(key)
204
+ if thread is None:
205
+ return False
206
+ thread.cancel(timeout_ms=timeout_ms)
207
+ return True
208
+
209
+ def cancel_all(self, timeout_ms: int = 5000) -> None:
210
+ """Cancel all active threads.
211
+
212
+ Args:
213
+ timeout_ms: Time to wait for each thread's graceful shutdown.
214
+ """
215
+ active = self.get_active()
216
+ logger.debug(f"Cancelling {len(active)} active thread(s)")
217
+ for thread in active:
218
+ thread.cancel(timeout_ms=timeout_ms)
219
+
220
+ def wait_all(self, timeout_ms: int | None = None) -> bool:
221
+ """Wait for all active threads to complete.
222
+
223
+ Args:
224
+ timeout_ms: Maximum time to wait in milliseconds. None for indefinite.
225
+
226
+ Returns:
227
+ True if all threads finished, False if timeout occurred.
228
+ """
229
+ active = self.get_active()
230
+ if not active:
231
+ return True
232
+
233
+ deadline = None
234
+ if timeout_ms is not None:
235
+ deadline = time.monotonic() + timeout_ms / 1000
236
+
237
+ for thread in active:
238
+ if deadline is not None:
239
+ remaining = deadline - time.monotonic()
240
+ if remaining <= 0:
241
+ return False
242
+ if not thread.wait(int(remaining * 1000)):
243
+ return False
244
+ else:
245
+ thread.wait()
246
+
247
+ return True
248
+
249
+ def shutdown(self) -> None:
250
+ """Shutdown all threads and pools. Called automatically on application quit."""
251
+ logger.debug("ThreadManager shutting down")
252
+ self.cancel_all(timeout_ms=3000)
253
+ ManagedThreadPool.shutdown_all(wait=False)
254
+
255
+
256
+ def get_thread_manager() -> ThreadManager:
257
+ """Get the global ThreadManager instance."""
258
+ return ThreadManager()
259
+
260
+
261
+ # Module-level singleton access
262
+ thread_manager = get_thread_manager()
263
+
264
+
265
+ # -----------------------------------------------------------------------------
266
+ # Managed Thread Pool
267
+ # -----------------------------------------------------------------------------
268
+ class ManagedThreadPool:
269
+ """A lightweight thread pool with daemon threads and lifecycle management.
270
+
271
+ Unlike ``ThreadPoolExecutor``, this creates daemon threads directly —
272
+ no monkey-patching of CPython internals, no conflicts with Sentry's
273
+ threading integration, and no non-daemon threads blocking process exit.
274
+
275
+ The pool registers itself with ``ThreadManager`` for automatic shutdown
276
+ on application quit.
277
+
278
+ Usage::
279
+
280
+ pool = ManagedThreadPool(max_workers=2, name="my-pool")
281
+ future = pool.submit(some_function, arg1, arg2)
282
+
283
+ # Pool shuts down automatically on app quit, or manually:
284
+ pool.shutdown()
285
+
286
+ Args:
287
+ max_workers: Maximum number of concurrent threads.
288
+ name: Name prefix for threads (used in logging and thread names).
289
+ """
290
+
291
+ # Class-level registry for all pools, so ThreadManager can shut them all down
292
+ _all_pools: list[ManagedThreadPool] = []
293
+ _pools_lock = threading.Lock()
294
+
295
+ def __init__(self, max_workers: int = 1, name: str = "managed-pool") -> None:
296
+ import queue as _queue
297
+ from concurrent.futures import Future
298
+
299
+ self._name = name
300
+ self._shutdown_flag = False
301
+ self._lock = threading.Lock()
302
+ self._work_queue: _queue.SimpleQueue[tuple[Callable, Future] | None] = _queue.SimpleQueue()
303
+ self._Future = Future
304
+
305
+ # Spin up daemon worker threads
306
+ self._workers: list[threading.Thread] = []
307
+ for i in range(max_workers):
308
+ t = threading.Thread(
309
+ target=self._worker,
310
+ daemon=True,
311
+ name=f"{name}_{i}",
312
+ )
313
+ t.start()
314
+ self._workers.append(t)
315
+
316
+ # Register for global cleanup
317
+ with ManagedThreadPool._pools_lock:
318
+ ManagedThreadPool._all_pools.append(self)
319
+
320
+ logger.debug("ManagedThreadPool '{}' created (max_workers={})", name, max_workers)
321
+
322
+ def _worker(self) -> None:
323
+ """Worker loop: pull tasks from the queue and execute them."""
324
+ while True:
325
+ item = self._work_queue.get()
326
+ if item is None:
327
+ # Poison pill — shut down this worker
328
+ return
329
+ fn, future = item
330
+ if future.cancelled():
331
+ continue
332
+ try:
333
+ result = fn()
334
+ future.set_result(result)
335
+ except Exception as exc:
336
+ future.set_exception(exc)
337
+
338
+ @property
339
+ def name(self) -> str:
340
+ """Pool name."""
341
+ return self._name
342
+
343
+ def submit(self, fn: Callable[..., T], *args: Any, **kwargs: Any) -> Any:
344
+ """Submit a callable for execution.
345
+
346
+ Args:
347
+ fn: The callable to execute.
348
+ *args: Positional arguments for the callable.
349
+ **kwargs: Keyword arguments for the callable.
350
+
351
+ Returns:
352
+ A ``concurrent.futures.Future`` representing the result.
353
+
354
+ Raises:
355
+ RuntimeError: If the pool has been shut down.
356
+ """
357
+ if self._shutdown_flag:
358
+ raise RuntimeError(f"ManagedThreadPool '{self._name}' is shut down")
359
+ future = self._Future()
360
+ # Bind args/kwargs into a no-arg callable
361
+ self._work_queue.put((lambda: fn(*args, **kwargs), future))
362
+ return future
363
+
364
+ def shutdown(self, wait: bool = False) -> None:
365
+ """Shut down the pool.
366
+
367
+ Args:
368
+ wait: If True, block until all worker threads finish.
369
+ Defaults to False (non-blocking) since threads are daemon.
370
+ """
371
+ with self._lock:
372
+ if self._shutdown_flag:
373
+ return
374
+ self._shutdown_flag = True
375
+
376
+ # Send poison pills to each worker
377
+ for _ in self._workers:
378
+ self._work_queue.put(None)
379
+
380
+ if wait:
381
+ for t in self._workers:
382
+ t.join(timeout=5.0)
383
+
384
+ # Remove from global registry
385
+ with ManagedThreadPool._pools_lock:
386
+ try:
387
+ ManagedThreadPool._all_pools.remove(self)
388
+ except ValueError:
389
+ pass
390
+
391
+ logger.debug("ManagedThreadPool '{}' shut down", self._name)
392
+
393
+ @classmethod
394
+ def shutdown_all(cls, wait: bool = False) -> None:
395
+ """Shut down all managed thread pools.
396
+
397
+ Called automatically by ThreadManager during application shutdown.
398
+
399
+ Args:
400
+ wait: If True, block until all running tasks complete.
401
+ """
402
+ with cls._pools_lock:
403
+ pools = list(cls._all_pools)
404
+
405
+ for pool in pools:
406
+ try:
407
+ pool.shutdown(wait=wait)
408
+ except Exception as exc:
409
+ logger.debug("Error shutting down pool '{}': {}", pool._name, exc)
410
+
411
+ def __del__(self) -> None:
412
+ """Clean up on garbage collection."""
413
+ if not self._shutdown_flag:
414
+ try:
415
+ self.shutdown(wait=False)
416
+ except Exception:
417
+ pass
418
+
419
+
420
+ # -----------------------------------------------------------------------------
421
+ # QThreadFuture
422
+ # -----------------------------------------------------------------------------
423
+ class QThreadFuture(QThread):
424
+ """A future-like QThread with automatic registration and improved cancellation.
425
+
426
+ Uses Qt signals for cross-thread callback delivery, which is more robust
427
+ than invoke_in_main_thread() as it doesn't require careful initialization
428
+ timing of the invoker object.
429
+
430
+ Signals:
431
+ sigResult: Emitted with the return value when method completes.
432
+ sigError: Emitted with the exception when an error occurs.
433
+ sigDone: Emitted when thread finishes successfully (after sigResult).
434
+
435
+ Example:
436
+ def long_task(x):
437
+ time.sleep(1)
438
+ return x * 2
439
+
440
+ future = QThreadFuture(long_task, 5, callback_slot=print)
441
+ future.start()
442
+ # Later: print receives 10
443
+ """
444
+
445
+ # Signals for cross-thread callback delivery
446
+ # Qt handles thread marshalling automatically when these are emitted
447
+ sigResult = Signal(object) # Emitted with return value
448
+ sigError = Signal(object) # Emitted with exception
449
+ sigDone = Signal() # Emitted when finished successfully
450
+ sigProgress = Signal(object, object, object, object) # (thread, current, minimum, maximum)
451
+
452
+ def __init__(
453
+ self,
454
+ method: Callable[..., Any],
455
+ *args: Any,
456
+ callback_slot: Callable[..., Any] | None = None,
457
+ finished_slot: Callable[[], None] | None = None,
458
+ except_slot: Callable[[Exception], None] | None = None,
459
+ progress_slot: Callable[..., Any] | None = None,
460
+ interrupt_callable: Callable[[], None] | None = None,
461
+ priority: QThread.Priority = QThread.Priority.InheritPriority,
462
+ timeout: int = 0,
463
+ key: str | None = None,
464
+ name: str | None = None,
465
+ register: bool = True,
466
+ **kwargs: Any,
467
+ ) -> None:
468
+ """Initialize the thread future.
469
+
470
+ Args:
471
+ method: The callable to run in the background.
472
+ *args: Positional arguments for the method.
473
+ callback_slot: Called with the return value(s) when method completes.
474
+ finished_slot: Called (no args) when thread finishes successfully.
475
+ except_slot: Called with exception if an error occurs.
476
+ progress_slot: Called with (thread, current, minimum, maximum) on progress.
477
+ interrupt_callable: Called when interrupt is requested (for custom cleanup).
478
+ priority: Thread priority.
479
+ timeout: Auto-cancel after this many milliseconds (0 = no timeout).
480
+ key: Unique key for ThreadManager lookup. Threads with duplicate keys
481
+ will cancel the previous thread.
482
+ name: Name for the thread (for debugging).
483
+ register: Whether to register with ThreadManager (default True).
484
+ **kwargs: Keyword arguments for the method.
485
+ """
486
+ super().__init__()
487
+
488
+ self._method = method
489
+ self._args = args
490
+ self._kwargs = kwargs
491
+ self._callback_slot = callback_slot
492
+ self._finished_slot = finished_slot
493
+ self._except_slot = except_slot
494
+ self._progress_slot = progress_slot
495
+ self._interrupt_callable = interrupt_callable
496
+ self._priority = priority
497
+ self._timeout = timeout
498
+ self._key = key
499
+ self._name = name or getattr(method, "__name__", "anonymous")
500
+ self._register = register
501
+
502
+ self._cancelled = False
503
+ self._exception: Exception | None = None
504
+ self._result: Any = None
505
+ self._manager_key: str | None = None
506
+
507
+ # Connect user-provided slots to signals
508
+ # Qt's signal/slot mechanism handles cross-thread marshalling automatically
509
+ if callback_slot:
510
+ self.sigResult.connect(callback_slot)
511
+ if except_slot:
512
+ self.sigError.connect(except_slot)
513
+ if finished_slot:
514
+ self.sigDone.connect(finished_slot)
515
+ if progress_slot:
516
+ self.sigProgress.connect(progress_slot)
517
+
518
+ @property
519
+ def cancelled(self) -> bool:
520
+ """Whether the thread was cancelled."""
521
+ return self._cancelled
522
+
523
+ @property
524
+ def exception(self) -> Exception | None:
525
+ """The exception raised during execution, if any."""
526
+ return self._exception
527
+
528
+ @property
529
+ def done(self) -> bool:
530
+ """Whether the thread has finished."""
531
+ return self.isFinished()
532
+
533
+ @property
534
+ def running(self) -> bool:
535
+ """Whether the thread is currently running."""
536
+ return self.isRunning()
537
+
538
+ def start(self) -> None:
539
+ """Start the thread."""
540
+ if self.running:
541
+ raise RuntimeError("Thread is already running")
542
+
543
+ if self._register:
544
+ thread_manager.register(self, self._key)
545
+ # Unregister when the thread finishes. The finished signal is
546
+ # emitted by QThread's C++ internals AFTER run() returns, so
547
+ # the thread is in a safe state. This is more reliable than
548
+ # calling unregister inside run()'s finally block, because:
549
+ # 1. run() is still on the call stack when finally runs
550
+ # 2. invoke_in_main_thread uses a Python QEvent subclass whose
551
+ # wrapper can be GC'd after postEvent transfers C++ ownership
552
+ self.finished.connect(self._deferred_unregister)
553
+
554
+ super().start(self._priority)
555
+
556
+ if self._timeout > 0:
557
+ QTimer.singleShot(self._timeout, self.cancel)
558
+
559
+ def _deferred_unregister(self) -> None:
560
+ """Unregister from ThreadManager after thread has finished.
561
+
562
+ Connected to the finished signal in start(). The finished signal
563
+ is emitted by QThread's C++ internals after run() has fully
564
+ returned, so it's safe to drop the ThreadManager reference here.
565
+ """
566
+ thread_manager.unregister(self)
567
+
568
+ @_coverage_resolve_trace
569
+ def run(self) -> None:
570
+ """Execute the method. Do not call directly; use start()."""
571
+ threading.current_thread().name = self._name
572
+ self._cancelled = False
573
+ self._exception = None
574
+
575
+ try:
576
+ runner = self._run()
577
+ while not self.isInterruptionRequested():
578
+ try:
579
+ value = next(runner)
580
+ except StopIteration as ex:
581
+ value = ex.value
582
+ self._result = value
583
+ if self._callback_slot:
584
+ self.sigResult.emit(value)
585
+ break
586
+
587
+ # For regular QThreadFuture, emit result on each yield
588
+ if not isinstance(self, QThreadFutureIterator) and self._callback_slot:
589
+ self.sigResult.emit(value)
590
+
591
+ except Exception as ex:
592
+ self._exception = ex
593
+ try:
594
+ args_repr = repr(self._args)
595
+ except Exception:
596
+ args_repr = f"<{len(self._args)} args, repr failed>"
597
+ try:
598
+ kwargs_repr = repr(self._kwargs)
599
+ except Exception:
600
+ kwargs_repr = f"<{len(self._kwargs)} kwargs, repr failed>"
601
+ logger.error(
602
+ f"Error in thread '{self._name}': {ex}\n"
603
+ f"Method: {getattr(self._method, '__name__', 'UNKNOWN')}\n"
604
+ f"Args: {args_repr}\n"
605
+ f"Kwargs: {kwargs_repr}"
606
+ )
607
+ logger.exception(ex)
608
+ if self._except_slot:
609
+ self.sigError.emit(ex)
610
+ else:
611
+ if self._finished_slot:
612
+ self.sigDone.emit()
613
+
614
+ def _run(self) -> Generator[Any, None, Any]:
615
+ """Internal run implementation. Override in subclasses.
616
+
617
+ For regular QThreadFuture, returns the method result via StopIteration
618
+ so the callback is only invoked once. QThreadFutureIterator overrides
619
+ this to yield intermediate values.
620
+ """
621
+ return self._method(*self._args, **self._kwargs)
622
+ yield # Makes this a generator function (never reached)
623
+
624
+ def result(self, timeout_ms: int | None = None) -> Any:
625
+ """Wait for and return the result.
626
+
627
+ Args:
628
+ timeout_ms: Maximum time to wait. None for indefinite.
629
+
630
+ Returns:
631
+ The return value of the method, or the exception if one occurred.
632
+
633
+ Raises:
634
+ TimeoutError: If timeout is exceeded.
635
+ """
636
+ if not self.running and not self.done:
637
+ self.start()
638
+
639
+ if timeout_ms is not None:
640
+ if not self.wait(timeout_ms):
641
+ raise TimeoutError(f"Thread did not complete within {timeout_ms}ms")
642
+ else:
643
+ self.wait()
644
+
645
+ if self._exception:
646
+ raise self._exception
647
+ return self._result
648
+
649
+ def cancel(self, timeout_ms: int = 5000) -> bool:
650
+ """Cancel the thread.
651
+
652
+ Args:
653
+ timeout_ms: Time to wait for graceful shutdown before force-terminating.
654
+
655
+ Returns:
656
+ True if thread stopped, False if it had to be force-terminated.
657
+ """
658
+ if not self.running:
659
+ return True
660
+
661
+ self._cancelled = True
662
+ self.requestInterruption()
663
+
664
+ if self._interrupt_callable:
665
+ try:
666
+ self._interrupt_callable()
667
+ except Exception as ex:
668
+ logger.warning(f"Error in interrupt callable: {ex}")
669
+
670
+ # Wait for graceful shutdown
671
+ if self.wait(timeout_ms):
672
+ logger.debug(f"Thread '{self._name}' stopped gracefully")
673
+ return True
674
+
675
+ # Force terminate
676
+ logger.warning(f"Thread '{self._name}' did not respond to interrupt, force terminating")
677
+ self.terminate()
678
+ self.wait(1000) # Brief wait after terminate
679
+ return False
680
+
681
+ def report_progress(self, current: float, minimum: float = 0, maximum: float = 100) -> None:
682
+ """Report progress from within the running thread.
683
+
684
+ Can be called from the thread's method via
685
+ ``QThread.currentThread().report_progress(current, minimum, maximum)``.
686
+
687
+ Args:
688
+ current: Current progress value.
689
+ minimum: Minimum progress value.
690
+ maximum: Maximum progress value.
691
+ """
692
+ self.sigProgress.emit(self, current, minimum, maximum)
693
+
694
+ def interrupt(self) -> None:
695
+ """Request interruption without waiting."""
696
+ self.requestInterruption()
697
+ if self._interrupt_callable:
698
+ self._interrupt_callable()
699
+
700
+ def __enter__(self) -> QThreadFuture:
701
+ """Context manager entry - starts the thread."""
702
+ self.start()
703
+ return self
704
+
705
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
706
+ """Context manager exit - waits for completion."""
707
+ self.wait()
708
+
709
+
710
+ # -----------------------------------------------------------------------------
711
+ # QThreadFutureIterator
712
+ # -----------------------------------------------------------------------------
713
+ class QThreadFutureIterator(QThreadFuture):
714
+ """QThreadFuture variant for generators that yields intermediate values.
715
+
716
+ The yield_slot is called for each yielded value, while callback_slot
717
+ is called with the final return value.
718
+
719
+ Signals:
720
+ sigYield: Emitted with each yielded value from the generator.
721
+ """
722
+
723
+ # Signal for yielded values (separate from sigResult which is for final value)
724
+ sigYield = Signal(object)
725
+
726
+ def __init__(
727
+ self,
728
+ method: Callable[..., Generator[Any, None, Any]],
729
+ *args: Any,
730
+ yield_slot: Callable[..., Any] | None = None,
731
+ **kwargs: Any,
732
+ ) -> None:
733
+ """Initialize the iterator thread.
734
+
735
+ Args:
736
+ method: A generator function.
737
+ *args: Positional arguments for the generator.
738
+ yield_slot: Called with each yielded value.
739
+ **kwargs: Additional arguments (see QThreadFuture).
740
+ """
741
+ super().__init__(method, *args, **kwargs)
742
+ self._yield_slot = yield_slot
743
+
744
+ # Connect yield_slot to sigYield signal
745
+ if yield_slot:
746
+ self.sigYield.connect(yield_slot)
747
+
748
+ def _run(self) -> Generator[Any, None, Any]:
749
+ """Run the generator, yielding each value."""
750
+ gen = self._method(*self._args, **self._kwargs)
751
+ for value in gen:
752
+ if self.isInterruptionRequested():
753
+ return
754
+ if self._yield_slot:
755
+ self.sigYield.emit(value)
756
+ yield value
757
+
758
+
759
+ # -----------------------------------------------------------------------------
760
+ # Main Thread Invocation
761
+ # -----------------------------------------------------------------------------
762
+ # Lazy-initialized to avoid creating Qt objects before QApplication exists.
763
+ # On Windows, creating QObjects before QApplication can cause crashes.
764
+ _invoke_event_type: QEvent.Type | None = None
765
+ _invoker: _Invoker | None = None
766
+ _invoker_lock = threading.Lock()
767
+
768
+
769
+ def _get_invoke_event_type() -> QEvent.Type:
770
+ """Get or create the custom event type (lazy initialization)."""
771
+ global _invoke_event_type
772
+ if _invoke_event_type is None:
773
+ _invoke_event_type = QEvent.Type(QEvent.registerEventType())
774
+ return _invoke_event_type
775
+
776
+
777
+ def _get_invoker() -> _Invoker:
778
+ """Get or create the invoker singleton (lazy initialization)."""
779
+ global _invoker
780
+ if _invoker is None:
781
+ with _invoker_lock:
782
+ if _invoker is None:
783
+ _invoker = _Invoker()
784
+ return _invoker
785
+
786
+
787
+ def initialize_main_thread_invoker() -> None:
788
+ """Initialize the invoker on the main thread.
789
+
790
+ Call this after QApplication is created but before starting any
791
+ background threads that use invoke_in_main_thread().
792
+
793
+ This is required because the invoker (a QObject) must be created
794
+ on the main thread for proper event delivery.
795
+ """
796
+ if not is_main_thread():
797
+ raise RuntimeError("initialize_main_thread_invoker must be called from main thread")
798
+ _get_invoker()
799
+ _get_invoke_event_type()
800
+
801
+
802
+ class _InvokeEvent(QEvent):
803
+ """QEvent that carries a callable for main thread execution."""
804
+
805
+ def __init__(self, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
806
+ super().__init__(_get_invoke_event_type())
807
+ self.fn = fn
808
+ self.args = args
809
+ self.kwargs = kwargs
810
+
811
+
812
+ class _Invoker(QObject):
813
+ """QObject that processes InvokeEvents in the main thread."""
814
+
815
+ def event(self, event: QEvent) -> bool:
816
+ if isinstance(event, _InvokeEvent):
817
+ try:
818
+ # Check if it's a signal (has emit method)
819
+ if hasattr(event.fn, "emit"):
820
+ event.fn.emit(*event.args)
821
+ else:
822
+ event.fn(*event.args, **event.kwargs)
823
+ except Exception as ex:
824
+ logger.error(f"Error invoking callback in main thread: {ex}")
825
+ logger.exception(ex)
826
+ return True
827
+ return super().event(event)
828
+
829
+
830
+ def invoke_in_main_thread(fn: Callable[..., Any], *args: Any, force_event: bool = False, **kwargs: Any) -> None:
831
+ """Invoke a callable in the main thread.
832
+
833
+ If already in the main thread and force_event is False, calls immediately.
834
+ Otherwise posts an event to be processed in the main thread's event loop.
835
+
836
+ Args:
837
+ fn: The callable to invoke.
838
+ *args: Positional arguments.
839
+ force_event: If True, always post as event even if in main thread.
840
+ **kwargs: Keyword arguments.
841
+ """
842
+ if not force_event and is_main_thread():
843
+ fn(*args, **kwargs)
844
+ else:
845
+ QCoreApplication.postEvent(_get_invoker(), _InvokeEvent(fn, *args, **kwargs))
846
+
847
+
848
+ def invoke_as_event(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
849
+ """Invoke a callable as an event in the main thread (always posts event)."""
850
+ invoke_in_main_thread(fn, *args, force_event=True, **kwargs)
851
+
852
+
853
+ def is_main_thread() -> bool:
854
+ """Check if the current thread is the main thread."""
855
+ return threading.current_thread() is threading.main_thread()
856
+
857
+
858
+ # -----------------------------------------------------------------------------
859
+ # Decorators
860
+ # -----------------------------------------------------------------------------
861
+ def method(
862
+ callback_slot: Callable[..., Any] | None = None,
863
+ finished_slot: Callable[[], None] | None = None,
864
+ except_slot: Callable[[Exception], None] | None = None,
865
+ priority: QThread.Priority = QThread.Priority.InheritPriority,
866
+ timeout: int = 0,
867
+ block: bool = False,
868
+ key: str | None = None,
869
+ name: str | None = None,
870
+ ) -> Callable[[Callable[..., T]], Callable[..., QThreadFuture]]:
871
+ """Decorator to run a function on a background thread.
872
+
873
+ The decorated function returns a QThreadFuture that starts immediately.
874
+ Callback slots can be overridden at call time using underscore-prefixed kwargs:
875
+ _callback_slot, _finished_slot, _except_slot.
876
+
877
+ Args:
878
+ callback_slot: Default callback for return value.
879
+ finished_slot: Default slot called on completion.
880
+ except_slot: Default slot called on exception.
881
+ priority: Thread priority.
882
+ timeout: Auto-cancel timeout in milliseconds.
883
+ block: If True, wait for result before returning.
884
+ key: Thread key for ThreadManager.
885
+ name: Thread name for debugging.
886
+
887
+ Example:
888
+ @threads.method(callback_slot=handle_result)
889
+ def compute(x):
890
+ return x * 2
891
+
892
+ # Use default callback:
893
+ future = compute(5)
894
+
895
+ # Override callback at call time:
896
+ future = compute(5, _callback_slot=other_handler)
897
+ """
898
+ def decorator(func: Callable[..., T]) -> Callable[..., QThreadFuture]:
899
+ @wraps(func)
900
+ def wrapper(*args: Any, **kwargs: Any) -> QThreadFuture:
901
+ # Extract override kwargs
902
+ cb = kwargs.pop("_callback_slot", callback_slot)
903
+ fs = kwargs.pop("_finished_slot", finished_slot)
904
+ es = kwargs.pop("_except_slot", except_slot)
905
+
906
+ future = QThreadFuture(
907
+ func,
908
+ *args,
909
+ callback_slot=cb,
910
+ finished_slot=fs,
911
+ except_slot=es,
912
+ priority=priority,
913
+ timeout=timeout,
914
+ key=key,
915
+ name=name or func.__name__,
916
+ **kwargs,
917
+ )
918
+ future.start()
919
+
920
+ if block:
921
+ future.result()
922
+
923
+ return future
924
+
925
+ return wrapper
926
+
927
+ return decorator
928
+
929
+
930
+ def iterator(
931
+ yield_slot: Callable[..., Any] | None = None,
932
+ callback_slot: Callable[..., Any] | None = None,
933
+ finished_slot: Callable[[], None] | None = None,
934
+ except_slot: Callable[[Exception], None] | None = None,
935
+ priority: QThread.Priority = QThread.Priority.InheritPriority,
936
+ key: str | None = None,
937
+ name: str | None = None,
938
+ ) -> Callable[[Callable[..., Generator[Any, None, T]]], Callable[..., QThreadFutureIterator]]:
939
+ """Decorator to run a generator on a background thread.
940
+
941
+ Each yielded value is passed to yield_slot. The final return value
942
+ goes to callback_slot. Slots can be overridden at call time using
943
+ underscore-prefixed kwargs.
944
+
945
+ Args:
946
+ yield_slot: Called with each yielded value.
947
+ callback_slot: Called with the final return value.
948
+ finished_slot: Called on completion.
949
+ except_slot: Called on exception.
950
+ priority: Thread priority.
951
+ key: Thread key for ThreadManager.
952
+ name: Thread name for debugging.
953
+
954
+ Example:
955
+ @threads.iterator(yield_slot=update_progress)
956
+ def process_items(items):
957
+ for i, item in enumerate(items):
958
+ yield i / len(items) # Progress
959
+ process(item)
960
+ return "done"
961
+
962
+ future = process_items(my_items)
963
+ """
964
+ def decorator(func: Callable[..., Generator[Any, None, T]]) -> Callable[..., QThreadFutureIterator]:
965
+ @wraps(func)
966
+ def wrapper(*args: Any, **kwargs: Any) -> QThreadFutureIterator:
967
+ # Extract override kwargs
968
+ ys = kwargs.pop("_yield_slot", yield_slot)
969
+ cb = kwargs.pop("_callback_slot", callback_slot)
970
+ fs = kwargs.pop("_finished_slot", finished_slot)
971
+ es = kwargs.pop("_except_slot", except_slot)
972
+
973
+ future = QThreadFutureIterator(
974
+ func,
975
+ *args,
976
+ yield_slot=ys,
977
+ callback_slot=cb,
978
+ finished_slot=fs,
979
+ except_slot=es,
980
+ priority=priority,
981
+ key=key,
982
+ name=name or func.__name__,
983
+ **kwargs,
984
+ )
985
+ future.start()
986
+
987
+ return future
988
+
989
+ return wrapper
990
+
991
+ return decorator