forked from balisujohn/localwriter
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdocument_helpers.py
More file actions
1588 lines (1363 loc) · 69.3 KB
/
Copy pathdocument_helpers.py
File metadata and controls
1588 lines (1363 loc) · 69.3 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)
# Copyright (c) 2026 LibreCalc AI Assistant (Calc integration features, originally MIT)
#
# 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/>.
import logging
import uno
from typing import TypedDict, Any, cast
from enum import Enum, auto
from plugin.calc.bridge import CalcBridge
from plugin.calc.analyzer import SheetAnalyzer
from plugin.framework.constants import CHAT_DOCUMENT_CONTEXT_MAX_CHARS
from plugin.framework.uno_context import get_active_document as get_active_doc
from plugin.framework.errors import UnoObjectError, check_disposed, safe_call, safe_uno_call
from plugin.framework.thread_guard import main_thread_only, _wrap_uno
try:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
UNO_DISPOSED_EXCEPTIONS = (DisposedException, RuntimeException, UnoException)
except ImportError:
UNO_DISPOSED_EXCEPTIONS = cast("Any", (Exception,))
def normalize_linebreaks(text: str | None) -> str:
"""Ensure all linebreaks use \n (LF).
Some UNO APIs (especially on Windows) or clipboard paths can return \r\n
or \r. This ensures consistent offsets and string length for the LLM.
"""
if text is None:
return ""
# Normalize \r\n -> \n
text = text.replace("\r\n", "\n")
# Normalize \n\r (rare but possible) -> \n
text = text.replace("\n\r", "\n")
# Normalize remaining \r -> \n
text = text.replace("\r", "\n")
return text
class HeadingTreeNode(TypedDict):
"""Shape of nodes returned by :func:`build_heading_tree` (recursive heading tree)."""
level: int
text: str
para_index: int
children: list["HeadingTreeNode"]
body_paragraphs: int
class DocumentType(Enum):
UNKNOWN = auto()
WRITER = auto()
CALC = auto()
DRAW = auto()
IMPRESS = auto()
_DOCUMENT_SERVICE_MAP = {DocumentType.WRITER: "com.sun.star.text.TextDocument", DocumentType.CALC: "com.sun.star.sheet.SpreadsheetDocument", DocumentType.DRAW: "com.sun.star.drawing.DrawingDocument", DocumentType.IMPRESS: "com.sun.star.presentation.PresentationDocument"}
# Lowercase doc_type labels (ToolContext / sidebar) -> UNO services for tool compatibility
# without re-querying the live document. Impress is distinct; sidebar "Draw" covers both draw kinds.
_DOC_TYPE_LABEL_TO_UNO_SERVICES: dict[str, frozenset[str]] = {
"writer": frozenset({"com.sun.star.text.TextDocument"}),
"calc": frozenset({"com.sun.star.sheet.SpreadsheetDocument"}),
"draw": frozenset({"com.sun.star.drawing.DrawingDocument", "com.sun.star.presentation.PresentationDocument"}),
"impress": frozenset({"com.sun.star.presentation.PresentationDocument"}),
}
def uno_services_for_doc_type_label(doc_type: str | None) -> frozenset[str]:
"""Return UNO services implied by a sidebar/doc_type label (no live document)."""
if not doc_type:
return frozenset()
return _DOC_TYPE_LABEL_TO_UNO_SERVICES.get(str(doc_type).strip().lower(), frozenset())
def uno_services_for_document(model, doc_type: str | None) -> frozenset[str]:
"""Return UNO services for tool filtering: main-thread probe when possible, else doc_type map."""
from plugin.framework.thread_guard import on_main_thread
if model is not None and on_main_thread():
try:
services = get_document_uno_services(model)
if services:
return services
except Exception:
pass
return uno_services_for_doc_type_label(doc_type)
@safe_uno_call(default=frozenset())
@main_thread_only
def get_document_uno_services(model) -> frozenset[str]:
"""Return UNO service names supported by *model* (main thread only; cache in sidebar/MCP)."""
if model is None:
return frozenset()
found: set[str] = set()
for _doc_type, service_name in _DOCUMENT_SERVICE_MAP.items():
if safe_call(model.supportsService, f"Check {service_name}", service_name):
found.add(service_name)
return frozenset(found)
def doc_type_label_for_enum(doc_type: DocumentType) -> str:
"""Lowercase ToolContext doc_type label for a DocumentType enum value."""
if doc_type == DocumentType.CALC:
return "calc"
if doc_type == DocumentType.WRITER:
return "writer"
if doc_type == DocumentType.IMPRESS:
return "impress"
if doc_type == DocumentType.DRAW:
return "draw"
return "unknown"
def doc_type_title_for_label(label: str | None) -> str:
"""Sidebar display title (Writer/Calc/Draw) for a cached lowercase doc_type label."""
if not label:
return "Unknown"
return {
"writer": "Writer",
"calc": "Calc",
"draw": "Draw",
"impress": "Draw",
}.get(str(label).strip().lower(), "Unknown")
@safe_uno_call(default=DocumentType.UNKNOWN)
@main_thread_only
def get_document_type(model):
"""Return the DocumentType for the given model."""
if model is None:
return DocumentType.UNKNOWN
# Check services in priority order
for doc_type, service_name in _DOCUMENT_SERVICE_MAP.items():
if safe_call(model.supportsService, f"Check {service_name}", service_name):
return doc_type
return DocumentType.UNKNOWN
def is_writer(model):
"""Return True if model is a Writer document."""
return get_document_type(model) == DocumentType.WRITER
def is_calc(model):
"""Return True if model is a Calc document."""
return get_document_type(model) == DocumentType.CALC
def is_draw(model):
"""Return True if model is a Draw/Impress document."""
doc_type = get_document_type(model)
return doc_type in (DocumentType.DRAW, DocumentType.IMPRESS)
def get_string_without_tracked_deletions(text_range) -> str:
"""Return text_range text while skipping tracked deletions when possible."""
if hasattr(text_range, "_mock_return_value") or type(text_range).__name__ in ("Mock", "MagicMock"):
return text_range.getString()
try:
para_enum = text_range.createEnumeration()
except Exception:
return text_range.getString()
parts: list[str] = []
try:
first_para = True
while para_enum.hasMoreElements():
para = para_enum.nextElement()
if not first_para:
parts.append("\n")
first_para = False
try:
portion_enum = para.createEnumeration()
except Exception:
parts.append(para.getString())
continue
in_delete = False
while portion_enum.hasMoreElements():
portion = portion_enum.nextElement()
try:
try:
portion_type = portion.getPropertyValue("TextPortionType")
except Exception:
portion_type = portion.TextPortionType
except Exception:
continue
if portion_type == "Redline":
try:
if str(portion.getPropertyValue("RedlineType")) == "Delete":
in_delete = not in_delete
except Exception:
pass
continue
if in_delete:
continue
try:
chunk = portion.getString()
except Exception:
continue
if chunk:
parts.append(chunk)
except Exception:
return text_range.getString()
return "".join(parts)
def collect_tracked_changes(text_range, max_per_change: int = 300, max_changes: int = 100):
"""Walk text portions and collect tracked insertions/deletions WITH their text, so a reader can
see what is pending and that it awaits the user's review (rather than the default read, which
hides deletions and gives no hint that changes are pending).
Returns a list of ``{"type": "insertion"|"deletion", "text": str}`` in document order. Best-effort:
returns ``[]`` on any failure. Mirrors get_string_without_tracked_deletions' portion walk, but also
toggles on Insert redlines and buffers the text of each change instead of dropping deletions."""
out: list[dict] = []
if hasattr(text_range, "_mock_return_value") or type(text_range).__name__ in ("Mock", "MagicMock"):
return out
try:
para_enum = text_range.createEnumeration()
except Exception:
return out
in_delete = False
in_insert = False
del_buf: list[str] = []
ins_buf: list[str] = []
def _flush(buf, kind):
if buf and len(out) < max_changes:
out.append({"type": kind, "text": "".join(buf)[:max_per_change]})
buf.clear()
try:
while para_enum.hasMoreElements() and len(out) < max_changes:
para = para_enum.nextElement()
try:
portion_enum = para.createEnumeration()
except Exception:
continue
while portion_enum.hasMoreElements():
portion = portion_enum.nextElement()
try:
try:
ptype = portion.getPropertyValue("TextPortionType")
except Exception:
ptype = portion.TextPortionType
except Exception:
continue
if ptype == "Redline":
try:
rtype = str(portion.getPropertyValue("RedlineType"))
except Exception:
rtype = ""
if rtype == "Delete":
if in_delete:
_flush(del_buf, "deletion")
in_delete = not in_delete
elif rtype == "Insert":
if in_insert:
_flush(ins_buf, "insertion")
in_insert = not in_insert
continue
try:
chunk = portion.getString()
except Exception:
chunk = ""
if not chunk:
continue
if in_delete:
del_buf.append(chunk)
elif in_insert:
ins_buf.append(chunk)
_flush(del_buf, "deletion")
_flush(ins_buf, "insertion")
except Exception:
return out
return out
def build_writer_rewrite_prompt(original_text: str, instructions: str) -> str:
"""Return a direct rewrite prompt for Writer selection edits."""
return f"Rewrite the following text according to the instructions below. Output only the rewritten text with no labels, headings, or explanations.\n\nInstructions: {instructions}\n\nText to rewrite:\n{original_text}"
class WriterCompoundUndo:
"""Wrap ``XUndoManager.enterUndoContext`` / ``leaveUndoContext`` for one Ctrl+Z step.
Call :meth:`close` when the operation finishes (success or error). Safe to call
multiple times.
"""
def __init__(self, doc, title: str) -> None:
self._log = logging.getLogger(__name__)
self._title = title
self._undo_manager = None
self._open = False
try:
if not hasattr(doc, "getUndoManager"):
self._log.warning("WriterCompoundUndo: doc has no getUndoManager, undo grouping skipped (title=%r)", title)
return
um = doc.getUndoManager()
if um is None:
self._log.warning("WriterCompoundUndo: getUndoManager() returned None, undo grouping skipped (title=%r)", title)
return
# Probe undo manager state to detect prior unclosed contexts (best-effort; UNO may not expose these).
try:
is_in_ctx = um.isInContext()
undo_enabled = um.isUndoEnabled()
self._log.info("WriterCompoundUndo: pre-enter state isInContext=%s isUndoEnabled=%s (title=%r)", is_in_ctx, undo_enabled, title)
except Exception as probe_e:
self._log.debug("WriterCompoundUndo: could not probe undo manager state: %s", probe_e)
um.enterUndoContext(title)
self._undo_manager = um
self._open = True
# Log after success so we always see this when the context is live.
self._log.info("WriterCompoundUndo: context entered %r", title)
except Exception as e:
# Upgrade from debug to warning so failures are visible without debug logging.
# "Insert $1" in the undo menu means this context was never opened.
self._log.warning("WriterCompoundUndo: enterUndoContext failed, undo grouping disabled (title=%r): %s", title, e)
def close(self) -> None:
"""End the compound undo context if :meth:`__init__` opened one."""
if not self._open:
self._log.debug("WriterCompoundUndo.close: already closed or never opened (title=%r)", self._title)
return
self._open = False
um = self._undo_manager
self._undo_manager = None
if um is None:
return
try:
self._log.info("WriterCompoundUndo: leaving context %r", self._title)
um.leaveUndoContext()
except Exception:
self._log.exception("leaveUndoContext failed (title=%r)", self._title)
class WriterStreamedRewriteSession:
"""Manage a streamed Writer edit that collapses to one tracked change."""
_UNDO_CONTEXT_TITLE = "WriterAgent: Edit selection"
def __init__(self, doc, text_range, original_text: str, track_reviewable: bool = False):
self.doc = doc
self.text_range = text_range
self.original_text = original_text
self.generated_text = ""
self.was_recording = False
# When True (opt-in flag), the agent's edit is collapsed into one tracked
# change for the user to review even if they did not have Track Changes on.
self.track_reviewable = track_reviewable
self._compound_undo = WriterCompoundUndo(doc, self._UNDO_CONTEXT_TITLE)
try:
self.was_recording = bool(self.doc.getPropertyValue("RecordChanges"))
except Exception:
self.was_recording = False
_log = logging.getLogger(__name__)
_log.info("WriterStreamedRewriteSession: was_recording=%s, compound_undo open=%s", self.was_recording, self._compound_undo._open)
try:
if self.was_recording:
self.doc.setPropertyValue("RecordChanges", False)
self.text_range.setString("")
except Exception:
if self.was_recording:
try:
self.doc.setPropertyValue("RecordChanges", True)
except Exception:
pass
self._compound_undo.close()
raise
def append_chunk(self, chunk: str) -> None:
"""Append streamed text to the visible range and shadow buffer."""
if not chunk:
return
self.generated_text += chunk
self.text_range.setString(self.generated_text)
def finish(self) -> str | None:
"""Finalize the rewrite. Returns a warning message on degraded success."""
try:
if not (self.was_recording or self.track_reviewable):
return None
try:
# Review mode only (NOT when the user merely has their own Track Changes on):
# snapshot the redlines so the collapsed change can be tagged as an agent change
# afterward, and author it as the agent for the by-author coloring.
before_ids = None
before_ids_ok = False
prior_author = None
if self.track_reviewable:
try:
from plugin.framework.uno_context import get_ctx
from plugin.writer import review_authors
from plugin.writer.edit_review import snapshot_redline_ids
before_ids, before_ids_ok = snapshot_redline_ids(self.doc)
prior_author = review_authors.begin(get_ctx())
# Make the markup visible so a reviewable change isn't left invisible
# when the user has Track Changes display off (matches
# EditReviewSession.__enter__). Review mode only -- never when the user
# merely has their own Track Changes on (we respect their view setting).
try:
self.doc.setPropertyValue("ShowChanges", True)
except Exception:
logging.getLogger(__name__).debug("streamed rewrite: could not force ShowChanges", exc_info=True)
except Exception:
logging.getLogger(__name__).debug("streamed rewrite: review tagging setup failed", exc_info=True)
try:
self.text_range.setString(self.original_text)
self.doc.setPropertyValue("RecordChanges", True)
self.text_range.setString(self.generated_text)
finally:
if prior_author is not None:
try:
from plugin.framework.uno_context import get_ctx
from plugin.writer import review_authors
review_authors.end(get_ctx(), prior_author)
except Exception:
logging.getLogger(__name__).warning("streamed rewrite: author restore failed", exc_info=True)
# Restore the user's prior recording state. If they had Track Changes
# OFF and we only turned it ON to capture this edit as one reviewable
# redline (track_reviewable flag), turn it back OFF so their later
# manual typing is not tracked. Existing redlines persist regardless.
if not self.was_recording:
self.doc.setPropertyValue("RecordChanges", False)
# Tag the collapsed redline(s) with a session token so the inline review UI
# (click popup / context menu) treats this streamed edit as an agent change.
if before_ids is not None:
try:
from plugin.writer.edit_review import tag_agent_redlines
tag_agent_redlines(self.doc, before_ids, before_reliable=before_ids_ok)
except Exception:
logging.getLogger(__name__).debug("streamed rewrite: redline tagging failed", exc_info=True)
return None
except Exception:
logging.getLogger(__name__).exception("Failed to collapse streamed edit into one tracked change")
fallback_errors: list[str] = []
try:
self.doc.setPropertyValue("RecordChanges", False)
except Exception as e:
fallback_errors.append(f"disable tracking failed: {e}")
try:
self.text_range.setString(self.generated_text)
except Exception as e:
fallback_errors.append(f"restore generated text failed: {e}")
try:
self.doc.setPropertyValue("RecordChanges", self.was_recording)
except Exception as e:
fallback_errors.append(f"restore recording state failed: {e}")
if fallback_errors:
return "Failed to finalize the tracked edit and preserve the generated text: " + "; ".join(fallback_errors)
return "Failed to collapse the streamed edit into a single tracked change. The generated text was kept, but it may still appear as multiple tracked changes."
finally:
self._compound_undo.close()
def abort_and_restore(self) -> None:
"""Restore the original text and recording state after an error."""
try:
if self.was_recording:
try:
self.doc.setPropertyValue("RecordChanges", False)
except Exception:
pass
self.text_range.setString(self.original_text)
finally:
if self.was_recording:
try:
self.doc.setPropertyValue("RecordChanges", True)
except Exception:
pass
self._compound_undo.close()
class WriterStreamedAppendSession:
"""Manage a streamed Writer APPEND (extend-selection) that collapses to one tracked insertion.
Unlike :class:`WriterStreamedRewriteSession` (which REPLACES the range), extend-selection
keeps the user's original text and streams the agent's continuation AFTER it. Streaming runs
with tracking OFF (the user sees the text appear without a redline per chunk); ``finish()``
then converts ONLY the appended continuation into a single tracked INSERTION -- the original
is never struck through -- authored as the agent and tagged for the inline review UI.
"""
_UNDO_CONTEXT_TITLE = "WriterAgent: Extend selection"
def __init__(self, doc, text_range, original_text: str, track_reviewable: bool = False):
self.doc = doc
self.text_range = text_range
self.original_text = original_text
self.appended_text = ""
self.track_reviewable = track_reviewable
self._compound_undo = WriterCompoundUndo(doc, self._UNDO_CONTEXT_TITLE)
try:
self.was_recording = bool(self.doc.getPropertyValue("RecordChanges"))
except Exception:
self.was_recording = False
# Stream with tracking OFF so the live continuation isn't recorded as a redline per
# chunk; finish() re-records the whole appended run as one tracked insertion.
try:
if self.was_recording:
self.doc.setPropertyValue("RecordChanges", False)
except Exception:
pass
def append_chunk(self, chunk: str) -> None:
"""Append streamed text after the original (tracking off; one redline created at finish)."""
if not chunk:
return
self.appended_text += chunk
try:
self.text_range.setString(self.original_text + self.appended_text)
except Exception:
logging.getLogger(__name__).debug("streamed append: chunk apply failed", exc_info=True)
def finish(self) -> str | None:
"""Collapse the appended continuation into one tracked insertion. Returns a warning on degraded success."""
try:
if not self.appended_text:
# We may have turned off the user's own Record Changes in __init__ to avoid a
# redline per streamed chunk. If the model produced nothing, there is no edit to
# collapse, but the user's prior tracking state still must be restored.
if self.was_recording:
try:
self.doc.setPropertyValue("RecordChanges", True)
except Exception:
pass
return None
if not (self.was_recording or self.track_reviewable):
return None
before_ids = None
before_ids_ok = False
prior_author = None
if self.track_reviewable:
try:
from plugin.framework.uno_context import get_ctx
from plugin.writer import review_authors
from plugin.writer.edit_review import snapshot_redline_ids
before_ids, before_ids_ok = snapshot_redline_ids(self.doc)
prior_author = review_authors.begin(get_ctx())
# Make the markup visible so a reviewable change isn't invisible when the
# user has Track Changes display off (matches EditReviewSession.__enter__).
try:
self.doc.setPropertyValue("ShowChanges", True)
except Exception:
logging.getLogger(__name__).debug("streamed append: could not force ShowChanges", exc_info=True)
except Exception:
logging.getLogger(__name__).debug("streamed append: review tagging setup failed", exc_info=True)
try:
# Drop the untracked appended run (back to just the original), then re-insert ONLY
# that run as a tracked insertion at the end -- so the original carries no redline.
self.text_range.setString(self.original_text)
self.doc.setPropertyValue("RecordChanges", True)
text = self.text_range.getText()
end_cursor = text.createTextCursorByRange(self.text_range.getEnd())
text.insertString(end_cursor, self.appended_text, False)
finally:
if prior_author is not None:
try:
from plugin.framework.uno_context import get_ctx
from plugin.writer import review_authors
review_authors.end(get_ctx(), prior_author)
except Exception:
logging.getLogger(__name__).warning("streamed append: author restore failed", exc_info=True)
# Restore the user's prior recording state (existing redlines persist regardless).
if not self.was_recording:
try:
self.doc.setPropertyValue("RecordChanges", False)
except Exception:
pass
if before_ids is not None:
try:
from plugin.writer.edit_review import tag_agent_redlines
tag_agent_redlines(self.doc, before_ids, before_reliable=before_ids_ok)
except Exception:
logging.getLogger(__name__).debug("streamed append: redline tagging failed", exc_info=True)
return None
except Exception:
logging.getLogger(__name__).exception("Failed to collapse streamed append into one tracked change")
# Degrade: keep the user's continuation (untracked) rather than losing it.
try:
self.doc.setPropertyValue("RecordChanges", False)
except Exception:
pass
try:
self.text_range.setString(self.original_text + self.appended_text)
except Exception:
pass
try:
self.doc.setPropertyValue("RecordChanges", self.was_recording)
except Exception:
pass
return "Failed to collapse the streamed continuation into a single tracked change. The text was kept, but may not be reviewable."
finally:
self._compound_undo.close()
def abort_and_restore(self) -> None:
"""After a streaming error, restore the recording state and close the undo group.
The partial continuation is left in place, matching the prior extend-selection behavior."""
try:
self.doc.setPropertyValue("RecordChanges", bool(self.was_recording))
except Exception:
pass
finally:
self._compound_undo.close()
def _user_defined_property_exists(props, name) -> bool:
"""Return True iff ``name`` is already defined on ``UserDefinedProperties``.
Delegates to :mod:`plugin.doc.udprops` (kept here for callers that imported this name).
"""
from plugin.doc.udprops import _user_defined_property_exists as _exists
return _exists(props, name)
def get_document_property(model, name, default=None):
"""Get a custom document property from the model."""
from plugin.doc.udprops import get_document_property as _get
return _get(model, name, default)
def set_document_property(model, name, value):
"""Set a custom document property in the model."""
from plugin.doc.udprops import set_document_property as _set
return _set(model, name, value)
def _normalize_doc_url(url):
"""Normalize document URL for comparison (strip, optional trailing slash)."""
if not url:
return ""
s = str(url).strip()
if s.endswith("/") and len(s) > 1:
s = s[:-1]
return s
def get_runtime_uid(model):
"""Stable per-session id for an open component.
Unlike the document URL, ``RuntimeUID`` exists even for unsaved/untitled
documents, so it can address a document that has no file on disk yet.
Returns "" if unavailable.
Tries ``getRuntimeUID()``, attribute access, and ``getPropertyValue("RuntimeUID")`` in turn
because LibreOffice builds expose the id through different UNO surfaces. Only plain ``str`` /
``int`` values are accepted so auto-mocked UNO attributes (e.g. ``MagicMock.RuntimeUID``)
cannot masquerade as a real uid.
"""
for accessor in (
lambda m: m.getRuntimeUID() if callable(getattr(m, "getRuntimeUID", None)) else None,
lambda m: getattr(m, "RuntimeUID", None),
lambda m: m.getPropertyValue("RuntimeUID"),
):
try:
raw = accessor(model)
if isinstance(raw, bool):
continue
if isinstance(raw, int):
return str(raw)
if isinstance(raw, str) and raw:
return raw
except Exception:
continue
return ""
@main_thread_only
def resolve_document_by_url(ctx, url):
"""Resolve an open document by URL or RuntimeUID. Must be called on the UNO main thread.
``url`` may be a document URL or a ``RuntimeUID`` (as returned by
``list_open_documents``); the RuntimeUID also matches unsaved/untitled
documents that have no URL yet.
Returns (doc, doc_type) or (None, None) if not found.
doc_type is one of 'writer', 'calc', 'draw'.
"""
if not url or not str(url).strip():
return (None, None)
from plugin.framework.uno_context import get_desktop
target = _normalize_doc_url(url)
try:
desktop = get_desktop(ctx)
comps = desktop.getComponents()
if not comps:
return (None, None)
enum = comps.createEnumeration()
if not enum:
return (None, None)
while enum and enum.hasMoreElements():
elem = enum.nextElement()
try:
model = None
if hasattr(elem, "getURL") and callable(getattr(elem, "getURL")):
model = elem
elif hasattr(elem, "getController") and elem.getController():
model = elem.getController().getModel()
if model is not None:
doc_url = _normalize_doc_url(model.getURL()) if hasattr(model, "getURL") else ""
uid = get_runtime_uid(model)
if (doc_url and doc_url == target) or (uid and uid == target):
doc_type_enum = get_document_type(model)
doc_type = "writer"
if doc_type_enum == DocumentType.CALC:
doc_type = "calc"
elif doc_type_enum in (DocumentType.DRAW, DocumentType.IMPRESS):
doc_type = "draw"
return (_wrap_uno(model), doc_type)
except Exception as e:
logging.getLogger(__name__).debug("resolve_document_by_url element error: %s", type(e).__name__)
continue
except Exception:
logging.getLogger(__name__).exception("resolve_document_by_url enumeration error")
return (None, None)
@main_thread_only
def get_document_from_frame(frame):
"""Get the document model strictly from the frame controller.
This is the preferred path for sidebar panels to ensure we resolve
the document bound to the active window rather than relying on Desktop.
"""
if not frame:
return None
try:
check_disposed(frame, "Frame")
controller = frame.getController()
if not controller:
return None
check_disposed(controller, "Controller")
model = controller.getModel()
if model is not None:
from plugin.framework.thread_guard import guard_uno
return guard_uno(model)
except Exception as e:
if isinstance(e, UNO_DISPOSED_EXCEPTIONS):
logging.getLogger(__name__).debug("Failed to get model from frame controller (likely disposed): %s", e)
else:
logging.getLogger(__name__).exception("Error resolving document from frame")
return None
@main_thread_only
def get_selection_text(model):
"""Return the selected text or None if selection is empty/unavailable/fails. Handles Writer, Calc, Draw."""
try:
check_disposed(model, "Document Model")
controller = safe_call(model.getCurrentController, "Get current controller")
if not controller:
return None
check_disposed(controller, "Controller")
doc_type = get_document_type(model)
if doc_type == DocumentType.WRITER:
sel = safe_call(controller.getSelection, "Get selection")
sel_count = 0
if sel and hasattr(sel, "getCount"):
sel_count = safe_call(sel.getCount, "Get selection count")
if not sel or sel_count == 0:
vc = safe_call(controller.getViewCursor, "Get view cursor")
if vc:
check_disposed(vc, "View Cursor")
return safe_call(vc.getString, "Get view cursor string")
else:
rng = safe_call(sel.getByIndex, "Get selection by index", 0)
if rng:
check_disposed(rng, "Selection Range")
return safe_call(rng.getString, "Get selection string")
elif doc_type == DocumentType.CALC:
selection = safe_call(controller.getSelection, "Get selection")
if selection:
if hasattr(selection, "getString"):
return safe_call(selection.getString, "Get selection string")
elif doc_type in (DocumentType.DRAW, DocumentType.IMPRESS):
selection = safe_call(controller.getSelection, "Get selection")
if selection and hasattr(selection, "getCount"):
count = safe_call(selection.getCount, "Get selection count")
parts = []
for i in range(count):
shape = safe_call(selection.getByIndex, "Get selection shape", i)
if shape and hasattr(shape, "getString"):
parts.append(safe_call(shape.getString, "Get shape string"))
if parts:
return "\n".join(parts)
except Exception:
pass
return None
def get_document_path(model):
"""Return the local filesystem path for the document, or None if not a file URL (e.g. untitled)."""
try:
url = model.getURL()
if not url or not str(url).startswith("file://"):
return None
return str(uno.fileUrlToSystemPath(url))
except Exception as e:
logging.getLogger(__name__).debug("get_document_path exception: %s", type(e).__name__)
return None
@main_thread_only
def get_full_document_text(model, max_chars=CHAT_DOCUMENT_CONTEXT_MAX_CHARS):
"""Get full document text for Writer or summary for Calc, truncated to max_chars."""
try:
check_disposed(model, "Document Model")
doc_type = get_document_type(model)
if doc_type == DocumentType.CALC:
# Calc document
bridge = CalcBridge(model)
analyzer = SheetAnalyzer(bridge)
summary = analyzer.get_sheet_summary()
text = f"Sheet: {summary['sheet_name']}\nUsed Range: {summary['used_range']}\n"
text += f"Columns: {', '.join(filter(None, summary['headers']))}\n"
# Maybe add some preview rows?
return text
if doc_type == DocumentType.WRITER:
doc_len = _writer_char_count(model)
take = min(doc_len, max_chars)
excerpt = _read_writer_text_slice(model, 0, take)
if doc_len > max_chars:
excerpt += "\n\n[... document truncated ...]"
return excerpt
if doc_type in (DocumentType.DRAW, DocumentType.IMPRESS):
return get_draw_context_for_chat(model, max_chars)
return ""
except UnoObjectError:
logging.getLogger(__name__).exception("get_full_document_text failed")
return ""
def get_document_end(model, max_chars=4000):
"""Get the last max_chars of the document."""
try:
check_disposed(model, "Document Model")
text = safe_call(model.getText, "Get document text")
cursor = safe_call(text.createTextCursor, "Create text cursor")
safe_call(cursor.gotoEnd, "Cursor gotoEnd", False)
safe_call(cursor.gotoStart, "Cursor gotoStart", True) # expand backward to select from start to end
full = get_string_without_tracked_deletions(cursor)
if len(full) <= max_chars:
return full
return full[-max_chars:]
except UnoObjectError:
logging.getLogger(__name__).exception("get_document_end failed")
return ""
# goRight(nCount, bExpand) takes short; max 32767 per call
_GO_RIGHT_CHUNK = 8192
def _writer_char_count(model) -> int:
"""Writer document character count; prefers O(1) CharacterCount over full getString()."""
try:
check_disposed(model, "Document Model")
count = getattr(model, "CharacterCount", None)
if count is not None:
return max(0, int(count))
except Exception:
pass
try:
text = safe_call(model.getText, "Get document text")
cursor = safe_call(text.createTextCursor, "Create text cursor")
safe_call(cursor.gotoStart, "Cursor gotoStart", False)
safe_call(cursor.gotoEnd, "Cursor gotoEnd", True)
return len(normalize_linebreaks(safe_call(cursor.getString, "Cursor getString")))
except UnoObjectError:
logging.getLogger(__name__).exception("_writer_char_count failed")
return 0
def _read_writer_text_slice(model, start_offset: int, length: int) -> str:
"""Read up to *length* characters from *start_offset* without loading the full document."""
if length <= 0:
return ""
end_offset = start_offset + length
cursor = get_text_cursor_at_range(model, start_offset, end_offset)
if cursor is None:
return ""
# cursor.getString() concatenates tracked deletions as plain text; enumerate portions instead.
return normalize_linebreaks(get_string_without_tracked_deletions(cursor))
def _char_offset_of_position(model, target_start, doc_len: int) -> int:
"""Character offset of a UNO text position from document start (no prefix getString())."""
if doc_len <= 0:
return 0
try:
text = safe_call(model.getText, "Get document text")
cursor = safe_call(text.createTextCursor, "Create text cursor")
safe_call(cursor.gotoStart, "Cursor gotoStart", False)
offset = 0
while offset < doc_len:
cmp = safe_call(text.compareRegionStarts, "compareRegionStarts", target_start, safe_call(cursor.getStart, "Cursor getStart"))
if cmp == 0:
return offset
if cmp > 0:
if offset == 0:
return 0
safe_call(cursor.goLeft, "Cursor goLeft", 1, False)
offset -= 1
continue
step = min(_GO_RIGHT_CHUNK, doc_len - offset)
if step <= 0:
return offset
safe_call(cursor.goRight, "Cursor goRight", step, False)
offset += step
cmp_after = safe_call(text.compareRegionStarts, "compareRegionStarts", target_start, safe_call(cursor.getStart, "Cursor getStart"))
if cmp_after >= 0:
while offset > 0 and safe_call(text.compareRegionStarts, "compareRegionStarts", target_start, safe_call(cursor.getStart, "Cursor getStart")) > 0:
safe_call(cursor.goLeft, "Cursor goLeft", 1, False)
offset -= 1
while safe_call(text.compareRegionStarts, "compareRegionStarts", target_start, safe_call(cursor.getStart, "Cursor getStart")) < 0 and offset < doc_len:
safe_call(cursor.goRight, "Cursor goRight", 1, False)
offset += 1
return offset
return doc_len
except UnoObjectError:
logging.getLogger(__name__).exception("_char_offset_of_position failed")
return 0
def _get_writer_selection_positions(model):
"""Return (text, sel_start_pos, sel_end_pos) or None when selection unavailable."""
try:
check_disposed(model, "Document Model")
controller = safe_call(model.getCurrentController, "Get current controller")
sel = safe_call(controller.getSelection, "Get selection")
sel_count = 0
if sel and hasattr(sel, "getCount"):
sel_count = safe_call(sel.getCount, "Get selection count")
if not sel or sel_count == 0:
vc = safe_call(controller.getViewCursor, "Get view cursor")
rng = vc
else:
rng = safe_call(sel.getByIndex, "Get selection by index", 0)
if not rng or not hasattr(rng, "getStart") or not hasattr(rng, "getEnd"):
return None
text = safe_call(model.getText, "Get document text")
return text, safe_call(rng.getStart, "Get range start"), safe_call(rng.getEnd, "Get range end")
except UnoObjectError:
return None
def _writer_excerpt_overlaps_selection(model, excerpt_start: int, excerpt_end: int, sel_start_pos, sel_end_pos) -> bool:
"""True when selection UNO range overlaps [excerpt_start, excerpt_end) character window."""