Repository navigation
Expand file tree
/
Copy pathvenv_probe_ui.py
More file actions
288 lines (248 loc) · 10.4 KB
/
Copy pathvenv_probe_ui.py
File metadata and controls
288 lines (248 loc) · 10.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
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Shared Settings → Python modal progress UI (venv probe / download workers)."""
from __future__ import annotations
import logging
from typing import Any, Callable
from plugin.chatbot.dialogs import (
get_control_text,
get_optional,
load_writeragent_dialog_detail,
msgbox,
set_control_enabled,
set_control_text,
)
from plugin.framework.uno_listeners import BaseActionListener
from plugin.framework.i18n import N_, _
from plugin.framework.queue_executor import main
from plugin.framework.uno_context import get_desktop, get_toolkit, process_events_to_idle
from plugin.framework.worker_pool import run_in_background
log = logging.getLogger(__name__)
# probe_fn(on_display, on_status) -> (ok, message)
ProbeFn = Callable[[Callable[[str], None], Callable[[str], None]], tuple[bool, str]]
def _dialog_parent_for_child(ctx: Any, parent_dlg: Any) -> Any:
"""Resolve a parent window for a child modal opened above an executing dialog."""
if parent_dlg is not None:
try:
peer = parent_dlg.getPeer()
if peer is not None:
return peer
except Exception:
log.debug("parent_dlg.getPeer failed for child modal", exc_info=True)
try:
desktop = get_desktop(ctx)
frame = desktop.getCurrentFrame() if desktop else None
if frame is not None:
return frame.getContainerWindow()
except Exception:
log.debug("getCurrentFrame parent fallback failed for child modal", exc_info=True)
return None
class VenvProbeProgressDialog:
"""Modal progress window for Settings → Python Test (probe runs in a worker thread)."""
_ctx: Any
_parent_dlg: Any
_dlg: Any
_append_log: bool
_log_parts: list[str]
_pumping: bool
def __init__(self, ctx: Any, parent_dlg: Any = None) -> None:
self._ctx = ctx
self._parent_dlg = parent_dlg
self._dlg = None
self._append_log = False
self._log_parts = []
self._pumping = False
def run_modal_probe(
self,
probe_fn: ProbeFn,
*,
title: str | None = None,
success_title: str | None = None,
failure_title: str | None = None,
append_log: bool = False,
) -> None:
"""Show a modal dialog and run *probe_fn(on_display, on_status)* in a worker."""
try:
if not self._create_dialog(title=title):
return
self._append_log = append_log
self._log_parts = []
dlg = self._dlg
assert dlg is not None
def on_display(text: str) -> None:
main.post(self.set_display, text)
def on_status(text: str) -> None:
main.post(self.set_status, text)
def post_finish(success: bool, body: str | None) -> None:
def ui() -> None:
if not success and body and self._dlg is not None:
log_ctrl = self._dlg.getControl("LogArea")
if not get_control_text(log_ctrl).strip():
self.set_display(body)
self.finish(success_title if success else failure_title, success)
main.post(ui)
def work() -> None:
try:
ok, msg = probe_fn(on_display, on_status)
post_finish(ok, msg)
except BaseException as exc:
log.exception("Scripting venv probe failed")
err_msg = str(exc)
def fail_ui() -> None:
self.set_display(err_msg)
self.finish(failure_title, False)
main.post(fail_ui)
if not isinstance(exc, Exception):
raise
run_in_background(work, name="settings-venv-test")
dlg.execute()
finally:
self._dispose()
def _create_dialog(self, *, title: str | None = None) -> bool:
dlg, detail = load_writeragent_dialog_detail("PythonTestProgressDialog", self._ctx)
if dlg is None:
log.warning("Failed to load PythonTestProgressDialog: %s", detail)
msgbox(
self._ctx,
_("Python Test"),
_("Could not open the Python test progress dialog."),
box_type=3,
)
return False
self._dlg = dlg
if title:
dlg.getModel().Title = _(title)
btn_close = dlg.getControl("BtnClose")
if btn_close is not None:
# Close stays disabled until finish() so the user cannot dismiss the dialog while the probe worker still runs.
set_control_enabled(btn_close, False)
btn_close.addActionListener(_VenvProbeCloseListener(dlg))
self._parent_progress_dialog(dlg)
return True
def _parent_progress_dialog(self, dlg: Any) -> None:
"""Parents the modal to Settings via createPeer so the progress window is anchored to the
settings dialog instead of floating as a separate top-level window.
"""
parent = _dialog_parent_for_child(self._ctx, self._parent_dlg)
try:
if dlg.getPeer() is not None:
return
except Exception:
log.debug("venv probe progress getPeer failed", exc_info=True)
try:
toolkit = get_toolkit(self._ctx)
if toolkit is None:
return
dlg.setVisible(False)
dlg.createPeer(toolkit, parent)
except Exception:
log.debug("venv probe progress createPeer failed", exc_info=True)
def _pump_dialog(self) -> None:
# finish() is posted from the probe worker via main.post.
# Opengrep intrafile taint still treats process_events_to_idle in
# finish() as a worker sink (uno-off-main-thread). A bare
# if main.is_current() is the documented sanitizer; pumping VCL
# off-main is never correct.
if not main.is_current():
return
# _pumping prevents recursive processEventsToIdle during download status updates, which would stack AsyncCallback dispatches and stall the UI.
if self._pumping:
return
self._pumping = True
try:
process_events_to_idle(self._ctx)
finally:
self._pumping = False
def set_display(self, text: str) -> None:
if self._dlg is None:
return
# append_log mode concatenates download lines into LogArea; without it, per-chunk set_control_text would show only the latest fragment.
shown = text
if self._append_log:
self._log_parts.append(text)
shown = "".join(self._log_parts)
set_control_text(self._dlg.getControl("LogArea"), shown)
self._pump_dialog()
def set_status(self, text: str) -> None:
if self._dlg is None:
return
status = text.strip() or _("Testing Python environment...")
if len(status) > 80:
status = status[:77] + "..."
set_control_text(self._dlg.getControl("StatusLbl"), status)
self._pump_dialog()
def finish(self, title: str | None, ok: bool) -> None:
if self._dlg is None:
return
# finish title=None keeps the caller's dialog title so audio/Cython/PPT probes are not forced to "Venv OK" / "Venv check failed".
if title:
try:
self._dlg.getModel().Title = _(title)
except Exception:
log.debug("venv probe dialog title failed", exc_info=True)
set_control_text(self._dlg.getControl("StatusLbl"), _("Done") if ok else _("Failed"))
set_control_enabled(self._dlg.getControl("BtnClose"), True)
self._pump_dialog()
def _dispose(self) -> None:
dlg = self._dlg
self._dlg = None
if dlg is None:
return
try:
dlg.dispose()
except Exception:
log.debug("Failed to dispose venv probe progress dialog", exc_info=True)
class _VenvProbeCloseListener(BaseActionListener):
_dlg: Any
def __init__(self, dlg: Any) -> None:
self._dlg = dlg
def on_action_performed(self, rEvent: Any) -> None:
try:
self._dlg.endDialog(0)
except Exception:
log.debug("Failed to close venv probe progress dialog", exc_info=True)
class ScriptingVenvTestListener(BaseActionListener):
"""Settings → Python: run a quick subprocess check using the path in the text field (saved or not)."""
_ctx: Any
_dlg: Any
_include_vector_search: bool
_include_audio: bool
def __init__(
self,
ctx: Any,
dlg: Any,
*,
include_vector_search: bool = True,
include_audio: bool = True,
) -> None:
self._ctx = ctx
self._dlg = dlg
self._include_vector_search = include_vector_search
self._include_audio = include_audio
def on_action_performed(self, rEvent: Any) -> None:
from plugin.scripting.native_binaries import ensure_native_binaries_on_path
from plugin.scripting.payload_codec import host_cython_status_line
from plugin.scripting.venv_diagnostics import probe_venv_path_with_progress
# User-downloaded writeragent_vec may be on sys.path via audio_binaries.
ensure_native_binaries_on_path()
# Reload on the main thread (not the probe worker): after redownload the
# worker must not be the first site that imports / calls into natives.
cython_status = host_cython_status_line(reload=True)
path_ctrl = get_optional(self._dlg, "scripting__python_venv_path")
raw = get_control_text(path_ctrl) if path_ctrl else ""
def probe(on_display: Callable[[str], None], on_status: Callable[[str], None]) -> tuple[bool, str]:
return probe_venv_path_with_progress(
raw,
on_display,
on_status=on_status,
extra_lines_after_header=(cython_status,),
include_vector_search=self._include_vector_search,
include_audio=self._include_audio,
)
VenvProbeProgressDialog(self._ctx, parent_dlg=self._dlg).run_modal_probe(
probe,
success_title=N_("Venv OK"),
failure_title=N_("Venv check failed"),
)