forked from balisujohn/localwriter
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdialog_views.py
More file actions
727 lines (607 loc) · 29.4 KB
/
Copy pathdialog_views.py
File metadata and controls
727 lines (607 loc) · 29.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
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
# 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/>.
import logging
import threading
import uno
from com.sun.star.awt import XItemListener, XTextListener
from plugin.framework.errors import format_error_payload, UnoObjectError, ConfigValidationError
from plugin.framework.uno_context import get_active_document, get_desktop, get_extension_url, get_toolkit
from plugin.framework.i18n import _
from plugin.framework.config import get_config, get_current_endpoint, set_config, get_config_str, get_config_int, as_bool
from plugin.framework.client.model_fetcher import get_text_model, get_stt_model, set_text_model
from plugin.framework.logging import init_logging
from plugin.chatbot.config_ui_helpers import populate_combobox_with_lru
from plugin.chatbot.history_db import HAS_SQLITE
from plugin.scripting.venv_probe_ui import ScriptingVenvTestListener, VenvProbeProgressDialog
from .listeners import BaseActionListener, BaseListener
from .dialogs import (
TabListener, is_checkbox_control, get_checkbox_state, set_checkbox_state,
get_optional, set_control_enabled, set_control_text, get_control_text, translate_dialog,
msgbox,
)
log = logging.getLogger(__name__)
def _load_selection_token_controls(extend_ctrl, edit_extra_ctrl) -> None:
if extend_ctrl:
set_control_text(extend_ctrl, str(get_config_int("extend_selection_max_tokens")))
if edit_extra_ctrl:
set_control_text(edit_extra_ctrl, str(get_config_int("edit_selection_max_new_tokens")))
def _save_selection_token_controls(extend_ctrl, edit_extra_ctrl) -> None:
if extend_ctrl:
set_config("extend_selection_max_tokens", get_control_text(extend_ctrl))
if edit_extra_ctrl:
set_config("edit_selection_max_new_tokens", get_control_text(edit_extra_ctrl))
# ── Generic Helpers ──────────────────────────────────────────────────
def input_box(ctx, message, title="", default="", x=None, y=None):
"""Shows input dialog (EditInputDialog.xdl). Returns (result_text, extra_prompt) if OK, else ("", "")."""
init_logging(ctx)
log.debug("input_box: opening Edit Input dialog")
try:
smgr = ctx.getServiceManager()
base_url = get_extension_url()
dp = smgr.createInstanceWithContext("com.sun.star.awt.DialogProvider", ctx)
dlg_url = base_url + "/Dialogs/EditInputDialog.xdl"
dlg = dp.createDialog(dlg_url)
except Exception as e:
log.error("input_box: failed to create dialog: %s", e)
raise UnoObjectError(f"Failed to create dialog: {e}") from e
need_dispose = True
try:
translate_dialog(dlg)
dlg.getControl("label").getModel().Label = str(message)
set_control_text(dlg.getControl("edit"), str(default))
if title:
dlg.getModel().Title = title
prompt_ctrl = dlg.getControl("prompt_selector")
current_prompt = get_config_str("additional_instructions")
populate_combobox_with_lru(ctx, prompt_ctrl, current_prompt, "prompt_lru", "")
model_selector = get_optional(dlg, "model_selector")
if model_selector:
current_endpoint = get_current_endpoint()
current_model = get_text_model()
populate_combobox_with_lru(ctx, model_selector, current_model, "model_lru", current_endpoint)
extend_tokens_ctrl = get_optional(dlg, "extend_max_tokens")
extra_tokens_ctrl = get_optional(dlg, "edit_extra_tokens")
_load_selection_token_controls(extend_tokens_ctrl, extra_tokens_ctrl)
dlg.getControl("edit").setFocus()
dlg.getControl("edit").setSelection(uno.createUnoStruct("com.sun.star.awt.Selection", 0, len(str(default))))
if dlg.execute():
ret_text = get_control_text(dlg.getControl("edit"))
ret_prompt = prompt_ctrl.getText()
if model_selector:
chosen = model_selector.getText()
if chosen:
set_text_model(chosen, update_lru=True)
_save_selection_token_controls(extend_tokens_ctrl, extra_tokens_ctrl)
return ret_text, ret_prompt
# ESC/close: execute() returned false — skip dispose in finally (double dispose segfaults LO).
need_dispose = False
return "", ""
except Exception as e:
log.error("input_box error: %s", e)
raise UnoObjectError(f"Error in input_box: {e}") from e
finally:
if need_dispose:
dlg.dispose()
class SettingsDialog:
"""Manages the lifecycle of the WriterAgent Settings dialog."""
def __init__(self, ctx):
self._ctx = ctx
self._dlg = None
self._endpoint_listener = None
self._api_key_listener = None
self._scripting_venv_test_listener = None
self._ppt_master_data_test_listener = None
self._download_audio_listener = None
def show(self):
"""Execute the settings dialog and apply results."""
from .settings_dialog import get_settings_field_specs, apply_settings_result
log.debug("SettingsDialog.show entry")
init_logging(self._ctx)
try:
self._create_dialog()
if self._dlg is None:
return {}
field_specs = get_settings_field_specs(self._ctx)
current_endpoint = get_current_endpoint()
self._setup_tabs()
self._populate_fields(field_specs, current_endpoint)
self._schedule_initial_models_fetch(current_endpoint)
self._apply_sqlite_restrictions()
translate_dialog(self._dlg)
try:
self._dlg.getModel().Title = _("Settings")
except Exception:
pass
self._dlg.getControl("endpoint").setFocus()
if self._dlg.execute():
result = self._extract_results(field_specs)
if result:
try:
apply_settings_result(self._ctx, result)
return result
except ConfigValidationError as ve:
msgbox(self._ctx, _("Invalid Setting"), str(ve))
return {}
return {}
except Exception as e:
log.exception("Failed to open Settings")
msgbox(self._ctx, _("Error"), _("Failed to open Settings: {0}").format(e))
return format_error_payload(e)
finally:
self._cleanup()
def _create_dialog(self):
smgr = self._ctx.getServiceManager()
base_url = get_extension_url()
dp = smgr.createInstanceWithContext("com.sun.star.awt.DialogProvider", self._ctx)
dialog_url = base_url + "/Dialogs/SettingsDialog.xdl"
self._dlg = dp.createDialog(dialog_url)
def _setup_tabs(self):
assert self._dlg is not None
self._dlg.getControl("btn_tab_chat").addActionListener(TabListener(self._dlg, 1))
self._dlg.getControl("btn_tab_image").addActionListener(TabListener(self._dlg, 2))
edit_config_btn = get_optional(self._dlg, "btn_edit_config_json")
if edit_config_btn:
edit_config_btn.addActionListener(EditConfigListener(self._ctx))
self._setup_module_tabs()
test_venv_btn = get_optional(self._dlg, "scripting__test_venv")
if test_venv_btn:
self._scripting_venv_test_listener = ScriptingVenvTestListener(self._ctx, self._dlg)
test_venv_btn.addActionListener(self._scripting_venv_test_listener)
test_ppt_btn = get_optional(self._dlg, "scripting__test_ppt_master_data")
if test_ppt_btn:
self._ppt_master_data_test_listener = PptMasterDataTestListener(self._ctx, self._dlg)
test_ppt_btn.addActionListener(self._ppt_master_data_test_listener)
download_audio_btn = get_optional(self._dlg, "scripting__download_audio_binaries")
if download_audio_btn:
self._download_audio_listener = DownloadAudioListener(self._ctx, self._dlg)
download_audio_btn.addActionListener(self._download_audio_listener)
def _setup_module_tabs(self):
try:
# Register module tabs in the Settings dialog
setup_module_tabs(self._dlg)
except Exception:
pass
def _api_key_from_field_specs(self, field_specs):
for field in field_specs:
if field.get("name") == "api_key":
return str(field.get("value") or "")
return ""
def _populate_fields(self, field_specs, current_endpoint):
assert self._dlg is not None
from plugin.chatbot.config_ui_helpers import (
populate_combobox_with_lru, populate_image_model_selector, populate_endpoint_selector
)
api_key_val = self._api_key_from_field_specs(field_specs)
for field in field_specs:
ctrl = self._dlg.getControl(field["name"])
if not ctrl:
continue
name = field["name"]
val = field["value"]
if name == "text_model":
populate_combobox_with_lru(
self._ctx, ctrl, val, "model_lru", current_endpoint, api_key_override=api_key_val,
)
elif name == "image_model":
populate_image_model_selector(
self._ctx, ctrl, override_endpoint=current_endpoint, api_key_override=api_key_val,
)
elif name == "stt_model":
populate_combobox_with_lru(
self._ctx, ctrl, val, "audio_model_lru", current_endpoint, api_key_override=api_key_val,
)
elif name == "additional_instructions":
populate_combobox_with_lru(self._ctx, ctrl, val, "prompt_lru", "")
elif name == "endpoint":
populate_endpoint_selector(self._ctx, ctrl, val)
self._setup_endpoint_listener(ctrl)
elif name == "image_base_size":
populate_combobox_with_lru(self._ctx, ctrl, val, "image_base_size_lru", "")
else:
self._populate_generic_field(ctrl, field)
def _schedule_initial_models_fetch(self, endpoint):
"""OpenRouter/Together skip inline fetch; load full catalog when a saved key exists."""
from plugin.framework.config import get_api_key_for_endpoint
from plugin.framework.client.model_fetcher import get_provider_from_endpoint
listener = self._endpoint_listener
if not listener or not endpoint:
return
provider = get_provider_from_endpoint(endpoint)
if provider not in {"openrouter", "together"}:
return
if not str(get_api_key_for_endpoint(endpoint) or "").strip():
return
listener._schedule_debounced_models_fetch()
def _populate_generic_field(self, ctrl, field):
if is_checkbox_control(ctrl):
set_checkbox_state(ctrl, 1 if as_bool(field["value"]) else 0)
elif hasattr(ctrl, "setText"):
if "options" in field:
self._set_ctrl_options(ctrl, field)
ctrl.setText(str(field.get("value", "")))
else:
set_control_text(ctrl, field["value"])
def _set_ctrl_options(self, ctrl, field):
try:
opts = field["options"]
labels = tuple(o.get("label", o.get("value", "")) for o in opts if isinstance(o, dict))
model = ctrl.getModel()
if hasattr(model, "StringItemList"):
model.StringItemList = labels
except Exception as e:
log.error(f"Failed to set options for {field['name']}: {e}")
def _setup_endpoint_listener(self, ctrl):
if hasattr(ctrl, "addItemListener"):
self._endpoint_listener = EndpointCombinedListener(self._dlg, self._ctx, ctrl)
ctrl.addItemListener(self._endpoint_listener)
if hasattr(ctrl, "addTextListener"):
ctrl.addTextListener(self._endpoint_listener)
ak_ctrl = get_optional(self._dlg, "api_key")
if ak_ctrl and hasattr(ak_ctrl, "addTextListener"):
self._api_key_listener = ApiKeyTextListener(self._endpoint_listener)
ak_ctrl.addTextListener(self._api_key_listener)
def _apply_sqlite_restrictions(self):
if not HAS_SQLITE:
for name in (
"chatbot__web_cache_max_mb",
"chatbot__web_cache_validity_days",
"chatbot__web_research_cache_enabled",
):
ctrl = get_optional(self._dlg, name)
if ctrl:
set_control_enabled(ctrl, False)
def _extract_results(self, field_specs):
assert self._dlg is not None
result = {}
for field in field_specs:
name = field["name"]
ctrl = self._dlg.getControl(name)
if not ctrl:
result[name] = ""
continue
try:
if is_checkbox_control(ctrl):
result[name] = get_checkbox_state(ctrl) == 1
elif hasattr(ctrl, "getText"):
result[name] = ctrl.getText()
else:
result[name] = get_control_text(ctrl)
except Exception as e:
log.error(f"Failed to extract field {name}: {e}")
result[name] = ""
return result
def _cleanup(self):
if self._api_key_listener:
ak = get_optional(self._dlg, "api_key")
if ak and hasattr(ak, "removeTextListener"):
ak.removeTextListener(self._api_key_listener)
if self._endpoint_listener:
self._endpoint_listener.close()
if self._scripting_venv_test_listener and self._dlg is not None:
test_venv_btn = get_optional(self._dlg, "scripting__test_venv")
if test_venv_btn and hasattr(test_venv_btn, "removeActionListener"):
try:
test_venv_btn.removeActionListener(self._scripting_venv_test_listener)
except Exception:
pass
self._scripting_venv_test_listener = None
if self._ppt_master_data_test_listener and self._dlg is not None:
test_ppt_btn = get_optional(self._dlg, "scripting__test_ppt_master_data")
if test_ppt_btn and hasattr(test_ppt_btn, "removeActionListener"):
try:
test_ppt_btn.removeActionListener(self._ppt_master_data_test_listener)
except Exception:
pass
self._ppt_master_data_test_listener = None
if self._download_audio_listener and self._dlg is not None:
download_audio_btn = get_optional(self._dlg, "scripting__download_audio_binaries")
if download_audio_btn and hasattr(download_audio_btn, "removeActionListener"):
try:
download_audio_btn.removeActionListener(self._download_audio_listener)
except Exception:
pass
self._download_audio_listener = None
if self._dlg:
self._dlg.dispose()
def settings_box(ctx, **kwargs):
"""Entry point for settings dialog."""
return SettingsDialog(ctx).show()
# ── Listeners ────────────────────────────────────────────────────────
class EditConfigListener(BaseActionListener):
def __init__(self, ctx):
self._ctx = ctx
def on_action_performed(self, rEvent):
from .external_editor import open_writeragent_json_in_editor
open_writeragent_json_in_editor(self._ctx)
def _dialog_parent_for_child(ctx, parent_dlg):
"""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 PptMasterDataTestListener(BaseActionListener):
"""Settings → Python: verify ppt-master skill tree at the path in the text field (saved or not)."""
def __init__(self, ctx, dlg):
self._ctx = ctx
self._dlg = dlg
def on_action_performed(self, rEvent):
from plugin.ppt_master.paths import probe_data_path_with_progress
path_ctrl = get_optional(self._dlg, "scripting__ppt_master_data_path")
raw = get_control_text(path_ctrl) if path_ctrl else ""
def probe(on_display, on_status):
return probe_data_path_with_progress(raw, on_display, on_status=on_status)
VenvProbeProgressDialog(self._ctx, parent_dlg=self._dlg).run_modal_probe(probe)
class ApiKeyTextListener(BaseListener, XTextListener):
def __init__(self, endpoint_listener):
self._el = endpoint_listener
def textChanged(self, rEvent):
self._el._schedule_debounced_models_fetch()
class EndpointCombinedListener(BaseListener, XItemListener, XTextListener):
def __init__(self, dialog, context, combo_ctrl):
from plugin.framework.queue_executor import post_to_main_thread
from plugin.framework.worker_pool import run_in_background
from plugin.framework.config import get_api_key_for_endpoint
from plugin.chatbot.config_ui_helpers import (
populate_combobox_with_lru, populate_image_model_selector, endpoint_from_selector_text,
_sanitize_model_combobox_value,
)
from plugin.framework.client.model_fetcher import (
endpoint_url_suitable_for_v1_models_fetch, fetch_available_models, fetch_available_image_models,
get_provider_from_endpoint, get_image_model,
)
self._dlg = dialog
self._ctx = context
self._ctrl = combo_ctrl
self._debounce_gen = 0
self._closed = False
self._timer = None
self.post_to_main_thread = post_to_main_thread
self.run_in_background = run_in_background
self.get_api_key_for_endpoint = get_api_key_for_endpoint
self.populate_combobox_with_lru = populate_combobox_with_lru
self.populate_image_model_selector = populate_image_model_selector
self.endpoint_from_selector_text = endpoint_from_selector_text
self.endpoint_url_suitable_for_v1_models_fetch = endpoint_url_suitable_for_v1_models_fetch
self.fetch_available_models = fetch_available_models
self.fetch_available_image_models = fetch_available_image_models
self._sanitize_model_combobox_value = _sanitize_model_combobox_value
self.get_provider_from_endpoint = get_provider_from_endpoint
self.get_image_model = get_image_model
def _live_api_key(self):
ak_ctrl = get_optional(self._dlg, "api_key")
return str(get_control_text(ak_ctrl)) if ak_ctrl else ""
def _apply_dropdowns(self, resolved, models=None, skip_fetch=False):
api_key_ov = self._live_api_key()
populate_kw = {"api_key_override": api_key_ov, "skip_remote_fetch": skip_fetch}
resolved_provider = self.get_provider_from_endpoint(resolved)
saved_provider = self.get_provider_from_endpoint(get_current_endpoint())
same_provider = bool(resolved_provider and resolved_provider == saved_provider)
text_ctrl = get_optional(self._dlg, "text_model")
if text_ctrl:
current = self._sanitize_model_combobox_value(str(text_ctrl.getText() or ""))
if not current:
current = get_text_model() if same_provider else ""
self.populate_combobox_with_lru(
self._ctx,
text_ctrl,
current,
"model_lru",
resolved,
remote_models=models,
**populate_kw,
)
stt_ctrl = get_optional(self._dlg, "stt_model")
if stt_ctrl:
stt_val = self._sanitize_model_combobox_value(str(stt_ctrl.getText() or ""))
if not stt_val:
if same_provider:
stt_val = str(get_config("stt_model") or get_stt_model() or "")
else:
stt_val = ""
stt_remote = None if resolved_provider in {"openrouter", "together"} else models
self.populate_combobox_with_lru(
self._ctx,
stt_ctrl,
stt_val,
"audio_model_lru",
resolved,
remote_models=stt_remote,
**populate_kw,
)
image_ctrl = get_optional(self._dlg, "image_model")
if image_ctrl:
image_models = (
self.fetch_available_image_models(resolved, api_key_override=api_key_ov)
if models is not None
else None
)
image_val = self._sanitize_model_combobox_value(str(image_ctrl.getText() or ""))
if not image_val:
image_val = str(self.get_image_model() or "")
self.populate_combobox_with_lru(
self._ctx,
image_ctrl,
image_val,
"image_model_lru",
resolved,
remote_models=image_models,
**populate_kw,
)
def close(self):
self._closed = True
self._debounce_gen += 1
if self._timer:
self._timer.cancel()
def _sync_api_key(self):
resolved = self.endpoint_from_selector_text(self._ctrl.getText())
if not resolved: return
ak_ctrl = get_optional(self._dlg, "api_key")
if ak_ctrl:
set_control_text(ak_ctrl, self.get_api_key_for_endpoint(resolved))
def _bg_fetch(self, gen, resolved):
if self._closed or gen != self._debounce_gen: return
ak_ctrl = get_optional(self._dlg, "api_key")
key_ov = str(get_control_text(ak_ctrl)) if ak_ctrl else None
models = None
if resolved and self.endpoint_url_suitable_for_v1_models_fetch(resolved):
models = self.fetch_available_models(resolved, api_key_override=key_ov)
def apply_ui():
if self._closed or gen != self._debounce_gen: return
if self.endpoint_from_selector_text(self._ctrl.getText()) != resolved: return
self._apply_dropdowns(resolved, models=models, skip_fetch=(models is None))
self.post_to_main_thread(apply_ui)
def _schedule_debounced_models_fetch(self):
if self._timer: self._timer.cancel()
self._debounce_gen += 1
gen = self._debounce_gen
self._timer = threading.Timer(1.0, lambda: self.post_to_main_thread(lambda: self._run_fetch(gen)))
self._timer.daemon = True
self._timer.start()
def _run_fetch(self, gen):
resolved = self.endpoint_from_selector_text(self._ctrl.getText())
if resolved:
self.run_in_background(lambda: self._bg_fetch(gen, resolved), name="settings-fetch")
def textChanged(self, rEvent):
self._sync_api_key()
self._schedule_debounced_models_fetch()
def itemStateChanged(self, rEvent):
idx = getattr(rEvent, "Selected", -1)
if idx < 0: return
item = self._ctrl.getItem(idx)
if not item: return
url = self.endpoint_from_selector_text(item)
if url: self._ctrl.setText(url)
if self._timer: self._timer.cancel()
self._debounce_gen += 1
resolved = self.endpoint_from_selector_text(self._ctrl.getText())
if resolved:
self._sync_api_key()
provider = self.get_provider_from_endpoint(resolved)
skip_sync_fetch = provider in {"openrouter", "together"}
self._apply_dropdowns(resolved, models=None, skip_fetch=skip_sync_fetch)
self.run_in_background(lambda: self._bg_fetch(self._debounce_gen, resolved), name="settings-select")
# ── Evaluation Dashboard ─────────────────────────────────────────────
class EvalDashboard:
def __init__(self, ctx):
self._ctx = ctx
self._dlg = None
def show(self):
smgr = self._ctx.getServiceManager()
base_url = get_extension_url()
dp = smgr.createInstanceWithContext("com.sun.star.awt.DialogProvider", self._ctx)
self._dlg = dp.createDialog(base_url + "/Dialogs/EvalDialog.xdl")
try:
self._populate()
if self._dlg:
self._dlg.execute()
finally:
self._dlg.dispose()
def _populate(self):
assert self._dlg is not None
endpoint_ctrl = self._dlg.getControl("endpoint")
set_control_text(endpoint_ctrl, get_config_str("endpoint"))
model_ctrl = self._dlg.getControl("models")
current_model = str(get_text_model())
current_endpoint = get_config_str("endpoint").strip()
populate_combobox_with_lru(self._ctx, model_ctrl, current_model, "model_lru", current_endpoint)
self._dlg.getControl("btn_run").addActionListener(EvalRunListener(self._ctx, self._dlg))
self._dlg.getControl("btn_close").addActionListener(SimpleCloseListener(self._dlg))
class EvalRunListener(BaseActionListener):
def __init__(self, ctx, dialog):
self.ctx = ctx
self.dialog = dialog
self.is_running = False
def on_action_performed(self, rEvent):
if self.is_running: return
self.is_running = True
try:
self.run_suite()
finally:
self.is_running = False
def run_suite(self):
from tests.eval_runner import run_benchmark_suite
toolkit = get_toolkit(self.ctx)
model_name = self.dialog.getControl("models").getText()
categories = []
for cat in ("writer", "calc", "draw", "multimodal"):
if self.dialog.getControl(f"cat_{cat}").getState():
categories.append(cat.capitalize())
self.dialog.getControl("log_area").setText(f"Starting benchmark for {model_name}...\n")
self.dialog.getControl("status").setText("Running...")
if toolkit:
toolkit.processEventsToIdle()
doc = get_active_document(self.ctx)
summary = run_benchmark_suite(self.ctx, doc, model_name, categories)
log_text = f"Benchmarks Complete for {model_name}!\n"
log_text += f"Passed: {summary['passed']}, Failed: {summary['failed']}\n"
log_text += f"Total Est. Cost: ${summary['total_cost']:.4f}\n\n Details:\n"
for res in summary["results"]:
log_text += f"[{res['status']}] {res['name']} ({res.get('latency', 0):.1f}s)\n"
self.dialog.getControl("log_area").setText(log_text)
self.dialog.getControl("status").setText("Finished")
class SimpleCloseListener(BaseActionListener):
def __init__(self, dialog):
self.dialog = dialog
def on_action_performed(self, rEvent):
self.dialog.endDialog(0)
def show_eval_dashboard(ctx):
EvalDashboard(ctx).show()
# ── Helper for module tabs ───────────────────────────────────────────
def setup_module_tabs(dlg):
"""Register action listeners for module-specific tabs in the Settings dialog."""
try:
from plugin._manifest import MODULES
from plugin.chatbot.settings_tab_order import iter_settings_tab_modules
# Map button ID to step index (starting from 3 for module tabs)
# Core tabs: 1=Chat, 2=Image
step = 3
for m in iter_settings_tab_modules(MODULES):
m_name = str(m.get("name", ""))
prefix = m_name.replace(".", "_")
btn_id = f"btn_tab_{prefix}"
btn = get_optional(dlg, btn_id)
if btn:
btn.addActionListener(TabListener(dlg, step))
step += 1
except ImportError:
pass
except Exception as e:
log.error(f"Failed to setup module tabs: {e}")
class DownloadAudioListener(BaseActionListener):
"""Settings → Python: download audio binaries and pure Python dependencies from GitHub."""
def __init__(self, ctx, dlg):
self._ctx = ctx
self._dlg = dlg
def on_action_performed(self, rEvent):
from plugin.scripting.audio_recorder_service import run_audio_download
def probe(on_display, on_status):
ok = run_audio_download(on_display, on_status)
return ok, ""
VenvProbeProgressDialog(self._ctx, parent_dlg=self._dlg).run_modal_probe(
probe, title=_("Audio Library Download")
)