forked from balisujohn/localwriter
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathpython_runner_ui.py
More file actions
528 lines (458 loc) · 21.4 KB
/
Copy pathpython_runner_ui.py
File metadata and controls
528 lines (458 loc) · 21.4 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
# WriterAgent - AI Writing Assistant for LibreOffice
# 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.
"""UI Dialog logic for 'Run Python Script...' in Writer."""
import logging
from typing import Any
import unohelper
from com.sun.star.awt import XActionListener, XItemListener, XTopWindowListener
from plugin.framework.config import get_config, get_config_str, set_config
from plugin.framework.i18n import _
from plugin.chatbot.dialogs import load_writeragent_dialog_detail, msgbox, set_control_text, show_approval_dialog
from plugin.chatbot.dialogs import show_text_input_dialog
from plugin.framework.worker_pool import run_in_background
from plugin.scripting.document_scripts import (
SCRIPT_ORIGIN_DOCUMENT,
SCRIPT_ORIGIN_USER,
attach_document_script,
build_xdl_script_picker_state,
delete_document_script,
resolve_script_picker_entry,
save_document_script,
)
from plugin.scripting.venv_worker import warm_venv_worker
log = logging.getLogger("writeragent.scripting")
def native_run_script_modeless_enabled(ctx: Any) -> bool:
"""When True, the plain-text Run Python Script dialog floats (document stays editable)."""
return bool(get_config("scripting.native_run_script_modeless"))
def _picker_selected_name(select_ctrl: Any) -> str:
"""Return the selected script name from ScriptSelect (listbox or combobox)."""
if hasattr(select_ctrl, "getSelectedItemPos"):
pos = select_ctrl.getSelectedItemPos()
items = select_ctrl.getItems()
if pos >= 0 and pos < len(items):
return str(items[pos])
if hasattr(select_ctrl, "getText"):
return str(select_ctrl.getText() or "").strip()
return ""
def _picker_select_name(select_ctrl: Any, name: str, names: list[str]) -> None:
"""Select *name* in ScriptSelect (listbox or combobox)."""
if not name:
return
if hasattr(select_ctrl, "selectItemPos"):
for idx, nm in enumerate(names):
if nm == name:
select_ctrl.selectItemPos(idx, True)
return
if hasattr(select_ctrl, "setText"):
select_ctrl.setText(name)
class NativePythonScriptDialog:
"""Plain-text Run Python Script dialog (modal or optional modeless).
Each menu open creates its own instance, bound to the document that was active
at open time. Multiple modeless dialogs may be open at once (one per document/window).
Future: re-resolve the target document on each action when the user switches
focus between LO windows (getCurrentComponent() did not track that in manual testing).
"""
def __init__(
self,
ctx: Any,
*,
initial_text: str,
config_key: str,
initial_doc: Any | None,
modeless: bool,
) -> None:
self._ctx = ctx
self._config_key = config_key
self._doc = initial_doc
self._modeless = modeless
self._dlg: Any | None = None
self._select_ctrl: Any | None = None
self._current_scripts: dict[str, str] = {}
self._script_origin_map: dict[str, str] = {}
self._closed = False
self._top_listener: Any | None = None
self._open_failure_detail: str | None = None
self._opened = self._open(initial_text)
@classmethod
def show(
cls,
ctx: Any,
*,
initial_text: str,
config_key: str,
doc: Any | None,
modeless: bool,
) -> tuple[bool, str | None]:
inst = cls(
ctx,
initial_text=initial_text,
config_key=config_key,
initial_doc=doc,
modeless=modeless,
)
if inst._opened:
return True, None
return False, inst._open_failure_detail
def close(self) -> None:
if self._closed:
return
self._closed = True
dlg = self._dlg
self._dlg = None
if dlg is None:
return
try:
dlg.setVisible(False)
except Exception:
log.exception("Failed to hide native script dialog")
try:
dlg.dispose()
except Exception:
log.exception("Failed to dispose native script dialog")
def _refresh_script_dropdown(self, select_display: str | None = None) -> None:
select_ctrl = self._select_ctrl
if select_ctrl is None:
return
saved = get_config("saved_python_scripts")
if not isinstance(saved, dict):
saved = {}
names, merged, origin_map = build_xdl_script_picker_state(self._ctx, self._doc, saved)
self._current_scripts = merged
self._script_origin_map = origin_map
select_ctrl.removeItems(0, select_ctrl.getItemCount())
select_ctrl.addItems(tuple(names), 0)
selected_name = ""
if select_display and select_display in names:
selected_name = select_display
else:
from plugin.scripting.python_runner import resolve_run_script_name_config_key
name_config_key = resolve_run_script_name_config_key(self._doc)
last_name = get_config_str(name_config_key)
if last_name and last_name in names:
selected_name = last_name
if not selected_name and names:
selected_name = names[0]
if selected_name:
_picker_select_name(select_ctrl, selected_name, names)
from plugin.scripting.python_runner import resolve_run_script_name_config_key
name_config_key = resolve_run_script_name_config_key(self._doc)
set_config(name_config_key, selected_name)
if self._dlg is not None:
try:
code_ctrl = self._dlg.getControl("CodeEdit")
if code_ctrl is not None:
code_ctrl.setText(merged.get(selected_name, ""))
except Exception:
pass
def _open(self, initial_text: str) -> bool:
ctx = self._ctx
try:
dlg, load_detail = load_writeragent_dialog_detail("PythonScriptDialog", ctx)
if dlg is None:
log.error(
"NativePythonScriptDialog: PythonScriptDialog XDL load failed:\n%s",
load_detail or "(no load detail captured)",
)
self._open_failure_detail = load_detail or _("PythonScriptDialog could not be loaded from the extension.")
self.close()
return False
self._dlg = dlg
# Trigger background pre-warming of the venv subprocess for the native fallback case as well
run_in_background(warm_venv_worker, ctx, name="warm-venv-worker")
select_ctrl = dlg.getControl("ScriptSelect")
self._select_ctrl = select_ctrl
saved_scripts = get_config("saved_python_scripts")
if not isinstance(saved_scripts, dict):
saved_scripts = {}
doc = self._doc
script_names, merged_scripts, origin_map = build_xdl_script_picker_state(ctx, doc, saved_scripts)
self._current_scripts = dict(merged_scripts)
self._script_origin_map = dict(origin_map)
# Re-initialize picker items and selection cleanly
self._refresh_script_dropdown()
self._wire_listeners(dlg, select_ctrl)
code_ctrl = dlg.getControl("CodeEdit")
if code_ctrl is not None:
code_ctrl.setFocus()
if self._modeless:
owner = self
class _TopWindowListener(unohelper.Base, XTopWindowListener):
def windowClosing(self, e):
owner.close()
def windowClosed(self, e):
pass
def windowOpened(self, e):
pass
def windowMinimized(self, e):
pass
def windowNormalized(self, e):
pass
def windowActivated(self, e):
pass
def windowDeactivated(self, e):
pass
def disposing(self, Source):
pass
self._top_listener = _TopWindowListener()
dlg.addTopWindowListener(self._top_listener)
dlg.setVisible(True)
return True
dlg.execute()
dlg.dispose()
self._dlg = None
return True
except Exception as exc:
from plugin.scripting.editor_ipc import exception_traceback
log.exception("NativePythonScriptDialog._open failed")
self._open_failure_detail = exception_traceback(exc)
self.close()
return False
def _save_current_script(self, t: str) -> str | None:
select_ctrl = self._select_ctrl
if select_ctrl is None:
return None
display_name = _picker_selected_name(select_ctrl)
if display_name:
real_name, origin = resolve_script_picker_entry(display_name, self._script_origin_map)
self._current_scripts[display_name] = t
if origin == SCRIPT_ORIGIN_DOCUMENT:
if self._doc is None:
return _("No document is open to save scripts.")
err = save_document_script(self._doc, real_name, t)
if err:
user_scripts = get_config("saved_python_scripts")
if not isinstance(user_scripts, dict):
user_scripts = {}
user_scripts[real_name] = t
set_config("saved_python_scripts", user_scripts)
return _("%s Saved to My Scripts instead.") % err
return _("Script '%s' saved to this document.") % real_name
else:
user_scripts = get_config("saved_python_scripts")
if not isinstance(user_scripts, dict):
user_scripts = {}
user_scripts[real_name] = t
set_config("saved_python_scripts", user_scripts)
return _("Script '%s' saved successfully.") % real_name
return None
def _wire_listeners(self, dlg: Any, select_ctrl: Any) -> None:
ctx = self._ctx
owner = self
doc = owner._doc
class _ScriptSelectListener(unohelper.Base, XItemListener):
def itemStateChanged(self, rEvent):
try:
name = _picker_selected_name(select_ctrl)
if name:
code_ctrl = dlg.getControl("CodeEdit")
# Save the selected name to config
from plugin.scripting.python_runner import resolve_run_script_name_config_key
name_config_key = resolve_run_script_name_config_key(owner._doc)
set_config(name_config_key, name)
t = owner._current_scripts.get(name, "")
code_ctrl.setText(t)
except Exception:
log.exception("Failed to change script selection")
def disposing(self, Source):
pass
class _RunListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
try:
ec = dlg.getControl("CodeEdit")
t = (ec.getModel().Text or "").strip()
lbl = dlg.getControl("InstructionLbl")
owner._save_current_script(t)
from plugin.scripting.python_runner import execute_and_insert_result
outcome = execute_and_insert_result(ctx, doc, t)
_report_run_outcome(ctx, lbl, outcome)
except Exception as e:
log.exception("Run failed in dialog")
msgbox(ctx, _("Error"), str(e))
def disposing(self, Source):
pass
class _SaveListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
try:
ec = dlg.getControl("CodeEdit")
t = (ec.getModel().Text or "").strip()
lbl = dlg.getControl("InstructionLbl")
res = owner._save_current_script(t)
if res:
set_control_text(lbl, res)
except Exception:
log.exception("Save failed in dialog")
def disposing(self, Source):
pass
class _AttachListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
try:
lbl = dlg.getControl("InstructionLbl")
if doc is None:
set_control_text(lbl, _("No document is open to attach scripts."))
return
ec = dlg.getControl("CodeEdit")
t = (ec.getModel().Text or "").strip()
curr = _picker_selected_name(select_ctrl)
curr = curr if curr != "Sample" else ""
real_curr, _curr_origin = resolve_script_picker_entry(curr, owner._script_origin_map) if curr else ("", SCRIPT_ORIGIN_USER)
name = show_text_input_dialog(ctx, _("Enter script name:"), _("Attach to Document"), real_curr)
if not name:
return
name = name.strip()
if not name:
return
from plugin.scripting.document_scripts import document_script_display_name, get_document_scripts
overwrite = name in get_document_scripts(doc)
if overwrite and not show_approval_dialog(
ctx,
_("A script named '{0}' already exists in this document. Overwrite?").format(name),
_("Attach Script"),
):
return
err = attach_document_script(doc, name, t, overwrite=True)
if err:
set_control_text(lbl, err)
return
owner._refresh_script_dropdown(document_script_display_name(name))
set_control_text(lbl, _("Script '%s' attached to this document.") % name)
except Exception:
log.exception("Attach failed in dialog")
def disposing(self, Source):
pass
class _SaveAsListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
try:
ec = dlg.getControl("CodeEdit")
t = (ec.getModel().Text or "").strip()
curr_display = _picker_selected_name(select_ctrl)
curr_display = curr_display if curr_display != "Sample" else ""
real_curr, curr_origin = (
resolve_script_picker_entry(curr_display, owner._script_origin_map)
if curr_display
else ("", SCRIPT_ORIGIN_USER)
)
name = show_text_input_dialog(ctx, _("Enter script name:"), _("Save Script"), real_curr)
if not name:
return
name = name.strip()
if not name:
return
lbl = dlg.getControl("InstructionLbl")
save_to_document = curr_origin == SCRIPT_ORIGIN_DOCUMENT
if doc is not None and not save_to_document:
save_to_document = show_approval_dialog(
ctx,
_("Save script '{0}' to this document?").format(name),
_("Save Script"),
)
if doc is not None and save_to_document:
from plugin.scripting.document_scripts import document_script_display_name
err = save_document_script(doc, name, t)
if err:
user_scripts = get_config("saved_python_scripts")
if not isinstance(user_scripts, dict):
user_scripts = {}
user_scripts[name] = t
set_config("saved_python_scripts", user_scripts)
set_control_text(lbl, _("%s Saved to My Scripts instead.") % err)
else:
set_control_text(lbl, _("Script '%s' saved to this document.") % name)
owner._refresh_script_dropdown(document_script_display_name(name))
return
user_scripts = get_config("saved_python_scripts")
if not isinstance(user_scripts, dict):
user_scripts = {}
user_scripts[name] = t
set_config("saved_python_scripts", user_scripts)
owner._refresh_script_dropdown(name)
set_control_text(lbl, _("Script '%s' saved successfully.") % name)
except Exception:
log.exception("Save As failed in dialog")
def disposing(self, Source):
pass
class _DeleteListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
try:
display_name = _picker_selected_name(select_ctrl)
if not display_name:
return
lbl = dlg.getControl("InstructionLbl")
real_name, origin = resolve_script_picker_entry(display_name, owner._script_origin_map)
if show_approval_dialog(
ctx,
_("Are you sure you want to delete script '%s'?") % real_name,
_("Delete Script"),
):
if origin == SCRIPT_ORIGIN_DOCUMENT:
if doc is None:
set_control_text(lbl, _("No document is open."))
return
delete_document_script(doc, real_name)
else:
user_scripts = get_config("saved_python_scripts")
if not isinstance(user_scripts, dict):
user_scripts = {}
user_scripts.pop(real_name, None)
set_config("saved_python_scripts", user_scripts)
owner._refresh_script_dropdown()
set_control_text(lbl, _("Script '%s' deleted.") % real_name)
except Exception:
log.exception("Delete failed in dialog")
def disposing(self, Source):
pass
class _CancelListener(unohelper.Base, XActionListener):
def actionPerformed(self, rEvent):
if owner._modeless:
owner.close()
else:
dlg.endDialog(0)
def disposing(self, Source):
pass
select_ctrl.addItemListener(_ScriptSelectListener())
dlg.getControl("BtnRun").addActionListener(_RunListener())
dlg.getControl("BtnSave").addActionListener(_SaveListener())
dlg.getControl("BtnAttach").addActionListener(_AttachListener())
dlg.getControl("BtnSaveAs").addActionListener(_SaveAsListener())
dlg.getControl("BtnDelete").addActionListener(_DeleteListener())
dlg.getControl("BtnCancel").addActionListener(_CancelListener())
def show_python_input_dialog(
ctx: Any,
initial_text: str = "",
config_key: str = "last_python_script_writer",
doc: Any | None = None,
) -> tuple[bool, str | None]:
"""Show the plain-text Run Python Script dialog (modeless when configured).
Returns (opened, failure_detail). failure_detail is set when opened is False.
"""
try:
modeless = native_run_script_modeless_enabled(ctx)
return NativePythonScriptDialog.show(
ctx,
initial_text=initial_text,
config_key=config_key,
doc=doc,
modeless=modeless,
)
except Exception as exc:
from plugin.scripting.editor_ipc import exception_traceback
log.exception("show_python_input_dialog failed")
return False, exception_traceback(exc)
def _report_run_outcome(ctx: Any, lbl: Any | None, outcome: dict[str, Any]) -> None:
"""Update native dialog status / msgboxes after Run."""
if not outcome.get("ok"):
msgbox(ctx, _("Execution Error"), outcome.get("message", _("Unknown error")))
return
status_text = outcome.get("status_ok_text", _("Script executed successfully."))
if status_text.startswith(_(
"Script executed successfully, but returned no result and produced no output."
)):
msgbox(ctx, _("Success"), status_text)
elif outcome.get("stdout") and outcome.get("result") is None:
msgbox(ctx, _("Output"), outcome.get("stdout"))
if lbl is not None:
set_control_text(lbl, status_text)