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
|
@@ -0,0 +1,1397 @@
|
|
|
1
|
+
"""
|
|
2
|
+
WYSIWYG rich text editor with markdown as source of truth.
|
|
3
|
+
|
|
4
|
+
Provides a QTextEdit-based editor that displays rendered markdown
|
|
5
|
+
and intercepts all edits, translating them to markdown operations.
|
|
6
|
+
The markdown content is the single source of truth.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import TYPE_CHECKING, Any, ClassVar
|
|
12
|
+
|
|
13
|
+
from loguru import logger
|
|
14
|
+
from PySide6.QtCore import Qt, QTimer, QUrl, Signal
|
|
15
|
+
from PySide6.QtGui import (
|
|
16
|
+
QFont,
|
|
17
|
+
QKeyEvent,
|
|
18
|
+
QMouseEvent,
|
|
19
|
+
QTextCursor,
|
|
20
|
+
QUndoCommand,
|
|
21
|
+
QUndoStack,
|
|
22
|
+
)
|
|
23
|
+
from PySide6.QtWidgets import QTextEdit, QWidget
|
|
24
|
+
|
|
25
|
+
from lightfall.logbook.block_mapper import BlockMapper, BlockProtectionData
|
|
26
|
+
from lightfall.logbook.position_mapper import MarkdownPositionMapper, PositionMapping
|
|
27
|
+
from lightfall.logbook.style import LogbookStyles
|
|
28
|
+
from lightfall.logbook.visual_protection import (
|
|
29
|
+
PROTECTED_END,
|
|
30
|
+
PROTECTED_START,
|
|
31
|
+
VisualProtectionTracker,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from lightfall.logbook.converter import MarkdownConverter
|
|
36
|
+
from lightfall.logbook.protection import ProtectionManager
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MarkdownEditCommand(QUndoCommand):
|
|
40
|
+
"""Undo command for markdown edits."""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
editor: RichTextEditor,
|
|
45
|
+
old_markdown: str,
|
|
46
|
+
new_markdown: str,
|
|
47
|
+
old_cursor_pos: int,
|
|
48
|
+
new_cursor_pos: int,
|
|
49
|
+
description: str = "Edit",
|
|
50
|
+
) -> None:
|
|
51
|
+
super().__init__(description)
|
|
52
|
+
self._editor = editor
|
|
53
|
+
self._old_markdown = old_markdown
|
|
54
|
+
self._new_markdown = new_markdown
|
|
55
|
+
self._old_cursor_pos = old_cursor_pos
|
|
56
|
+
self._new_cursor_pos = new_cursor_pos
|
|
57
|
+
|
|
58
|
+
def redo(self) -> None:
|
|
59
|
+
"""Apply the edit."""
|
|
60
|
+
self._editor._apply_markdown_state(self._new_markdown, self._new_cursor_pos)
|
|
61
|
+
|
|
62
|
+
def undo(self) -> None:
|
|
63
|
+
"""Revert the edit."""
|
|
64
|
+
self._editor._apply_markdown_state(self._old_markdown, self._old_cursor_pos)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class RichTextEditor(QTextEdit):
|
|
68
|
+
"""
|
|
69
|
+
WYSIWYG rich text editor with markdown as source of truth.
|
|
70
|
+
|
|
71
|
+
This editor provides:
|
|
72
|
+
- Rich text display rendered from markdown
|
|
73
|
+
- Edit interception that translates to markdown operations
|
|
74
|
+
- Visual highlighting of protected regions
|
|
75
|
+
- Signal emission when protection is violated
|
|
76
|
+
- Undo/redo support for markdown edits
|
|
77
|
+
|
|
78
|
+
The editor does NOT store content internally. All content is managed
|
|
79
|
+
externally via markdown, and the editor re-renders after each edit.
|
|
80
|
+
|
|
81
|
+
Attributes:
|
|
82
|
+
widget_type: Type identifier for introspection.
|
|
83
|
+
widget_description: Description for introspection.
|
|
84
|
+
|
|
85
|
+
Signals:
|
|
86
|
+
content_changed: Emitted when the content is modified.
|
|
87
|
+
protection_violated(str, int): Emitted when an edit is attempted
|
|
88
|
+
in a protected region. Args are (region_id, cursor_position).
|
|
89
|
+
markdown_edit_requested(str): Emitted with the new markdown content
|
|
90
|
+
when an edit operation completes. The parent widget should
|
|
91
|
+
update its markdown and call render_markdown().
|
|
92
|
+
|
|
93
|
+
Example:
|
|
94
|
+
>>> editor = RichTextEditor(protection_manager, converter)
|
|
95
|
+
>>> editor.markdown_edit_requested.connect(widget.on_markdown_edit)
|
|
96
|
+
>>> editor.render_markdown("# Hello\\n\\nWorld")
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
widget_type: ClassVar[str] = "RichTextEditor"
|
|
100
|
+
widget_description: ClassVar[str] = "WYSIWYG rich text editor with markdown source of truth"
|
|
101
|
+
|
|
102
|
+
# Signals
|
|
103
|
+
content_changed = Signal()
|
|
104
|
+
protection_violated = Signal(str, int) # (region_id, cursor_position)
|
|
105
|
+
markdown_edit_requested = Signal(str) # new markdown content
|
|
106
|
+
action_group_clicked = Signal(str) # region_id
|
|
107
|
+
|
|
108
|
+
# Undo stack settings
|
|
109
|
+
MAX_UNDO_STATES: ClassVar[int] = 100
|
|
110
|
+
|
|
111
|
+
def __init__(
|
|
112
|
+
self,
|
|
113
|
+
protection_manager: ProtectionManager,
|
|
114
|
+
converter: MarkdownConverter,
|
|
115
|
+
parent: QWidget | None = None,
|
|
116
|
+
) -> None:
|
|
117
|
+
"""
|
|
118
|
+
Initialize the rich text editor.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
protection_manager: Manager for protected content regions.
|
|
122
|
+
converter: Markdown to HTML converter.
|
|
123
|
+
parent: Optional Qt parent widget.
|
|
124
|
+
"""
|
|
125
|
+
super().__init__(parent)
|
|
126
|
+
self._protection_manager = protection_manager
|
|
127
|
+
self._converter = converter
|
|
128
|
+
self._position_mapper = MarkdownPositionMapper()
|
|
129
|
+
|
|
130
|
+
# Block-based mapper for stable position tracking
|
|
131
|
+
self._block_mapper = BlockMapper()
|
|
132
|
+
|
|
133
|
+
# Visual protection tracker using zero-width markers
|
|
134
|
+
self._visual_tracker = VisualProtectionTracker()
|
|
135
|
+
|
|
136
|
+
# Current state
|
|
137
|
+
self._markdown: str = ""
|
|
138
|
+
self._mapping: PositionMapping | None = None
|
|
139
|
+
self._visual_to_md_map: list[int] | None = None # Visual pos -> Markdown pos
|
|
140
|
+
self._updating_content = False
|
|
141
|
+
|
|
142
|
+
# Undo/redo stack
|
|
143
|
+
self._undo_stack = QUndoStack(self)
|
|
144
|
+
self._undo_stack.setUndoLimit(100)
|
|
145
|
+
self._applying_undo = False # Flag to prevent nested undo pushes
|
|
146
|
+
|
|
147
|
+
# Debounce timer for re-rendering
|
|
148
|
+
self._render_timer: QTimer | None = None
|
|
149
|
+
self._pending_markdown: str | None = None
|
|
150
|
+
|
|
151
|
+
self._setup_ui()
|
|
152
|
+
|
|
153
|
+
def _setup_ui(self) -> None:
|
|
154
|
+
"""Configure the editor UI."""
|
|
155
|
+
self.setStyleSheet(LogbookStyles.editor_base())
|
|
156
|
+
self.setAcceptRichText(True)
|
|
157
|
+
self.setPlaceholderText("Enter content...")
|
|
158
|
+
|
|
159
|
+
def render_markdown(self, markdown: str) -> None:
|
|
160
|
+
"""
|
|
161
|
+
Render markdown content into the editor.
|
|
162
|
+
|
|
163
|
+
This replaces the current display with the rendered markdown.
|
|
164
|
+
Call this whenever the markdown source changes.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
markdown: The markdown content to render.
|
|
168
|
+
"""
|
|
169
|
+
self._updating_content = True
|
|
170
|
+
try:
|
|
171
|
+
# Store markdown and build position mapping
|
|
172
|
+
self._markdown = markdown
|
|
173
|
+
self._mapping = self._position_mapper.build_map(markdown)
|
|
174
|
+
|
|
175
|
+
# Parse protected regions
|
|
176
|
+
self._protection_manager.parse_regions(markdown)
|
|
177
|
+
|
|
178
|
+
# Convert to HTML (this injects zero-width markers)
|
|
179
|
+
html = self._converter.markdown_to_html(markdown)
|
|
180
|
+
|
|
181
|
+
# Store cursor position before update (as visual position)
|
|
182
|
+
old_cursor = self.textCursor()
|
|
183
|
+
old_visual_pos = old_cursor.position()
|
|
184
|
+
|
|
185
|
+
# Clear and reload
|
|
186
|
+
self.clear()
|
|
187
|
+
self.setHtml(html)
|
|
188
|
+
|
|
189
|
+
# Rebuild visual protection tracker from the rendered text
|
|
190
|
+
# The markers are now part of the visual text
|
|
191
|
+
visual_text = self.toPlainText()
|
|
192
|
+
self._visual_tracker.rebuild_from_text(
|
|
193
|
+
visual_text,
|
|
194
|
+
self._protection_manager.get_regions(),
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
# Build block-based mappings for stable position tracking
|
|
198
|
+
self._block_mapper.build_mappings(markdown, self.document())
|
|
199
|
+
|
|
200
|
+
# Attach protection data to each block for O(1) lookup
|
|
201
|
+
for mapping in self._block_mapper.mappings:
|
|
202
|
+
block = self.document().findBlockByNumber(mapping.visual_block_num)
|
|
203
|
+
if block.isValid():
|
|
204
|
+
data = BlockProtectionData(
|
|
205
|
+
region_id=mapping.region_id,
|
|
206
|
+
md_line_num=mapping.md_line_start,
|
|
207
|
+
is_protected=mapping.is_protected,
|
|
208
|
+
)
|
|
209
|
+
block.setUserData(data)
|
|
210
|
+
|
|
211
|
+
# Build accurate visual -> markdown position mapping (legacy, for formatting)
|
|
212
|
+
self._visual_to_md_map = self._build_position_map(markdown, visual_text)
|
|
213
|
+
|
|
214
|
+
# Restore cursor position
|
|
215
|
+
self._restore_cursor_position(old_visual_pos)
|
|
216
|
+
|
|
217
|
+
finally:
|
|
218
|
+
self._updating_content = False
|
|
219
|
+
|
|
220
|
+
def _restore_cursor_position(self, visual_pos: int) -> None:
|
|
221
|
+
"""Restore cursor to approximate visual position after re-render."""
|
|
222
|
+
cursor = self.textCursor()
|
|
223
|
+
doc_length = len(self.toPlainText())
|
|
224
|
+
new_pos = min(visual_pos, doc_length)
|
|
225
|
+
cursor.setPosition(new_pos)
|
|
226
|
+
self.setTextCursor(cursor)
|
|
227
|
+
|
|
228
|
+
def _build_position_map(self, markdown: str, visual_text: str) -> list[int]:
|
|
229
|
+
"""
|
|
230
|
+
Build accurate visual_pos -> markdown_pos mapping.
|
|
231
|
+
|
|
232
|
+
This builds a mapping by finding anchors (unique strings) in both texts
|
|
233
|
+
and interpolating positions between anchors.
|
|
234
|
+
|
|
235
|
+
The challenge: visual text differs from markdown in many ways:
|
|
236
|
+
- Markdown syntax (# for headers, ** for bold) is stripped
|
|
237
|
+
- HTML comments (<!-- PROTECTED:... -->) are stripped
|
|
238
|
+
- Zero-width markers are added
|
|
239
|
+
- Paragraph breaks differ (\\n\\n vs \\n)
|
|
240
|
+
|
|
241
|
+
Strategy: Find words/tokens that exist in both and use them as anchors.
|
|
242
|
+
|
|
243
|
+
Args:
|
|
244
|
+
markdown: The source markdown text.
|
|
245
|
+
visual_text: The rendered plain text from QTextEdit (with markers).
|
|
246
|
+
|
|
247
|
+
Returns:
|
|
248
|
+
List where index is visual position, value is markdown position.
|
|
249
|
+
"""
|
|
250
|
+
import re
|
|
251
|
+
|
|
252
|
+
# Strip zero-width markers from visual for matching
|
|
253
|
+
clean_visual = visual_text.replace(PROTECTED_START, "").replace(PROTECTED_END, "")
|
|
254
|
+
|
|
255
|
+
# Find word anchors that appear in both texts
|
|
256
|
+
# Words are sequences of alphanumeric characters
|
|
257
|
+
word_pattern = re.compile(r"\b\w+\b")
|
|
258
|
+
|
|
259
|
+
visual_words = [(m.group(), m.start(), m.end()) for m in word_pattern.finditer(clean_visual)]
|
|
260
|
+
md_words = [(m.group(), m.start(), m.end()) for m in word_pattern.finditer(markdown)]
|
|
261
|
+
|
|
262
|
+
# Build anchor mapping: visual_start -> markdown_start for matching words
|
|
263
|
+
anchors: list[tuple[int, int]] = [] # (visual_pos, md_pos)
|
|
264
|
+
md_word_idx = 0
|
|
265
|
+
|
|
266
|
+
for v_word, v_start, _v_end in visual_words:
|
|
267
|
+
# Find this word in markdown (starting from where we left off)
|
|
268
|
+
while md_word_idx < len(md_words):
|
|
269
|
+
m_word, m_start, m_end = md_words[md_word_idx]
|
|
270
|
+
if m_word == v_word:
|
|
271
|
+
anchors.append((v_start, m_start))
|
|
272
|
+
md_word_idx += 1
|
|
273
|
+
break
|
|
274
|
+
md_word_idx += 1
|
|
275
|
+
|
|
276
|
+
# Add start and end anchors
|
|
277
|
+
anchors.insert(0, (0, 0))
|
|
278
|
+
anchors.append((len(clean_visual), len(markdown)))
|
|
279
|
+
|
|
280
|
+
# Now build full position map by interpolating between anchors
|
|
281
|
+
clean_to_md: list[int] = []
|
|
282
|
+
anchor_idx = 0
|
|
283
|
+
|
|
284
|
+
for clean_pos in range(len(clean_visual) + 1):
|
|
285
|
+
# Find surrounding anchors
|
|
286
|
+
while anchor_idx < len(anchors) - 1 and anchors[anchor_idx + 1][0] <= clean_pos:
|
|
287
|
+
anchor_idx += 1
|
|
288
|
+
|
|
289
|
+
v_anchor, m_anchor = anchors[anchor_idx]
|
|
290
|
+
|
|
291
|
+
if anchor_idx + 1 < len(anchors):
|
|
292
|
+
v_next, m_next = anchors[anchor_idx + 1]
|
|
293
|
+
# Interpolate
|
|
294
|
+
v_range = v_next - v_anchor
|
|
295
|
+
m_range = m_next - m_anchor
|
|
296
|
+
if v_range > 0:
|
|
297
|
+
offset = clean_pos - v_anchor
|
|
298
|
+
md_pos = m_anchor + int(offset * m_range / v_range)
|
|
299
|
+
else:
|
|
300
|
+
md_pos = m_anchor
|
|
301
|
+
else:
|
|
302
|
+
# Past last anchor
|
|
303
|
+
md_pos = len(markdown)
|
|
304
|
+
|
|
305
|
+
clean_to_md.append(min(md_pos, len(markdown)))
|
|
306
|
+
|
|
307
|
+
# Now map from actual visual (with markers) to markdown
|
|
308
|
+
# by mapping through clean_visual
|
|
309
|
+
visual_to_md: list[int] = []
|
|
310
|
+
clean_pos = 0
|
|
311
|
+
|
|
312
|
+
for vis_char in visual_text:
|
|
313
|
+
if vis_char in (PROTECTED_START, PROTECTED_END):
|
|
314
|
+
# Zero-width marker - map to current clean position's markdown pos
|
|
315
|
+
if clean_pos < len(clean_to_md):
|
|
316
|
+
visual_to_md.append(clean_to_md[clean_pos])
|
|
317
|
+
else:
|
|
318
|
+
visual_to_md.append(len(markdown))
|
|
319
|
+
else:
|
|
320
|
+
# Regular character
|
|
321
|
+
if clean_pos < len(clean_to_md):
|
|
322
|
+
visual_to_md.append(clean_to_md[clean_pos])
|
|
323
|
+
else:
|
|
324
|
+
visual_to_md.append(len(markdown))
|
|
325
|
+
clean_pos += 1
|
|
326
|
+
|
|
327
|
+
# Add end mapping
|
|
328
|
+
visual_to_md.append(len(markdown))
|
|
329
|
+
|
|
330
|
+
return visual_to_md
|
|
331
|
+
|
|
332
|
+
def get_markdown(self) -> str:
|
|
333
|
+
"""
|
|
334
|
+
Get the current markdown content.
|
|
335
|
+
|
|
336
|
+
Returns:
|
|
337
|
+
The markdown content (source of truth).
|
|
338
|
+
"""
|
|
339
|
+
return self._markdown
|
|
340
|
+
|
|
341
|
+
# Legacy compatibility method
|
|
342
|
+
def set_markdown(self, markdown: str) -> None:
|
|
343
|
+
"""
|
|
344
|
+
Set markdown content (legacy compatibility).
|
|
345
|
+
|
|
346
|
+
This is an alias for render_markdown().
|
|
347
|
+
|
|
348
|
+
Args:
|
|
349
|
+
markdown: The markdown content to display.
|
|
350
|
+
"""
|
|
351
|
+
self.render_markdown(markdown)
|
|
352
|
+
|
|
353
|
+
def _is_cursor_in_protected(self, cursor: QTextCursor) -> tuple[bool, str | None]:
|
|
354
|
+
"""
|
|
355
|
+
Check if a cursor is within a protected region.
|
|
356
|
+
|
|
357
|
+
Uses block-based mapping for stable position tracking.
|
|
358
|
+
|
|
359
|
+
Args:
|
|
360
|
+
cursor: The text cursor to check.
|
|
361
|
+
|
|
362
|
+
Returns:
|
|
363
|
+
Tuple of (is_protected, region_id or None).
|
|
364
|
+
"""
|
|
365
|
+
block_num = cursor.blockNumber()
|
|
366
|
+
return self._block_mapper.is_block_protected(block_num)
|
|
367
|
+
|
|
368
|
+
def _is_selection_protected(
|
|
369
|
+
self, cursor: QTextCursor
|
|
370
|
+
) -> tuple[bool, str | None]:
|
|
371
|
+
"""
|
|
372
|
+
Check if a selection overlaps any protected regions.
|
|
373
|
+
|
|
374
|
+
Uses block-based mapping to check all blocks in the selection.
|
|
375
|
+
|
|
376
|
+
Args:
|
|
377
|
+
cursor: The text cursor with selection.
|
|
378
|
+
|
|
379
|
+
Returns:
|
|
380
|
+
Tuple of (is_protected, first_region_id or None).
|
|
381
|
+
"""
|
|
382
|
+
if not cursor.hasSelection():
|
|
383
|
+
return False, None
|
|
384
|
+
|
|
385
|
+
# Get start and end blocks of the selection
|
|
386
|
+
start_cursor = QTextCursor(cursor)
|
|
387
|
+
start_cursor.setPosition(cursor.selectionStart())
|
|
388
|
+
end_cursor = QTextCursor(cursor)
|
|
389
|
+
end_cursor.setPosition(cursor.selectionEnd())
|
|
390
|
+
|
|
391
|
+
start_block = start_cursor.blockNumber()
|
|
392
|
+
end_block = end_cursor.blockNumber()
|
|
393
|
+
|
|
394
|
+
# Check all blocks in the selection
|
|
395
|
+
for block_num in range(start_block, end_block + 1):
|
|
396
|
+
is_protected, region_id = self._block_mapper.is_block_protected(block_num)
|
|
397
|
+
if is_protected:
|
|
398
|
+
return True, region_id
|
|
399
|
+
|
|
400
|
+
return False, None
|
|
401
|
+
|
|
402
|
+
def _visual_to_md_pos(self, visual_pos: int) -> int:
|
|
403
|
+
"""Convert visual position to markdown position.
|
|
404
|
+
|
|
405
|
+
Uses block-based mapping for stable position tracking.
|
|
406
|
+
Falls back to anchor-based mapping if block mapping unavailable.
|
|
407
|
+
"""
|
|
408
|
+
# Create a cursor at the visual position to get block info
|
|
409
|
+
cursor = QTextCursor(self.document())
|
|
410
|
+
cursor.setPosition(min(visual_pos, len(self.toPlainText())))
|
|
411
|
+
|
|
412
|
+
block_num = cursor.blockNumber()
|
|
413
|
+
offset_in_block = cursor.positionInBlock()
|
|
414
|
+
|
|
415
|
+
return self._block_mapper.visual_to_md_pos(block_num, offset_in_block)
|
|
416
|
+
|
|
417
|
+
def _visual_to_md_pos_legacy(self, visual_pos: int) -> int:
|
|
418
|
+
"""Legacy position conversion using anchor-based mapping.
|
|
419
|
+
|
|
420
|
+
Kept for formatting operations that need precise character mapping.
|
|
421
|
+
"""
|
|
422
|
+
if self._visual_to_md_map is None:
|
|
423
|
+
# Fallback if map not built yet
|
|
424
|
+
return visual_pos
|
|
425
|
+
|
|
426
|
+
# Clamp to valid range
|
|
427
|
+
if visual_pos < 0:
|
|
428
|
+
return 0
|
|
429
|
+
if visual_pos >= len(self._visual_to_md_map):
|
|
430
|
+
return len(self._markdown)
|
|
431
|
+
|
|
432
|
+
return self._visual_to_md_map[visual_pos]
|
|
433
|
+
|
|
434
|
+
def _apply_markdown_state(self, markdown: str, visual_pos: int) -> None:
|
|
435
|
+
"""
|
|
436
|
+
Apply a markdown state without pushing to undo stack.
|
|
437
|
+
|
|
438
|
+
This is called by undo/redo commands to restore state.
|
|
439
|
+
|
|
440
|
+
Args:
|
|
441
|
+
markdown: The markdown content to set.
|
|
442
|
+
visual_pos: The cursor position to restore.
|
|
443
|
+
"""
|
|
444
|
+
self._applying_undo = True
|
|
445
|
+
try:
|
|
446
|
+
self._markdown = markdown
|
|
447
|
+
self.markdown_edit_requested.emit(markdown)
|
|
448
|
+
self.render_markdown(markdown)
|
|
449
|
+
|
|
450
|
+
# Restore cursor
|
|
451
|
+
cursor = self.textCursor()
|
|
452
|
+
doc_length = len(self.toPlainText())
|
|
453
|
+
cursor.setPosition(min(visual_pos, doc_length))
|
|
454
|
+
self.setTextCursor(cursor)
|
|
455
|
+
|
|
456
|
+
self.content_changed.emit()
|
|
457
|
+
finally:
|
|
458
|
+
self._applying_undo = False
|
|
459
|
+
|
|
460
|
+
def _apply_edit_and_rerender(self, new_markdown: str, new_visual_pos: int) -> None:
|
|
461
|
+
"""Apply markdown edit, push to undo stack, and re-render.
|
|
462
|
+
|
|
463
|
+
DEPRECATED: Use _apply_edit_and_rerender_block for stable cursor positioning.
|
|
464
|
+
"""
|
|
465
|
+
# Skip undo push if we're applying an undo/redo operation
|
|
466
|
+
if not self._applying_undo:
|
|
467
|
+
# Get current state for undo
|
|
468
|
+
old_markdown = self._markdown
|
|
469
|
+
old_visual_pos = self.textCursor().position()
|
|
470
|
+
|
|
471
|
+
# Create and push undo command
|
|
472
|
+
command = MarkdownEditCommand(
|
|
473
|
+
self,
|
|
474
|
+
old_markdown,
|
|
475
|
+
new_markdown,
|
|
476
|
+
old_visual_pos,
|
|
477
|
+
new_visual_pos,
|
|
478
|
+
"Edit",
|
|
479
|
+
)
|
|
480
|
+
self._undo_stack.push(command)
|
|
481
|
+
# The command's redo() is called automatically by push()
|
|
482
|
+
else:
|
|
483
|
+
# Direct apply without undo (called from undo command)
|
|
484
|
+
self._markdown = new_markdown
|
|
485
|
+
self.markdown_edit_requested.emit(new_markdown)
|
|
486
|
+
self.render_markdown(new_markdown)
|
|
487
|
+
|
|
488
|
+
# Restore cursor to new position
|
|
489
|
+
cursor = self.textCursor()
|
|
490
|
+
doc_length = len(self.toPlainText())
|
|
491
|
+
cursor.setPosition(min(new_visual_pos, doc_length))
|
|
492
|
+
self.setTextCursor(cursor)
|
|
493
|
+
|
|
494
|
+
self.content_changed.emit()
|
|
495
|
+
|
|
496
|
+
def _apply_edit_and_rerender_block(
|
|
497
|
+
self, new_markdown: str, block_num: int, offset_in_block: int
|
|
498
|
+
) -> None:
|
|
499
|
+
"""Apply markdown edit and re-render, restoring cursor using block-relative position.
|
|
500
|
+
|
|
501
|
+
This method uses block-relative coordinates for cursor restoration, which
|
|
502
|
+
is more stable across re-renders since block-relative offsets don't change
|
|
503
|
+
when content in earlier blocks changes.
|
|
504
|
+
|
|
505
|
+
Args:
|
|
506
|
+
new_markdown: The new markdown content.
|
|
507
|
+
block_num: Target block number for cursor.
|
|
508
|
+
offset_in_block: Target offset within the block.
|
|
509
|
+
"""
|
|
510
|
+
# For undo support, we still need visual positions
|
|
511
|
+
# Calculate approximate visual position for undo command
|
|
512
|
+
old_markdown = self._markdown
|
|
513
|
+
old_cursor = self.textCursor()
|
|
514
|
+
old_visual_pos = old_cursor.position()
|
|
515
|
+
|
|
516
|
+
# Skip undo push if we're applying an undo/redo operation
|
|
517
|
+
if not self._applying_undo:
|
|
518
|
+
# Estimate new visual position for undo (approximate)
|
|
519
|
+
# This is used by undo/redo which doesn't need block precision
|
|
520
|
+
approx_visual_pos = old_visual_pos
|
|
521
|
+
|
|
522
|
+
# Create and push undo command
|
|
523
|
+
command = MarkdownEditCommand(
|
|
524
|
+
self,
|
|
525
|
+
old_markdown,
|
|
526
|
+
new_markdown,
|
|
527
|
+
old_visual_pos,
|
|
528
|
+
approx_visual_pos,
|
|
529
|
+
"Edit",
|
|
530
|
+
)
|
|
531
|
+
self._undo_stack.push(command)
|
|
532
|
+
# Note: The redo() is called by push(), but we override cursor below
|
|
533
|
+
|
|
534
|
+
# Apply the change
|
|
535
|
+
self._markdown = new_markdown
|
|
536
|
+
self.markdown_edit_requested.emit(new_markdown)
|
|
537
|
+
self.render_markdown(new_markdown)
|
|
538
|
+
|
|
539
|
+
# Restore cursor using block-relative position
|
|
540
|
+
self._restore_cursor_block(block_num, offset_in_block)
|
|
541
|
+
|
|
542
|
+
self.content_changed.emit()
|
|
543
|
+
|
|
544
|
+
def _restore_cursor_block(self, block_num: int, offset_in_block: int) -> None:
|
|
545
|
+
"""Restore cursor to a block-relative position.
|
|
546
|
+
|
|
547
|
+
Args:
|
|
548
|
+
block_num: The target block number.
|
|
549
|
+
offset_in_block: Offset within the block.
|
|
550
|
+
"""
|
|
551
|
+
doc = self.document()
|
|
552
|
+
block = doc.findBlockByNumber(block_num)
|
|
553
|
+
|
|
554
|
+
if block.isValid():
|
|
555
|
+
# Calculate absolute position from block start + offset
|
|
556
|
+
block_start = block.position()
|
|
557
|
+
block_length = block.length() - 1 # -1 for block separator
|
|
558
|
+
|
|
559
|
+
# Clamp offset to block bounds
|
|
560
|
+
safe_offset = min(offset_in_block, max(0, block_length))
|
|
561
|
+
new_pos = block_start + safe_offset
|
|
562
|
+
|
|
563
|
+
cursor = self.textCursor()
|
|
564
|
+
cursor.setPosition(new_pos)
|
|
565
|
+
self.setTextCursor(cursor)
|
|
566
|
+
else:
|
|
567
|
+
# Fallback: move to end of document
|
|
568
|
+
cursor = self.textCursor()
|
|
569
|
+
cursor.movePosition(QTextCursor.MoveOperation.End)
|
|
570
|
+
self.setTextCursor(cursor)
|
|
571
|
+
|
|
572
|
+
def keyPressEvent(self, event: QKeyEvent) -> None:
|
|
573
|
+
"""
|
|
574
|
+
Handle key press events, intercepting edits and translating to markdown.
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
event: The key event.
|
|
578
|
+
"""
|
|
579
|
+
key = event.key()
|
|
580
|
+
modifiers = event.modifiers()
|
|
581
|
+
|
|
582
|
+
# Handle undo/redo shortcuts
|
|
583
|
+
if modifiers & Qt.KeyboardModifier.ControlModifier:
|
|
584
|
+
if key == Qt.Key.Key_Z:
|
|
585
|
+
if modifiers & Qt.KeyboardModifier.ShiftModifier:
|
|
586
|
+
# Ctrl+Shift+Z = Redo
|
|
587
|
+
self._undo_stack.redo()
|
|
588
|
+
else:
|
|
589
|
+
# Ctrl+Z = Undo
|
|
590
|
+
self._undo_stack.undo()
|
|
591
|
+
return
|
|
592
|
+
elif key == Qt.Key.Key_Y:
|
|
593
|
+
# Ctrl+Y = Redo
|
|
594
|
+
self._undo_stack.redo()
|
|
595
|
+
return
|
|
596
|
+
|
|
597
|
+
# Non-editing keys pass through
|
|
598
|
+
if not self._is_editing_key(event):
|
|
599
|
+
super().keyPressEvent(event)
|
|
600
|
+
return
|
|
601
|
+
|
|
602
|
+
# Check for protection
|
|
603
|
+
cursor = self.textCursor()
|
|
604
|
+
|
|
605
|
+
# Check selection protection
|
|
606
|
+
if cursor.hasSelection():
|
|
607
|
+
is_protected, region_id = self._is_selection_protected(cursor)
|
|
608
|
+
if is_protected and region_id:
|
|
609
|
+
logger.debug(f"Selection overlaps protected: {region_id}")
|
|
610
|
+
self.protection_violated.emit(region_id, cursor.selectionStart())
|
|
611
|
+
return
|
|
612
|
+
|
|
613
|
+
# Check cursor position protection
|
|
614
|
+
is_protected, region_id = self._is_cursor_in_protected(cursor)
|
|
615
|
+
|
|
616
|
+
# Handle backspace
|
|
617
|
+
if key == Qt.Key.Key_Backspace:
|
|
618
|
+
if cursor.hasSelection():
|
|
619
|
+
self._handle_delete_selection(cursor)
|
|
620
|
+
elif cursor.position() > 0:
|
|
621
|
+
# Check if backspace would delete into protected region
|
|
622
|
+
# If we're at the start of a block, backspace affects the previous block
|
|
623
|
+
if cursor.atBlockStart() and cursor.blockNumber() > 0:
|
|
624
|
+
prev_block = cursor.blockNumber() - 1
|
|
625
|
+
is_prev_protected, prev_region_id = self._block_mapper.is_block_protected(prev_block)
|
|
626
|
+
if is_prev_protected and prev_region_id:
|
|
627
|
+
self.protection_violated.emit(prev_region_id, cursor.position() - 1)
|
|
628
|
+
return
|
|
629
|
+
# Also check if current block is protected (deleting within it)
|
|
630
|
+
elif is_protected and region_id:
|
|
631
|
+
self.protection_violated.emit(region_id, cursor.position())
|
|
632
|
+
return
|
|
633
|
+
|
|
634
|
+
self._handle_backspace(cursor)
|
|
635
|
+
return
|
|
636
|
+
|
|
637
|
+
# Handle delete
|
|
638
|
+
if key == Qt.Key.Key_Delete:
|
|
639
|
+
if cursor.hasSelection():
|
|
640
|
+
self._handle_delete_selection(cursor)
|
|
641
|
+
else:
|
|
642
|
+
# Check if delete would affect protected region
|
|
643
|
+
# Delete removes the character AT the cursor position
|
|
644
|
+
if is_protected and region_id:
|
|
645
|
+
self.protection_violated.emit(region_id, cursor.position())
|
|
646
|
+
return
|
|
647
|
+
# If we're at end of block, delete affects the next block
|
|
648
|
+
if cursor.atBlockEnd():
|
|
649
|
+
next_block = cursor.blockNumber() + 1
|
|
650
|
+
is_next_protected, next_region_id = self._block_mapper.is_block_protected(next_block)
|
|
651
|
+
if is_next_protected and next_region_id:
|
|
652
|
+
self.protection_violated.emit(next_region_id, cursor.position())
|
|
653
|
+
return
|
|
654
|
+
|
|
655
|
+
self._handle_delete(cursor)
|
|
656
|
+
return
|
|
657
|
+
|
|
658
|
+
# Handle enter - insert paragraph break in markdown
|
|
659
|
+
if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
|
|
660
|
+
if is_protected and region_id:
|
|
661
|
+
# Instead of blocking, create a new paragraph after the protected block
|
|
662
|
+
self._handle_enter_in_protected(cursor, region_id)
|
|
663
|
+
return
|
|
664
|
+
if cursor.hasSelection():
|
|
665
|
+
self._handle_delete_selection(cursor)
|
|
666
|
+
cursor = self.textCursor()
|
|
667
|
+
# Use double newline for proper markdown paragraph break
|
|
668
|
+
self._handle_paragraph_break(cursor)
|
|
669
|
+
return
|
|
670
|
+
|
|
671
|
+
# Handle regular text input
|
|
672
|
+
text = event.text()
|
|
673
|
+
if text and text.isprintable():
|
|
674
|
+
if is_protected and region_id:
|
|
675
|
+
self.protection_violated.emit(region_id, cursor.position())
|
|
676
|
+
return
|
|
677
|
+
if cursor.hasSelection():
|
|
678
|
+
self._handle_delete_selection(cursor)
|
|
679
|
+
cursor = self.textCursor()
|
|
680
|
+
self._handle_insert(cursor, text)
|
|
681
|
+
return
|
|
682
|
+
|
|
683
|
+
# Pass through unhandled events
|
|
684
|
+
super().keyPressEvent(event)
|
|
685
|
+
|
|
686
|
+
def mouseReleaseEvent(self, event: QMouseEvent) -> None:
|
|
687
|
+
"""
|
|
688
|
+
Handle mouse release events to detect clicks on links.
|
|
689
|
+
|
|
690
|
+
Uses QTextEdit.anchorAt() to check if the click was on a link,
|
|
691
|
+
which is more reliable than tracking block user data.
|
|
692
|
+
|
|
693
|
+
Args:
|
|
694
|
+
event: The mouse event.
|
|
695
|
+
"""
|
|
696
|
+
# Check if we clicked on an anchor (link)
|
|
697
|
+
anchor = self.anchorAt(event.pos())
|
|
698
|
+
if anchor:
|
|
699
|
+
url = QUrl(anchor)
|
|
700
|
+
self._on_anchor_clicked(url)
|
|
701
|
+
# Don't pass through for action links - we handled it
|
|
702
|
+
if url.scheme() == "ncs":
|
|
703
|
+
return
|
|
704
|
+
|
|
705
|
+
# Normal click handling
|
|
706
|
+
super().mouseReleaseEvent(event)
|
|
707
|
+
|
|
708
|
+
def _on_anchor_clicked(self, url: QUrl) -> None:
|
|
709
|
+
"""
|
|
710
|
+
Handle anchor (link) clicks, detecting action group links.
|
|
711
|
+
|
|
712
|
+
The action group links use a custom URL scheme: ncs://action/{group_id}
|
|
713
|
+
|
|
714
|
+
Args:
|
|
715
|
+
url: The clicked URL.
|
|
716
|
+
"""
|
|
717
|
+
if url.scheme() == "ncs" and url.host() == "action":
|
|
718
|
+
# Extract the group ID from the path
|
|
719
|
+
group_id = url.path().lstrip("/")
|
|
720
|
+
region_id = f"action-{group_id}"
|
|
721
|
+
logger.debug(f"Action group link clicked: {region_id}")
|
|
722
|
+
self.action_group_clicked.emit(region_id)
|
|
723
|
+
else:
|
|
724
|
+
# For other links, could open externally or emit another signal
|
|
725
|
+
logger.debug(f"Link clicked: {url.toString()}")
|
|
726
|
+
|
|
727
|
+
def _handle_insert(self, cursor: QTextCursor, text: str) -> None:
|
|
728
|
+
"""Handle text insertion at cursor position."""
|
|
729
|
+
# Use block-relative coordinates for stable position tracking
|
|
730
|
+
block_num = cursor.blockNumber()
|
|
731
|
+
offset_in_block = cursor.positionInBlock()
|
|
732
|
+
|
|
733
|
+
# Check if we're in a placeholder paragraph (contains only nbsp)
|
|
734
|
+
# If so, replace the placeholder instead of inserting
|
|
735
|
+
block = cursor.block()
|
|
736
|
+
block_text = block.text()
|
|
737
|
+
if block_text.strip() in ("", "\u00a0") and cursor.atBlockStart():
|
|
738
|
+
# Find this block's position in markdown and replace the placeholder
|
|
739
|
+
# The placeholder paragraph is "\n\n\xa0" at the end
|
|
740
|
+
if self._markdown.endswith("\n\n\u00a0") or self._markdown.endswith("\n\n "):
|
|
741
|
+
# Replace the trailing placeholder with the new text
|
|
742
|
+
base = self._markdown.rstrip("\u00a0 ")
|
|
743
|
+
if base.endswith("\n\n"):
|
|
744
|
+
new_markdown = base + text
|
|
745
|
+
else:
|
|
746
|
+
new_markdown = base + "\n\n" + text
|
|
747
|
+
# Restore cursor using block-relative position
|
|
748
|
+
self._apply_edit_and_rerender_block(
|
|
749
|
+
new_markdown, block_num, offset_in_block + len(text)
|
|
750
|
+
)
|
|
751
|
+
return
|
|
752
|
+
|
|
753
|
+
# Convert visual position to markdown position using block-relative coords
|
|
754
|
+
md_pos = self._block_mapper.visual_to_md_pos(block_num, offset_in_block)
|
|
755
|
+
new_markdown = self._markdown[:md_pos] + text + self._markdown[md_pos:]
|
|
756
|
+
|
|
757
|
+
# Restore cursor using block-relative position
|
|
758
|
+
self._apply_edit_and_rerender_block(
|
|
759
|
+
new_markdown, block_num, offset_in_block + len(text)
|
|
760
|
+
)
|
|
761
|
+
|
|
762
|
+
def _handle_paragraph_break(self, cursor: QTextCursor) -> None:
|
|
763
|
+
"""Handle Enter key - insert paragraph break in markdown.
|
|
764
|
+
|
|
765
|
+
This needs special handling because QTextEdit's visual representation
|
|
766
|
+
of paragraphs doesn't match markdown newlines character-for-character.
|
|
767
|
+
"""
|
|
768
|
+
block_num = cursor.blockNumber()
|
|
769
|
+
offset_in_block = cursor.positionInBlock()
|
|
770
|
+
|
|
771
|
+
# Map to markdown position using block-relative coords
|
|
772
|
+
md_pos = self._block_mapper.visual_to_md_pos(block_num, offset_in_block)
|
|
773
|
+
|
|
774
|
+
# Check if we're at the end (nothing after cursor in markdown)
|
|
775
|
+
at_end = md_pos >= len(self._markdown) or self._markdown[md_pos:].strip() == ""
|
|
776
|
+
|
|
777
|
+
if at_end:
|
|
778
|
+
# At end of content - insert newlines and a non-breaking space placeholder
|
|
779
|
+
# The nbsp ensures a new paragraph is created in HTML rendering
|
|
780
|
+
# It will be replaced/removed when user types
|
|
781
|
+
new_markdown = self._markdown[:md_pos].rstrip() + "\n\n\u00a0"
|
|
782
|
+
else:
|
|
783
|
+
# In middle of content - just insert double newline
|
|
784
|
+
new_markdown = self._markdown[:md_pos] + "\n\n" + self._markdown[md_pos:]
|
|
785
|
+
|
|
786
|
+
# After paragraph break, cursor goes to start of the next block
|
|
787
|
+
self._apply_edit_and_rerender_block(new_markdown, block_num + 1, 0)
|
|
788
|
+
|
|
789
|
+
def _handle_backspace(self, cursor: QTextCursor) -> None:
|
|
790
|
+
"""Handle backspace at cursor position."""
|
|
791
|
+
block_num = cursor.blockNumber()
|
|
792
|
+
offset_in_block = cursor.positionInBlock()
|
|
793
|
+
|
|
794
|
+
if cursor.position() <= 0:
|
|
795
|
+
return
|
|
796
|
+
|
|
797
|
+
# Check if we're at start of a block (would delete paragraph break)
|
|
798
|
+
if cursor.atBlockStart() and block_num > 0:
|
|
799
|
+
# Deleting a paragraph break - need to remove \n\n from markdown
|
|
800
|
+
md_pos = self._block_mapper.visual_to_md_pos(block_num, 0)
|
|
801
|
+
# Find the paragraph break before this position
|
|
802
|
+
# It should be \n\n just before md_pos
|
|
803
|
+
if md_pos >= 2 and self._markdown[md_pos-2:md_pos] == "\n\n":
|
|
804
|
+
new_markdown = self._markdown[:md_pos-2] + self._markdown[md_pos:]
|
|
805
|
+
# After merging paragraphs, cursor goes to end of previous block
|
|
806
|
+
# Get the previous block's length from the mapping
|
|
807
|
+
prev_mapping = self._block_mapper.get_block_mapping(block_num - 1)
|
|
808
|
+
if prev_mapping:
|
|
809
|
+
prev_block_len = len(prev_mapping.visual_text)
|
|
810
|
+
self._apply_edit_and_rerender_block(
|
|
811
|
+
new_markdown, block_num - 1, prev_block_len
|
|
812
|
+
)
|
|
813
|
+
else:
|
|
814
|
+
# Fallback
|
|
815
|
+
self._apply_edit_and_rerender_block(new_markdown, block_num - 1, 0)
|
|
816
|
+
return
|
|
817
|
+
|
|
818
|
+
# Regular backspace - delete one character
|
|
819
|
+
md_pos = self._block_mapper.visual_to_md_pos(block_num, offset_in_block)
|
|
820
|
+
if md_pos > 0:
|
|
821
|
+
new_markdown = self._markdown[:md_pos-1] + self._markdown[md_pos:]
|
|
822
|
+
# Cursor moves back one position in same block
|
|
823
|
+
self._apply_edit_and_rerender_block(
|
|
824
|
+
new_markdown, block_num, max(0, offset_in_block - 1)
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
def _handle_delete(self, cursor: QTextCursor) -> None:
|
|
828
|
+
"""Handle delete at cursor position."""
|
|
829
|
+
block_num = cursor.blockNumber()
|
|
830
|
+
offset_in_block = cursor.positionInBlock()
|
|
831
|
+
md_pos = self._block_mapper.visual_to_md_pos(block_num, offset_in_block)
|
|
832
|
+
|
|
833
|
+
if md_pos >= len(self._markdown):
|
|
834
|
+
return
|
|
835
|
+
|
|
836
|
+
# Check if we're at end of a block (would delete paragraph break)
|
|
837
|
+
if cursor.atBlockEnd():
|
|
838
|
+
# Deleting forward into paragraph break - remove \n\n
|
|
839
|
+
if self._markdown[md_pos:md_pos+2] == "\n\n":
|
|
840
|
+
new_markdown = self._markdown[:md_pos] + self._markdown[md_pos+2:]
|
|
841
|
+
# Cursor stays at same position
|
|
842
|
+
self._apply_edit_and_rerender_block(new_markdown, block_num, offset_in_block)
|
|
843
|
+
return
|
|
844
|
+
|
|
845
|
+
# Regular delete - delete one character
|
|
846
|
+
new_markdown = self._markdown[:md_pos] + self._markdown[md_pos+1:]
|
|
847
|
+
# Cursor stays at same position
|
|
848
|
+
self._apply_edit_and_rerender_block(new_markdown, block_num, offset_in_block)
|
|
849
|
+
|
|
850
|
+
def _handle_delete_selection(self, cursor: QTextCursor) -> None:
|
|
851
|
+
"""Handle deletion of selected text."""
|
|
852
|
+
# Get start position as block-relative
|
|
853
|
+
start_cursor = QTextCursor(cursor)
|
|
854
|
+
start_cursor.setPosition(cursor.selectionStart())
|
|
855
|
+
start_block = start_cursor.blockNumber()
|
|
856
|
+
start_offset = start_cursor.positionInBlock()
|
|
857
|
+
|
|
858
|
+
# Get end position
|
|
859
|
+
end_cursor = QTextCursor(cursor)
|
|
860
|
+
end_cursor.setPosition(cursor.selectionEnd())
|
|
861
|
+
end_block = end_cursor.blockNumber()
|
|
862
|
+
end_offset = end_cursor.positionInBlock()
|
|
863
|
+
|
|
864
|
+
# Convert to markdown positions using block-relative coords
|
|
865
|
+
md_start = self._block_mapper.visual_to_md_pos(start_block, start_offset)
|
|
866
|
+
md_end = self._block_mapper.visual_to_md_pos(end_block, end_offset)
|
|
867
|
+
|
|
868
|
+
new_markdown = self._markdown[:md_start] + self._markdown[md_end:]
|
|
869
|
+
|
|
870
|
+
# Cursor goes to start of selection
|
|
871
|
+
self._apply_edit_and_rerender_block(new_markdown, start_block, start_offset)
|
|
872
|
+
|
|
873
|
+
def _handle_enter_in_protected(self, cursor: QTextCursor, region_id: str) -> None:
|
|
874
|
+
"""Handle Enter key pressed inside a protected block.
|
|
875
|
+
|
|
876
|
+
Creates a new paragraph after the protected block and moves cursor there.
|
|
877
|
+
|
|
878
|
+
Args:
|
|
879
|
+
cursor: The text cursor (inside protected block).
|
|
880
|
+
region_id: The ID of the protected region.
|
|
881
|
+
"""
|
|
882
|
+
import re
|
|
883
|
+
|
|
884
|
+
# Find the protected region's end marker in markdown
|
|
885
|
+
# Pattern: <!-- /PROTECTED:region_id -->
|
|
886
|
+
end_pattern = re.compile(
|
|
887
|
+
rf"<!--\s*/PROTECTED:{re.escape(region_id)}\s*-->"
|
|
888
|
+
)
|
|
889
|
+
|
|
890
|
+
match = end_pattern.search(self._markdown)
|
|
891
|
+
if not match:
|
|
892
|
+
logger.warning(f"Could not find end marker for protected region: {region_id}")
|
|
893
|
+
return
|
|
894
|
+
|
|
895
|
+
# Insert new paragraph after the end marker
|
|
896
|
+
end_pos = match.end()
|
|
897
|
+
|
|
898
|
+
# Check if there's already content after the protected block
|
|
899
|
+
after_content = self._markdown[end_pos:].lstrip("\n")
|
|
900
|
+
|
|
901
|
+
if after_content:
|
|
902
|
+
# There's content after - insert paragraph break before it
|
|
903
|
+
new_markdown = (
|
|
904
|
+
self._markdown[:end_pos]
|
|
905
|
+
+ "\n\n"
|
|
906
|
+
+ after_content
|
|
907
|
+
)
|
|
908
|
+
else:
|
|
909
|
+
# Nothing after - add new paragraph with placeholder
|
|
910
|
+
new_markdown = self._markdown[:end_pos] + "\n\n\u00a0"
|
|
911
|
+
|
|
912
|
+
# Find the block number of the protected region
|
|
913
|
+
# The new paragraph will be the next block after the protected block
|
|
914
|
+
current_block = cursor.blockNumber()
|
|
915
|
+
|
|
916
|
+
# Re-render and move cursor to the new paragraph (block after protected)
|
|
917
|
+
self._apply_edit_and_rerender_block(new_markdown, current_block + 1, 0)
|
|
918
|
+
|
|
919
|
+
def _is_editing_key(self, event: QKeyEvent) -> bool:
|
|
920
|
+
"""
|
|
921
|
+
Check if a key event would modify content.
|
|
922
|
+
|
|
923
|
+
Args:
|
|
924
|
+
event: The key event.
|
|
925
|
+
|
|
926
|
+
Returns:
|
|
927
|
+
True if the key would modify content.
|
|
928
|
+
"""
|
|
929
|
+
key = event.key()
|
|
930
|
+
|
|
931
|
+
non_editing_keys = {
|
|
932
|
+
Qt.Key.Key_Left,
|
|
933
|
+
Qt.Key.Key_Right,
|
|
934
|
+
Qt.Key.Key_Up,
|
|
935
|
+
Qt.Key.Key_Down,
|
|
936
|
+
Qt.Key.Key_Home,
|
|
937
|
+
Qt.Key.Key_End,
|
|
938
|
+
Qt.Key.Key_PageUp,
|
|
939
|
+
Qt.Key.Key_PageDown,
|
|
940
|
+
Qt.Key.Key_Shift,
|
|
941
|
+
Qt.Key.Key_Control,
|
|
942
|
+
Qt.Key.Key_Alt,
|
|
943
|
+
Qt.Key.Key_Meta,
|
|
944
|
+
Qt.Key.Key_Escape,
|
|
945
|
+
Qt.Key.Key_CapsLock,
|
|
946
|
+
Qt.Key.Key_NumLock,
|
|
947
|
+
Qt.Key.Key_ScrollLock,
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
if key in non_editing_keys:
|
|
951
|
+
return False
|
|
952
|
+
|
|
953
|
+
modifiers = event.modifiers()
|
|
954
|
+
if modifiers & Qt.KeyboardModifier.ControlModifier:
|
|
955
|
+
if key in {Qt.Key.Key_C, Qt.Key.Key_A}:
|
|
956
|
+
return False
|
|
957
|
+
|
|
958
|
+
return True
|
|
959
|
+
|
|
960
|
+
def insertFromMimeData(self, source) -> None:
|
|
961
|
+
"""
|
|
962
|
+
Handle paste operations, checking for protection.
|
|
963
|
+
|
|
964
|
+
Args:
|
|
965
|
+
source: The mime data being pasted.
|
|
966
|
+
"""
|
|
967
|
+
cursor = self.textCursor()
|
|
968
|
+
|
|
969
|
+
if cursor.hasSelection():
|
|
970
|
+
is_protected, region_id = self._is_selection_protected(cursor)
|
|
971
|
+
else:
|
|
972
|
+
is_protected, region_id = self._is_cursor_in_protected(cursor)
|
|
973
|
+
|
|
974
|
+
if is_protected and region_id:
|
|
975
|
+
logger.debug(f"Paste blocked in protected: {region_id}")
|
|
976
|
+
self.protection_violated.emit(region_id, cursor.position())
|
|
977
|
+
return
|
|
978
|
+
|
|
979
|
+
# Get plain text from clipboard
|
|
980
|
+
text = source.text() if source.hasText() else ""
|
|
981
|
+
if text:
|
|
982
|
+
# Strip any zero-width protection markers from pasted text
|
|
983
|
+
text = VisualProtectionTracker.strip_markers(text)
|
|
984
|
+
if cursor.hasSelection():
|
|
985
|
+
self._handle_delete_selection(cursor)
|
|
986
|
+
cursor = self.textCursor()
|
|
987
|
+
self._handle_insert(cursor, text)
|
|
988
|
+
|
|
989
|
+
def canInsertFromMimeData(self, source) -> bool:
|
|
990
|
+
"""
|
|
991
|
+
Check if mime data can be inserted.
|
|
992
|
+
|
|
993
|
+
Args:
|
|
994
|
+
source: The mime data.
|
|
995
|
+
|
|
996
|
+
Returns:
|
|
997
|
+
True if insertion is allowed.
|
|
998
|
+
"""
|
|
999
|
+
cursor = self.textCursor()
|
|
1000
|
+
|
|
1001
|
+
if cursor.hasSelection():
|
|
1002
|
+
is_protected, _ = self._is_selection_protected(cursor)
|
|
1003
|
+
else:
|
|
1004
|
+
is_protected, _ = self._is_cursor_in_protected(cursor)
|
|
1005
|
+
|
|
1006
|
+
if is_protected:
|
|
1007
|
+
return False
|
|
1008
|
+
|
|
1009
|
+
return source.hasText()
|
|
1010
|
+
|
|
1011
|
+
# Formatting methods - these now operate on markdown
|
|
1012
|
+
|
|
1013
|
+
def set_bold(self, bold: bool) -> None:
|
|
1014
|
+
"""Apply or remove bold formatting to the selection.
|
|
1015
|
+
|
|
1016
|
+
Args:
|
|
1017
|
+
bold: Whether text should be bold.
|
|
1018
|
+
"""
|
|
1019
|
+
cursor = self.textCursor()
|
|
1020
|
+
is_protected, _ = self._is_cursor_in_protected(cursor)
|
|
1021
|
+
if is_protected:
|
|
1022
|
+
return
|
|
1023
|
+
|
|
1024
|
+
if not cursor.hasSelection():
|
|
1025
|
+
return
|
|
1026
|
+
|
|
1027
|
+
self._apply_formatting(cursor, "**", "**", bold)
|
|
1028
|
+
|
|
1029
|
+
def set_italic(self, italic: bool) -> None:
|
|
1030
|
+
"""Apply or remove italic formatting to the selection.
|
|
1031
|
+
|
|
1032
|
+
Args:
|
|
1033
|
+
italic: Whether text should be italic.
|
|
1034
|
+
"""
|
|
1035
|
+
cursor = self.textCursor()
|
|
1036
|
+
is_protected, _ = self._is_cursor_in_protected(cursor)
|
|
1037
|
+
if is_protected:
|
|
1038
|
+
return
|
|
1039
|
+
|
|
1040
|
+
if not cursor.hasSelection():
|
|
1041
|
+
return
|
|
1042
|
+
|
|
1043
|
+
self._apply_formatting(cursor, "*", "*", italic)
|
|
1044
|
+
|
|
1045
|
+
def set_strikethrough(self, strikethrough: bool) -> None:
|
|
1046
|
+
"""Apply or remove strikethrough formatting to the selection.
|
|
1047
|
+
|
|
1048
|
+
Args:
|
|
1049
|
+
strikethrough: Whether text should have strikethrough.
|
|
1050
|
+
"""
|
|
1051
|
+
cursor = self.textCursor()
|
|
1052
|
+
is_protected, _ = self._is_cursor_in_protected(cursor)
|
|
1053
|
+
if is_protected:
|
|
1054
|
+
return
|
|
1055
|
+
|
|
1056
|
+
if not cursor.hasSelection():
|
|
1057
|
+
return
|
|
1058
|
+
|
|
1059
|
+
self._apply_formatting(cursor, "~~", "~~", strikethrough)
|
|
1060
|
+
|
|
1061
|
+
def _apply_formatting(
|
|
1062
|
+
self, cursor: QTextCursor, prefix: str, suffix: str, apply: bool
|
|
1063
|
+
) -> None:
|
|
1064
|
+
"""
|
|
1065
|
+
Apply or remove formatting to the selection.
|
|
1066
|
+
|
|
1067
|
+
Args:
|
|
1068
|
+
cursor: Text cursor with selection.
|
|
1069
|
+
prefix: Markdown prefix (e.g., "**").
|
|
1070
|
+
suffix: Markdown suffix (e.g., "**").
|
|
1071
|
+
apply: True to apply formatting, False to remove.
|
|
1072
|
+
"""
|
|
1073
|
+
# Get block-relative coordinates for start and end of selection
|
|
1074
|
+
start_cursor = QTextCursor(cursor)
|
|
1075
|
+
start_cursor.setPosition(cursor.selectionStart())
|
|
1076
|
+
start_block = start_cursor.blockNumber()
|
|
1077
|
+
start_offset = start_cursor.positionInBlock()
|
|
1078
|
+
|
|
1079
|
+
end_cursor = QTextCursor(cursor)
|
|
1080
|
+
end_cursor.setPosition(cursor.selectionEnd())
|
|
1081
|
+
end_block = end_cursor.blockNumber()
|
|
1082
|
+
end_offset = end_cursor.positionInBlock()
|
|
1083
|
+
|
|
1084
|
+
# Convert to markdown positions using block-relative mapping
|
|
1085
|
+
md_start = self._block_mapper.visual_to_md_pos(start_block, start_offset)
|
|
1086
|
+
md_end = self._block_mapper.visual_to_md_pos(end_block, end_offset)
|
|
1087
|
+
|
|
1088
|
+
logger.debug(
|
|
1089
|
+
f"Formatting: visual blocks ({start_block},{start_offset})-({end_block},{end_offset}) "
|
|
1090
|
+
f"-> md [{md_start}:{md_end}]"
|
|
1091
|
+
)
|
|
1092
|
+
|
|
1093
|
+
if apply:
|
|
1094
|
+
# Apply formatting by wrapping with prefix/suffix in markdown
|
|
1095
|
+
new_markdown = (
|
|
1096
|
+
self._markdown[:md_start]
|
|
1097
|
+
+ prefix
|
|
1098
|
+
+ self._markdown[md_start:md_end]
|
|
1099
|
+
+ suffix
|
|
1100
|
+
+ self._markdown[md_end:]
|
|
1101
|
+
)
|
|
1102
|
+
# After adding prefix, cursor selection expands
|
|
1103
|
+
new_end_offset = end_offset + len(prefix)
|
|
1104
|
+
else:
|
|
1105
|
+
# Remove formatting - need to find and remove the markers
|
|
1106
|
+
new_markdown = self._remove_formatting_block(
|
|
1107
|
+
md_start, md_end, prefix, suffix
|
|
1108
|
+
)
|
|
1109
|
+
if new_markdown is None:
|
|
1110
|
+
return
|
|
1111
|
+
new_end_offset = end_offset - len(prefix)
|
|
1112
|
+
|
|
1113
|
+
# Push to undo stack and re-render
|
|
1114
|
+
self._apply_formatting_with_undo(
|
|
1115
|
+
new_markdown, start_block, start_offset, end_block, new_end_offset
|
|
1116
|
+
)
|
|
1117
|
+
|
|
1118
|
+
def _apply_formatting_with_undo(
|
|
1119
|
+
self,
|
|
1120
|
+
new_markdown: str,
|
|
1121
|
+
start_block: int,
|
|
1122
|
+
start_offset: int,
|
|
1123
|
+
end_block: int,
|
|
1124
|
+
end_offset: int,
|
|
1125
|
+
) -> None:
|
|
1126
|
+
"""Apply formatting change with undo support and restore selection.
|
|
1127
|
+
|
|
1128
|
+
Args:
|
|
1129
|
+
new_markdown: The new markdown content.
|
|
1130
|
+
start_block: Selection start block number.
|
|
1131
|
+
start_offset: Selection start offset within block.
|
|
1132
|
+
end_block: Selection end block number.
|
|
1133
|
+
end_offset: Selection end offset within block.
|
|
1134
|
+
"""
|
|
1135
|
+
# Get current state for undo
|
|
1136
|
+
old_markdown = self._markdown
|
|
1137
|
+
old_cursor = self.textCursor()
|
|
1138
|
+
old_visual_pos = old_cursor.position()
|
|
1139
|
+
|
|
1140
|
+
# Create and push undo command
|
|
1141
|
+
if not self._applying_undo:
|
|
1142
|
+
command = MarkdownEditCommand(
|
|
1143
|
+
self,
|
|
1144
|
+
old_markdown,
|
|
1145
|
+
new_markdown,
|
|
1146
|
+
old_visual_pos,
|
|
1147
|
+
old_visual_pos, # Approximate - selection restore handles cursor
|
|
1148
|
+
"Format",
|
|
1149
|
+
)
|
|
1150
|
+
self._undo_stack.push(command)
|
|
1151
|
+
|
|
1152
|
+
# Apply the change
|
|
1153
|
+
self._markdown = new_markdown
|
|
1154
|
+
self.markdown_edit_requested.emit(new_markdown)
|
|
1155
|
+
self.render_markdown(new_markdown)
|
|
1156
|
+
|
|
1157
|
+
# Restore selection using block-relative positions
|
|
1158
|
+
self._restore_selection_block(start_block, start_offset, end_block, end_offset)
|
|
1159
|
+
|
|
1160
|
+
self.content_changed.emit()
|
|
1161
|
+
|
|
1162
|
+
def _restore_selection_block(
|
|
1163
|
+
self, start_block: int, start_offset: int, end_block: int, end_offset: int
|
|
1164
|
+
) -> None:
|
|
1165
|
+
"""Restore a selection using block-relative coordinates."""
|
|
1166
|
+
doc = self.document()
|
|
1167
|
+
|
|
1168
|
+
# Get start position
|
|
1169
|
+
start_blk = doc.findBlockByNumber(start_block)
|
|
1170
|
+
if not start_blk.isValid():
|
|
1171
|
+
return
|
|
1172
|
+
start_pos = start_blk.position() + min(start_offset, start_blk.length() - 1)
|
|
1173
|
+
|
|
1174
|
+
# Get end position
|
|
1175
|
+
end_blk = doc.findBlockByNumber(end_block)
|
|
1176
|
+
if not end_blk.isValid():
|
|
1177
|
+
end_blk = start_blk
|
|
1178
|
+
end_pos = end_blk.position() + min(end_offset, end_blk.length() - 1)
|
|
1179
|
+
|
|
1180
|
+
cursor = self.textCursor()
|
|
1181
|
+
cursor.setPosition(start_pos)
|
|
1182
|
+
cursor.setPosition(end_pos, QTextCursor.MoveMode.KeepAnchor)
|
|
1183
|
+
self.setTextCursor(cursor)
|
|
1184
|
+
|
|
1185
|
+
def _remove_formatting_block(
|
|
1186
|
+
self, md_start: int, md_end: int, prefix: str, suffix: str
|
|
1187
|
+
) -> str | None:
|
|
1188
|
+
"""Remove formatting markers around a markdown selection."""
|
|
1189
|
+
# Look for prefix before md_start and suffix after md_end
|
|
1190
|
+
prefix_pos = self._markdown.rfind(prefix, 0, md_start + len(prefix))
|
|
1191
|
+
suffix_pos = self._markdown.find(suffix, md_end - len(suffix))
|
|
1192
|
+
|
|
1193
|
+
if prefix_pos == -1 or suffix_pos == -1:
|
|
1194
|
+
return None
|
|
1195
|
+
|
|
1196
|
+
# Remove the markers
|
|
1197
|
+
new_md = (
|
|
1198
|
+
self._markdown[:prefix_pos]
|
|
1199
|
+
+ self._markdown[prefix_pos + len(prefix) : suffix_pos]
|
|
1200
|
+
+ self._markdown[suffix_pos + len(suffix) :]
|
|
1201
|
+
)
|
|
1202
|
+
return new_md
|
|
1203
|
+
|
|
1204
|
+
def _remove_formatting(
|
|
1205
|
+
self, visual_start: int, visual_end: int, prefix: str, suffix: str
|
|
1206
|
+
) -> str | None:
|
|
1207
|
+
"""
|
|
1208
|
+
Remove formatting markers around a selection.
|
|
1209
|
+
|
|
1210
|
+
Args:
|
|
1211
|
+
visual_start: Start of selection in visual view.
|
|
1212
|
+
visual_end: End of selection in visual view.
|
|
1213
|
+
prefix: Markdown prefix to remove.
|
|
1214
|
+
suffix: Markdown suffix to remove.
|
|
1215
|
+
|
|
1216
|
+
Returns:
|
|
1217
|
+
New markdown with formatting removed, or None if not found.
|
|
1218
|
+
"""
|
|
1219
|
+
if self._mapping is None:
|
|
1220
|
+
return None
|
|
1221
|
+
|
|
1222
|
+
md_start = self._position_mapper.visual_to_markdown(self._mapping, visual_start)
|
|
1223
|
+
md_end = self._position_mapper.visual_to_markdown(self._mapping, visual_end)
|
|
1224
|
+
|
|
1225
|
+
# Look for prefix before md_start and suffix after md_end
|
|
1226
|
+
prefix_pos = self._markdown.rfind(prefix, 0, md_start + 1)
|
|
1227
|
+
suffix_pos = self._markdown.find(suffix, md_end - 1)
|
|
1228
|
+
|
|
1229
|
+
if prefix_pos == -1 or suffix_pos == -1:
|
|
1230
|
+
return None
|
|
1231
|
+
|
|
1232
|
+
# Remove the markers
|
|
1233
|
+
new_md = (
|
|
1234
|
+
self._markdown[:prefix_pos]
|
|
1235
|
+
+ self._markdown[prefix_pos + len(prefix) : suffix_pos]
|
|
1236
|
+
+ self._markdown[suffix_pos + len(suffix) :]
|
|
1237
|
+
)
|
|
1238
|
+
return new_md
|
|
1239
|
+
|
|
1240
|
+
def toggle_bold(self) -> None:
|
|
1241
|
+
"""Toggle bold formatting on the selection."""
|
|
1242
|
+
cursor = self.textCursor()
|
|
1243
|
+
# Check if currently bold by looking at char format
|
|
1244
|
+
is_bold = cursor.charFormat().fontWeight() == QFont.Weight.Bold
|
|
1245
|
+
self.set_bold(not is_bold)
|
|
1246
|
+
|
|
1247
|
+
def toggle_italic(self) -> None:
|
|
1248
|
+
"""Toggle italic formatting on the selection."""
|
|
1249
|
+
cursor = self.textCursor()
|
|
1250
|
+
self.set_italic(not cursor.charFormat().fontItalic())
|
|
1251
|
+
|
|
1252
|
+
def toggle_strikethrough(self) -> None:
|
|
1253
|
+
"""Toggle strikethrough formatting on the selection."""
|
|
1254
|
+
cursor = self.textCursor()
|
|
1255
|
+
self.set_strikethrough(not cursor.charFormat().fontStrikeOut())
|
|
1256
|
+
|
|
1257
|
+
def set_heading(self, level: int) -> None:
|
|
1258
|
+
"""
|
|
1259
|
+
Set the current line as a heading.
|
|
1260
|
+
|
|
1261
|
+
Args:
|
|
1262
|
+
level: The heading level (1-6), or 0 for normal text.
|
|
1263
|
+
"""
|
|
1264
|
+
import re
|
|
1265
|
+
|
|
1266
|
+
cursor = self.textCursor()
|
|
1267
|
+
is_protected, _ = self._is_cursor_in_protected(cursor)
|
|
1268
|
+
if is_protected:
|
|
1269
|
+
return
|
|
1270
|
+
|
|
1271
|
+
# Get block number for the current line
|
|
1272
|
+
block_num = cursor.blockNumber()
|
|
1273
|
+
|
|
1274
|
+
# Get the block mapping to find the markdown line
|
|
1275
|
+
mapping = self._block_mapper.get_block_mapping(block_num)
|
|
1276
|
+
if mapping is None:
|
|
1277
|
+
logger.warning(f"No block mapping for block {block_num}")
|
|
1278
|
+
return
|
|
1279
|
+
|
|
1280
|
+
# Get the markdown line start position
|
|
1281
|
+
line_begin = mapping.md_char_start
|
|
1282
|
+
|
|
1283
|
+
# Get the line content
|
|
1284
|
+
line_content = self._markdown[line_begin:mapping.md_char_end]
|
|
1285
|
+
|
|
1286
|
+
# Skip protected regions (device actions, runs)
|
|
1287
|
+
if mapping.is_protected:
|
|
1288
|
+
return
|
|
1289
|
+
|
|
1290
|
+
# Remove existing heading markers
|
|
1291
|
+
stripped_line = re.sub(r"^#{1,6}\s*", "", line_content)
|
|
1292
|
+
|
|
1293
|
+
# Build new line
|
|
1294
|
+
if level == 0:
|
|
1295
|
+
new_line = stripped_line
|
|
1296
|
+
else:
|
|
1297
|
+
new_line = "#" * level + " " + stripped_line
|
|
1298
|
+
|
|
1299
|
+
# Replace the line in markdown
|
|
1300
|
+
new_markdown = (
|
|
1301
|
+
self._markdown[:line_begin]
|
|
1302
|
+
+ new_line
|
|
1303
|
+
+ self._markdown[mapping.md_char_end:]
|
|
1304
|
+
)
|
|
1305
|
+
|
|
1306
|
+
# Use block-based cursor restoration
|
|
1307
|
+
self._apply_edit_and_rerender_block(new_markdown, block_num, 0)
|
|
1308
|
+
|
|
1309
|
+
def insert_link(self, url: str, text: str | None = None) -> None:
|
|
1310
|
+
"""
|
|
1311
|
+
Insert a link at the current cursor position.
|
|
1312
|
+
|
|
1313
|
+
Args:
|
|
1314
|
+
url: The link URL.
|
|
1315
|
+
text: The link text (defaults to URL if not provided).
|
|
1316
|
+
"""
|
|
1317
|
+
cursor = self.textCursor()
|
|
1318
|
+
is_protected, _ = self._is_cursor_in_protected(cursor)
|
|
1319
|
+
if is_protected:
|
|
1320
|
+
return
|
|
1321
|
+
|
|
1322
|
+
if text is None:
|
|
1323
|
+
text = url
|
|
1324
|
+
|
|
1325
|
+
link_md = f"[{text}]({url})"
|
|
1326
|
+
|
|
1327
|
+
if cursor.hasSelection():
|
|
1328
|
+
self._handle_delete_selection(cursor)
|
|
1329
|
+
cursor = self.textCursor()
|
|
1330
|
+
|
|
1331
|
+
self._handle_insert(cursor, link_md)
|
|
1332
|
+
|
|
1333
|
+
def insert_code_block(self) -> None:
|
|
1334
|
+
"""Insert a code block at the current cursor position."""
|
|
1335
|
+
cursor = self.textCursor()
|
|
1336
|
+
is_protected, _ = self._is_cursor_in_protected(cursor)
|
|
1337
|
+
if is_protected:
|
|
1338
|
+
return
|
|
1339
|
+
|
|
1340
|
+
code_md = "\n```\n\n```\n"
|
|
1341
|
+
|
|
1342
|
+
if cursor.hasSelection():
|
|
1343
|
+
self._handle_delete_selection(cursor)
|
|
1344
|
+
cursor = self.textCursor()
|
|
1345
|
+
|
|
1346
|
+
self._handle_insert(cursor, code_md)
|
|
1347
|
+
|
|
1348
|
+
def get_introspection_data(self) -> dict[str, Any]:
|
|
1349
|
+
"""
|
|
1350
|
+
Get introspection data for Claude MCP tools.
|
|
1351
|
+
|
|
1352
|
+
Returns:
|
|
1353
|
+
Dictionary with widget information.
|
|
1354
|
+
"""
|
|
1355
|
+
return {
|
|
1356
|
+
"widget_type": self.widget_type,
|
|
1357
|
+
"widget_description": self.widget_description,
|
|
1358
|
+
"object_name": self.objectName(),
|
|
1359
|
+
"class_name": self.__class__.__name__,
|
|
1360
|
+
"content_length": len(self._markdown),
|
|
1361
|
+
"line_count": self.document().blockCount(),
|
|
1362
|
+
"cursor_position": self.textCursor().position(),
|
|
1363
|
+
"has_selection": self.textCursor().hasSelection(),
|
|
1364
|
+
"protected_regions": len(self._visual_tracker.get_regions()),
|
|
1365
|
+
"enabled": self.isEnabled(),
|
|
1366
|
+
"visible": self.isVisible(),
|
|
1367
|
+
"read_only": self.isReadOnly(),
|
|
1368
|
+
"can_undo": self.can_undo(),
|
|
1369
|
+
"can_redo": self.can_redo(),
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
# Undo/redo methods
|
|
1373
|
+
|
|
1374
|
+
def undo(self) -> None:
|
|
1375
|
+
"""Undo the last edit."""
|
|
1376
|
+
self._undo_stack.undo()
|
|
1377
|
+
|
|
1378
|
+
def redo(self) -> None:
|
|
1379
|
+
"""Redo the last undone edit."""
|
|
1380
|
+
self._undo_stack.redo()
|
|
1381
|
+
|
|
1382
|
+
def can_undo(self) -> bool:
|
|
1383
|
+
"""Check if undo is available."""
|
|
1384
|
+
return self._undo_stack.canUndo()
|
|
1385
|
+
|
|
1386
|
+
def can_redo(self) -> bool:
|
|
1387
|
+
"""Check if redo is available."""
|
|
1388
|
+
return self._undo_stack.canRedo()
|
|
1389
|
+
|
|
1390
|
+
def clear_undo_stack(self) -> None:
|
|
1391
|
+
"""Clear the undo/redo history."""
|
|
1392
|
+
self._undo_stack.clear()
|
|
1393
|
+
|
|
1394
|
+
@property
|
|
1395
|
+
def undo_stack(self) -> QUndoStack:
|
|
1396
|
+
"""Get the undo stack for external use (e.g., menu actions)."""
|
|
1397
|
+
return self._undo_stack
|