Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
644 lines (559 loc) · 25.5 KB
/
Copy pathapp.py
File metadata and controls
644 lines (559 loc) · 25.5 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
"""Application controller: wires the tray, hotkey, main window and injector."""
from __future__ import annotations
from typing import Optional
from PySide6.QtCore import QCoreApplication, QObject, QTimer
from PySide6.QtWidgets import QApplication, QMessageBox
import config
from models.tree import Folder, Settings, Snippet, nodes_from_raw, nodes_to_raw
from services import autostart as autostart_svc
from services import context as context_svc
from services import edition as edition_svc
from services import focus as focus_svc
from services import icons as icons_svc
from services import injector as injector_svc
from services import team_pack as team_pack_svc
from services import tokens as tokens_svc
from services.database import DatabaseRegistry
from services.hotkey_manager import HotkeyManager
from services.theme import ThemeService
from services.translation import (
TranslationError,
TranslationService,
text_has_translations,
translation_pairs_in_text,
)
from ui.about_dialog import AboutDialog
from ui.main_window import MainWindow
from ui.options_dialog import OptionsDialog
from ui.popup_menu import close_current as popup_close
from ui.popup_menu import is_open as popup_is_open
from ui.popup_menu import toggle_popup
from ui.raw_text_dialog import RawTextDialog
from ui.tray import Tray
APP_VERSION = "1.3.0"
def _top_level_folders(nodes):
"""Yield every top-level ``Folder`` in ``nodes`` (ignores snippets
and does not recurse). Used to build the folder-scoped hotkey
bindings in :meth:`Poltergeist._reinstall_hotkeys`."""
for n in nodes:
if isinstance(n, Folder):
yield n
class Poltergeist(QObject):
def __init__(self, qt_app: QApplication) -> None:
super().__init__()
self._qt_app = qt_app
data = config.load()
self._settings = Settings.from_dict(data.get("settings") or {})
self._personal_nodes = nodes_from_raw(data.get("tree_personal") or [])
self._team_nodes = nodes_from_raw(data.get("tree_team") or [])
# One-time cleanup: the "Start with Windows" checkbox is
# hidden from the UI pending security review (see note in
# ``ui/options_dialog.py``). If a previous session had it
# enabled, take the Startup-folder .lnk down here and persist
# the flipped flag immediately so a user who force-kills the
# app moments later doesn't boot-autostart again. Remove this
# block (and re-show the checkbox) once the feature is
# approved by cyber defense.
self._scrub_autostart_once(data)
self._theme = ThemeService(self)
icons_svc.bind_theme(self._theme)
self._theme.set_mode(self._settings.theme)
self._hotkey = HotkeyManager(self)
self._hotkey.triggered.connect(self._on_hotkey)
self._translation = TranslationService(self._settings.deepl_api_key, self)
self._translation.validity_changed.connect(self._on_translation_validity)
self._tray = Tray(self)
self._tray.open_requested.connect(self._show_main_window)
self._tray.options_requested.connect(self._show_options)
self._tray.about_requested.connect(self._show_about)
self._tray.pause_toggled.connect(self._on_pause_toggled)
self._tray.exit_requested.connect(self._quit)
self._main_window = MainWindow(self._settings)
self._main_window.set_is_light(self._theme.is_light())
self._main_window.refresh_icons()
self._main_window.set_translation_available(self._translation.is_valid())
self._main_window.load(self._personal_nodes, self._team_nodes)
self._reinstall_hotkeys()
self._main_window.tree_changed.connect(self._persist)
self._main_window.shortcuts_changed.connect(self._on_shortcuts_changed)
self._main_window.options_requested.connect(self._show_options)
self._main_window.about_requested.connect(self._show_about)
self._main_window.theme_toggle_requested.connect(self._cycle_theme)
self._main_window.publish_team_requested.connect(
self._on_publish_team_requested
)
self._theme.changed.connect(self._on_theme_changed)
self._saved_hwnd: Optional[int] = None
self._save_timer = QTimer(self)
self._save_timer.setSingleShot(True)
self._save_timer.setInterval(150)
self._save_timer.timeout.connect(self._write_now)
self._team_loader: Optional[team_pack_svc.TeamPackLoader] = None
self._team_share_status = team_pack_svc.ShareStatus.UNCONFIGURED
self._team_manifest_version = 0
self._team_poll_timer = QTimer(self)
self._team_poll_timer.setInterval(5 * 60 * 1000)
self._team_poll_timer.timeout.connect(self._poll_team_share)
self._databases = DatabaseRegistry()
self._current_context: dict[str, str] = {}
self._tray.show()
if not self._personal_nodes and not self._team_nodes:
self._show_main_window()
self._tray.notify(
QCoreApplication.translate("Poltergeist", "Poltergeist is running"),
QCoreApplication.translate(
"Poltergeist",
"Activate with {0}. Right-click the tray icon for more.",
).format(self._settings.hotkey),
)
if self._settings.deepl_api_key.strip():
QTimer.singleShot(0, self._translation.validate)
self._reload_databases()
if not edition_svc.is_admin() and self._settings.team_share_path:
QTimer.singleShot(0, self._refresh_team_pack_async)
self._team_poll_timer.start()
def shutdown(self) -> None:
self._write_now()
self._hotkey.shutdown()
self._tray.hide()
def _on_hotkey(self, name: str) -> None:
"""Slot for :data:`HotkeyManager.triggered`.
``name`` identifies which binding fired. ``"main"`` opens the
global popup with every snippet; ``"personal:<id>"`` and
``"team:<id>"`` open the popup scoped to that top-level
folder's subtree.
"""
if popup_is_open():
popup_close()
return
if name == "main":
nodes = self._main_window.dump_all_nodes()
elif name.startswith("team:"):
nodes = self._folder_subtree(
self._main_window.dump_team_nodes(), name[len("team:") :]
)
elif name.startswith("personal:"):
nodes = self._folder_subtree(
self._main_window.dump_personal_nodes(), name[len("personal:") :]
)
else:
return
if not nodes:
return
self._saved_hwnd = focus_svc.get_foreground()
self._current_context = self._capture_context()
toggle_popup(
nodes,
self._on_snippet_chosen,
context=self._current_context,
)
def _capture_context(self) -> dict[str, str]:
"""Read the clipboard and run it through the user's context
patterns. Returns an empty dict when there's no clipboard
text or no patterns configured."""
clipboard_text = ""
try:
cb = QApplication.clipboard()
if cb is not None:
clipboard_text = cb.text() or ""
except Exception:
clipboard_text = ""
return context_svc.parse(clipboard_text, self._settings.context_patterns)
@staticmethod
def _folder_subtree(nodes, folder_id: str):
for n in nodes:
if isinstance(n, Folder) and n.id == folder_id:
return list(n.children)
return []
def _reinstall_hotkeys(self) -> None:
"""Recompute the full hotkey set and hand it to the manager.
Order matters: HotkeyManager.install registers bindings in
iteration order and first-in wins on conflicts. We therefore
list team-folder shortcuts first, then personal-folder ones,
then the main popup hotkey - that gives the 'team > personal
> main' precedence the design calls for."""
bindings: list[tuple[str, str]] = []
for folder in _top_level_folders(self._main_window.dump_team_nodes()):
hk = self._settings.team_shortcuts.get(folder.id) or folder.shortcut
if hk:
bindings.append((f"team:{folder.id}", hk))
for folder in _top_level_folders(self._main_window.dump_personal_nodes()):
if folder.shortcut:
bindings.append((f"personal:{folder.id}", folder.shortcut))
if self._settings.hotkey:
bindings.append(("main", self._settings.hotkey))
skipped = self._hotkey.install(bindings)
if skipped:
for name, reason in skipped.items():
print(f"[hotkey] skipped {name}: {reason}")
def _on_shortcuts_changed(self) -> None:
self._reinstall_hotkeys()
self._persist()
def _refresh_team_pack_async(
self,
*,
on_done=None,
force: bool = False,
) -> None:
"""Trigger a background read of the team pack.
``force=False`` (the default, used by the periodic poll)
short-circuits if a load is already in flight. ``on_done`` is
an optional callback the caller gets after the normal apply
path runs - used by the Options dialog to close its progress
indicator."""
if self._team_loader is not None and not force:
return
share = self._settings.team_share_path
if not share:
self._team_share_status = team_pack_svc.ShareStatus.UNCONFIGURED
if on_done is not None:
on_done(team_pack_svc.TeamPack())
return
def _handle(pack):
self._team_loader = None
self._on_team_pack_loaded(pack)
if on_done is not None:
on_done(pack)
self._team_loader = team_pack_svc.load_async(share, _handle, parent=self)
def _on_team_pack_loaded(self, pack) -> None:
"""Apply a freshly-loaded team pack to the UI.
User edition: always replace the Team tab contents with what
came back. If we only got a cached pack (share unreachable),
we still apply it so the user keeps working - the next poll
will pick up the real share.
Admin edition: this path is only entered when the admin
explicitly pressed 'Refresh from share' in Options, so we
overwrite their local working copy too. The confirmation
dialog 'discard local changes?' lives in the Options
dialog, not here."""
self._team_share_status = pack.source
self._team_manifest_version = pack.manifest.version
if pack.source == team_pack_svc.ShareStatus.UNCONFIGURED and not pack.tree:
return
self._main_window.load_team(pack.tree)
self._reload_databases()
self._reinstall_hotkeys()
self._persist()
def _snippet_lookup(self, name: str) -> Optional[str]:
"""Resolve ``{INCLUDE=<name>}`` references by snippet name.
Walks the personal + team trees, returning the body text of
the first snippet whose name matches (case-insensitive, whole
name, leading/trailing whitespace ignored). Returns ``None``
when no such snippet exists so the token expander can emit an
empty string for that reference instead of raising.
We search every time rather than caching because snippet
names can be renamed at will and the cost is trivial - the
tree is at most a few hundred nodes."""
if not name:
return None
needle = name.strip().lower()
if not needle:
return None
def _walk(nodes) -> Optional[str]:
for node in nodes:
if isinstance(node, Snippet):
if (node.name or "").strip().lower() == needle:
return node.text
else:
found = _walk(node.children)
if found is not None:
return found
return None
found = _walk(self._main_window.dump_personal_nodes())
if found is not None:
return found
return _walk(self._main_window.dump_team_nodes())
def _reload_databases(self) -> None:
"""Rebuild the DatabaseRegistry from the currently-configured
share path. Safe to call on the UI thread - file IO is small
(CSV / XLSX headers and a few thousand rows tops)."""
try:
self._databases.load_from_sources(self._settings.team_share_path)
except Exception as exc:
print(f"[database] load failed: {exc}")
def _poll_team_share(self) -> None:
"""Periodic poll (user edition only) that checks manifest
version and refreshes the pack when the admin has published a
newer one. The reachability check itself is a tiny manifest
read on the UI thread; the full refresh only starts when
there's actually new content to pull in."""
share = self._settings.team_share_path
if not share:
return
from pathlib import Path as _Path
try:
root = _Path(share)
manifest_path = root / team_pack_svc.MANIFEST_BASENAME
if not manifest_path.is_file():
return
import json as _json
data = _json.loads(manifest_path.read_text(encoding="utf-8"))
except (OSError, ValueError, TypeError):
return
remote_manifest = team_pack_svc.TeamManifest.from_dict(data)
if remote_manifest.version > self._team_manifest_version:
self._refresh_team_pack_async()
def refresh_team_pack(self, *, on_done=None) -> None:
"""Public entry point for the Options dialog 'Refresh from
share' button. Always forces a reload."""
self._refresh_team_pack_async(on_done=on_done, force=True)
def publish_team_pack(self) -> team_pack_svc.TeamManifest:
"""Admin-only: push the current Team tab contents to the
share. Returns the fresh manifest. Raises on failure so the
caller can surface a clear error message."""
if not edition_svc.is_admin():
raise PermissionError("Only the admin edition may publish")
share = self._settings.team_share_path
if not share:
raise FileNotFoundError("No team share path configured")
tree = self._main_window.dump_team_nodes()
manifest = team_pack_svc.publish_to_share(share, tree)
self._team_manifest_version = manifest.version
self._team_share_status = team_pack_svc.ShareStatus.REACHABLE
return manifest
def team_share_status(self) -> team_pack_svc.ShareStatus:
return self._team_share_status
def team_manifest_version(self) -> int:
return self._team_manifest_version
def _on_publish_team_requested(self) -> None:
"""Admin clicked the toolbar's 'Publish to team share' button.
Same flow as the Options dialog's Publish action, but with
the confirm / result dialogs parented to the main window so
the admin never has to open Options just to publish."""
if not self._settings.team_share_path:
QMessageBox.information(
self._main_window,
QCoreApplication.translate("Poltergeist", "Publish to team share"),
QCoreApplication.translate(
"Poltergeist",
"No team share path is configured. Set one in Options first.",
),
)
return
choice = QMessageBox.question(
self._main_window,
QCoreApplication.translate("Poltergeist", "Publish to team share"),
QCoreApplication.translate(
"Poltergeist",
"Publish the current Team tree to the shared drive? "
"All users will pick up the new version on their next "
"refresh.",
),
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No,
)
if choice != QMessageBox.StandardButton.Yes:
return
try:
manifest = self.publish_team_pack()
except Exception as exc:
QMessageBox.warning(
self._main_window,
QCoreApplication.translate("Poltergeist", "Publish failed"),
str(exc),
)
return
self._tray.notify(
QCoreApplication.translate("Poltergeist", "Team pack published"),
QCoreApplication.translate(
"Poltergeist", "Deployed pack v{0} to the share."
).format(manifest.version),
)
def _on_snippet_chosen(self, snippet: Snippet) -> None:
target = self._saved_hwnd
self._saved_hwnd = None
mode = snippet.injection or self._settings.default_injection
expanded_override: Optional[str] = None
translation_body_override: Optional[str] = None
try:
if getattr(snippet, "prompt_untranslated_before_paste", True):
prepared = tokens_svc.expand_includes(
snippet.text, self._snippet_lookup
)
prepared = tokens_svc.expand_conditionals(
prepared, self._current_context
)
if text_has_translations(prepared):
preview_text, shared_translation_source = (
injector_svc.build_untranslated_preview(
snippet.text,
default_date_format=self._settings.default_date_format,
context=self._current_context,
databases=self._databases,
snippet_lookup=self._snippet_lookup,
)
)
dialog = RawTextDialog(preview_text, parent=None)
if dialog.exec() != dialog.DialogCode.Accepted:
return
edited = dialog.edited_text()
if edited != preview_text:
if shared_translation_source:
translation_body_override = edited
elif text_has_translations(snippet.text):
pairs = translation_pairs_in_text(snippet.text)
if len(pairs) != 1:
raise TranslationError(
"Edited translation preview requires exactly one "
"{TRANSLATION=...} language pair in the snippet."
)
src_lang, tgt_lang = next(iter(pairs))
expanded_override = self._translation.translate_plain_text(
edited,
source_lang=src_lang,
target_lang=tgt_lang,
)
else:
expanded_override = edited
injector_svc.inject(
snippet.text,
mode=mode,
default_date_format=self._settings.default_date_format,
target_hwnd=target,
translation=self._translation,
context=self._current_context,
databases=self._databases,
snippet_lookup=self._snippet_lookup,
expanded_override=expanded_override,
translation_body_override=translation_body_override,
)
except TranslationError as exc:
QMessageBox.warning(
None,
QCoreApplication.translate("Poltergeist", "Translation failed"),
str(exc),
)
def _show_main_window(self) -> None:
self._main_window.showNormal()
self._main_window.raise_()
self._main_window.activateWindow()
def _show_options(self) -> None:
dialog = OptionsDialog(
self._settings,
APP_VERSION,
translation=self._translation,
controller=self,
parent=self._main_window,
)
if dialog.exec() != dialog.DialogCode.Accepted:
return
new_settings = dialog.result_settings()
self._apply_settings(new_settings)
def _show_about(self) -> None:
parent = self._main_window if self._main_window.isVisible() else None
dialog = AboutDialog(APP_VERSION, parent=parent)
dialog.exec()
def _apply_settings(self, new: Settings) -> None:
autostart_changed = new.start_with_windows != self._settings.start_with_windows
hotkey_changed = new.hotkey != self._settings.hotkey
theme_changed = new.theme != self._settings.theme
deepl_changed = new.deepl_api_key != self._settings.deepl_api_key
language_changed = new.language != self._settings.language
share_changed = new.team_share_path != self._settings.team_share_path
self._settings = new
self._main_window.set_settings(new)
if language_changed:
QMessageBox.information(
self._main_window,
QCoreApplication.translate("Poltergeist", "Language changed"),
QCoreApplication.translate(
"Poltergeist",
"The new language will be applied the next time you "
"start Poltergeist.",
),
)
if hotkey_changed:
self._reinstall_hotkeys()
if theme_changed:
self._theme.set_mode(new.theme)
if autostart_changed:
err = autostart_svc.apply(new.start_with_windows)
if err:
QMessageBox.warning(
self._main_window,
QCoreApplication.translate("Poltergeist", "Autostart"),
err,
)
if deepl_changed:
already_in_sync = self._translation.api_key() == new.deepl_api_key.strip()
if not already_in_sync:
self._translation.set_api_key(new.deepl_api_key)
if new.deepl_api_key.strip():
self._translation.validate()
if share_changed:
if new.team_share_path and not edition_svc.is_admin():
if not self._team_poll_timer.isActive():
self._team_poll_timer.start()
QTimer.singleShot(0, self._refresh_team_pack_async)
elif not new.team_share_path:
self._team_poll_timer.stop()
self._reload_databases()
self._persist()
def _on_translation_validity(self, valid: bool, _message: str) -> None:
self._main_window.set_translation_available(valid)
def _on_pause_toggled(self, paused: bool) -> None:
self._hotkey.set_paused(paused)
def _cycle_theme(self) -> None:
new_mode = "dark" if self._theme.is_light() else "light"
self._theme.set_mode(new_mode)
self._settings.theme = new_mode
self._main_window.set_settings(self._settings)
self._persist()
def _on_theme_changed(self, is_light: bool) -> None:
icons_svc.bind_theme(self._theme)
self._main_window.set_is_light(is_light)
self._main_window.refresh_icons()
self._tray.refresh_icons()
def _scrub_autostart_once(self, data: dict) -> None:
"""Disable Windows autostart for any user who still has it on
and persist the cleared flag immediately so the cleanup only
runs once per affected user.
Rationale: the "Start with Windows" checkbox was hidden from
the UI after the corporate cyber defense team flagged the
Startup-folder .lnk as an unreviewed persistence mechanism.
Hiding the checkbox alone doesn't help users who'd previously
opted in - they'd keep autostarting silently forever. This
method takes the .lnk down and flips the persisted setting to
False, so the feature is genuinely off across the whole team
after the next launch.
``data`` is the raw dict returned by :func:`config.load`; we
mutate its ``settings.start_with_windows`` and write it back
directly rather than going through the normal save pipeline
(which isn't wired up yet at __init__ time). The write is
best-effort: if it fails the scrub simply runs again on the
next launch, which is idempotent.
Remove this method (and its caller, plus the
``setVisible(False)`` on the checkbox in ``OptionsDialog``)
when cyber defense has approved the app and the feature can
come back.
"""
if not self._settings.start_with_windows:
return
autostart_svc.apply(False)
self._settings.start_with_windows = False
settings_dict = data.setdefault("settings", {})
settings_dict["start_with_windows"] = False
try:
config.save(data)
except OSError:
pass
def _persist(self) -> None:
self._save_timer.start()
def _write_now(self) -> None:
data = {
"version": 2,
"settings": self._settings.to_dict(),
"tree_personal": nodes_to_raw(self._main_window.dump_personal_nodes()),
"tree_team": nodes_to_raw(self._main_window.dump_team_nodes()),
}
try:
config.save(data)
except Exception as exc:
QMessageBox.warning(
self._main_window,
QCoreApplication.translate("Poltergeist", "Save failed"),
str(exc),
)
def _quit(self) -> None:
self.shutdown()
self._qt_app.quit()