forked from balisujohn/localwriter
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmain.py
More file actions
1071 lines (825 loc) · 39.7 KB
/
Copy pathmain.py
File metadata and controls
1071 lines (825 loc) · 39.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2024 John Balis
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
import os
import sys
# --- Minimal stdlib-only bootstrap (MUST be before any "from plugin..." import) ---
# unopkg / pythonloader can load this file during `make deploy` (writeRegistryInfo)
# before the extension root is on sys.path. We must fix that using only stdlib.
_this = os.path.abspath(__file__)
for __ in range(2): # plugin/main.py → plugin/ → extension root
_this = os.path.dirname(_this)
if _this not in sys.path:
sys.path.insert(0, _this)
import logging
from plugin.framework.uno_bootstrap import ensure_plugin_on_path
# Central bootstrap for UNO-loaded entry points.
# This replaces the previous manual sys.path manipulation that was duplicated
# across main.py and the Calc add-ins.
ensure_plugin_on_path(
__file__,
levels_up=2, # plugin/main.py → plugin/ → extension root
also_add_plugin_dir=True,
also_add_lib=True,
also_add_vendor=True, # root-level vendor/ when present (optional dev wheels)
)
# Inject downloaded binaries path (audio + serialization)
try:
from plugin.scripting.audio_recorder_service import ensure_downloaded_audio_on_path
ensure_downloaded_audio_on_path()
except Exception:
pass
import unohelper
from typing import TYPE_CHECKING, Any, Callable, Protocol, cast
if TYPE_CHECKING:
from types import ModuleType
from com.sun.star.util import URL as UnoURL
from plugin.framework.module_base import ModuleBase
from plugin.framework.tool import ToolRegistry
officehelper: ModuleType | None = None
try:
import officehelper as _officehelper_module
officehelper = _officehelper_module
except ImportError:
pass
from plugin.framework.logging import init_logging
import uno
from com.sun.star.task import XJobExecutor, XJob
from com.sun.star.frame import DispatchDescriptor, XDispatch, XDispatchProvider
from com.sun.star.lang import XInitialization, XServiceInfo
from plugin.framework.uno_context import get_active_document, get_extension_url, get_ctx
from plugin.framework.thread_guard import background
# ---------------------------------------------------------------------------
# HTTP / MCP Server (Module wrapper)
# ---------------------------------------------------------------------------
class McpModuleActions(Protocol):
"""``plugin.mcp`` entry points used from main for MCP menu commands."""
name: str | None
def shutdown(self) -> None: ...
def _action_toggle_server(self) -> None: ...
def _action_server_status(self) -> None: ...
# ---------------------------------------------------------------------------
# Bootstrapping (Dynamic discovery from loaded manifest)
# ---------------------------------------------------------------------------
import threading
_services = None
log = logging.getLogger(__name__)
# Action handler registry
_ACTION_HANDLERS: dict[str, Callable[..., Any]] = {}
def register_action_handler(module_name, action_name, handler_func):
"""Register an action handler function."""
key = f"{module_name}.{action_name}"
_ACTION_HANDLERS[key] = handler_func
_tools: ToolRegistry | None = None
_modules: list[ModuleBase] = []
_init_lock = threading.Lock()
_initialized = False
_extension_update_check_scheduled = False
_extension_update_check_lock = threading.Lock()
def _schedule_extension_update_check_once(ctx):
"""Run weekly update check at most once per process, after init_logging."""
global _extension_update_check_scheduled
with _extension_update_check_lock:
if _extension_update_check_scheduled:
log.info("extension update check: already queued this process, skipping duplicate schedule")
return
_extension_update_check_scheduled = True
from plugin.framework.worker_pool import run_in_background
from plugin.chatbot.extension_update_check import run_extension_update_check
log.info("extension update check: scheduling background worker")
run_in_background(run_extension_update_check, ctx, name="extension_update_check")
def get_services():
global _services
if _services is None:
bootstrap()
return _services
def get_tools() -> ToolRegistry:
global _tools
if _tools is None:
bootstrap()
assert _tools is not None
return _tools
def bootstrap(ctx=None):
"""Bootstraps the service container and modules.
This is currently triggered eagerly by Jobs.xcu on OnStartApp to ensure the
MCP server starts automatically in headless mode. We could make this lazy
again in the future if startup performance becomes a concern.
"""
global _services, _tools, _modules, _initialized
if _initialized:
return
with _init_lock:
if _initialized:
return
# 1. Basic UNO context
if ctx is None:
from plugin.framework.uno_context import get_ctx
ctx = get_ctx()
from plugin.framework.config import init_config
init_config(ctx)
# 2. Service Container
from plugin.framework.service import ServiceRegistry
_services = ServiceRegistry()
_services.register("uno", ctx)
# 3. Core Services (Framework)
from plugin.framework.config_service import ConfigService
from plugin.doc.document_helpers import DocumentService
from plugin.writer.format import FormatService
from plugin.framework.event_bus import get_event_bus
_services.register("config", ConfigService())
_services.register("document", DocumentService())
_services.register("format", FormatService())
_services.register("events", get_event_bus())
# 4. Tool Registry
from plugin.framework.tool import ToolRegistry
_tools = ToolRegistry(_services)
_services.register("tools", _tools)
# 4b. Main Thread Execution Service
from plugin.framework.queue_executor import default_executor
_services.register("main_thread", default_executor)
# Wire config service to events
config_svc = _services.get("config")
events_svc = _services.get("events")
if config_svc and events_svc:
config_svc.set_events(events_svc)
# Initialize i18n
from plugin.framework.i18n import init_i18n
init_i18n(ctx)
# Set initialized early to prevent recursive calls from re-running bootstrap
# but after _services and _tools are created.
_initialized = True
# 5. Load manifest and initialize modules
from plugin.framework.module_base import ModuleLoader
_modules.extend(ModuleLoader.load_modules(_services))
# 6. Background phase: modules that start listeners/servers (e.g. McpModule when MCP enabled)
for mod in _modules:
mod.start_background(_services)
# Wire event bus into config service
events_svc = _services.get("events")
if events_svc:
# Subscribe to menu:update for dynamic menu text + icons
main_thread = _services.get("main_thread")
events_svc.subscribe("menu:update", lambda **kw: main_thread.execute(notify_menu_update) if main_thread else notify_menu_update())
if os.environ.get("WRITERAGENT_TESTING") != "1":
# Pre-load icons into ImageManager so first menu display has them.
from plugin.framework.worker_pool import run_in_background
run_in_background(_update_menu_icons)
# Register core handlers
_register_core_handlers()
def _register_core_handlers():
"""Register core application handlers during bootstrap."""
from plugin.chatbot.dialog_views import settings_box, show_eval_dashboard
from plugin.doc.document_helpers import is_writer, is_calc, is_draw
import importlib
def _open_settings():
_open_dialog_safely(settings_box, "Failed to open settings")
register_action_handler("main", "settings", _open_settings)
def _report_bug():
from plugin.framework.bug_report import open_bug_report_in_browser
from plugin.framework.uno_context import get_ctx
open_bug_report_in_browser(get_ctx(), title="Bug report")
register_action_handler("main", "report_bug", _report_bug)
register_action_handler("main", "EvaluationDashboard", lambda: _open_dialog_safely(show_eval_dashboard, "Failed to show eval dashboard"))
register_action_handler("main", "RunFormatTests", lambda: _run_test_suite(importlib.import_module("plugin.tests.writer.test_format_uno"), is_writer, "writer.format_tests") if _tests_bundled() else _show_tests_unavailable("writer.format_tests"))
register_action_handler("main", "RunCalcTests", lambda: _run_test_suite(importlib.import_module("plugin.tests.calc.test_calc_uno"), is_calc, "calc.tests") if _tests_bundled() else _show_tests_unavailable("calc.tests"))
register_action_handler("main", "RunCalcIntegrationTests", lambda: _run_test_suite(importlib.import_module("plugin.tests.calc.test_calc_uno"), is_calc, "calc.integration_tests") if _tests_bundled() else _show_tests_unavailable("calc.integration_tests"))
register_action_handler("main", "RunDrawTests", lambda: _run_test_suite(importlib.import_module("plugin.tests.draw.test_draw_uno"), is_draw, "draw.tests") if _tests_bundled() else _show_tests_unavailable("draw.tests"))
register_action_handler("main", "NoOp", lambda: None)
def _run_python():
from plugin.scripting.python_runner import run_python_dialog
run_python_dialog(get_ctx())
register_action_handler("scripting", "run_python_dialog", _run_python)
def _edit_python_cell():
from plugin.calc.python.editor import open_python_cell_editor
open_python_cell_editor(get_ctx())
register_action_handler("scripting", "edit_python_cell", _edit_python_cell)
def _reset_python_session():
from plugin.scripting.session_manager import reset_workbook_python_session
reset_workbook_python_session(get_ctx())
register_action_handler("scripting", "reset_python_session", _reset_python_session)
def _convert_spreadsheet():
from plugin.calc.spreadsheet_import.import_dialog import show_import_dialog
_open_dialog_safely(show_import_dialog, "Failed to open Convert Sheet to Python dialog")
register_action_handler("calc", "convert_spreadsheet_to_python", _convert_spreadsheet)
try:
from plugin.calc.python.editor_context_menu import install_calc_cell_context_menu
from plugin.notebook.notebook_controls import install_notebook_run_button_wiring
install_calc_cell_context_menu(get_ctx())
install_notebook_run_button_wiring(get_ctx())
except Exception:
log.debug("Calc cell context menu install failed", exc_info=True)
def _import_ipynb():
from plugin.notebook.import_dialog import run_import_ipynb_dialog
run_import_ipynb_dialog(get_ctx())
register_action_handler("scripting", "import_ipynb", _import_ipynb)
def _open_vision_settings():
from plugin.chatbot.module_config_dialog import show_vision_settings_dialog
_open_dialog_safely(show_vision_settings_dialog, "Failed to open Vision OCR settings")
register_action_handler("vision", "open_settings", _open_vision_settings)
def _insert_latex():
from plugin.writer.math.latex_dialog import insert_latex_math_dialog
insert_latex_math_dialog(get_ctx())
register_action_handler("writer", "insert_latex_dialog", _insert_latex)
def _open_search_dialog():
from plugin.embeddings.search_ui import show_search_dialog
show_search_dialog(get_ctx())
register_action_handler("embeddings", "search_dialog", _open_search_dialog)
def _open_text_analytics():
from plugin.scripting.text_analytics_ui import TextAnalyticsDialog
TextAnalyticsDialog.show(get_ctx())
register_action_handler("textanalytics", "open_dialog", _open_text_analytics)
def _refresh_review_toolbar(model):
"""Re-evaluate the review toolbar's visibility (hide once nothing is left to review).
Also a catch-up point if changes were resolved via LibreOffice's native UI."""
try:
from plugin.writer.review_toolbar import refresh_review_toolbar
refresh_review_toolbar(model)
except Exception:
logging.getLogger("writeragent.main").debug("review toolbar refresh failed", exc_info=True)
def _resolve_change_at_cursor(accept):
from plugin.framework.uno_context import get_active_document
from plugin.writer.inline_review import resolve_change_at_cursor, show_review_message
c = get_ctx()
model = get_active_document(c)
if model is not None:
ok, msg = resolve_change_at_cursor(model, c, accept)
logging.getLogger("writeragent.main").debug("inline review: accept=%s -> ok=%s msg=%s", accept, ok, msg)
if not ok:
show_review_message(c, msg)
_refresh_review_toolbar(model)
else:
logging.getLogger("writeragent.main").debug("inline review: no current component")
register_action_handler("writer", "accept_change", lambda: _resolve_change_at_cursor(True))
register_action_handler("writer", "reject_change", lambda: _resolve_change_at_cursor(False))
def _resolve_all_agent(accept):
from plugin.framework.uno_context import get_active_document
from plugin.writer.inline_review import resolve_all_with_feedback, show_review_message
c = get_ctx()
model = get_active_document(c)
if model is not None:
n, msg = resolve_all_with_feedback(model, c, accept)
logging.getLogger("writeragent.main").debug("inline review: resolve-all accept=%s -> %d changes", accept, n)
show_review_message(c, msg)
_refresh_review_toolbar(model)
register_action_handler("writer", "review_accept_all", lambda: _resolve_all_agent(True))
register_action_handler("writer", "review_reject_all", lambda: _resolve_all_agent(False))
def _goto_adjacent_change(forward):
"""Fast-travel (#2): move the cursor to the next/previous pending agent change, in document
order, cycling. Drives the review toolbar's Next/Previous buttons (and any shortcut)."""
from plugin.framework.uno_context import get_active_document
from plugin.writer.inline_review import goto_adjacent_agent_change
c = get_ctx()
model = get_active_document(c)
if model is None:
return
token = goto_adjacent_agent_change(model, forward)
logging.getLogger("writeragent.main").debug("review nav: forward=%s -> token=%s", forward, token)
_refresh_review_toolbar(model)
register_action_handler("writer", "review_next", lambda: _goto_adjacent_change(True))
register_action_handler("writer", "review_prev", lambda: _goto_adjacent_change(False))
try:
from plugin.writer.change_context_menu import install_writer_change_context_menu
install_writer_change_context_menu(get_ctx())
except Exception:
# WARNING, not debug: a silent install failure looks identical to "menu ignored".
log.warning("Writer change context menu install failed", exc_info=True)
try:
from plugin.writer.review_toolbar import install_review_toolbar
install_review_toolbar(get_ctx())
except Exception:
log.warning("Review toolbar visibility install failed", exc_info=True)
# ── Dynamic menu text infrastructure ─────────────────────────────────
_DISPATCH_PROTOCOL = "org.extension.writeragent:"
_status_listeners: list[tuple[Any, Any]] = [] # [(listener, url)]
_status_lock = threading.Lock()
EXTENSION_ID = "org.extension.writeragent"
_TESTS_AVAILABLE = None
def _tests_bundled() -> bool:
"""True when `plugin.tests` test modules are included in this build."""
global _TESTS_AVAILABLE
if _TESTS_AVAILABLE is None:
try:
import importlib.util
_TESTS_AVAILABLE = importlib.util.find_spec("plugin.tests.conftest") is not None
except Exception:
_TESTS_AVAILABLE = False
return bool(_TESTS_AVAILABLE)
def _show_tests_unavailable(test_name: str) -> None:
"""Show a message when test suites are not bundled (release builds)."""
try:
from plugin.chatbot.dialogs import msgbox
from plugin.framework.uno_context import get_ctx
msgbox(get_ctx(), test_name, "This WriterAgent build was packaged without the optional `plugin.tests` test modules.")
except Exception:
# Never let test menu state/messaging break core UI dispatch.
pass
def _open_dialog_safely(dialog_func, error_msg, *args, **kwargs):
"""Safely open a dialog with standardized error handling."""
from plugin.framework.errors import DocumentDisposedError, UnoObjectError
from plugin.framework.uno_context import get_ctx
ctx_getter = get_ctx
try:
dialog_func(ctx_getter(), *args, **kwargs)
except DocumentDisposedError:
log.debug("Dialog opening aborted: document disposed")
except UnoObjectError as e:
log.warning(f"UNO error opening dialog: {e.message}")
except Exception as e:
log.exception("%s", error_msg)
# Show user-friendly error message
from plugin.chatbot.dialogs import msgbox_with_report
from plugin.framework.i18n import _
msgbox_with_report(
ctx_getter(),
_("Error"),
_(f"{error_msg}: {str(e)}"),
box_type=3,
reportable=True,
report_title=error_msg,
report_extra=str(e),
)
def _run_test_suite(test_func, doc_checker, test_name):
"""Run a bundled in-OXT test suite on the UI thread and show the result.
Must not use ``run_blocking_in_thread``: synchronous UNO tools reject calls from
worker threads (see ``ToolBase.execute_safe``).
"""
from plugin.framework.uno_context import get_ctx
from plugin.chatbot.dialogs import msgbox
print(f"DEBUG: _run_test_suite entry. name={test_name}")
if not _tests_bundled():
print("DEBUG: _run_test_suite: tests not bundled!")
_show_tests_unavailable(test_name)
return
print("DEBUG: _run_test_suite: tests are bundled.")
ctx = get_ctx()
try:
log.info(f"_run_test_suite start: {test_name}")
from plugin.testing_runner import run_module_suite
model = get_active_document(ctx)
doc_model = model if (model and doc_checker(model)) else None
log.debug(f"Calling run_module_suite for {test_name}")
p, f, suite_log = run_module_suite(ctx, test_func, test_name, doc_model)
log.info(f"_run_test_suite finished: {test_name}, p={p}, f={f}")
from plugin.framework.i18n import _
msgbox(ctx, test_name, _("{0}: {1} passed, {2} failed.").format(test_name, p, f) + "\n\n" + "\n".join(suite_log))
except Exception as e:
from plugin.framework.i18n import _
msgbox(ctx, test_name, _("Tests failed to run: {0}").format(str(e)))
_NOTEBOOK_RUN_CELL_PREFIX = "notebook.run_cell."
def _dispatch_command(command):
"""Dispatch command using handler registry, falling back to module actions."""
bootstrap()
if command.startswith(_NOTEBOOK_RUN_CELL_PREFIX):
from plugin.framework.uno_context import get_ctx
from plugin.notebook.notebook_runner import run_cell_by_hex
run_cell_by_hex(get_ctx(), command[len(_NOTEBOOK_RUN_CELL_PREFIX) :])
return
# First try the action registry
handler = _ACTION_HANDLERS.get(command)
if handler:
try:
handler()
except Exception:
logging.getLogger("writeragent.main").exception(f"Action {command} failed")
return
# If no handler, check for module delegation
dot = command.find(".")
if dot <= 0:
log = logging.getLogger("writeragent.main")
log.warning("Unhandled command: %s", command)
return
mod_name = command[:dot]
action = command[dot + 1 :]
# Module actions
for mod in _modules:
if mod.name == mod_name:
mod.on_action(action)
return
log = logging.getLogger("writeragent.main")
log.warning("No handler or module found for command: %s", command)
def get_menu_text(command):
"""Get dynamic menu text for a command, or None for default."""
bootstrap()
dot = command.find(".")
if dot <= 0:
return None
mod_name = command[:dot]
action = command[dot + 1 :]
from plugin.framework.i18n import _
# Check if the module provides a dynamic text
for mod in _modules:
if mod.name == mod_name:
text = mod.get_menu_text(action)
if text is not None:
return _(text)
# Fallback to the title from the manifest
try:
from plugin._manifest import MODULES
for m in MODULES:
if m["name"] == mod_name:
# The manifest doesn't store action titles directly in a map,
# but it might have an action list. If we don't have a specific title,
# we can translate the action name by capitalizing it as a fallback,
# or better, let the module define it. But for static menus,
# we can translate the static titles from the manifest if we had them.
# Since Addons.xcu has the static names, and notify_menu_update sets them,
# if we return None, LO uses the Addons.xcu name.
# To override Addons.xcu with translated static names, we need a map.
# For now, let's map known static actions directly here if mod didn't provide it.
pass
except ImportError:
pass
from plugin.framework.i18n import _
# Hardcoded fallback for static Addons.xcu items so they get translated
# without needing dynamic state in their respective modules.
static_titles = {
"chatbot.extend_selection": _("Extend Selection"),
"chatbot.edit_selection": _("Edit Selection"),
"main.settings": _("Settings"),
"main.report_bug": _("Report bug..."),
"mcp.toggle_server": _("Toggle MCP Server"),
"mcp.server_status": _("MCP Server Status"),
"main.NoOp": "Debug", # Excluded from translation per user request
"main.RunFormatTests": _("Run format tests"),
"main.RunCalcTests": _("Run calc tests"),
"main.RunCalcIntegrationTests": _("Run Calc API integration tests"),
"main.RunDrawTests": _("Run draw tests"),
"main.EvaluationDashboard": _("Evaluation Dashboard"),
"scripting.run_python_dialog": _("Run Python Script..."),
"scripting.edit_python_cell": _("Edit Python in Cell..."),
"scripting.reset_python_session": _("Reset Python Session"),
"scripting.import_ipynb": _("Import Jupyter Notebook..."),
"writer.insert_latex_dialog": _("Insert LaTeX Math..."),
"embeddings.search_dialog": _("Search Nearby Files..."),
"textanalytics.open_dialog": _("Text Analytics..."),
"calc.convert_spreadsheet_to_python": _("Convert Sheet to Python..."),
}
if command in static_titles:
return static_titles[command]
return None
@background
def notify_menu_update():
"""Push current menu text and icons to all registered status listeners.
Called by modules when state changes (e.g. server start/stop).
"""
# Snapshot the listeners under the lock, then fire OUTSIDE it. _fire_status_event ->
# listener.statusChanged is a UNO call to a UI control that marshals to the main thread, so
# holding _status_lock across it deadlocks: the main thread, while rebinding a toolbar
# controller (addStatusListener), waits for the same lock this background thread holds. (This is
# what froze LibreOffice on the toolbar's Accept all.) addStatusListener already fires outside
# the lock; this makes notify_menu_update consistent.
with _status_lock:
snapshot = list(_status_listeners)
failed = []
for listener, url in snapshot:
command = url.Path
text = get_menu_text(command)
try:
_fire_status_event(listener, url, text)
except Exception as e:
failed.append((listener, url))
log.warning("notify_menu_update: failed to fire status event for %s: %s", command, e)
if failed:
with _status_lock:
_status_listeners[:] = [
(lstnr, u) for (lstnr, u) in _status_listeners
if not any(lstnr is fl and u.Complete == fu.Complete for (fl, fu) in failed)
]
if os.environ.get("WRITERAGENT_TESTING") != "1":
# Update icons in a background thread (avoids blocking UI)
from plugin.framework.worker_pool import run_in_background
run_in_background(_update_menu_icons)
def _fire_status_event(listener, url, text):
"""Send a FeatureStateEvent to one listener."""
import typing
if typing.TYPE_CHECKING:
from com.sun.star.frame import FeatureStateEvent
ev = FeatureStateEvent()
else:
ev = uno.createUnoStruct("com.sun.star.frame.FeatureStateEvent")
ev.FeatureURL = url
command = url.Path
ev.IsEnabled = True
if command in {"main.RunFormatTests", "main.RunCalcTests", "main.RunCalcIntegrationTests", "main.RunDrawTests"}:
ev.IsEnabled = _tests_bundled()
ev.Requery = False
if text is not None:
ev.State = text
listener.statusChanged(ev)
# ── Dynamic menu icons via XImageManager ──────────────────────────────
# LO document modules that have their own ImageManager
_IMAGE_MANAGER_MODULES = ("com.sun.star.text.TextDocument", "com.sun.star.sheet.SpreadsheetDocument", "com.sun.star.presentation.PresentationDocument", "com.sun.star.drawing.DrawingDocument")
def _get_menu_icon(command):
"""Get dynamic icon prefix for a command, or None."""
bootstrap()
dot = command.find(".")
if dot <= 0:
return None
mod_name = command[:dot]
action = command[dot + 1 :]
for mod in _modules:
if mod.name == mod_name:
return mod.get_menu_icon(action)
return None
def _collect_icon_commands():
"""Collect all command URLs that declare icons in their manifest.
Returns {command_url: (module_name, icon_prefix)} for the current state.
"""
try:
from plugin._manifest import MODULES
except ImportError:
return {}
result = {}
import typing
for m in MODULES:
mod_name = m["name"]
action_icons = typing.cast("typing.Dict[str, str]", m.get("action_icons", {}))
for action_name, default_icon in action_icons.items():
cmd_url = "%s%s.%s" % (_DISPATCH_PROTOCOL, mod_name, action_name)
# Ask the module for dynamic icon (may override the default)
dynamic = _get_menu_icon("%s.%s" % (mod_name, action_name))
result[cmd_url] = (mod_name, dynamic or default_icon)
return result
def _load_icon_graphic(module_name, icon_filename, ctx=None):
"""Load a PNG icon from a module's icons/ directory as XGraphic."""
try:
from com.sun.star.beans import PropertyValue
import uno
if ctx is None:
ctx = uno.getComponentContext()
assert ctx is not None
ctx_any = cast("Any", ctx)
smgr = getattr(ctx_any, "ServiceManager", getattr(ctx_any, "getServiceManager", lambda: None)())
assert smgr is not None
gp = cast("Any", smgr).createInstanceWithContext("com.sun.star.graphic.GraphicProvider", ctx_any)
ext_url = get_extension_url(ctx_any)
if not ext_url:
return None
pv = PropertyValue()
# Support nested module directories
mod_dir = module_name.replace(".", "/")
pv.Value = "%s/plugin/%s/icons/%s" % (ext_url, mod_dir, icon_filename)
return gp.queryGraphic((pv,))
except Exception as e:
log.warning("_load_icon_graphic failed for %s/%s: %s", module_name, icon_filename, e)
return None
def _update_menu_icons_impl():
"""Push current-state icons into every module's ImageManager (UNO main thread)."""
try:
import uno
ctx = _services.get("uno") if _services else None
if ctx is None:
ctx = uno.getComponentContext()
icon_cmds = _collect_icon_commands()
if not icon_cmds:
return
# Group by (module, prefix) to avoid loading the same graphic twice
key_cmds = {} # (mod_name, prefix) -> [cmd_urls]
for cmd_url, (mod_name, prefix) in icon_cmds.items():
key_cmds.setdefault((mod_name, prefix), []).append(cmd_url)
# Load graphics
key_graphics = {}
for key in key_cmds:
mod_name, prefix = key
filename = "%s_16.png" % prefix
graphic = _load_icon_graphic(mod_name, filename, ctx)
if graphic:
key_graphics[key] = graphic
if not key_graphics:
return
smgr = getattr(ctx, "ServiceManager", getattr(ctx, "getServiceManager", lambda: None)())
assert smgr is not None
supplier = cast("Any", smgr).createInstanceWithContext("com.sun.star.ui.ModuleUIConfigurationManagerSupplier", ctx)
for mod_id in _IMAGE_MANAGER_MODULES:
try:
cfg_mgr = supplier.getUIConfigurationManager(mod_id)
img_mgr = cfg_mgr.getImageManager()
for key, cmds in key_cmds.items():
graphic = key_graphics.get(key)
if not graphic:
continue
for cmd in cmds:
try:
if img_mgr.hasImage(0, cmd):
img_mgr.replaceImages(0, (cmd,), (graphic,))
else:
img_mgr.insertImages(0, (cmd,), (graphic,))
except Exception as e:
log.warning("_update_menu_icons: failed to insert/replace image for %s: %s", cmd, e)
except Exception as e:
log.warning("_update_menu_icons: failed to process ImageManager for %s: %s", mod_id, e)
except Exception:
log.exception("_update_menu_icons: outer exception")
@background
def _update_menu_icons():
"""Background entrypoint: marshal UNO icon updates onto the main thread."""
from plugin.framework.queue_executor import execute_on_main_thread
execute_on_main_thread(_update_menu_icons_impl)
def _get_http_module(ctx=None) -> McpModuleActions | None:
for mod in _modules:
if mod.name == "mcp":
return cast("McpModuleActions", mod)
return None
def _start_mcp_server(ctx):
"""Ensure HTTP/MCP server is loaded. Start happens natively in module lifecycle."""
from plugin.framework.config import get_config_bool
if not get_config_bool("mcp_enabled"):
return
# Note: _get_http_module relies on bootstrap already having run.
_get_http_module(ctx)
def _stop_mcp_server():
mod = _get_http_module()
if mod:
mod.shutdown()
def _toggle_mcp_server(ctx):
mod = _get_http_module(ctx)
if mod:
mod._action_toggle_server()
def _do_mcp_status(ctx):
mod = _get_http_module(ctx)
if mod:
mod._action_server_status()
# Bootstrapper replaces the previous monolithic MainJob.
# It acts as an OnStartApp hook (triggered on office startup) and a proxy for legacy toolbar triggers.
class MainBootstrapJob(unohelper.Base, XJobExecutor, XJob):
def __init__(self, ctx):
self.ctx = ctx
try:
self.sm = ctx.getServiceManager()
except NameError:
self.sm = ctx.ServiceManager
def execute(self, Arguments):
"""Called by the Jobs framework on OnStartApp."""
try:
from plugin.framework.config import init_config
init_config(self.ctx)
except Exception:
pass
try:
init_logging(self.ctx)
except Exception:
pass
try:
bootstrap(self.ctx)
except Exception as e:
log.exception("MainBootstrapJob.execute failed to bootstrap: %s", e)
try:
from plugin.writer.locale.ai_grammar_proofreader import ensure_writeragent_proofreader_configured
ensure_writeragent_proofreader_configured(self.ctx)
except Exception as e:
log.warning("[grammar] OnStartApp: could not load or run grammar proofreader bootstrap: %s", e, exc_info=True)
return ()
def trigger(self, Event):
init_logging(self.ctx)
args = Event
if args and isinstance(args, str) and ("." in args or args.startswith("plugin.")):
cmd = args
if cmd.startswith("plugin."):
cmd = cmd[7:]
_dispatch_command(cmd)
return
if args == "settings":
_dispatch_command("main.settings")
return
if self._handle_framework_actions(args):
return
model = get_active_document(self.ctx)
from plugin.doc.document_helpers import get_document_type, DocumentType
doc_type = get_document_type(model)
if doc_type == DocumentType.WRITER:
self._handle_writer_actions(args, model)
elif doc_type == DocumentType.CALC:
self._handle_calc_actions(args, model)
def _handle_framework_actions(self, args):
framework_args = ("ToggleMCPServer", "MCPStatus", "TestTypes", "RunFormatTests", "RunCalcTests", "RunDrawTests", "RunCalcIntegrationTests", "EvaluationDashboard", "NoOp")
if args not in framework_args:
return False
if args == "ToggleMCPServer":
_dispatch_command("mcp.toggle_server")
elif args == "MCPStatus":
_dispatch_command("mcp.server_status")
else:
_dispatch_command("main." + args)
return True
def _handle_writer_actions(self, args, model):
if args in ("ExtendSelection", "EditSelection"):
self._handle_selection_action(args, model)
def _handle_calc_actions(self, args, model):
if args in ("ExtendSelection", "EditSelection"):
self._handle_selection_action(args, model)
def _handle_selection_action(self, args, model):
from plugin.chatbot.dialog_views import input_box
from plugin.chatbot.selection import do_selection_action_for_document
do_selection_action_for_document(self.ctx, model, input_box, args == "EditSelection")
# Starting from Python IDE
def main():
try:
# Using locals()/globals() bypasses static analyzer checks for XSCRIPTCONTEXT
ctx = globals()["XSCRIPTCONTEXT"]
except KeyError:
if officehelper is None:
print("ERROR: officehelper is not available (ImportError).")
sys.exit(1)
ctx = officehelper.bootstrap()
if ctx is None:
print("ERROR: Could not bootstrap default Office.")
sys.exit(1)
job = MainBootstrapJob(ctx)
job.trigger("hello")
# Starting from command line
if __name__ == "__main__":
main()
class DispatchHandler(unohelper.Base, XDispatch, XDispatchProvider, XInitialization, XServiceInfo):
"""Protocol handler for org.extension.writeragent: URLs.
Handles menu dispatch and supports dynamic menu text via
FeatureStateEvent / addStatusListener.
"""
IMPL_NAME = "org.extension.writeragent.DispatchHandler"
SERVICE_NAMES = ("com.sun.star.frame.ProtocolHandler",)
def __init__(self, ctx):
self.ctx = ctx
# ── XInitialization ──────────────────────────────────────────
def initialize(self, aArguments):
pass
# ── XServiceInfo ─────────────────────────────────────────────
def getImplementationName(self):
return self.IMPL_NAME
def supportsService(self, ServiceName):
return ServiceName in self.SERVICE_NAMES
def getSupportedServiceNames(self):
return self.SERVICE_NAMES
# ── XDispatchProvider ────────────────────────────────────────