forked from balisujohn/localwriter
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdialogs.py
More file actions
1113 lines (913 loc) · 40.2 KB
/
Copy pathdialogs.py
File metadata and controls
1113 lines (913 loc) · 40.2 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/>.
"""Dialog utilities for LibreOffice UNO.
Provides helpers for message boxes, clipboard operations, rich dialogs
(with buttons, live updates, etc.), and XDL dialog loading.
XDL loading rules (sidebar / extension dialogs):
- Use ``DialogProvider`` (``DialogProvider2`` fallback) + extension ``base_url`` from
``PackageInformationProvider`` (see ``load_writeragent_dialog`` /
``_load_xdl``). **Never** ``vnd.sun.star.script:…?location=application``
with sidebar components — that path deadlocks.
- Multi-page dialogs: ``dlg:page`` on controls + ``dlg.getModel().Step``;
``tabpagecontainer`` / ``tabpage`` fail silently.
- ListBox/ComboBox: set ``StringItemList``, not only ``.Text``.
- Tab listeners: subclass ``unohelper.Base`` + ``XActionListener`` (see
``TabListener`` in this module). Use AppFont for geometry; explicit layout.
Usage from modules::
from plugin.chatbot.dialogs import msgbox, msgbox_with_copy, copy_to_clipboard
from plugin.framework.uno_context import get_ctx
msgbox(get_ctx(), "Title", "Hello world")
msgbox_with_copy(get_ctx(), "URL", "Server running at:", "https://localhost:8766")
XDL dialog loading (used by ModuleBase helpers)::
from plugin.chatbot.dialogs import load_module_dialog, load_framework_dialog
dlg = load_framework_dialog("info_action")
dlg.getControl("MessageText").getModel().Label = "Hello"
dlg.execute()
dlg.dispose()
"""
import logging
import os
from typing import Any, cast
import unohelper
from .listeners import BaseActionListener
from plugin.framework.worker_pool import run_in_background
from com.sun.star.awt import XActionListener
from plugin.framework.uno_context import get_ctx, get_desktop, get_extension_url
from plugin.framework.i18n import _
log = logging.getLogger("writeragent.dialogs")
EXTENSION_ID = "org.extension.writeragent"
# ── Simple message box ──────────────────────────────────────────────
def msgbox(ctx, title, message, *, box_type=1):
"""Show a message box.
Args:
box_type: LO message box type (1=INFO, 2=WARNING, 3=ERROR, 4=QUERY).
"""
if not ctx:
log.info("MSGBOX (no ctx) - %s: %s", title, message)
return
try:
desktop = get_desktop(ctx)
frame = desktop.getCurrentFrame()
if frame is None:
log.info("MSGBOX (no frame) - %s: %s", title, message)
return
window = frame.getContainerWindow()
smgr = ctx.getServiceManager()
toolkit = smgr.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx)
box = toolkit.createMessageBox(window, box_type, 1, _(title), _(message)) # OK button
log.debug("msgbox execute start title=%s", title)
try:
box.execute()
finally:
try:
box.dispose()
except Exception:
log.debug("msgbox dispose failed", exc_info=True)
if hasattr(toolkit, "processEventsToIdle"):
toolkit.processEventsToIdle()
log.debug("msgbox execute done title=%s", title)
except Exception:
log.exception("MSGBOX fallback - %s: %s", title, message)
def show_approval_dialog(ctx, description, tool_name="", parent_frame=None):
"""Show HITL approval dialog: description + Approve (Yes) / Reject (No). Runs on main thread.
Returns True if user chose Approve, False if Reject or on error.
If ``parent_frame`` is set (e.g. sidebar ``XFrame``), it is used as the dialog parent so the
box is anchored correctly when ``getCurrentFrame()`` is wrong (e.g. focus in sidebar).
"""
if not ctx:
log.warning("show_approval_dialog: no ctx")
return False
try:
frame = parent_frame
if frame is None:
desktop = get_desktop(ctx)
frame = desktop.getCurrentFrame()
if frame is None:
log.warning("show_approval_dialog: no frame (parent_frame=%r, getCurrentFrame=None)", parent_frame)
return False
window = frame.getContainerWindow()
if window is None:
log.warning("show_approval_dialog: frame has no container window")
return False
smgr = ctx.getServiceManager()
toolkit = smgr.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx)
title = _("Agent requests approval")
message = (description or _("Proceed with this action?")) + ("\n\n" + _("Tool: %s") % tool_name if tool_name else "")
log.debug("show_approval_dialog: tool_name=%s parent_frame=%s", tool_name, parent_frame is not None)
# 4 = QUERYBOX, 3 = BUTTONS_YES_NO. Result 2 = Yes (Approve), 3 = No (Reject), 1 = OK
box = toolkit.createMessageBox(window, 4, 3, title, message)
result = box.execute()
return result in (1, 2)
except Exception as e:
log.exception("Approval dialog failed")
if "com.sun.star" in str(type(e)):
log.debug("Approval dialog UNO failure: %s", e)
return False
def show_web_search_query_edit_dialog(ctx, parent_frame, initial_text) -> str | None:
"""Modal multiline edit for a web-search query before DuckDuckGo runs.
``parent_frame`` is typically the sidebar ``XFrame`` so the dialog parents correctly.
Returns the edited text (stripped) if the user clicks OK, or ``None`` if Cancel/close/error.
"""
if not ctx:
log.warning("show_web_search_query_edit_dialog: no ctx")
return None
try:
dlg = load_writeragent_dialog("WebSearchQueryEditDialog", ctx)
if dlg is None:
return None
edit = dlg.getControl("QueryEdit")
if edit is not None:
edit.setText(initial_text or "")
# Single-slot outcome: None = dialog closed without OK/Cancel; else [str] or [None].
_outcome: list[str | None] | None = None
class _OkListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
nonlocal _outcome
try:
ec = dlg.getControl("QueryEdit")
t = (ec.getModel().Text or "").strip() if ec and ec.getModel() else ""
except Exception:
t = ""
_outcome = [t]
dlg.endDialog(1)
def disposing(self, Source):
pass
class _CancelListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
nonlocal _outcome
_outcome = [None]
dlg.endDialog(0)
def disposing(self, Source):
pass
btn_ok = dlg.getControl("BtnOK")
if btn_ok is not None:
btn_ok.addActionListener(_OkListener())
btn_cancel = dlg.getControl("BtnCancel")
if btn_cancel is not None:
btn_cancel.addActionListener(_CancelListener())
dlg.execute()
dlg.dispose()
if _outcome is None:
return None
return _outcome[0]
except Exception:
log.exception("show_web_search_query_edit_dialog failed")
return None
def show_text_input_dialog(ctx, message: str, title: str = "", default: str = "") -> str | None:
"""Modal single-line text input (no LLM / prompt controls).
Used for short names (e.g. Save Script As). Returns stripped text on OK, ``None`` on Cancel.
"""
if not ctx:
log.warning("show_text_input_dialog: no ctx")
return None
try:
dlg = load_writeragent_dialog("ShortTextInputDialog", ctx)
if dlg is None:
return None
if title:
dlg.getModel().Title = _(title)
lbl = dlg.getControl("PromptLbl")
if lbl is not None:
lbl.getModel().Label = message
edit = dlg.getControl("TextEdit")
if edit is not None:
edit.setText(default or "")
_outcome: list[str | None] | None = None
class _OkListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
nonlocal _outcome
try:
ec = dlg.getControl("TextEdit")
t = (ec.getModel().Text or "").strip() if ec and ec.getModel() else ""
except Exception:
t = ""
_outcome = [t]
dlg.endDialog(1)
def disposing(self, Source):
pass
class _CancelListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
nonlocal _outcome
_outcome = [None]
dlg.endDialog(0)
def disposing(self, Source):
pass
btn_ok = dlg.getControl("BtnOK")
if btn_ok is not None:
btn_ok.addActionListener(_OkListener())
btn_cancel = dlg.getControl("BtnCancel")
if btn_cancel is not None:
btn_cancel.addActionListener(_CancelListener())
if edit is not None:
edit.setFocus()
dlg.execute()
dlg.dispose()
if _outcome is None:
return None
return _outcome[0]
except Exception:
log.exception("show_text_input_dialog failed")
return None
# ── Clipboard ────────────────────────────────────────────────────────
def copy_to_clipboard(ctx, text):
"""Copy text to system clipboard via LO API. Returns True on success."""
if not ctx:
return False
try:
import uno
import unohelper
from com.sun.star.datatransfer import XTransferable, DataFlavor
smgr = ctx.ServiceManager
clip = smgr.createInstanceWithContext("com.sun.star.datatransfer.clipboard.SystemClipboard", ctx)
class _TextTransferable(unohelper.Base, XTransferable):
def __init__(self, txt):
self._text = txt
def getTransferData(self, aFlavor):
return self._text
def getTransferDataFlavors(self):
f = DataFlavor()
f.MimeType = "text/plain;charset=utf-16"
f.HumanPresentableName = "Unicode Text"
f.DataType = uno.getTypeByName("string")
return (f,)
def isDataFlavorSupported(self, aFlavor):
return "text/plain" in aFlavor.MimeType
clip.setContents(_TextTransferable(text), None)
log.info("Copied to clipboard: %s", text)
return True
except Exception:
log.exception("Clipboard copy failed")
return False
# ── Dialog control helpers ──────────────────────────────────────────
def add_dialog_button(dlg_model, name, label, x, y, width, height, push_button_type=None, enabled=True):
"""Add a button to a dialog model."""
btn = dlg_model.createInstance("com.sun.star.awt.UnoControlButtonModel")
btn.Name = name
btn.PositionX = x
btn.PositionY = y
btn.Width = width
btn.Height = height
btn.Label = _(label)
btn.Enabled = enabled
if push_button_type is not None:
btn.PushButtonType = push_button_type
dlg_model.insertByName(name, btn)
return btn
def add_dialog_label(dlg_model, name, label, x, y, width, height, multiline=True):
"""Add a fixed text label to a dialog model."""
lbl = dlg_model.createInstance("com.sun.star.awt.UnoControlFixedTextModel")
lbl.Name = name
lbl.PositionX = x
lbl.PositionY = y
lbl.Width = width
lbl.Height = height
lbl.MultiLine = multiline
lbl.Label = _(label)
dlg_model.insertByName(name, lbl)
return lbl
def add_dialog_edit(dlg_model, name, text, x, y, width, height, readonly=False):
"""Add an edit (text field) control to a dialog model."""
edit = dlg_model.createInstance("com.sun.star.awt.UnoControlEditModel")
edit.Name = name
edit.PositionX = x
edit.PositionY = y
edit.Width = width
edit.Height = height
edit.Text = text
edit.ReadOnly = readonly
dlg_model.insertByName(name, edit)
return edit
def add_dialog_hyperlink(dlg_model, name, label, url, x, y, width, height):
"""Add a clickable hyperlink to a dialog model."""
link = dlg_model.createInstance("com.sun.star.awt.UnoControlFixedHyperlinkModel")
link.Name = name
link.PositionX = x
link.PositionY = y
link.Width = width
link.Height = height
link.Label = _(label)
link.URL = url
link.TextColor = 0x0563C1 # standard link blue
dlg_model.insertByName(name, link)
return link
# ── Message box with Copy button ─────────────────────────────────────
def msgbox_with_copy(ctx, title, message, copy_text):
"""Show a dialog with a message and a Copy button."""
if not ctx:
log.info("MSGBOX_COPY (no ctx) - %s: %s", title, message)
return
try:
dlg = load_writeragent_dialog("MsgBoxWithCopyDialog", ctx)
if dlg is None:
msgbox(ctx, title, message)
return
if title:
dlg.getModel().Title = _(title)
msg_ctrl = dlg.getControl("Msg")
if msg_ctrl is not None:
msg_ctrl.getModel().Label = _(message)
class _CopyListener(BaseActionListener):
def __init__(self, dialog, context, text):
self._dlg = dialog
self._ctx = context
self._text = text
def on_action_performed(self, rEvent):
if copy_to_clipboard(self._ctx, self._text):
try:
self._dlg.getModel().getByName("CopyBtn").Label = _("Copied!")
except Exception as e:
log.debug("Failed to set CopyBtn Label: %s", e)
copy_btn = dlg.getControl("CopyBtn")
if copy_btn is not None:
copy_btn.addActionListener(_CopyListener(dlg, ctx, copy_text))
class _OkListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
dlg.endDialog(1)
def disposing(self, Source):
pass
ok_btn = dlg.getControl("OKBtn")
if ok_btn is not None:
ok_btn.addActionListener(_OkListener())
dlg.execute()
dlg.dispose()
except Exception:
log.exception("Copy dialog error")
msgbox(ctx, title, message)
def msgbox_with_report(ctx, title, message, *, reportable=False, report_title="", report_extra="", box_type=3):
"""Show a message box; when ``reportable``, offer Copy URL and Report bug buttons."""
if not reportable:
msgbox(ctx, title, message, box_type=box_type)
return
if not ctx:
log.info("MSGBOX_REPORT (no ctx) - %s: %s", title, message)
return
try:
from plugin.framework.bug_report import build_github_issue_url, open_bug_report_in_browser
dlg = load_writeragent_dialog("ErrorReportDialog", ctx)
if dlg is None:
msgbox(ctx, title, message, box_type=box_type)
return
issue_title = (report_title or title or "").strip()
msg = (message or "").strip()
rep = (report_extra or "").strip()
if msg and rep and rep != msg:
extra = f"{msg}\n\n{rep}"
else:
extra = rep or msg
report_url = build_github_issue_url(title=issue_title, extra_body=extra, ctx=ctx)
if title:
dlg.getModel().Title = _(title)
msg_ctrl = dlg.getControl("Msg")
if msg_ctrl is not None:
msg_ctrl.getModel().Label = _(message)
class _CopyListener(BaseActionListener):
def __init__(self, dialog, context, text):
self._dlg = dialog
self._ctx = context
self._text = text
def on_action_performed(self, rEvent):
if copy_to_clipboard(self._ctx, self._text):
try:
self._dlg.getModel().getByName("CopyBtn").Label = _("Copied!")
except Exception as e:
log.debug("Failed to set CopyBtn Label: %s", e)
copy_btn = dlg.getControl("CopyBtn")
if copy_btn is not None:
copy_btn.getModel().Label = _("Copy URL")
copy_btn.addActionListener(_CopyListener(dlg, ctx, report_url))
class _ReportListener(BaseActionListener):
def __init__(self, context, dlg_title, dlg_extra):
self._ctx = context
self._title = dlg_title
self._extra = dlg_extra
def on_action_performed(self, rEvent):
open_bug_report_in_browser(self._ctx, title=self._title, extra_body=self._extra)
report_btn = dlg.getControl("ReportBtn")
if report_btn is not None:
report_btn.getModel().Label = _("Report bug...")
report_btn.addActionListener(_ReportListener(ctx, issue_title, extra))
class _OkListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
dlg.endDialog(1)
def disposing(self, Source):
pass
ok_btn = dlg.getControl("OKBtn")
if ok_btn is not None:
ok_btn.addActionListener(_OkListener())
dlg.execute()
dlg.dispose()
except Exception:
log.exception("Report dialog error")
msgbox(ctx, title, message, box_type=box_type)
# ── Status dialog with live updates ──────────────────────────────────
def status_dialog(ctx, title, build_status_fn, copy_url_fn=None):
"""Show a status dialog that updates live via a background thread.
Args:
ctx: UNO component context.
title: Dialog title.
build_status_fn: Callable() -> str returning the status text.
Called once immediately, then once more after a short delay
for live probe results.
copy_url_fn: Optional callable() -> str returning a URL to copy.
If provided and returns non-empty, a Copy button is shown.
"""
if not ctx:
log.info("STATUS (no ctx) - %s", title)
return
try:
dlg = load_writeragent_dialog("StatusUpdateDialog", ctx)
if dlg is None:
msgbox(ctx, title, build_status_fn())
return
if title:
dlg.getModel().Title = _(title)
initial_text = build_status_fn()
status_ctrl = dlg.getControl("StatusText")
if status_ctrl is not None:
status_ctrl.getModel().Label = initial_text
# Copy button (disabled until copy_url_fn returns something)
has_copy = copy_url_fn is not None
copy_btn = dlg.getControl("CopyBtn")
if copy_btn is not None:
if has_copy:
copy_btn.getModel().Enabled = bool(copy_url_fn() if copy_url_fn else False)
class _CopyListener(BaseActionListener):
def __init__(self, dialog, context, url_fn):
self._dlg = dialog
self._ctx = context
self._url_fn = url_fn
def on_action_performed(self, rEvent):
url = self._url_fn()
if url and copy_to_clipboard(self._ctx, url):
try:
self._dlg.getModel().getByName("CopyBtn").Label = _("Copied!")
except Exception as e:
log.debug("Failed to set CopyBtn Label: %s", e)
copy_btn.addActionListener(_CopyListener(dlg, ctx, copy_url_fn))
else:
copy_btn.getModel().Visible = False
class _OkListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
dlg.endDialog(1)
def disposing(self, Source):
pass
ok_btn = dlg.getControl("OKBtn")
if ok_btn is not None:
ok_btn.addActionListener(_OkListener())
# Background update
import time
def _probe_update():
time.sleep(0.05)
try:
updated = build_status_fn()
if status_ctrl is not None:
status_ctrl.getModel().Label = updated
if has_copy and copy_btn is not None:
url = copy_url_fn() if copy_url_fn else None
copy_btn.getModel().Enabled = bool(url)
except Exception:
pass # dialog already closed
run_in_background(_probe_update, daemon=True, name="status-dialog-probe")
dlg.execute()
dlg.dispose()
except Exception:
log.exception("Status dialog error")
msgbox(ctx, title, build_status_fn())
# ── XDL dialog loading ──────────────────────────────────────────────
def _xcc(ctrl):
"""Return ``XControlContainer`` for ``ctrl``, or None.
LibreOffice pyuno expects ``obj.queryInterface(iface)``. The ``uno`` module
does not provide ``queryInterface`` (unlike some Java examples), which
previously broke recursion in ``translate_dialog``.
"""
if ctrl is None:
return None
from com.sun.star.awt import XControlContainer
try:
return ctrl.queryInterface(XControlContainer)
except Exception:
return None
def _uno_impl_to_control_type(impl_name):
"""Map ``stardiv.Toolkit.UnoButtonControl``-style names to ``control_types`` keys.
VCL uses ``Uno`` + ``FixedText``/``Button``/… + ``Control``, not ``UnoControl``
+ ``Button``; the old strip only matched names starting with ``UnoControl``.
"""
seg = impl_name.split(".")[-1]
if seg.startswith("Uno") and seg.endswith("Control") and len(seg) > 10:
return seg[3:-7]
if seg.startswith("UnoControl"):
return seg[10:]
return seg
def _dialog_model_element_names(dlg):
"""Return control name strings from the dialog model (``ElementNames``), or ``()``."""
try:
dm = dlg.getModel()
if dm is None:
return ()
en = getattr(dm, "ElementNames", None)
if en is not None:
return tuple(en)
except Exception:
pass
return ()
def translate_dialog(dlg):
"""Translate all controls in a dialog at runtime.
Walks the full control tree. XDL dialogs typically wrap fields in a
bulletinboard child; only iterating top-level ``getControls()`` misses
every label inside the container.
"""
# Map control types to their translatable properties
control_types = {"Dialog": ("Title",), "FixedText": ("Text", "Label"), "Button": ("Label",), "CheckBox": ("Label",), "RadioButton": ("Label",), "ListBox": ("StringItemList",), "ComboBox": ("StringItemList",), "GroupBox": ("Label",), "FixedLine": ("Label",)}
_xcc_root = None
root_child_count = 0
try:
_xcc_root = _xcc(dlg)
if _xcc_root is not None:
root_child_count = len(_xcc_root.getControls())
except Exception:
root_child_count = 0
def translate_one(ctrl):
try:
impl_name = ctrl.getImplementationName()
short_type = _uno_impl_to_control_type(impl_name)
name = ctrl.getModel().Name if ctrl.getModel() else "?"
for prop in control_types.get(short_type, ()):
try:
if prop == "StringItemList":
# ListBox often exposes getStringItemList on the view; ComboBox
# typically only has StringItemList on the model.
model = ctrl.getModel()
used_control = False
try:
if hasattr(ctrl, "getStringItemList"):
items = ctrl.getStringItemList()
if items:
translated = tuple(_(item) if item else "" for item in items)
ctrl.setStringItemList(translated)
used_control = True
except Exception:
pass
if not used_control and model is not None and hasattr(model, "StringItemList"):
try:
items = model.StringItemList
if items:
translated = tuple(_(item) if item else "" for item in items)
model.StringItemList = translated
except Exception as e:
log.debug("Failed to translate %s.%s: %s", name, prop, e)
else:
model = ctrl.getModel()
if hasattr(model, prop):
current = getattr(model, prop)
if current:
setattr(model, prop, _(current))
except Exception as e:
log.debug("Failed to translate %s.%s: %s", name, prop, e)
xcc = _xcc(ctrl)
if xcc:
for child in xcc.getControls():
translate_one(child)
except Exception as e:
log.debug("Failed to inspect control for translation: %s", e)
try:
translate_one(dlg)
except Exception as e:
log.debug("Failed to translate dialog: %s", e)
# ContainerWindow + XDL: root is often ``UnoDialogControl``, which does not
# implement ``XControlContainer``, so ``getControls()`` is never reached.
# Fall back to dialog model ``ElementNames`` + ``getControl(name)``.
if (_xcc_root is None or root_child_count == 0) and hasattr(dlg, "getControl") and hasattr(dlg, "getModel"):
names = _dialog_model_element_names(dlg)
if names:
for nm in names:
try:
c = dlg.getControl(nm)
if c:
translate_one(c)
except Exception as e:
log.debug("translate_dialog ElementNames id=%s: %s", nm, e)
def load_module_dialog(module_name, dialog_name):
"""Load an XDL dialog from a module's directory.
Returns an XDialog ready for execute()/dispose().
"""
module_dir = module_name.replace(".", "_")
xdl_path = "plugin/%s/%s.xdl" % (module_dir, dialog_name)
dlg = _load_xdl(xdl_path)
if dlg:
translate_dialog(dlg)
return dlg
def load_framework_dialog(dialog_name):
"""Load an XDL dialog from the framework's directory.
Returns an XDialog ready for execute()/dispose().
"""
xdl_path = "plugin/framework/%s.xdl" % dialog_name
dlg = _load_xdl(xdl_path)
if dlg:
translate_dialog(dlg)
return dlg
def format_exception_detail(exc: BaseException, *, _depth: int = 0) -> str:
"""Best-effort printable detail for Python and UNO exceptions (incl. nested Target/Context)."""
if _depth > 4:
return f"{type(exc).__name__}: (nested detail truncated)"
name = getattr(exc, "uno_type_name", None) or type(exc).__name__
text = str(exc).strip()
head = f"{name}: {text}" if text else name
lines = [head]
for attr in ("Message", "Name", "ArgumentName", "ArgumentPosition", "SQLError"):
if not hasattr(exc, attr):
continue
try:
val = getattr(exc, attr)
except Exception:
continue
if val is None or val == "":
continue
lines.append(f" {attr}={val!r}")
nested_context = _nested_exception_object(getattr(exc, "Context", None))
nested_target = _nested_exception_object(getattr(exc, "Target", None))
if nested_target is nested_context:
nested_target = None
if nested_context is not None:
lines.append(" Context:")
for nested_line in format_exception_detail(nested_context, _depth=_depth + 1).splitlines():
lines.append(f" {nested_line}")
if nested_target is not None:
lines.append(" Target:")
for nested_line in format_exception_detail(nested_target, _depth=_depth + 1).splitlines():
lines.append(f" {nested_line}")
return "\n".join(lines)
def _nested_exception_object(val: Any) -> BaseException | None:
"""Return a value suitable for recursive format_exception_detail (Python or pyuno UNO exceptions)."""
if val is None:
return None
if isinstance(val, BaseException):
return val
if hasattr(val, "Message") or hasattr(val, "Target") or hasattr(val, "Context"):
return _UnoExceptionAdapter(val)
text = str(val).strip()
if text:
return RuntimeError(text)
return None
class _UnoExceptionAdapter(BaseException):
"""Minimal BaseException wrapper for pyuno UNO exception objects."""
def __init__(self, uno_exc: Any) -> None:
self._uno_exc = uno_exc
self.uno_type_name = type(uno_exc).__name__
message = ""
if hasattr(uno_exc, "Message"):
try:
message = str(uno_exc.Message or "").strip()
except Exception:
pass
if not message:
message = type(uno_exc).__name__
super().__init__(message)
@property
def Message(self) -> Any:
return getattr(self._uno_exc, "Message", None)
@property
def Target(self) -> Any:
return getattr(self._uno_exc, "Target", None)
@property
def Context(self) -> Any:
return getattr(self._uno_exc, "Context", None)
def __getattr__(self, name: str) -> Any:
return getattr(self._uno_exc, name)
def _collect_xdl_load_diagnostics(ctx: Any, dialog_url: str, dialog_name: str) -> str:
"""Gather extension URL/path and on-disk XDL probes for failure reports."""
from plugin.framework.uno_context import get_extension_path, get_extension_url, resolve_package_extension_id
lines = [
f"dialog: {dialog_name}",
f"url: {dialog_url}",
]
try:
ext_id = resolve_package_extension_id(ctx)
lines.append(f"extension_id: {ext_id}")
lines.append(f"extension_base_url: {get_extension_url(ctx, ext_id)}")
ext_path = get_extension_path(ctx, ext_id)
lines.append(f"extension_path: {ext_path or '(empty)'}")
except Exception as exc:
lines.append(f"extension_probe: {format_exception_detail(exc)}")
if dialog_url.startswith("file://"):
try:
import uno
sys_path = uno.fileUrlToSystemPath(dialog_url)
lines.append(f"xdl_system_path: {sys_path}")
if os.path.isfile(sys_path):
lines.append(f"xdl_file_exists: yes ({os.path.getsize(sys_path)} bytes)")
else:
lines.append("xdl_file_exists: no")
parent = os.path.dirname(sys_path)
if os.path.isdir(parent):
try:
siblings = sorted(os.listdir(parent))
preview = ", ".join(siblings[:25])
if len(siblings) > 25:
preview += f", ... (+{len(siblings) - 25} more)"
lines.append(f"xdl_dir_listing: {preview}")
except OSError as list_exc:
lines.append(f"xdl_dir_listing_error: {format_exception_detail(list_exc)}")
except Exception as exc:
lines.append(f"xdl_path_probe: {format_exception_detail(exc)}")
return "\n".join(lines)
def _create_xdl_dialog(smgr: Any, ctx: Any, dialog_url: str) -> tuple[Any | None, str | None]:
"""Load an XDL dialog URL; prefer DialogProvider (Linux), fall back to DialogProvider2."""
attempt_lines: list[str] = []
for service in ("com.sun.star.awt.DialogProvider", "com.sun.star.awt.DialogProvider2"):
try:
dp = smgr.createInstanceWithContext(service, ctx)
if dp is None:
attempt_lines.append(f"{service}: createInstanceWithContext returned None")
continue
dlg = dp.createDialog(dialog_url)
if dlg is not None:
return dlg, None
attempt_lines.append(f"{service}: createDialog returned None")
except Exception as exc:
detail = format_exception_detail(exc)
attempt_lines.append(f"{service}: {detail}")
log.warning("createDialog via %s failed for %s:\n%s", service, dialog_url, detail)
provider_failure = "\n".join(attempt_lines) if attempt_lines else "no DialogProvider attempt recorded"
log.warning("Failed to load XDL dialog %s:\n%s", dialog_url, provider_failure)
return None, provider_failure
def load_writeragent_dialog_detail(dialog_name: str, ctx: Any | None = None) -> tuple[Any | None, str | None]:
"""Load an XDL dialog from WriterAgentDialogs/; return (dialog, failure_detail)."""
if ctx is None:
ctx = get_ctx()
assert ctx is not None
ctx_any = cast("Any", ctx)
if hasattr(ctx_any, "getServiceManager"):
smgr = ctx_any.getServiceManager()
else:
smgr = getattr(ctx_any, "ServiceManager", None)
assert smgr is not None
# Fallback for unit testing when ServiceManager or context is mocked
if "Mock" in type(smgr).__name__ or "Mock" in type(ctx).__name__:
return smgr.createInstanceWithContext("com.sun.star.awt.UnoControlDialog", ctx_any), None
base = get_extension_url(ctx)
url = base + "/WriterAgentDialogs/" + dialog_name + ".xdl"
dlg, provider_failure = _create_xdl_dialog(smgr, ctx_any, url)
if dlg:
translate_dialog(dlg)
return dlg, None
diagnostics = _collect_xdl_load_diagnostics(ctx_any, url, dialog_name)
combined = f"{diagnostics}\n\n--- DialogProvider ---\n{provider_failure or '(no details)'}"
return None, combined
def load_writeragent_dialog(dialog_name, ctx=None):
"""Load an XDL dialog from the WriterAgentDialogs/ directory."""
dlg, _detail = load_writeragent_dialog_detail(dialog_name, ctx=ctx)
return dlg
def _load_xdl(relative_path):
"""Load an XDL file from the extension bundle via DialogProvider (+ DP2 fallback)."""
ctx = get_ctx()
assert ctx is not None
ctx_any = cast("Any", ctx)
if hasattr(ctx_any, "getServiceManager"):
smgr = ctx_any.getServiceManager()
else:
smgr = getattr(ctx_any, "ServiceManager", None)
assert smgr is not None
base = get_extension_url(ctx)
url = base + "/" + relative_path
dlg, _detail = _create_xdl_dialog(smgr, ctx_any, url)
return dlg
def get_optional(root_window, name):
"""Return control by name or None if missing. Use for optional XDL controls.
Useful for backward-compatible dialogs where controls may not exist in all versions.
"""
try:
return root_window.getControl(name)
except Exception as e:
# Expected exception from UNO when an element is not found,
# but catch Exception broadly since LibreOffice Python bridges
# raise varying error types across platforms when missing names.
if "DisposedException" in str(type(e)):
log.warning("get_optional %s error: control disposed %s", name, e)
else:
log.debug("get_optional %s error: %s", name, e)
return None
def is_checkbox_control(ctrl):
"""Return True if the control is a checkbox (UnoControlCheckBox or has State/setState).
Handles LibreOffice checkbox quirks: checks service type, control methods, and model properties.
"""
if not ctrl:
return False
try:
if ctrl.supportsService("com.sun.star.awt.UnoControlCheckBox"):
return True
if hasattr(ctrl, "setState") or hasattr(ctrl, "getState"):
return True
if hasattr(ctrl.getModel(), "State"):
return True
except Exception as e:
log.debug("is_checkbox_control exception: %s", e)
return False
def set_control_enabled(ctrl, enabled):