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.
- lightfall/__init__.py +8 -0
- lightfall/__main__.py +10 -0
- lightfall/_version.py +24 -0
- lightfall/acquire/__init__.py +74 -0
- lightfall/acquire/buffer.py +363 -0
- lightfall/acquire/device_wrapper.py +416 -0
- lightfall/acquire/engine/__init__.py +155 -0
- lightfall/acquire/engine/base.py +587 -0
- lightfall/acquire/engine/bluesky.py +358 -0
- lightfall/acquire/engine/mock.py +165 -0
- lightfall/acquire/engine/plugins/__init__.py +9 -0
- lightfall/acquire/engine/plugins/bluesky_plugin.py +56 -0
- lightfall/acquire/engine/plugins/mock_plugin.py +55 -0
- lightfall/acquire/engine/protocol.py +145 -0
- lightfall/acquire/engine/registry.py +152 -0
- lightfall/acquire/engine/state.py +32 -0
- lightfall/acquire/engine/waiting_hook.py +225 -0
- lightfall/acquire/nats_bridge.py +62 -0
- lightfall/acquire/plan_ui.py +78 -0
- lightfall/acquire/plans/__init__.py +38 -0
- lightfall/acquire/plans/adaptive.py +288 -0
- lightfall/acquire/plans/example_plans.py +995 -0
- lightfall/acquire/plans/lightfall_plans.py +587 -0
- lightfall/acquire/plans/registry.py +543 -0
- lightfall/acquire/plans/standard_plans.py +186 -0
- lightfall/acquire/plans/user_plans.py +470 -0
- lightfall/acquire/runengine.py +36 -0
- lightfall/acquire/signals.py +452 -0
- lightfall/acquire/triggers/__init__.py +16 -0
- lightfall/acquire/triggers/base.py +25 -0
- lightfall/acquire/triggers/filter.py +37 -0
- lightfall/acquire/triggers/manager.py +73 -0
- lightfall/acquire/triggers/manual.py +36 -0
- lightfall/acquire/triggers/run_end.py +74 -0
- lightfall/acquire/triggers/run_start.py +52 -0
- lightfall/auth/__init__.py +38 -0
- lightfall/auth/policy.py +518 -0
- lightfall/auth/providers/__init__.py +30 -0
- lightfall/auth/providers/base.py +124 -0
- lightfall/auth/providers/keycloak.py +1017 -0
- lightfall/auth/providers/local.py +319 -0
- lightfall/auth/providers/pam.py +250 -0
- lightfall/auth/service_key.py +173 -0
- lightfall/auth/service_key_auth.py +79 -0
- lightfall/auth/session.py +656 -0
- lightfall/claude/__init__.py +52 -0
- lightfall/claude/_internal/__init__.py +1 -0
- lightfall/claude/_internal/serialization.py +195 -0
- lightfall/claude/_internal/threading.py +61 -0
- lightfall/claude/_internal/worker.py +757 -0
- lightfall/claude/_session_assembly.py +124 -0
- lightfall/claude/agent.py +596 -0
- lightfall/claude/lightfall_core_tools.py +410 -0
- lightfall/claude/markdown.py +103 -0
- lightfall/claude/permission_manager.py +588 -0
- lightfall/claude/tools/__init__.py +45 -0
- lightfall/claude/tools/controller.py +143 -0
- lightfall/claude/tools/interaction.py +177 -0
- lightfall/claude/tools/introspection.py +127 -0
- lightfall/claude/tools/logs.py +155 -0
- lightfall/claude/tools/screenshot.py +87 -0
- lightfall/claude/widget.py +851 -0
- lightfall/claude/widgets/__init__.py +5 -0
- lightfall/claude/widgets/permission_request.py +282 -0
- lightfall/claude/widgets/question_request.py +227 -0
- lightfall/claude/widgets/task_card.py +223 -0
- lightfall/config/__init__.py +23 -0
- lightfall/config/layers.py +317 -0
- lightfall/config/manager.py +244 -0
- lightfall/config/schema.py +154 -0
- lightfall/core/__init__.py +23 -0
- lightfall/core/application.py +727 -0
- lightfall/core/services.py +235 -0
- lightfall/devices/__init__.py +53 -0
- lightfall/devices/backends/__init__.py +17 -0
- lightfall/devices/backends/bcs.py +448 -0
- lightfall/devices/backends/happi.py +986 -0
- lightfall/devices/backends/mock.py +646 -0
- lightfall/devices/base.py +338 -0
- lightfall/devices/catalog.py +1039 -0
- lightfall/devices/connection_manager.py +676 -0
- lightfall/devices/model.py +290 -0
- lightfall/devices/monitoring.py +442 -0
- lightfall/devices/sim/__init__.py +26 -0
- lightfall/devices/sim/areadetector.py +436 -0
- lightfall/devices/sim/generators.py +223 -0
- lightfall/devices/sim/plugins.py +116 -0
- lightfall/epics/__init__.py +28 -0
- lightfall/epics/ca/__init__.py +10 -0
- lightfall/epics/ca/context.py +100 -0
- lightfall/epics/ca/pv.py +303 -0
- lightfall/epics/widgets/__init__.py +49 -0
- lightfall/epics/widgets/areadetector/__init__.py +16 -0
- lightfall/epics/widgets/areadetector/areadetector.py +281 -0
- lightfall/epics/widgets/areadetector/controls.py +478 -0
- lightfall/epics/widgets/areadetector/image_view.py +447 -0
- lightfall/epics/widgets/auto.py +319 -0
- lightfall/epics/widgets/base.py +404 -0
- lightfall/epics/widgets/checkbox.py +239 -0
- lightfall/epics/widgets/combobox.py +202 -0
- lightfall/epics/widgets/label.py +176 -0
- lightfall/epics/widgets/lineedit.py +253 -0
- lightfall/epics/widgets/motor.py +694 -0
- lightfall/epics/widgets/ophyd_base.py +469 -0
- lightfall/epics/widgets/ophyd_combobox.py +86 -0
- lightfall/epics/widgets/ophyd_label.py +54 -0
- lightfall/epics/widgets/ophyd_lineedit.py +170 -0
- lightfall/epics/widgets/ophyd_spinbox.py +79 -0
- lightfall/epics/widgets/slider.py +272 -0
- lightfall/epics/widgets/status_indicator.py +98 -0
- lightfall/epics/widgets/style.py +188 -0
- lightfall/exporter/__init__.py +1 -0
- lightfall/exporter/cli.py +67 -0
- lightfall/exporter/converters/__init__.py +26 -0
- lightfall/exporter/converters/base.py +39 -0
- lightfall/exporter/converters/noop.py +39 -0
- lightfall/exporter/converters/nxsas.py +73 -0
- lightfall/exporter/service.py +200 -0
- lightfall/exporter/tiled_utils.py +92 -0
- lightfall/ipc/__init__.py +6 -0
- lightfall/ipc/service.py +701 -0
- lightfall/ipc/trust.py +144 -0
- lightfall/logbook/__init__.py +46 -0
- lightfall/logbook/action_dialog.py +207 -0
- lightfall/logbook/action_logger.py +432 -0
- lightfall/logbook/block_mapper.py +562 -0
- lightfall/logbook/client.py +799 -0
- lightfall/logbook/converter.py +273 -0
- lightfall/logbook/editors/__init__.py +19 -0
- lightfall/logbook/editors/highlighter.py +305 -0
- lightfall/logbook/editors/markdown_editor.py +319 -0
- lightfall/logbook/editors/richtext_editor.py +1397 -0
- lightfall/logbook/entry_widget.py +1065 -0
- lightfall/logbook/event_listener.py +221 -0
- lightfall/logbook/fragment_widgets.py +925 -0
- lightfall/logbook/position_mapper.py +320 -0
- lightfall/logbook/protection.py +402 -0
- lightfall/logbook/style.py +394 -0
- lightfall/logbook/url.py +29 -0
- lightfall/logbook/visual_protection.py +330 -0
- lightfall/logbook/widget.py +680 -0
- lightfall/main.py +1091 -0
- lightfall/pipelines/__init__.py +4 -0
- lightfall/pipelines/client.py +148 -0
- lightfall/plugins/__init__.py +119 -0
- lightfall/plugins/agent_plugin.py +106 -0
- lightfall/plugins/agents/__init__.py +10 -0
- lightfall/plugins/agents/_mcp_helpers.py +52 -0
- lightfall/plugins/agents/alignment.py +94 -0
- lightfall/plugins/agents/autonomous_experiment/__init__.py +12 -0
- lightfall/plugins/agents/autonomous_experiment/nats_tools.py +210 -0
- lightfall/plugins/agents/autonomous_experiment/plugin.py +60 -0
- lightfall/plugins/agents/autonomous_experiment/prompts.py +164 -0
- lightfall/plugins/agents/current_esaf.py +435 -0
- lightfall/plugins/agents/device_tools.py +1043 -0
- lightfall/plugins/agents/engine_tools.py +720 -0
- lightfall/plugins/agents/ipython_tools.py +444 -0
- lightfall/plugins/agents/panel_builder.py +637 -0
- lightfall/plugins/agents/panel_design/references/cross_panel_patterns.md +95 -0
- lightfall/plugins/agents/panel_design/references/panel_design.md +680 -0
- lightfall/plugins/agents/panel_design.py +94 -0
- lightfall/plugins/agents/plan_design/references/plan_design.md +398 -0
- lightfall/plugins/agents/plan_design.py +90 -0
- lightfall/plugins/agents/plan_tools.py +878 -0
- lightfall/plugins/agents/scan_planning.py +101 -0
- lightfall/plugins/builtin_manifest.py +348 -0
- lightfall/plugins/controller_plugin.py +162 -0
- lightfall/plugins/engine_plugin.py +124 -0
- lightfall/plugins/errors.py +104 -0
- lightfall/plugins/info.py +112 -0
- lightfall/plugins/loader.py +878 -0
- lightfall/plugins/manifest.py +150 -0
- lightfall/plugins/panel_plugin.py +119 -0
- lightfall/plugins/plan_plugin.py +163 -0
- lightfall/plugins/registry.py +309 -0
- lightfall/plugins/settings_plugin.py +226 -0
- lightfall/plugins/statusbar_plugin.py +289 -0
- lightfall/plugins/theme_plugin.py +165 -0
- lightfall/plugins/types.py +136 -0
- lightfall/plugins/user_plugins.py +764 -0
- lightfall/project/__init__.py +37 -0
- lightfall/project/model.py +375 -0
- lightfall/project/service.py +427 -0
- lightfall/project/welcome.py +106 -0
- lightfall/resources/__init__.py +126 -0
- lightfall/resources/images/__init__.py +1 -0
- lightfall/resources/images/icon.ico +0 -0
- lightfall/resources/images/icon.png +0 -0
- lightfall/resources/images/logo.png +0 -0
- lightfall/services/__init__.py +33 -0
- lightfall/services/_alshub_client.py +73 -0
- lightfall/services/access_stamper.py +240 -0
- lightfall/services/als_beam_status.py +347 -0
- lightfall/services/ca_tunnel.py +325 -0
- lightfall/services/threaded_tiled_writer.py +174 -0
- lightfall/services/tiled_auth.py +21 -0
- lightfall/services/tiled_service.py +971 -0
- lightfall/services/tiled_writer_patch.py +301 -0
- lightfall/settings/__init__.py +1 -0
- lightfall/settings/image_helpers.py +30 -0
- lightfall/settings/user_settings_client.py +232 -0
- lightfall/ui/__init__.py +28 -0
- lightfall/ui/annotations.py +208 -0
- lightfall/ui/common/__init__.py +7 -0
- lightfall/ui/dialogs/__init__.py +26 -0
- lightfall/ui/dialogs/about_dialog.py +131 -0
- lightfall/ui/dialogs/add_trigger_dialog.py +152 -0
- lightfall/ui/dialogs/base.py +44 -0
- lightfall/ui/dialogs/bug_report_dialog.py +353 -0
- lightfall/ui/dialogs/create_plan_dialog.py +189 -0
- lightfall/ui/dialogs/device_edit_dialog.py +183 -0
- lightfall/ui/dialogs/export_dialog.py +565 -0
- lightfall/ui/dialogs/go_to_position_dialog.py +192 -0
- lightfall/ui/dialogs/login_dialog.py +756 -0
- lightfall/ui/dialogs/oauth_browser_dialog.py +305 -0
- lightfall/ui/dialogs/run_pipeline_dialog.py +131 -0
- lightfall/ui/dialogs/sample_metadata_dialog.py +316 -0
- lightfall/ui/docking/__init__.py +22 -0
- lightfall/ui/docking/icon_sidebar.py +806 -0
- lightfall/ui/docking/manager.py +682 -0
- lightfall/ui/docking/state.py +113 -0
- lightfall/ui/docking/theme.py +399 -0
- lightfall/ui/docking/widget.py +214 -0
- lightfall/ui/events.py +75 -0
- lightfall/ui/mainwindow.py +1006 -0
- lightfall/ui/models/__init__.py +49 -0
- lightfall/ui/models/device_selection.py +389 -0
- lightfall/ui/models/device_tree.py +1095 -0
- lightfall/ui/models/thread_model.py +667 -0
- lightfall/ui/models/tiled_model.py +384 -0
- lightfall/ui/panels/__init__.py +28 -0
- lightfall/ui/panels/base.py +525 -0
- lightfall/ui/panels/bluesky_panel.py +619 -0
- lightfall/ui/panels/claude/__init__.py +9 -0
- lightfall/ui/panels/claude/agent_registry.py +168 -0
- lightfall/ui/panels/claude_panel.py +887 -0
- lightfall/ui/panels/device_panel.py +370 -0
- lightfall/ui/panels/documents_panel.py +166 -0
- lightfall/ui/panels/ipython_panel.py +580 -0
- lightfall/ui/panels/logbook_entries_panel.py +84 -0
- lightfall/ui/panels/logbook_panel.py +627 -0
- lightfall/ui/panels/logging_panel.py +587 -0
- lightfall/ui/panels/pipeline_jobs_panel.py +160 -0
- lightfall/ui/panels/pipeline_triggers_panel.py +170 -0
- lightfall/ui/panels/plugins/__init__.py +34 -0
- lightfall/ui/panels/plugins/bluesky_plugin.py +27 -0
- lightfall/ui/panels/plugins/claude_plugin.py +29 -0
- lightfall/ui/panels/plugins/device_plugin.py +27 -0
- lightfall/ui/panels/plugins/documents_plugin.py +26 -0
- lightfall/ui/panels/plugins/ipython_plugin.py +27 -0
- lightfall/ui/panels/plugins/logbook_entries_plugin.py +23 -0
- lightfall/ui/panels/plugins/logbook_plugin.py +27 -0
- lightfall/ui/panels/plugins/logging_plugin.py +27 -0
- lightfall/ui/panels/plugins/pipeline_jobs_plugin.py +23 -0
- lightfall/ui/panels/plugins/pipeline_triggers_plugin.py +25 -0
- lightfall/ui/panels/plugins/queue_plugin.py +29 -0
- lightfall/ui/panels/plugins/synoptic_plugin.py +38 -0
- lightfall/ui/panels/plugins/threads_plugin.py +27 -0
- lightfall/ui/panels/plugins/tiled_browser_plugin.py +27 -0
- lightfall/ui/panels/plugins/visualization_plugin.py +27 -0
- lightfall/ui/panels/queue.py +754 -0
- lightfall/ui/panels/registry.py +483 -0
- lightfall/ui/panels/synoptic/__init__.py +27 -0
- lightfall/ui/panels/synoptic/editors.py +481 -0
- lightfall/ui/panels/synoptic/items.py +556 -0
- lightfall/ui/panels/synoptic/models.py +336 -0
- lightfall/ui/panels/synoptic/panel.py +889 -0
- lightfall/ui/panels/synoptic/serialization.py +300 -0
- lightfall/ui/panels/synoptic/view.py +504 -0
- lightfall/ui/panels/threads_panel.py +621 -0
- lightfall/ui/panels/tiled_browser_panel.py +854 -0
- lightfall/ui/panels/visualization_panel.py +508 -0
- lightfall/ui/preferences/__init__.py +24 -0
- lightfall/ui/preferences/backend.py +148 -0
- lightfall/ui/preferences/builtin.py +220 -0
- lightfall/ui/preferences/claude_settings.py +762 -0
- lightfall/ui/preferences/device_settings.py +461 -0
- lightfall/ui/preferences/dialog.py +234 -0
- lightfall/ui/preferences/editor_settings.py +227 -0
- lightfall/ui/preferences/ipc_settings.py +226 -0
- lightfall/ui/preferences/logbook_settings.py +232 -0
- lightfall/ui/preferences/login_settings.py +183 -0
- lightfall/ui/preferences/manager.py +562 -0
- lightfall/ui/preferences/plugin_settings.py +392 -0
- lightfall/ui/preferences/proxy_settings.py +561 -0
- lightfall/ui/preferences/skill_settings.py +28 -0
- lightfall/ui/preferences/tiled_settings.py +469 -0
- lightfall/ui/preferences/tool_settings.py +393 -0
- lightfall/ui/preferences/user_portable_backend.py +131 -0
- lightfall/ui/preferences/user_profile_settings.py +316 -0
- lightfall/ui/preferences/visualization_settings.py +159 -0
- lightfall/ui/resources/__init__.py +1 -0
- lightfall/ui/resources/logo.png +0 -0
- lightfall/ui/statusbar/__init__.py +11 -0
- lightfall/ui/statusbar/manager.py +379 -0
- lightfall/ui/statusbar/plugins/__init__.py +28 -0
- lightfall/ui/statusbar/plugins/als_beam_status.py +218 -0
- lightfall/ui/statusbar/plugins/auth_status.py +116 -0
- lightfall/ui/statusbar/plugins/connection_status.py +100 -0
- lightfall/ui/statusbar/plugins/thread_status.py +556 -0
- lightfall/ui/statusbar/plugins/tiled_status.py +179 -0
- lightfall/ui/statusbar/plugins/user_status.py +84 -0
- lightfall/ui/theater/__init__.py +28 -0
- lightfall/ui/theater/manager.py +124 -0
- lightfall/ui/theater/overlay.py +279 -0
- lightfall/ui/theater/proxy.py +111 -0
- lightfall/ui/theme/__init__.py +18 -0
- lightfall/ui/theme/builtin.py +1015 -0
- lightfall/ui/theme/manager.py +875 -0
- lightfall/ui/theme/registry.py +195 -0
- lightfall/ui/toast.py +221 -0
- lightfall/ui/tutorial.py +1100 -0
- lightfall/ui/widgets/__init__.py +110 -0
- lightfall/ui/widgets/base_control.py +259 -0
- lightfall/ui/widgets/camera/__init__.py +36 -0
- lightfall/ui/widgets/camera/base.py +815 -0
- lightfall/ui/widgets/camera/dark_frames.py +213 -0
- lightfall/ui/widgets/camera/image_view.py +649 -0
- lightfall/ui/widgets/camera/panels/__init__.py +14 -0
- lightfall/ui/widgets/camera/panels/cooler.py +320 -0
- lightfall/ui/widgets/camera/panels/temperature.py +192 -0
- lightfall/ui/widgets/camera/plan_based.py +202 -0
- lightfall/ui/widgets/compact_motor.py +522 -0
- lightfall/ui/widgets/controller_matcher.py +278 -0
- lightfall/ui/widgets/controller_registry.py +144 -0
- lightfall/ui/widgets/device_control.py +411 -0
- lightfall/ui/widgets/device_selector.py +438 -0
- lightfall/ui/widgets/device_tree_tab.py +461 -0
- lightfall/ui/widgets/document_stream.py +1028 -0
- lightfall/ui/widgets/favorites_tab.py +191 -0
- lightfall/ui/widgets/motor_control.py +1120 -0
- lightfall/ui/widgets/observers/__init__.py +8 -0
- lightfall/ui/widgets/observers/camera.py +48 -0
- lightfall/ui/widgets/observers/image_view.py +130 -0
- lightfall/ui/widgets/plan_config.py +954 -0
- lightfall/ui/widgets/plan_edit_dialog.py +294 -0
- lightfall/ui/widgets/plan_selector.py +452 -0
- lightfall/ui/widgets/profile_avatar.py +128 -0
- lightfall/ui/widgets/queue_view.py +647 -0
- lightfall/ui/widgets/runengine_control.py +549 -0
- lightfall/ui/widgets/signal_control.py +793 -0
- lightfall/ui/widgets/skill_trigger_button.py +183 -0
- lightfall/ui/widgets/tiled_filter_widget.py +314 -0
- lightfall/ui/widgets/tiled_status.py +149 -0
- lightfall/ui/widgets/warning_banner.py +185 -0
- lightfall/utils/__init__.py +53 -0
- lightfall/utils/crash_diagnostics.py +454 -0
- lightfall/utils/data_migration.py +22 -0
- lightfall/utils/editor_launcher.py +594 -0
- lightfall/utils/error_collector.py +245 -0
- lightfall/utils/git_tracker.py +197 -0
- lightfall/utils/log_buffer.py +233 -0
- lightfall/utils/logging.py +229 -0
- lightfall/utils/module_resolver.py +70 -0
- lightfall/utils/sentry.py +722 -0
- lightfall/utils/threads.py +991 -0
- lightfall/utils/tiled_helpers.py +96 -0
- lightfall/visualization/__init__.py +50 -0
- lightfall/visualization/base.py +5 -0
- lightfall/visualization/base_visualization.py +74 -0
- lightfall/visualization/fitting/__init__.py +24 -0
- lightfall/visualization/fitting/base.py +267 -0
- lightfall/visualization/fitting/fitters.py +325 -0
- lightfall/visualization/fitting/panel.py +265 -0
- lightfall/visualization/memory.py +392 -0
- lightfall/visualization/motor_mixin.py +524 -0
- lightfall/visualization/pg.py +156 -0
- lightfall/visualization/registry.py +144 -0
- lightfall/visualization/spec.py +79 -0
- lightfall/visualization/theme.py +266 -0
- lightfall/visualization/widgets/__init__.py +28 -0
- lightfall/visualization/widgets/adaptive/__init__.py +1 -0
- lightfall/visualization/widgets/adaptive/heatmap.py +655 -0
- lightfall/visualization/widgets/adaptive/plot.py +233 -0
- lightfall/visualization/widgets/heatmap.py +264 -0
- lightfall/visualization/widgets/image_stack.py +316 -0
- lightfall/visualization/widgets/image_view_toolbar.py +227 -0
- lightfall/visualization/widgets/lazy_image_view.py +590 -0
- lightfall/visualization/widgets/plot_1d.py +262 -0
- lightfall/visualization/widgets/scatter.py +247 -0
- lightfall/visualization/widgets/table.py +221 -0
- lightfall/visualization/widgets/time_axis.py +93 -0
- lightfall-0.1.1.dist-info/METADATA +223 -0
- lightfall-0.1.1.dist-info/RECORD +388 -0
- lightfall-0.1.1.dist-info/WHEEL +4 -0
- lightfall-0.1.1.dist-info/entry_points.txt +6 -0
- lightfall-0.1.1.dist-info/licenses/LEGAL.md +13 -0
- lightfall-0.1.1.dist-info/licenses/LICENSE.md +33 -0
lightfall/main.py
ADDED
|
@@ -0,0 +1,1091 @@
|
|
|
1
|
+
"""Main entry point for the Lightfall application."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
# Set Windows AppUserModelID BEFORE any Qt imports.
|
|
9
|
+
# This must happen before COM/Qt initialization for the taskbar icon to work.
|
|
10
|
+
# See: https://stackoverflow.com/a/1552105
|
|
11
|
+
if sys.platform == "win32":
|
|
12
|
+
import ctypes
|
|
13
|
+
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("gov.lbl.als.lightfall")
|
|
14
|
+
|
|
15
|
+
# Install crash diagnostics before QApplication is constructed so
|
|
16
|
+
# faulthandler is enabled and Qt environment knobs (QT_LOGGING_RULES) are
|
|
17
|
+
# in place when Qt's logging system is first read. PySide6 is transitively
|
|
18
|
+
# imported by lightfall.utils, but importing the package does not construct a
|
|
19
|
+
# QCoreApplication — env vars are still in time.
|
|
20
|
+
from lightfall.utils import crash_diagnostics # noqa: E402
|
|
21
|
+
|
|
22
|
+
crash_diagnostics.install()
|
|
23
|
+
|
|
24
|
+
from datetime import timedelta # noqa: E402
|
|
25
|
+
from typing import TYPE_CHECKING # noqa: E402
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _configure_remote_display() -> None:
|
|
29
|
+
"""Configure environment for remote displays BEFORE Qt is imported.
|
|
30
|
+
|
|
31
|
+
Detects VNC/remote X11 and sets environment variables for software rendering.
|
|
32
|
+
Must run before any Qt imports.
|
|
33
|
+
"""
|
|
34
|
+
# Check for VNC-specific environment variables
|
|
35
|
+
if os.environ.get("VNCDESKTOP") or os.environ.get("VNC_SESSION"):
|
|
36
|
+
is_remote = True
|
|
37
|
+
else:
|
|
38
|
+
# Check DISPLAY for remote X11 or high display numbers (VNC)
|
|
39
|
+
display = os.environ.get("DISPLAY", "")
|
|
40
|
+
is_remote = False
|
|
41
|
+
if display:
|
|
42
|
+
# Remote X11: hostname:0
|
|
43
|
+
if ":" in display and not display.startswith(":"):
|
|
44
|
+
is_remote = True
|
|
45
|
+
else:
|
|
46
|
+
# High display numbers often indicate VNC (:1, :2, etc.)
|
|
47
|
+
try:
|
|
48
|
+
display_num = int(display.split(":")[1].split(".")[0])
|
|
49
|
+
if display_num > 0:
|
|
50
|
+
is_remote = True
|
|
51
|
+
except (IndexError, ValueError):
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
if is_remote:
|
|
55
|
+
# Disable Vulkan at the loader level
|
|
56
|
+
os.environ.setdefault("VK_ICD_FILENAMES", "")
|
|
57
|
+
os.environ.setdefault("VK_DRIVER_FILES", "")
|
|
58
|
+
# Force software rendering for Mesa/OpenGL
|
|
59
|
+
os.environ.setdefault("LIBGL_ALWAYS_SOFTWARE", "1")
|
|
60
|
+
# Qt software rendering
|
|
61
|
+
os.environ.setdefault("QT_QUICK_BACKEND", "software")
|
|
62
|
+
os.environ.setdefault("QT_OPENGL", "software")
|
|
63
|
+
os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1")
|
|
64
|
+
# Chromium flags for WebEngine
|
|
65
|
+
existing = os.environ.get("QTWEBENGINE_CHROMIUM_FLAGS", "")
|
|
66
|
+
remote_flags = [
|
|
67
|
+
"--disable-gpu",
|
|
68
|
+
"--disable-gpu-compositing",
|
|
69
|
+
"--disable-vulkan",
|
|
70
|
+
"--disable-features=Vulkan,VulkanFromANGLE,UseSkiaRenderer",
|
|
71
|
+
"--no-sandbox",
|
|
72
|
+
"--disable-dev-shm-usage",
|
|
73
|
+
]
|
|
74
|
+
for flag in remote_flags:
|
|
75
|
+
if flag not in existing:
|
|
76
|
+
existing = f"{existing} {flag}".strip()
|
|
77
|
+
os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = existing
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# Configure remote display BEFORE any Qt imports
|
|
81
|
+
_configure_remote_display()
|
|
82
|
+
|
|
83
|
+
from PySide6.QtCore import Qt # noqa: E402
|
|
84
|
+
|
|
85
|
+
from lightfall.acquire import get_engine # noqa: E402
|
|
86
|
+
from lightfall.acquire.plans import get_registry as get_plan_registry # noqa: E402
|
|
87
|
+
from lightfall.auth.providers import LocalAuthProvider # noqa: E402
|
|
88
|
+
from lightfall.auth.session import SessionManager # noqa: E402
|
|
89
|
+
from lightfall.config import ConfigManager # noqa: E402
|
|
90
|
+
from lightfall.core import LFApplication # noqa: E402
|
|
91
|
+
from lightfall.devices import DeviceCatalog # noqa: E402
|
|
92
|
+
from lightfall.devices.backends import BCSBackend, HappiBackend, MockBackend # noqa: E402
|
|
93
|
+
from lightfall.project import ProjectService, create_welcome_project # noqa: E402
|
|
94
|
+
from lightfall.ui import LFMainWindow # noqa: E402
|
|
95
|
+
from lightfall.ui.panels.registry import PanelRegistry # noqa: E402
|
|
96
|
+
from lightfall.ui.preferences import PreferencesManager # noqa: E402
|
|
97
|
+
from lightfall.ui.theme import ThemeManager # noqa: E402
|
|
98
|
+
from lightfall.ui.widgets.warning_banner import DismissableWarningBanner # noqa: E402
|
|
99
|
+
from lightfall.utils.data_migration import migrate_legacy_data_dir # noqa: E402
|
|
100
|
+
from lightfall.utils.editor_launcher import CodeEditor, is_editor_available # noqa: E402
|
|
101
|
+
from lightfall.utils.logging import logger # noqa: E402
|
|
102
|
+
from lightfall.utils.sentry import clear_user as sentry_clear_user # noqa: E402
|
|
103
|
+
from lightfall.utils.sentry import init_sentry # noqa: E402
|
|
104
|
+
from lightfall.utils.sentry import set_user as sentry_set_user # noqa: E402
|
|
105
|
+
|
|
106
|
+
if TYPE_CHECKING:
|
|
107
|
+
pass
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _setup_auth(config: ConfigManager) -> None:
|
|
111
|
+
"""Setup authentication provider based on configuration.
|
|
112
|
+
|
|
113
|
+
Set environment variable NCS_AUTH=local to force local auth for development.
|
|
114
|
+
"""
|
|
115
|
+
import os
|
|
116
|
+
|
|
117
|
+
session_manager = SessionManager.get_instance()
|
|
118
|
+
|
|
119
|
+
auth_config = config.model.auth
|
|
120
|
+
provider_type = auth_config.provider.type
|
|
121
|
+
|
|
122
|
+
# Allow environment variable override for development
|
|
123
|
+
env_auth = os.environ.get("NCS_AUTH", "").lower()
|
|
124
|
+
if env_auth in ("local", "pam", "keycloak"):
|
|
125
|
+
provider_type = env_auth
|
|
126
|
+
logger.info("Using {} auth (NCS_AUTH={})", provider_type, env_auth)
|
|
127
|
+
|
|
128
|
+
if provider_type == "keycloak" and auth_config.provider.server_url:
|
|
129
|
+
# Use Keycloak if configured
|
|
130
|
+
try:
|
|
131
|
+
from lightfall.auth.providers.keycloak import KeycloakAuthProvider, KeycloakConfig
|
|
132
|
+
|
|
133
|
+
kc_config = KeycloakConfig(
|
|
134
|
+
server_url=auth_config.provider.server_url,
|
|
135
|
+
realm=auth_config.provider.realm,
|
|
136
|
+
client_id=auth_config.provider.client_id,
|
|
137
|
+
client_secret=auth_config.provider.client_secret or None,
|
|
138
|
+
redirect_uri=auth_config.provider.redirect_uri,
|
|
139
|
+
)
|
|
140
|
+
provider = KeycloakAuthProvider(kc_config)
|
|
141
|
+
logger.info("Using Keycloak authentication provider")
|
|
142
|
+
except ImportError:
|
|
143
|
+
logger.warning("aiohttp not available, falling back to local auth")
|
|
144
|
+
provider = LocalAuthProvider(
|
|
145
|
+
session_duration=timedelta(minutes=auth_config.session_timeout_minutes)
|
|
146
|
+
)
|
|
147
|
+
elif provider_type == "pam":
|
|
148
|
+
try:
|
|
149
|
+
# Build group→role map from config if provided
|
|
150
|
+
from lightfall.auth.policy import Role as _Role
|
|
151
|
+
from lightfall.auth.providers.pam import PamAuthProvider, PamConfig
|
|
152
|
+
|
|
153
|
+
group_role_map = {}
|
|
154
|
+
for group_name, role_str in auth_config.provider.pam_group_role_map.items():
|
|
155
|
+
try:
|
|
156
|
+
group_role_map[group_name] = _Role(role_str)
|
|
157
|
+
except ValueError:
|
|
158
|
+
logger.warning("Unknown role '{}' in pam_group_role_map", role_str)
|
|
159
|
+
|
|
160
|
+
pam_config = PamConfig(
|
|
161
|
+
session_duration=timedelta(minutes=auth_config.session_timeout_minutes),
|
|
162
|
+
)
|
|
163
|
+
if group_role_map:
|
|
164
|
+
pam_config.group_role_map = group_role_map
|
|
165
|
+
|
|
166
|
+
provider = PamAuthProvider(pam_config)
|
|
167
|
+
logger.info("Using Linux system authentication provider")
|
|
168
|
+
except ImportError:
|
|
169
|
+
logger.warning("python-pam not available, falling back to local auth")
|
|
170
|
+
provider = LocalAuthProvider(
|
|
171
|
+
session_duration=timedelta(minutes=auth_config.session_timeout_minutes)
|
|
172
|
+
)
|
|
173
|
+
else:
|
|
174
|
+
# Use local auth provider for development
|
|
175
|
+
provider = LocalAuthProvider(
|
|
176
|
+
session_duration=timedelta(minutes=auth_config.session_timeout_minutes)
|
|
177
|
+
)
|
|
178
|
+
logger.info("Using local development authentication provider")
|
|
179
|
+
|
|
180
|
+
session_manager.set_provider(provider)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _setup_services(app: LFApplication, config: ConfigManager) -> None:
|
|
184
|
+
"""Setup application services."""
|
|
185
|
+
# Register additional services
|
|
186
|
+
services = app.services
|
|
187
|
+
|
|
188
|
+
# Theme manager
|
|
189
|
+
services.register(ThemeManager, ThemeManager.get_instance)
|
|
190
|
+
|
|
191
|
+
# Session manager
|
|
192
|
+
services.register(SessionManager, SessionManager.get_instance)
|
|
193
|
+
|
|
194
|
+
# Preferences manager
|
|
195
|
+
prefs = PreferencesManager.get_instance()
|
|
196
|
+
prefs.set_config_manager(config)
|
|
197
|
+
services.register_instance(PreferencesManager, prefs)
|
|
198
|
+
|
|
199
|
+
# Panel registry - panels are registered via plugin system (preload plugins)
|
|
200
|
+
# External entry point panels can still use ncs.panels entry points via discover_plugins()
|
|
201
|
+
registry = PanelRegistry.get_instance()
|
|
202
|
+
services.register_instance(PanelRegistry, registry)
|
|
203
|
+
|
|
204
|
+
# Project service
|
|
205
|
+
project_service = ProjectService.get_instance()
|
|
206
|
+
services.register_instance(ProjectService, project_service)
|
|
207
|
+
|
|
208
|
+
# Device catalog with mock backend
|
|
209
|
+
device_catalog = DeviceCatalog.get_instance()
|
|
210
|
+
services.register_instance(DeviceCatalog, device_catalog)
|
|
211
|
+
|
|
212
|
+
# Initialize connection manager with settings
|
|
213
|
+
from lightfall.devices.connection_manager import DeviceConnectionManager
|
|
214
|
+
|
|
215
|
+
connection_manager = DeviceConnectionManager.get_instance()
|
|
216
|
+
connection_manager.load_settings()
|
|
217
|
+
services.register_instance(DeviceConnectionManager, connection_manager)
|
|
218
|
+
|
|
219
|
+
# Pipeline client - lazy singleton so IPCService and Tiled URL settings
|
|
220
|
+
# are read at first request, not at startup.
|
|
221
|
+
from lightfall.acquire.triggers.manager import TriggerManager
|
|
222
|
+
from lightfall.pipelines import PipelineClient
|
|
223
|
+
|
|
224
|
+
def _build_pipeline_client() -> PipelineClient:
|
|
225
|
+
import socket
|
|
226
|
+
|
|
227
|
+
from lightfall.core.services import ServiceRegistry
|
|
228
|
+
from lightfall.ipc.service import IPCService
|
|
229
|
+
from lightfall.services.tiled_service import get_tiled_base_url
|
|
230
|
+
|
|
231
|
+
ipc = ServiceRegistry.get_instance().get(IPCService)
|
|
232
|
+
session_manager = SessionManager.get_instance()
|
|
233
|
+
return PipelineClient(
|
|
234
|
+
ipc=ipc,
|
|
235
|
+
host=socket.gethostname(),
|
|
236
|
+
tiled_url=get_tiled_base_url().rstrip("/") + "/api/v1",
|
|
237
|
+
key_provider=session_manager.get_minted_key,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
services.register(PipelineClient, _build_pipeline_client)
|
|
241
|
+
|
|
242
|
+
def _build_trigger_manager() -> TriggerManager:
|
|
243
|
+
from lightfall.core.services import ServiceRegistry
|
|
244
|
+
|
|
245
|
+
def _submit_via_pipeline_client(
|
|
246
|
+
*,
|
|
247
|
+
pipeline: str,
|
|
248
|
+
run_uid: str,
|
|
249
|
+
parameters: dict,
|
|
250
|
+
input_access_blob: dict,
|
|
251
|
+
) -> None:
|
|
252
|
+
client = ServiceRegistry.get_instance().get(PipelineClient, None)
|
|
253
|
+
if client is None:
|
|
254
|
+
logger.warning(
|
|
255
|
+
"TriggerManager: no PipelineClient registered; "
|
|
256
|
+
"dropping fire for pipeline={} run_uid={}",
|
|
257
|
+
pipeline, run_uid,
|
|
258
|
+
)
|
|
259
|
+
return
|
|
260
|
+
session = SessionManager.get_instance()
|
|
261
|
+
user_id = session.current_user.attributes.get(
|
|
262
|
+
"preferred_username", ""
|
|
263
|
+
)
|
|
264
|
+
try:
|
|
265
|
+
client.submit(
|
|
266
|
+
pipeline=pipeline,
|
|
267
|
+
input_run_uid=run_uid,
|
|
268
|
+
parameters=parameters,
|
|
269
|
+
input_access_blob=input_access_blob,
|
|
270
|
+
user_id=user_id,
|
|
271
|
+
)
|
|
272
|
+
except Exception as exc:
|
|
273
|
+
logger.error(
|
|
274
|
+
"TriggerManager: submit failed for pipeline={} run_uid={}: {}",
|
|
275
|
+
pipeline, run_uid, exc,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
return TriggerManager(
|
|
279
|
+
engine=get_engine(),
|
|
280
|
+
submit_callable=_submit_via_pipeline_client,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
services.register(TriggerManager, _build_trigger_manager)
|
|
284
|
+
|
|
285
|
+
logger.debug("Application services registered")
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _setup_ca_tunnel() -> None:
|
|
289
|
+
"""Start the CA UDP-to-TCP tunnel if configured.
|
|
290
|
+
|
|
291
|
+
When connecting to a remote CA Gateway through an SSH tunnel,
|
|
292
|
+
CA clients need UDP for PV search but SSH only forwards TCP.
|
|
293
|
+
This service bridges the gap by forwarding local UDP packets
|
|
294
|
+
through the TCP tunnel.
|
|
295
|
+
|
|
296
|
+
Must run BEFORE any EPICS/ophyd initialization.
|
|
297
|
+
"""
|
|
298
|
+
prefs = PreferencesManager.get_instance()
|
|
299
|
+
|
|
300
|
+
enabled = prefs.get("ca_tunnel_enabled", False)
|
|
301
|
+
if not enabled:
|
|
302
|
+
return
|
|
303
|
+
|
|
304
|
+
gateway = prefs.get("ca_tunnel_gateway", "localhost:5099")
|
|
305
|
+
|
|
306
|
+
from lightfall.services.ca_tunnel import CATunnelService
|
|
307
|
+
|
|
308
|
+
service = CATunnelService.get_instance()
|
|
309
|
+
if service.start(gateway=gateway):
|
|
310
|
+
logger.info("CA tunnel active: gateway={}", gateway)
|
|
311
|
+
|
|
312
|
+
# Increase connection timeout for tunneled connections.
|
|
313
|
+
# ophyd passes timeout=1.0 to caproto's PV.wait_for_connection,
|
|
314
|
+
# which is too tight for initial SSH-tunneled connections.
|
|
315
|
+
# Use 3s minimum — enough for the tunnel round-trip without
|
|
316
|
+
# making the UI sluggish for unconnected PVs.
|
|
317
|
+
_tunnel_min_timeout = 3.0
|
|
318
|
+
try:
|
|
319
|
+
from caproto.threading.pyepics_compat import PV as _CaprotoPV
|
|
320
|
+
|
|
321
|
+
_orig_wait = _CaprotoPV.wait_for_connection
|
|
322
|
+
_CaprotoPV._orig_wait_for_connection = _orig_wait
|
|
323
|
+
|
|
324
|
+
def _patched_wait(self, timeout=None):
|
|
325
|
+
if timeout is None or timeout < _tunnel_min_timeout:
|
|
326
|
+
timeout = _tunnel_min_timeout
|
|
327
|
+
return _orig_wait(self, timeout=timeout)
|
|
328
|
+
|
|
329
|
+
_CaprotoPV.wait_for_connection = _patched_wait
|
|
330
|
+
logger.info(
|
|
331
|
+
"Patched caproto PV.wait_for_connection minimum timeout to {}s",
|
|
332
|
+
_tunnel_min_timeout,
|
|
333
|
+
)
|
|
334
|
+
except Exception as e:
|
|
335
|
+
logger.debug("Could not patch caproto timeout: {}", e)
|
|
336
|
+
# Schedule exponential backoff retries for failed device connections.
|
|
337
|
+
# The tunnel may not be fully working when devices first try to connect.
|
|
338
|
+
# Retry at 2s, 4s, 8s, 16s, 32s, 64s after device setup completes.
|
|
339
|
+
def _schedule_retries():
|
|
340
|
+
from PySide6.QtCore import QTimer
|
|
341
|
+
|
|
342
|
+
from lightfall.utils.threads import QThreadFuture
|
|
343
|
+
|
|
344
|
+
delays = [2000, 4000, 8000, 16000, 32000, 64000] # ms
|
|
345
|
+
|
|
346
|
+
def _do_reconnect():
|
|
347
|
+
from lightfall.devices import DeviceCatalog
|
|
348
|
+
|
|
349
|
+
catalog = DeviceCatalog.get_instance()
|
|
350
|
+
return catalog.reconnect_failed_devices(timeout=5.0)
|
|
351
|
+
|
|
352
|
+
def _on_done(result):
|
|
353
|
+
connected, failed = result
|
|
354
|
+
if connected > 0:
|
|
355
|
+
logger.info(
|
|
356
|
+
"CA tunnel retry: {} devices reconnected, {} still failed",
|
|
357
|
+
connected,
|
|
358
|
+
failed,
|
|
359
|
+
)
|
|
360
|
+
if failed == 0 or not delays:
|
|
361
|
+
logger.info("CA tunnel retry: all reachable devices connected")
|
|
362
|
+
return
|
|
363
|
+
# Schedule next retry
|
|
364
|
+
if delays:
|
|
365
|
+
next_delay = delays.pop(0)
|
|
366
|
+
QTimer.singleShot(next_delay, _start_retry)
|
|
367
|
+
|
|
368
|
+
def _start_retry():
|
|
369
|
+
thread = QThreadFuture(
|
|
370
|
+
_do_reconnect,
|
|
371
|
+
callback_slot=_on_done,
|
|
372
|
+
name="ca-tunnel-retry",
|
|
373
|
+
)
|
|
374
|
+
thread.start()
|
|
375
|
+
|
|
376
|
+
if delays:
|
|
377
|
+
first_delay = delays.pop(0)
|
|
378
|
+
QTimer.singleShot(first_delay, _start_retry)
|
|
379
|
+
|
|
380
|
+
# Store for later — will be called after _setup_devices()
|
|
381
|
+
app_module = __import__(__name__)
|
|
382
|
+
app_module._ca_tunnel_schedule_retries = _schedule_retries
|
|
383
|
+
else:
|
|
384
|
+
logger.error("Failed to start CA tunnel for gateway={}", gateway)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _setup_devices() -> None:
|
|
388
|
+
"""Setup the device catalog based on user preferences.
|
|
389
|
+
|
|
390
|
+
Initializes the DeviceCatalog with all enabled backends.
|
|
391
|
+
Multiple backends can be active simultaneously — their devices
|
|
392
|
+
are merged into a single unified catalog.
|
|
393
|
+
"""
|
|
394
|
+
catalog = DeviceCatalog.get_instance()
|
|
395
|
+
prefs = PreferencesManager.get_instance()
|
|
396
|
+
|
|
397
|
+
# Check which backends are enabled (with legacy compat)
|
|
398
|
+
legacy_backend = prefs.get("device_backend", "mock")
|
|
399
|
+
mock_enabled = prefs.get("device_mock_enabled", legacy_backend == "mock")
|
|
400
|
+
bcs_enabled = prefs.get("device_bcs_enabled", legacy_backend == "bcs")
|
|
401
|
+
happi_enabled = prefs.get("device_happi_enabled", False)
|
|
402
|
+
|
|
403
|
+
# If nothing is explicitly enabled, fall back to mock
|
|
404
|
+
if not any([mock_enabled, bcs_enabled, happi_enabled]):
|
|
405
|
+
mock_enabled = True
|
|
406
|
+
|
|
407
|
+
if mock_enabled:
|
|
408
|
+
include_noisy = prefs.get("device_mock_include_noisy", True)
|
|
409
|
+
catalog.add_backend(MockBackend(include_noisy=include_noisy))
|
|
410
|
+
logger.info("Mock backend enabled (include_noisy={})", include_noisy)
|
|
411
|
+
|
|
412
|
+
if bcs_enabled:
|
|
413
|
+
host = prefs.get("device_bcs_host", "localhost")
|
|
414
|
+
port = prefs.get("device_bcs_port", 5577)
|
|
415
|
+
timeout_ms = prefs.get("device_bcs_timeout_ms", 5000)
|
|
416
|
+
beamline = prefs.get("device_bcs_beamline") or None
|
|
417
|
+
catalog.add_backend(BCSBackend(
|
|
418
|
+
host=host, port=port, timeout_ms=timeout_ms, beamline=beamline,
|
|
419
|
+
))
|
|
420
|
+
logger.info("BCS backend enabled ({}:{})", host, port)
|
|
421
|
+
|
|
422
|
+
if happi_enabled:
|
|
423
|
+
happi_path = prefs.get("device_happi_path", "") or None
|
|
424
|
+
happi_beamline = prefs.get("device_happi_beamline", "") or None
|
|
425
|
+
|
|
426
|
+
# Get instantiation mode (new setting) with fallback to legacy bool
|
|
427
|
+
instantiate_mode = prefs.get("device_instantiate_mode", None)
|
|
428
|
+
if instantiate_mode is None:
|
|
429
|
+
# Legacy fallback: convert bool to mode string
|
|
430
|
+
legacy_instantiate = prefs.get("device_happi_instantiate", False)
|
|
431
|
+
instantiate_mode = "blocking" if legacy_instantiate else "none"
|
|
432
|
+
|
|
433
|
+
# Get connection timeout
|
|
434
|
+
connection_timeout = prefs.get("device_connection_timeout", 5.0)
|
|
435
|
+
|
|
436
|
+
catalog.add_backend(HappiBackend(
|
|
437
|
+
path=happi_path,
|
|
438
|
+
beamline=happi_beamline,
|
|
439
|
+
instantiate=instantiate_mode,
|
|
440
|
+
connection_timeout=connection_timeout,
|
|
441
|
+
))
|
|
442
|
+
logger.info(
|
|
443
|
+
"Happi backend enabled (path={}, mode={}, timeout={}s)",
|
|
444
|
+
happi_path or "default",
|
|
445
|
+
instantiate_mode,
|
|
446
|
+
connection_timeout,
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
if catalog.connect():
|
|
450
|
+
device_count = len(catalog.get_all_devices())
|
|
451
|
+
backends_str = ", ".join(catalog.backends.keys())
|
|
452
|
+
logger.info("Device catalog initialized: {} devices from [{}]", device_count, backends_str)
|
|
453
|
+
else:
|
|
454
|
+
logger.error("Failed to connect device catalog")
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _setup_bluesky(app: LFApplication) -> None:
|
|
458
|
+
"""Setup Bluesky engine and plan registry.
|
|
459
|
+
|
|
460
|
+
Initializes the BlueskyEngine singleton and plan registry
|
|
461
|
+
for use by the BlueskyPanel.
|
|
462
|
+
"""
|
|
463
|
+
services = app.services
|
|
464
|
+
|
|
465
|
+
# Get/create engine singleton
|
|
466
|
+
engine = get_engine()
|
|
467
|
+
services.register_instance(type(engine), engine)
|
|
468
|
+
|
|
469
|
+
# Get/create plan registry with standard bluesky plans
|
|
470
|
+
plan_registry = get_plan_registry()
|
|
471
|
+
services.register_instance(type(plan_registry), plan_registry)
|
|
472
|
+
|
|
473
|
+
# Load user-defined plans from ~/lightfall/plans/
|
|
474
|
+
from lightfall.acquire.plans import UserPlanService
|
|
475
|
+
|
|
476
|
+
user_plan_service = UserPlanService.get_instance()
|
|
477
|
+
results = user_plan_service.load_all_plans()
|
|
478
|
+
user_plan_count = sum(1 for _, r in results if not isinstance(r, Exception))
|
|
479
|
+
services.register_instance(UserPlanService, user_plan_service)
|
|
480
|
+
|
|
481
|
+
logger.info(
|
|
482
|
+
"Bluesky initialized: engine state={}, {} plans available ({} user plans)",
|
|
483
|
+
engine.state_name,
|
|
484
|
+
len(plan_registry),
|
|
485
|
+
user_plan_count,
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _setup_tiled(app: LFApplication, config: ConfigManager) -> None:
|
|
490
|
+
"""Setup Tiled service if configured.
|
|
491
|
+
|
|
492
|
+
Initializes the TiledService singleton and connects to the
|
|
493
|
+
Tiled server if enabled in preferences.
|
|
494
|
+
|
|
495
|
+
Args:
|
|
496
|
+
app: The NCS application instance.
|
|
497
|
+
config: The configuration manager.
|
|
498
|
+
"""
|
|
499
|
+
from lightfall.services.tiled_service import TiledAuthMode, TiledService
|
|
500
|
+
|
|
501
|
+
services = app.services
|
|
502
|
+
prefs = PreferencesManager.get_instance()
|
|
503
|
+
|
|
504
|
+
# Create service singleton
|
|
505
|
+
service = TiledService.get_instance()
|
|
506
|
+
|
|
507
|
+
# Configure from preferences
|
|
508
|
+
enabled = prefs.get("tiled_enabled", False)
|
|
509
|
+
url = prefs.get("tiled_url", "")
|
|
510
|
+
api_key = prefs.get("tiled_api_key") or None
|
|
511
|
+
|
|
512
|
+
# Determine auth mode
|
|
513
|
+
# If tiled_auth_mode is set in preferences, use that
|
|
514
|
+
# Otherwise, auto-detect: use KEYCLOAK if auth provider is keycloak
|
|
515
|
+
auth_mode_pref = prefs.get("tiled_auth_mode", "")
|
|
516
|
+
if auth_mode_pref:
|
|
517
|
+
auth_mode = TiledAuthMode(auth_mode_pref)
|
|
518
|
+
elif config.model.auth.provider.type == "keycloak":
|
|
519
|
+
# Auto-detect: if using Keycloak auth, use Keycloak for Tiled too
|
|
520
|
+
auth_mode = TiledAuthMode.KEYCLOAK
|
|
521
|
+
logger.info("Auto-detected Keycloak auth mode for Tiled")
|
|
522
|
+
elif api_key:
|
|
523
|
+
auth_mode = TiledAuthMode.API_KEY
|
|
524
|
+
else:
|
|
525
|
+
auth_mode = TiledAuthMode.NONE
|
|
526
|
+
|
|
527
|
+
if enabled and url:
|
|
528
|
+
service.configure(url=url, api_key=api_key, enabled=True, auth_mode=auth_mode)
|
|
529
|
+
|
|
530
|
+
if auth_mode == TiledAuthMode.KEYCLOAK:
|
|
531
|
+
# For Keycloak, connect to SessionManager and defer connection
|
|
532
|
+
service.connect_session_manager()
|
|
533
|
+
logger.info(
|
|
534
|
+
"Tiled service initialized with Keycloak auth, waiting for user login"
|
|
535
|
+
)
|
|
536
|
+
else:
|
|
537
|
+
# For API key or no auth, connect immediately
|
|
538
|
+
service.connect_async()
|
|
539
|
+
logger.info("Tiled service initialized, connecting in background")
|
|
540
|
+
else:
|
|
541
|
+
service.configure(url=url, api_key=api_key, enabled=False, auth_mode=auth_mode)
|
|
542
|
+
logger.debug("Tiled service initialized (disabled)")
|
|
543
|
+
|
|
544
|
+
# Register service
|
|
545
|
+
services.register(TiledService, TiledService.get_instance)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _setup_plugins(app: LFApplication) -> None:
|
|
549
|
+
"""Setup the plugin system and load preload plugins.
|
|
550
|
+
|
|
551
|
+
This must be called BEFORE creating the main window to ensure
|
|
552
|
+
preload plugins (like appearance/theme) can apply settings before
|
|
553
|
+
any UI is shown.
|
|
554
|
+
|
|
555
|
+
Args:
|
|
556
|
+
app: The Lightfall application instance.
|
|
557
|
+
"""
|
|
558
|
+
from lightfall.plugins import AgentPlugin, PluginLoader, PluginRegistry
|
|
559
|
+
from lightfall.plugins.builtin_manifest import builtin_manifest
|
|
560
|
+
from lightfall.plugins.controller_plugin import ControllerPlugin
|
|
561
|
+
from lightfall.plugins.engine_plugin import EnginePlugin
|
|
562
|
+
from lightfall.plugins.panel_plugin import PanelPlugin
|
|
563
|
+
from lightfall.plugins.settings_plugin import SettingsPlugin
|
|
564
|
+
from lightfall.plugins.statusbar_plugin import StatusBarPlugin
|
|
565
|
+
|
|
566
|
+
services = app.services
|
|
567
|
+
|
|
568
|
+
# Create registry and loader
|
|
569
|
+
registry = PluginRegistry()
|
|
570
|
+
loader = PluginLoader(registry)
|
|
571
|
+
|
|
572
|
+
# Register plugin types (theme must be first to load before appearance settings)
|
|
573
|
+
from lightfall.plugins.theme_plugin import ThemePlugin
|
|
574
|
+
|
|
575
|
+
loader.register_plugin_type("theme", ThemePlugin)
|
|
576
|
+
loader.register_plugin_type("settings", SettingsPlugin)
|
|
577
|
+
loader.register_plugin_type("engine", EnginePlugin)
|
|
578
|
+
loader.register_plugin_type("agent", AgentPlugin)
|
|
579
|
+
loader.register_plugin_type("statusbar", StatusBarPlugin)
|
|
580
|
+
loader.register_plugin_type("controller", ControllerPlugin)
|
|
581
|
+
loader.register_plugin_type("panel", PanelPlugin)
|
|
582
|
+
|
|
583
|
+
# Load built-in manifest first
|
|
584
|
+
loader.load_manifest(builtin_manifest)
|
|
585
|
+
|
|
586
|
+
# Discover external manifests from entry points
|
|
587
|
+
loader.discover_manifests()
|
|
588
|
+
|
|
589
|
+
# Load preload plugins synchronously BEFORE creating main window
|
|
590
|
+
# This ensures theme is applied before any UI appears
|
|
591
|
+
preload_ok, preload_failed = loader.load_preload_plugins()
|
|
592
|
+
if preload_ok > 0 or preload_failed > 0:
|
|
593
|
+
logger.info(
|
|
594
|
+
"Preload plugins: {} successful, {} failed",
|
|
595
|
+
preload_ok,
|
|
596
|
+
preload_failed,
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
# Register services
|
|
600
|
+
services.register_instance(PluginRegistry, registry)
|
|
601
|
+
services.register_instance(PluginLoader, loader)
|
|
602
|
+
|
|
603
|
+
# Start background loading for remaining plugins
|
|
604
|
+
loader.start_loading()
|
|
605
|
+
|
|
606
|
+
logger.debug("Plugin system initialized")
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _setup_user_plugins(app: LFApplication) -> None:
|
|
610
|
+
"""Load user-defined plugins from ~/lightfall/plugins/.
|
|
611
|
+
|
|
612
|
+
User plugins are Python files in ~/lightfall/plugins/. Plugin classes
|
|
613
|
+
auto-register via PluginType.__init_subclass__ when defined, so user
|
|
614
|
+
files do not need explicit Registry.register() calls.
|
|
615
|
+
|
|
616
|
+
Args:
|
|
617
|
+
app: The Lightfall application instance.
|
|
618
|
+
"""
|
|
619
|
+
from lightfall.plugins.user_plugins import UserPluginService
|
|
620
|
+
|
|
621
|
+
services = app.services
|
|
622
|
+
|
|
623
|
+
# Create and initialize the service
|
|
624
|
+
service = UserPluginService.get_instance()
|
|
625
|
+
|
|
626
|
+
# Load all user plugins
|
|
627
|
+
results = service.load_all_plugins()
|
|
628
|
+
user_plugin_count = sum(1 for _, err in results if err is None)
|
|
629
|
+
|
|
630
|
+
# Enable hot-reload by default
|
|
631
|
+
service.enable_hot_reload(True)
|
|
632
|
+
|
|
633
|
+
# Register service
|
|
634
|
+
services.register_instance(UserPluginService, service)
|
|
635
|
+
|
|
636
|
+
if user_plugin_count > 0:
|
|
637
|
+
logger.info("Loaded {} user plugin(s) from ~/lightfall/plugins/", user_plugin_count)
|
|
638
|
+
else:
|
|
639
|
+
logger.debug("No user plugins loaded")
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _setup_first_launch(project_service: ProjectService) -> None:
|
|
643
|
+
"""Setup the welcome project for first launch.
|
|
644
|
+
|
|
645
|
+
If no project is currently open (first launch or no recent project),
|
|
646
|
+
creates and opens the welcome project with introductory content.
|
|
647
|
+
|
|
648
|
+
Args:
|
|
649
|
+
project_service: The ProjectService instance.
|
|
650
|
+
"""
|
|
651
|
+
# Check if we have a recent project to restore
|
|
652
|
+
# For now, always create welcome project (persistence comes later)
|
|
653
|
+
if not project_service.has_project:
|
|
654
|
+
logger.info("First launch detected, creating welcome project")
|
|
655
|
+
welcome = create_welcome_project()
|
|
656
|
+
project_service.open_project(welcome)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _show_startup_login(window: LFMainWindow) -> None:
|
|
660
|
+
"""Show login dialog on application startup.
|
|
661
|
+
|
|
662
|
+
Creates an independent dialog (parent=None) so it gets its own
|
|
663
|
+
taskbar entry on Windows, rather than being owned by the hidden
|
|
664
|
+
main window.
|
|
665
|
+
|
|
666
|
+
Args:
|
|
667
|
+
window: The main window instance (unused, kept for API compatibility).
|
|
668
|
+
"""
|
|
669
|
+
from lightfall.resources import get_app_icon
|
|
670
|
+
from lightfall.ui.dialogs import LoginDialog
|
|
671
|
+
from lightfall.ui.dialogs.login_dialog import LoginResult
|
|
672
|
+
|
|
673
|
+
# Create dialog without parent - gets its own taskbar entry
|
|
674
|
+
dialog = LoginDialog(
|
|
675
|
+
parent=None,
|
|
676
|
+
title="Welcome to Lightfall",
|
|
677
|
+
allow_guest=True,
|
|
678
|
+
show_on_expiry=False,
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
# Explicitly set icon for taskbar (required when parent=None)
|
|
682
|
+
app_icon = get_app_icon()
|
|
683
|
+
if not app_icon.isNull():
|
|
684
|
+
dialog.setWindowIcon(app_icon)
|
|
685
|
+
sizes = app_icon.availableSizes()
|
|
686
|
+
logger.info("Login dialog icon set ({} sizes: {})", len(sizes), sizes)
|
|
687
|
+
else:
|
|
688
|
+
logger.warning("App icon is null for login dialog")
|
|
689
|
+
|
|
690
|
+
# Verify icon was set on dialog
|
|
691
|
+
dialog_icon = dialog.windowIcon()
|
|
692
|
+
logger.info("Dialog windowIcon isNull: {}", dialog_icon.isNull())
|
|
693
|
+
|
|
694
|
+
dialog.exec()
|
|
695
|
+
login_result = dialog.login_result
|
|
696
|
+
|
|
697
|
+
if login_result == LoginResult.AUTHENTICATED:
|
|
698
|
+
logger.info("User authenticated at startup")
|
|
699
|
+
elif login_result == LoginResult.GUEST:
|
|
700
|
+
logger.info("User chose guest mode at startup")
|
|
701
|
+
else:
|
|
702
|
+
logger.info("User cancelled login dialog")
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def _setup_session_expiry_handler(window: LFMainWindow) -> None:
|
|
706
|
+
"""Setup handler to show login dialog when session expires.
|
|
707
|
+
|
|
708
|
+
Args:
|
|
709
|
+
window: The main window instance.
|
|
710
|
+
"""
|
|
711
|
+
from lightfall.ui.dialogs import LoginDialog
|
|
712
|
+
|
|
713
|
+
session_manager = SessionManager.get_instance()
|
|
714
|
+
|
|
715
|
+
def on_session_expired() -> None:
|
|
716
|
+
"""Show login dialog when session expires."""
|
|
717
|
+
dialog = LoginDialog(
|
|
718
|
+
parent=window,
|
|
719
|
+
title="Session Expired",
|
|
720
|
+
allow_guest=True,
|
|
721
|
+
show_on_expiry=True,
|
|
722
|
+
)
|
|
723
|
+
dialog.exec()
|
|
724
|
+
|
|
725
|
+
# Connect to state changed to detect session expiry and update Sentry context
|
|
726
|
+
def on_state_changed(new_state, old_state) -> None:
|
|
727
|
+
from lightfall.auth.session import AuthState
|
|
728
|
+
|
|
729
|
+
if new_state == AuthState.AUTHENTICATED:
|
|
730
|
+
# User logged in - set Sentry user context
|
|
731
|
+
user = session_manager.current_user
|
|
732
|
+
if user:
|
|
733
|
+
sentry_set_user(
|
|
734
|
+
user_id=user.username,
|
|
735
|
+
username=user.username,
|
|
736
|
+
roles=user.roles,
|
|
737
|
+
)
|
|
738
|
+
elif old_state == AuthState.AUTHENTICATED and new_state == AuthState.UNAUTHENTICATED:
|
|
739
|
+
# Session expired or was invalidated - clear Sentry user context
|
|
740
|
+
sentry_clear_user()
|
|
741
|
+
logger.info("Session ended, showing login dialog")
|
|
742
|
+
on_session_expired()
|
|
743
|
+
|
|
744
|
+
session_manager.state_changed.connect(on_state_changed)
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def _check_editor_protocol(main_window: LFMainWindow) -> None:
|
|
748
|
+
"""Check if the configured editor's protocol handler is available.
|
|
749
|
+
|
|
750
|
+
Shows a warning banner if PyCharm is selected but JetBrains Toolbox
|
|
751
|
+
is not installed (jetbrains:// protocol not registered).
|
|
752
|
+
|
|
753
|
+
Args:
|
|
754
|
+
main_window: The main window to show the banner in.
|
|
755
|
+
"""
|
|
756
|
+
prefs = PreferencesManager.get_instance()
|
|
757
|
+
|
|
758
|
+
# Only check for PyCharm
|
|
759
|
+
editor = prefs.get("code_editor", CodeEditor.VSCODE.value)
|
|
760
|
+
if editor != CodeEditor.PYCHARM.value:
|
|
761
|
+
return
|
|
762
|
+
|
|
763
|
+
# Check if user has suppressed the warning
|
|
764
|
+
if prefs.get("suppress_pycharm_warning", False):
|
|
765
|
+
return
|
|
766
|
+
|
|
767
|
+
# Check if jetbrains:// protocol is registered
|
|
768
|
+
if is_editor_available(CodeEditor.PYCHARM):
|
|
769
|
+
return
|
|
770
|
+
|
|
771
|
+
# Show warning banner
|
|
772
|
+
logger.warning("JetBrains Toolbox not detected, PyCharm code links may not work")
|
|
773
|
+
|
|
774
|
+
from PySide6.QtCore import QTimer
|
|
775
|
+
|
|
776
|
+
def show_banner() -> None:
|
|
777
|
+
banner = DismissableWarningBanner(
|
|
778
|
+
warning_id="jetbrains_toolbox",
|
|
779
|
+
title="JetBrains Toolbox Required",
|
|
780
|
+
message=(
|
|
781
|
+
"Install JetBrains Toolbox for PyCharm code links to work. "
|
|
782
|
+
"Toolbox registers the jetbrains:// protocol handler."
|
|
783
|
+
),
|
|
784
|
+
parent=main_window.centralWidget(),
|
|
785
|
+
)
|
|
786
|
+
banner.permanently_dismissed.connect(
|
|
787
|
+
lambda wid: prefs.set("suppress_pycharm_warning", True)
|
|
788
|
+
)
|
|
789
|
+
|
|
790
|
+
# Position at top of central widget
|
|
791
|
+
banner.setFixedWidth(main_window.centralWidget().width() - 20)
|
|
792
|
+
banner.move(10, 10)
|
|
793
|
+
banner.show()
|
|
794
|
+
banner.raise_()
|
|
795
|
+
|
|
796
|
+
# Delay slightly to ensure window is fully shown
|
|
797
|
+
QTimer.singleShot(500, show_banner)
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def _setup_default_panels(window: LFMainWindow) -> None:
|
|
801
|
+
"""Setup default panels for the main window.
|
|
802
|
+
|
|
803
|
+
Opens panels that should be visible by default on startup.
|
|
804
|
+
Layout: Claude, Bluesky, and Devices tabbed on left, Logbook on right.
|
|
805
|
+
|
|
806
|
+
Args:
|
|
807
|
+
window: The main window instance.
|
|
808
|
+
"""
|
|
809
|
+
# Clear any saved window state to ensure our layout is applied
|
|
810
|
+
from PySide6.QtCore import QSettings
|
|
811
|
+
settings = QSettings("ALS", "NCS")
|
|
812
|
+
settings.remove("mainwindow/geometry")
|
|
813
|
+
settings.remove("mainwindow/state")
|
|
814
|
+
|
|
815
|
+
# Open Claude panel on the left first (will be a tab)
|
|
816
|
+
claude_dock = None
|
|
817
|
+
claude_panel = window.add_panel(
|
|
818
|
+
"lightfall.panels.claude",
|
|
819
|
+
area=Qt.DockWidgetArea.LeftDockWidgetArea,
|
|
820
|
+
)
|
|
821
|
+
if claude_panel:
|
|
822
|
+
claude_dock = window._panel_docks.get("lightfall.panels.claude")
|
|
823
|
+
|
|
824
|
+
# Open Bluesky panel on the left
|
|
825
|
+
window.add_panel(
|
|
826
|
+
"lightfall.panels.bluesky",
|
|
827
|
+
area=Qt.DockWidgetArea.LeftDockWidgetArea,
|
|
828
|
+
)
|
|
829
|
+
bluesky_dock = window._panel_docks.get("lightfall.panels.bluesky")
|
|
830
|
+
|
|
831
|
+
# Open Devices panel - add to left then tabify with Bluesky
|
|
832
|
+
window.add_panel(
|
|
833
|
+
"lightfall.panels.devices",
|
|
834
|
+
area=Qt.DockWidgetArea.LeftDockWidgetArea,
|
|
835
|
+
)
|
|
836
|
+
devices_dock = window._panel_docks.get("lightfall.panels.devices")
|
|
837
|
+
|
|
838
|
+
# Tabify Claude, Bluesky and Devices (stack as tabs)
|
|
839
|
+
if claude_dock and bluesky_dock:
|
|
840
|
+
window.tabifyDockWidget(claude_dock, bluesky_dock)
|
|
841
|
+
if bluesky_dock and devices_dock:
|
|
842
|
+
window.tabifyDockWidget(bluesky_dock, devices_dock)
|
|
843
|
+
|
|
844
|
+
# Raise Bluesky as the default visible tab
|
|
845
|
+
if bluesky_dock:
|
|
846
|
+
bluesky_dock.raise_()
|
|
847
|
+
|
|
848
|
+
# Open Logbook panel on the right
|
|
849
|
+
window.add_panel(
|
|
850
|
+
"lightfall.panels.logbook",
|
|
851
|
+
area=Qt.DockWidgetArea.RightDockWidgetArea,
|
|
852
|
+
)
|
|
853
|
+
logbook_dock = window._panel_docks.get("lightfall.panels.logbook")
|
|
854
|
+
|
|
855
|
+
# Use splitDockWidget to ensure left-right layout
|
|
856
|
+
first_left_dock = claude_dock or bluesky_dock
|
|
857
|
+
if first_left_dock and logbook_dock:
|
|
858
|
+
window.splitDockWidget(first_left_dock, logbook_dock, Qt.Orientation.Horizontal)
|
|
859
|
+
|
|
860
|
+
panels_opened = ["Bluesky", "Devices", "Logbook"]
|
|
861
|
+
if claude_dock:
|
|
862
|
+
panels_opened.insert(0, "Claude")
|
|
863
|
+
logger.info("Opened default panels: {} (left), Logbook (right)", "+".join(panels_opened[:-1]))
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
def main() -> int:
|
|
867
|
+
"""Run the Lightfall application.
|
|
868
|
+
|
|
869
|
+
Returns:
|
|
870
|
+
Exit code (0 for success, non-zero for errors).
|
|
871
|
+
"""
|
|
872
|
+
# One-time rebrand migration of the user data directory.
|
|
873
|
+
migrate_legacy_data_dir()
|
|
874
|
+
|
|
875
|
+
# Get/create the application singleton
|
|
876
|
+
app = LFApplication.get_instance()
|
|
877
|
+
|
|
878
|
+
# Initialize with default settings
|
|
879
|
+
app.initialize(log_level="DEBUG")
|
|
880
|
+
|
|
881
|
+
# Bridge Qt's internal warnings (thread-affinity violations, queued
|
|
882
|
+
# connection failures, paint-event errors) into loguru. Must run after
|
|
883
|
+
# PySide6.QtCore is importable, which app.initialize() guarantees.
|
|
884
|
+
crash_diagnostics.install_qt_bridge()
|
|
885
|
+
|
|
886
|
+
# Get config manager
|
|
887
|
+
config: ConfigManager = app.services.get(ConfigManager)
|
|
888
|
+
|
|
889
|
+
# Setup services (must be before Sentry so PreferencesManager has ConfigManager)
|
|
890
|
+
_setup_services(app, config)
|
|
891
|
+
|
|
892
|
+
# Initialize Sentry error reporting (after services so proxy settings are available)
|
|
893
|
+
if init_sentry():
|
|
894
|
+
logger.info("Sentry error reporting initialized")
|
|
895
|
+
else:
|
|
896
|
+
logger.warning("Sentry initialization failed or disabled")
|
|
897
|
+
|
|
898
|
+
# Install error collector to capture recent errors for bug reporting
|
|
899
|
+
from lightfall.utils.error_collector import ErrorCollector
|
|
900
|
+
|
|
901
|
+
ErrorCollector.get_instance().install()
|
|
902
|
+
|
|
903
|
+
# Install full-tail log buffer so the embedded agent can look back
|
|
904
|
+
# at recent activity when something unexpected happens.
|
|
905
|
+
from lightfall.utils.log_buffer import LogBuffer
|
|
906
|
+
|
|
907
|
+
LogBuffer.get_instance().install()
|
|
908
|
+
|
|
909
|
+
# Setup authentication
|
|
910
|
+
_setup_auth(config)
|
|
911
|
+
|
|
912
|
+
# Start CA tunnel if configured (must be before device setup)
|
|
913
|
+
_setup_ca_tunnel()
|
|
914
|
+
|
|
915
|
+
# Setup device catalog with mock backend
|
|
916
|
+
_setup_devices()
|
|
917
|
+
|
|
918
|
+
# Start CA tunnel retries if tunnel is active
|
|
919
|
+
app_module = __import__(__name__)
|
|
920
|
+
_retry_fn = getattr(app_module, "_ca_tunnel_schedule_retries", None)
|
|
921
|
+
if _retry_fn:
|
|
922
|
+
_retry_fn()
|
|
923
|
+
del app_module._ca_tunnel_schedule_retries
|
|
924
|
+
|
|
925
|
+
# Setup Bluesky RunEngine and plans
|
|
926
|
+
_setup_bluesky(app)
|
|
927
|
+
|
|
928
|
+
# Setup Tiled data catalog service
|
|
929
|
+
_setup_tiled(app, config)
|
|
930
|
+
|
|
931
|
+
# Setup plugin system and load preload plugins (before main window)
|
|
932
|
+
_setup_plugins(app)
|
|
933
|
+
|
|
934
|
+
# Load user plugins from ~/lightfall/plugins/
|
|
935
|
+
_setup_user_plugins(app)
|
|
936
|
+
|
|
937
|
+
# Setup first launch (welcome project)
|
|
938
|
+
project_service = ProjectService.get_instance()
|
|
939
|
+
_setup_first_launch(project_service)
|
|
940
|
+
|
|
941
|
+
# Create and set main window (after preload plugins applied theme)
|
|
942
|
+
window = LFMainWindow()
|
|
943
|
+
window.set_config_manager(config)
|
|
944
|
+
app.set_main_window(window)
|
|
945
|
+
|
|
946
|
+
# Connect engine to menubar control
|
|
947
|
+
engine = get_engine()
|
|
948
|
+
window.set_engine(engine)
|
|
949
|
+
|
|
950
|
+
# Setup default panel layout
|
|
951
|
+
window.setup_default_layout()
|
|
952
|
+
|
|
953
|
+
# Register built-in tutorials
|
|
954
|
+
from lightfall.ui.tutorial import register_builtin_tutorials
|
|
955
|
+
register_builtin_tutorials()
|
|
956
|
+
|
|
957
|
+
# Check editor protocol handler (shows warning if PyCharm selected but Toolbox missing)
|
|
958
|
+
_check_editor_protocol(window)
|
|
959
|
+
|
|
960
|
+
# Setup session expiry handler
|
|
961
|
+
_setup_session_expiry_handler(window)
|
|
962
|
+
|
|
963
|
+
# Show login dialog on startup
|
|
964
|
+
_show_startup_login(window)
|
|
965
|
+
|
|
966
|
+
# Register cleanup on exit — order matters:
|
|
967
|
+
# 1. Stop CA tunnel (kills relay sockets, stops new data arriving)
|
|
968
|
+
# 2. Disconnect devices (cancels ophyd connections)
|
|
969
|
+
# 3. Disconnect caproto Context (tears down circuits + threads)
|
|
970
|
+
# The watchdog ensures we exit within 5s even if caproto blocks.
|
|
971
|
+
import threading as _threading
|
|
972
|
+
|
|
973
|
+
from PySide6.QtCore import QCoreApplication
|
|
974
|
+
|
|
975
|
+
def _cleanup_on_exit():
|
|
976
|
+
# Schedule a hard exit as a safety net. If cleanup takes more
|
|
977
|
+
# than 5 seconds (e.g. caproto ThreadPoolExecutor.shutdown()
|
|
978
|
+
# blocks waiting for callbacks), force-terminate the process.
|
|
979
|
+
import logging as _logging
|
|
980
|
+
import os
|
|
981
|
+
import time as _time
|
|
982
|
+
|
|
983
|
+
# Mute caproto loggers during shutdown — stale commands arriving
|
|
984
|
+
# on closed channels/circuits are expected and harmless.
|
|
985
|
+
for _name in ("caproto", "caproto.ch", "caproto.circ", "caproto.ctx", "caproto.bcast"):
|
|
986
|
+
_logging.getLogger(_name).setLevel(_logging.CRITICAL)
|
|
987
|
+
|
|
988
|
+
def _log_active_threads(label: str = ""):
|
|
989
|
+
threads = _threading.enumerate()
|
|
990
|
+
non_daemon = [t for t in threads if not t.daemon and t.is_alive()]
|
|
991
|
+
daemon = [t for t in threads if t.daemon and t.is_alive()]
|
|
992
|
+
logger.info(
|
|
993
|
+
"Active threads ({}): {} total, {} non-daemon, {} daemon",
|
|
994
|
+
label, len(threads), len(non_daemon), len(daemon),
|
|
995
|
+
)
|
|
996
|
+
for t in non_daemon:
|
|
997
|
+
logger.info(
|
|
998
|
+
" [non-daemon] {!r} (ident={}, native_id={})",
|
|
999
|
+
t.name, t.ident, getattr(t, 'native_id', '?'),
|
|
1000
|
+
)
|
|
1001
|
+
for t in daemon:
|
|
1002
|
+
logger.debug(
|
|
1003
|
+
" [daemon] {!r} (ident={}, native_id={})",
|
|
1004
|
+
t.name, t.ident, getattr(t, 'native_id', '?'),
|
|
1005
|
+
)
|
|
1006
|
+
|
|
1007
|
+
def _force_exit():
|
|
1008
|
+
_time.sleep(5)
|
|
1009
|
+
_log_active_threads("watchdog-5s")
|
|
1010
|
+
logger.warning("Shutdown taking too long, forcing exit")
|
|
1011
|
+
sys.stderr.flush()
|
|
1012
|
+
sys.stdout.flush()
|
|
1013
|
+
os._exit(0)
|
|
1014
|
+
|
|
1015
|
+
_threading.Thread(
|
|
1016
|
+
target=_force_exit, daemon=True, name="shutdown-watchdog"
|
|
1017
|
+
).start()
|
|
1018
|
+
|
|
1019
|
+
# 1. Halt any running Bluesky plan immediately so it doesn't
|
|
1020
|
+
# try to read PVs while we're tearing down connections.
|
|
1021
|
+
try:
|
|
1022
|
+
import lightfall.acquire.engine as _eng_mod
|
|
1023
|
+
|
|
1024
|
+
engine = _eng_mod._engine
|
|
1025
|
+
if engine is not None and hasattr(engine, '_RE') and engine._RE is not None:
|
|
1026
|
+
if engine._RE.state in ("running", "paused"):
|
|
1027
|
+
logger.info("Halting Bluesky plan for shutdown")
|
|
1028
|
+
engine._RE.halt()
|
|
1029
|
+
except Exception:
|
|
1030
|
+
pass
|
|
1031
|
+
|
|
1032
|
+
# 2. Stop CA tunnel — kill the relay sockets so no more
|
|
1033
|
+
# data arrives on caproto circuits. This prevents the
|
|
1034
|
+
# "cannot schedule new futures after shutdown" errors that
|
|
1035
|
+
# happen when data arrives after executor.shutdown().
|
|
1036
|
+
try:
|
|
1037
|
+
from lightfall.services.ca_tunnel import CATunnelService
|
|
1038
|
+
|
|
1039
|
+
tunnel = CATunnelService.get_instance()
|
|
1040
|
+
if tunnel.is_running:
|
|
1041
|
+
tunnel.stop()
|
|
1042
|
+
logger.debug("CA tunnel stopped during shutdown")
|
|
1043
|
+
except Exception:
|
|
1044
|
+
pass
|
|
1045
|
+
|
|
1046
|
+
# 3. Disconnect device catalog (ophyd devices, connection manager)
|
|
1047
|
+
try:
|
|
1048
|
+
catalog = DeviceCatalog.get_instance()
|
|
1049
|
+
catalog.disconnect()
|
|
1050
|
+
logger.debug("Device catalog disconnected during shutdown")
|
|
1051
|
+
except Exception:
|
|
1052
|
+
pass
|
|
1053
|
+
|
|
1054
|
+
# 4. Shut down managed thread pools (dev-values, etc.)
|
|
1055
|
+
# ThreadManager.shutdown() also does this via aboutToQuit,
|
|
1056
|
+
# but belt-and-suspenders in case ordering varies.
|
|
1057
|
+
from lightfall.utils.threads import ManagedThreadPool
|
|
1058
|
+
|
|
1059
|
+
ManagedThreadPool.shutdown_all(wait=False)
|
|
1060
|
+
logger.debug("Managed thread pools shut down")
|
|
1061
|
+
|
|
1062
|
+
# 5. Skip caproto Context.disconnect().
|
|
1063
|
+
# Previously we called ctx.disconnect(wait=False) here, but it
|
|
1064
|
+
# triggers an access violation (0xC0000005) on Windows — caproto's
|
|
1065
|
+
# C-level socket code touches memory freed by earlier teardown.
|
|
1066
|
+
# With ManagedThreadPool (daemon threads) and CA tunnel stopped,
|
|
1067
|
+
# all caproto threads will die automatically on process exit.
|
|
1068
|
+
logger.debug("Skipping caproto context disconnect (daemon threads exit with process)")
|
|
1069
|
+
|
|
1070
|
+
# Log remaining threads so we can see what's blocking exit
|
|
1071
|
+
_log_active_threads("post-cleanup")
|
|
1072
|
+
sys.stderr.flush()
|
|
1073
|
+
sys.stdout.flush()
|
|
1074
|
+
|
|
1075
|
+
QCoreApplication.instance().aboutToQuit.connect(_cleanup_on_exit)
|
|
1076
|
+
|
|
1077
|
+
# Run the application
|
|
1078
|
+
return app.run()
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
def cli() -> None:
|
|
1082
|
+
"""Entry point for console scripts.
|
|
1083
|
+
|
|
1084
|
+
This wrapper ensures the process exit code is set correctly
|
|
1085
|
+
when running via installed entry points (e.g., `ncs` command).
|
|
1086
|
+
"""
|
|
1087
|
+
sys.exit(main())
|
|
1088
|
+
|
|
1089
|
+
|
|
1090
|
+
if __name__ == "__main__":
|
|
1091
|
+
cli()
|