Repository navigation
Expand file tree
/
Copy pathdesktop.py
More file actions
1741 lines (1615 loc) · 90.2 KB
/
Copy pathdesktop.py
File metadata and controls
1741 lines (1615 loc) · 90.2 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
"""Light Windows desktop client for the local dictation engine."""
import ctypes
import faulthandler
import json
import ntpath
import os
import queue
import subprocess
import sys
import time
import tkinter as tk
from tkinter import ttk, messagebox
import webbrowser
import winreg
from ctypes import wintypes
from datetime import date, time as clock_time, timedelta
from pathlib import Path
from urllib.parse import urlsplit
from ipc_protocol import APP_DIR
from app_update import MANUAL_COOLDOWN, UpdateManager, installed_version
from pill import Pill
from windows_support import ChildJob
PREFERENCES = APP_DIR / "ui.json"
def model_controls(value):
state = value.get("state", "missing")
if state in ("deleting", "pausing", "canceling"):
return ()
if state == "verifying":
return ("pause", "cancel") if value.get("operation") in ("download", "repair") else ()
if state == "downloading":
return ("pause", "cancel")
if state == "paused":
return ("resume", "cancel")
if state == "ready" or value.get("installed") or value.get("operation") == "delete":
return ("verify", "delete")
if value.get("partial"):
return ("resume", "cancel")
if state == "failed":
return ("retry",)
return ("download",)
ASSETS = Path(__file__).resolve().parent / "assets"
RELEASES = "https://github.com/ABhattacharya-dev/stt-core-structure/releases"
LIGHT = {"bg": "#FFFFFF", "side": "#F4F4F2", "card": "#FFFFFF", "text": "#18181B",
"muted": "#71717A", "soft": "#A1A1AA", "line": "#E7E7E4", "accent": "#18181B",
"button": "#ECEAE3", "link": "#7C3AED", "subtle": "#FAF8F5", "value": "#F4F4F2",
"banner": "#FCFBF3", "banner_line": "#EFEBD9", "danger": "#EF4444",
"focus": "#F3E8FF"}
DARK = {"bg": "#1F1F1E", "side": "#292927", "card": "#32322F", "text": "#F4F0E9",
"muted": "#B9B3A9", "soft": "#8D887F", "line": "#454541", "accent": "#F4F0E9",
"button": "#3C3C38", "link": "#AD86FF", "subtle": "#292927", "value": "#3C3C38",
"banner": "#302D24", "banner_line": "#484236", "danger": "#FF7777",
"focus": "#46345B"}
FONT_FILES = {"sans": ("Figtree", "Figtree.ttf"),
"serif": ("EB Garamond", "EBGaramond.ttf"),
"mono": ("JetBrains Mono", "JetBrainsMono.ttf")}
SHORTCUT_LABELS = {"app": ("App", "App path"),
"directory": ("Folder Directory", "Folder path"),
"url": ("Website", "Website URL")}
def shortcut_target(kind, text):
value = text.strip()
if kind == "url":
try:
url = urlsplit(value)
if url.scheme not in ("http", "https") or not url.hostname or any(c.isspace() for c in value):
raise ValueError()
url.port
except ValueError as exc:
raise ValueError("Website URL must be a valid http or https address.") from exc
return value
while len(value) >= 2 and (value[0], value[-1]) in (("<", ">"), ("'", "'"), ('"', '"')):
value = value[1:-1].strip()
value = value.replace("/", "\\")
tail = value[2:] if len(value) >= 2 and value[1] == ":" else value
if any(char in '<>:"|?*' or ord(char) < 32 for char in tail):
raise ValueError("Path contains characters Windows does not allow.")
if not Path(value).is_absolute():
raise ValueError("Use an absolute Windows path, such as C:\\Apps\\App.exe.")
if kind == "app" and Path(value).suffix.casefold() not in (".exe", ".lnk"):
raise ValueError("App path must end in .exe or .lnk.")
return ntpath.normpath(value)
def system_dark():
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize") as key:
return winreg.QueryValueEx(key, "AppsUseLightTheme")[0] == 0
except OSError:
return False
def history_heading(value, today=None):
today = today or date.today()
try:
day = date.fromisoformat(value)
except (TypeError, ValueError):
return value or "Unknown date"
if day == today:
return "Today"
if day == today - timedelta(days=1):
return "Yesterday"
return f"{day.day}/{day.month}/{day.year % 100:02d}"
def history_time(value):
try:
clock = clock_time.fromisoformat(value)
return f"{clock.hour % 12 or 12}:{clock.minute:02d}"
except (TypeError, ValueError):
return value or ""
def startup_command():
if getattr(sys, "frozen", False):
return f'"{sys.executable}"'
pythonw = Path(sys.executable).with_name("pythonw.exe")
return f'"{pythonw if pythonw.exists() else sys.executable}" "{Path(__file__).resolve()}"'
def login_enabled():
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run") as key:
for name in ("WaveType", "STT Core"):
try:
if winreg.QueryValueEx(key, name)[0] == startup_command():
return True
except FileNotFoundError:
pass
return False
except OSError:
return False
def set_login(enabled):
with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run", 0,
winreg.KEY_SET_VALUE) as key:
if enabled:
winreg.SetValueEx(key, "WaveType", 0, winreg.REG_SZ, startup_command())
for name in (("STT Core",) if enabled else ("WaveType", "STT Core")):
try:
winreg.DeleteValue(key, name)
except FileNotFoundError:
pass
class NOTIFYICONDATAW(ctypes.Structure):
_fields_ = [("cbSize", wintypes.DWORD), ("hWnd", wintypes.HWND),
("uID", wintypes.UINT), ("uFlags", wintypes.UINT),
("uCallbackMessage", wintypes.UINT), ("hIcon", wintypes.HICON),
("szTip", wintypes.WCHAR * 128)]
class TrayIcon:
MESSAGE = 0x8000 + 17
def __init__(self, hwnd, callback):
self.callback = callback
self.data = NOTIFYICONDATAW()
self.data.cbSize = ctypes.sizeof(self.data)
self.data.hWnd = hwnd
self.data.uID = 1
self.data.uFlags = 1 | 2 | 4 # message, icon, tooltip
self.data.uCallbackMessage = self.MESSAGE
user32 = ctypes.windll.user32
user32.LoadImageW.argtypes = [wintypes.HINSTANCE, wintypes.LPCWSTR, wintypes.UINT,
ctypes.c_int, ctypes.c_int, wintypes.UINT]
user32.LoadImageW.restype = wintypes.HANDLE
self.data.hIcon = user32.LoadImageW(None, str(ASSETS / "WaveType.ico"), 1, 0, 0, 0x10 | 0x40)
if not self.data.hIcon:
raise ctypes.WinError()
self.data.szTip = "WaveType dictation"
if not ctypes.windll.shell32.Shell_NotifyIconW(0, ctypes.byref(self.data)):
self.close()
raise ctypes.WinError()
def message(self, message, _wparam, lparam):
if message != self.MESSAGE:
return False
if lparam & 0xFFFF in (0x202, 0x203, 0x205):
self.callback(lparam & 0xFFFF)
return True
def close(self):
ctypes.windll.shell32.Shell_NotifyIconW(2, ctypes.byref(self.data))
if self.data.hIcon:
ctypes.windll.user32.DestroyIcon.argtypes = [wintypes.HICON]
ctypes.windll.user32.DestroyIcon(self.data.hIcon)
self.data.hIcon = None
class DesktopApp:
def __init__(self):
APP_DIR.mkdir(parents=True, exist_ok=True)
try:
self.preferences = json.loads(PREFERENCES.read_text(encoding="utf-8"))
except (FileNotFoundError, ValueError):
self.preferences = {}
self.first_run = not PREFERENCES.exists()
self.updates = UpdateManager(APP_DIR, installed_version(sys.executable))
self.update_state = {"state": "idle"}
self.update_manual = False
self.prompted_version = None
self.update_error_on_start = self.read_update_result()
self.theme = self.preferences.get("theme", "Light")
self.colors = DARK if self.theme == "Dark" or self.theme == "System" and system_dark() else LIGHT
self.page = "Setup" if self.first_run else "History"
self.history = []
self.dictionary = {"snippets": {}, "vocabulary": {}}
self.shortcuts = {}
self.shortcut_draft = None
self.shortcut_pending = False
self.devices = []
self.model = {}
self.setup_error = ""
self.engine_job = ChildJob(assign_self=False)
self.pill = Pill(smart=bool(self.preferences.get("smart", False)),
tap_threshold_ms=int(self.preferences.get("tap_threshold_ms", 250)),
settings={"tier": self.preferences.get("tier", "auto"),
"language": "auto", "microphone": self.preferences.get("microphone"),
"assistant_enabled": bool(self.preferences.get("assistant_enabled", False))},
on_event=self.on_engine_event, on_window_message=self.on_window_message,
engine_job=self.engine_job)
self.root = self.pill.root
self.ui_fonts = {"sans": "Segoe UI", "serif": "Georgia", "mono": "Consolas"}
for style, (family, filename) in FONT_FILES.items():
path = Path(__file__).resolve().parent / "assets" / filename
if path.is_file() and ctypes.windll.gdi32.AddFontResourceExW(str(path), 0x10, None):
self.ui_fonts[style] = family
self.main = tk.Toplevel(self.root)
self.main.title("WaveType")
self.main.iconbitmap(str(ASSETS / "WaveType.ico"))
work = wintypes.RECT()
if ctypes.windll.user32.SystemParametersInfoW(0x30, 0, ctypes.byref(work), 0):
width = min(1100, work.right - work.left - 40)
height = min(720, work.bottom - work.top - 40)
self.main.geometry(f"{width}x{height}+{work.left + (work.right - work.left - width) // 2}"
f"+{work.top + (work.bottom - work.top - height) // 2}")
else:
self.main.geometry("1100x720")
self.main.resizable(False, False)
self.main.configure(bg=self.colors["bg"])
self.main.protocol("WM_DELETE_WINDOW", self.hide)
self.main.bind("<Escape>", lambda _event: self.hide())
self.main.withdraw()
self.main.update_idletasks()
self.style_titlebar()
self.tray_events = queue.SimpleQueue()
self.tray = TrayIcon(self.pill.hwnd, self.tray_events.put)
self.menu = tk.Menu(self.root, tearoff=False)
self.tray_smart_var = tk.BooleanVar(value=bool(self.preferences.get("smart", False)))
self.smart_pending = False
self.menu.add_command(label="WaveType", command=self.show)
self.menu.add_checkbutton(label="Smart cleanup", variable=self.tray_smart_var,
command=self.toggle_tray_smart)
self.menu.add_separator()
self.menu.add_command(label="Exit", command=self.quit)
self.menu.bind("<ButtonRelease-3>", lambda _event: "break")
self.render()
if self.first_run:
self.show()
self.root.after(100, self.drain_tray)
self.root.after(500, self.watch_ready)
self.root.after(250, self.poll_updates)
self.root.after(5000, self.auto_check_update)
def on_window_message(self, message, wparam, lparam):
return getattr(self, "tray", None) is not None and self.tray.message(message, wparam, lparam)
def on_tray(self, button):
if button in (0x202, 0x203):
self.show()
elif button == 0x205:
self.root.after(120, self.popup_menu)
def drain_tray(self):
while not self.tray_events.empty():
self.on_tray(self.tray_events.get_nowait())
if not getattr(self, "quitting", False):
self.root.after(100, self.drain_tray)
def popup_menu(self):
x, y = self.root.winfo_pointerxy()
self.menu.entryconfigure("Smart cleanup", state="normal" if self.pill.ready and
self.pill.state == "idle" and not self.smart_pending else "disabled")
try:
self.menu.tk_popup(x, y)
finally:
self.menu.grab_release()
def toggle_tray_smart(self):
enabled = self.tray_smart_var.get()
if self.smart_pending or not self.pill.ready or self.pill.state != "idle":
self.tray_smart_var.set(bool(self.preferences.get("smart", False)))
return
self.smart_pending = True
self.pill.request("settings", lambda result, error: self.after_tray_smart(result, error),
smart=enabled)
def after_tray_smart(self, result, error):
self.smart_pending = False
if error:
self.tray_smart_var.set(bool(self.preferences.get("smart", False)))
self.pill.messages.put({"event": "error", "message": error})
return
enabled = bool(result["smart"])
self.tray_smart_var.set(enabled)
self.preferences["smart"] = enabled
self.save_preferences()
if self.page == "Settings":
self.smart_var.set(enabled)
self.settings_initial["smart"] = enabled
self.update_apply_visibility()
def show(self):
self.style_titlebar()
self.main.deiconify()
self.main.update_idletasks()
self.main.lift()
self.main.focus_force()
self.refresh_page()
def style_titlebar(self):
user32 = ctypes.windll.user32
user32.GetAncestor.argtypes = (wintypes.HWND, wintypes.UINT)
user32.GetAncestor.restype = wintypes.HWND
hwnd = user32.GetAncestor(self.main.winfo_id(), 2)
user32.GetWindowLongPtrW.argtypes = (wintypes.HWND, ctypes.c_int)
user32.GetWindowLongPtrW.restype = ctypes.c_ssize_t
user32.SetWindowLongPtrW.argtypes = (wintypes.HWND, ctypes.c_int, ctypes.c_ssize_t)
user32.SetWindowLongPtrW.restype = ctypes.c_ssize_t
# Only the main window gets a taskbar entry; withdrawing it leaves the tray active.
user32.SetWindowLongPtrW(hwnd, -8, 0)
extended = (user32.GetWindowLongPtrW(hwnd, -20) | 0x40000) & ~0x80
user32.SetWindowLongPtrW(hwnd, -20, extended)
style = user32.GetWindowLongPtrW(hwnd, -16)
user32.SetWindowLongPtrW(hwnd, -16, (style | 0x20000 | 0x80000) & ~(0x10000 | 0x40000))
user32.SetWindowPos.argtypes = (wintypes.HWND, wintypes.HWND, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int, wintypes.UINT)
user32.SetWindowPos(hwnd, None, 0, 0, 0, 0, 0x37)
ctypes.windll.dwmapi.DwmSetWindowAttribute.argtypes = (
wintypes.HWND, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD)
ctypes.windll.dwmapi.DwmSetWindowAttribute.restype = wintypes.LONG
dark = ctypes.c_int(self.colors is DARK)
for attribute in (20, 19):
if ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd, attribute, ctypes.byref(dark), ctypes.sizeof(dark)) == 0:
break
def hide(self):
self.main.withdraw()
def quit(self):
if getattr(self, "quitting", False):
return
self.quitting = True
self.pill.closing = True
if self.pill.ready:
self.pill.request("shutdown", lambda _result, _error: self.finish_quit())
self.root.after(45000, self.finish_quit)
else:
self.finish_quit()
def finish_quit(self):
if getattr(self, "exited", False):
return
self.exited = True
self.tray.close()
self.main.destroy()
self.root.quit()
def save_preferences(self):
PREFERENCES.write_text(json.dumps(self.preferences, indent=2) + "\n", encoding="utf-8")
def read_update_result(self):
result = APP_DIR / "update-result.json"
try:
value = json.loads(result.read_text(encoding="utf-8-sig"))
return value.get("message", "") if value.get("status") == "failed" else ""
except (OSError, ValueError, AttributeError):
return ""
finally:
result.unlink(missing_ok=True)
def auto_check_update(self, reschedule=True):
if self.preferences.get("auto_update") and self.updates.current_version:
if self.updates.check(automatic=True):
self.root.after(MANUAL_COOLDOWN * 1000, self.update_update_card)
if reschedule and not getattr(self, "quitting", False):
self.root.after(60 * 60 * 1000, self.auto_check_update)
def poll_updates(self):
while not self.updates.events.empty():
event = self.updates.events.get_nowait()
self.update_state = event
state = event["state"]
if state == "available" and self.update_manual:
self.update_manual = False
self.show()
if messagebox.askyesno("WaveType update available",
f"Download WaveType {event['version']} now?",
parent=self.main):
self.updates.download()
elif state == "ready" and self.prompted_version != event["version"]:
self.prompted_version = event["version"]
self.show()
if messagebox.askyesno("Install WaveType update?",
f"WaveType {event['version']} is downloaded and verified. "
"WaveType will close, update, then reopen. Install now?",
parent=self.main):
self.install_update(approved=True)
elif state in ("current", "error"):
self.update_manual = False
self.update_update_card()
if self.update_error_on_start:
self.show()
messagebox.showerror("WaveType update failed", self.update_error_on_start, parent=self.main)
self.update_error_on_start = ""
if not getattr(self, "quitting", False):
self.root.after(250, self.poll_updates)
def manual_check_update(self):
if not self.updates.current_version:
self.update_state = {"state": "error", "message": "Update checks require an installed WaveType build."}
self.update_update_card()
return
self.update_manual = True
if not self.updates.check():
self.update_manual = False
else:
self.root.after(MANUAL_COOLDOWN * 1000, self.update_update_card)
self.update_update_card()
def set_auto_update(self):
self.preferences["auto_update"] = self.auto_update_var.get()
self.save_preferences()
if self.auto_update_var.get():
self.auto_check_update(reschedule=False)
def install_update(self, approved=False):
installer = self.updates.ready_installer()
package = Path(sys.executable).parent
helper_source = Path(__file__).resolve().parent / "packaging" / "update_helper.ps1"
if not installer or not helper_source.is_file() or not (package / "Uninstall.exe").is_file():
self.report("Express update requires an installed WaveType build and a verified download.")
return
if not approved and not messagebox.askyesno("Install WaveType update?",
"WaveType will close, install the update, then reopen. Continue?", parent=self.main):
return
helper = APP_DIR / "update-helper.ps1"
command = [str(Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" /
"WindowsPowerShell" / "v1.0" / "powershell.exe"),
"-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(helper),
"-Installer", str(installer), "-InstallDir", str(package), "-AppPid", str(os.getpid()),
"-ExpectedSha256", self.updates.expected_hash,
"-ResultFile", str(APP_DIR / "update-result.json")]
try:
helper.write_bytes(helper_source.read_bytes())
subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, close_fds=True,
creationflags=subprocess.CREATE_NO_WINDOW)
except OSError as exc:
self.report(f"Could not start the update: {exc}")
return
self.quit()
def watch_ready(self):
if self.pill.ready and not getattr(self, "initialized", False):
self.initialized = True
self.pill.request("model_status", self.receive_model)
self.refresh_page()
elif not self.pill.ready and not getattr(self, "initialized", False):
self.root.after(500, self.watch_ready)
def receive_model(self, data, error):
if error:
self.setup_error = error
self.update_setup_issue()
return
else:
self.model = data
self.setup_error = ""
self.update_model_cards()
self.update_setup_issue()
if hasattr(self, "microphone_status_label") and self.microphone_status_label.winfo_exists():
self.microphone_status_label.configure(text=data.get("capture_error") or "Microphone ready")
if self.page == "Setup" and hasattr(self, "setup_tier_label"):
tier = "NVIDIA GPU detected" if self.model.get("gpu_available") else "CPU mode available"
self.setup_tier_label.configure(text=tier + " · Smart cleanup is optional")
if hasattr(self, "sidebar_engine_label"):
self.sidebar_engine_label.configure(text=self.engine_description() if self.model else "Checking model…")
def on_engine_event(self, event):
if getattr(self, "exited", False):
return
kind = event["event"]
if kind == "error":
message = event["message"]
if "Qwen model unavailable" in message:
self.preferences["smart"] = False
self.tray_smart_var.set(False)
self.save_preferences()
if "Saved microphone unavailable" in message:
self.preferences["microphone"] = None
self.save_preferences()
if "Model unavailable" in message or "model unavailable" in message or "Microphone unavailable" in message:
self.setup_error = message
self.update_setup_issue()
else:
self.report(message)
elif kind == "model_progress":
self.model.setdefault("models", {})[event["model"]] = {
key: value for key, value in event.items() if key not in ("event", "model")}
self.update_model_cards()
if event["model"] == "asr" and event["state"] == "ready":
self.setup_error = ""
self.update_setup_issue()
elif kind == "cleanup_disabled":
self.preferences["smart"] = False
self.tray_smart_var.set(False)
if hasattr(self, "smart_var"):
self.smart_var.set(False)
self.save_preferences()
elif kind == "history_added" and self.page == "History":
self.refresh_page()
def font(self, size=10, weight="normal", style="sans"):
return (getattr(self, "ui_fonts", {}).get(style, "Segoe UI"), size, weight)
def label(self, parent, text, size=10, color="text", weight="normal", style="sans", **kwargs):
return tk.Label(parent, text=text, bg=parent.cget("bg"), fg=self.colors[color],
font=self.font(size, weight, style), anchor="w", **kwargs)
def button(self, parent, text, command, primary=False, **kwargs):
bg = self.colors["accent"] if primary else self.colors["button"]
fg = self.colors["bg"] if primary else self.colors["text"]
return tk.Button(parent, text=text, command=command, bg=bg, fg=fg,
activebackground=self.colors["line"], activeforeground=self.colors["text"],
relief="flat", bd=0, padx=14, pady=7, cursor="hand2",
font=self.font(9, "bold" if primary else "normal"), **kwargs)
def placeholder(self, entry, text):
entry.insert(0, text)
entry.configure(fg=self.colors["soft"])
entry.placeholder = text
def focus_in(_event):
if entry.get() == text and entry.cget("fg") == self.colors["soft"]:
entry.delete(0, tk.END)
entry.configure(fg=self.colors["text"])
def focus_out(_event):
if not entry.get():
entry.insert(0, text)
entry.configure(fg=self.colors["soft"])
entry.bind("<FocusIn>", focus_in)
entry.bind("<FocusOut>", focus_out)
def focus_entry(self, entry, background):
entry.bind("<FocusIn>", lambda _event: entry.configure(bg=self.colors["focus"]), add="+")
entry.bind("<FocusOut>", lambda _event: entry.configure(bg=background), add="+")
def entry_text(self, entry):
return "" if entry.get() == getattr(entry, "placeholder", None) and \
entry.cget("fg") == self.colors["soft"] else entry.get()
def icon_image(self, name, color):
palette = "dark" if self.colors["bg"] == DARK["bg"] else "light"
tone = ("main" if color == self.colors["text"] else
"soft" if color == self.colors["soft"] else "muted")
key = name.lower(), palette, tone
if not hasattr(self, "icon_images"):
self.icon_images = {}
if key not in self.icon_images:
path = Path(__file__).resolve().parent / "assets" / "icons" / f"{key[0]}-{palette}-{tone}.png"
self.icon_images[key] = tk.PhotoImage(master=self.root, file=str(path))
return self.icon_images[key]
def icon(self, parent, name, color=None):
return tk.Label(parent, image=self.icon_image(name, color or self.colors["muted"]),
bg=parent.cget("bg"), bd=0, padx=0, pady=0)
def render(self):
self.main.unbind_all("<MouseWheel>")
for child in self.main.winfo_children():
child.destroy()
c = self.colors
self.shell = tk.Frame(self.main, bg=c["bg"])
self.shell.pack(fill="both", expand=True)
side = tk.Frame(self.shell, bg=c["side"], width=228)
side.pack(side="left", fill="y")
side.pack_propagate(False)
brand = tk.Frame(side, bg=c["side"])
brand.pack(fill="x", padx=20, pady=(22, 26))
if not hasattr(self, "brand_image"):
self.brand_image = tk.PhotoImage(master=self.root, file=str(ASSETS / "logo_expanded.png"))
tk.Label(brand, image=self.brand_image, bg=c["side"], bd=0).pack(side="left")
tk.Label(brand, text="Beta", bg="#EADBFC" if self.theme != "Dark" else c["button"],
fg=c["link"], font=self.font(8, "bold"), padx=5, pady=2).pack(side="left", padx=(6, 0))
self.nav_buttons = {}
for page in ("History", "Dictionary", "Shortcuts", "Settings"):
row = tk.Frame(side, bg=c["button"] if self.page == page else c["side"],
cursor="hand2", height=36)
row.pack(fill="x", padx=12, pady=2)
row.pack_propagate(False)
icon = (self.label(row, "↗", 16, color="text" if self.page == page else "muted")
if page == "Shortcuts" else
self.icon(row, page, c["text"] if self.page == page else c["muted"]))
icon.pack(side="left", padx=(12, 10))
label = self.label(row, page, 10, weight="bold" if self.page == page else "normal")
label.pack(side="left")
for widget in (row, icon, label):
widget.bind("<Button-1>", lambda _event, target=page: self.navigate(target))
widget.bind("<Enter>", lambda _event, target=page: self.nav_hover(target))
widget.bind("<Leave>", lambda _event, target=page: self.nav_hover(target))
self.nav_buttons[page] = row, icon, label
footer = tk.Frame(side, bg=c["side"])
footer.pack(side="bottom", fill="x")
engine_card = tk.Frame(footer, bg=c["card"], padx=12, pady=11,
highlightbackground=c["line"], highlightcolor=c["line"], highlightthickness=1)
engine_card.pack(fill="x", padx=12, pady=(0, 12))
self.label(engine_card, "Local Engine", 9, weight="bold").pack(fill="x")
self.sidebar_engine_label = self.label(engine_card, "Checking model…", 8, color="muted")
self.sidebar_engine_label.pack(fill="x", pady=(5, 0))
if self.model:
self.sidebar_engine_label.configure(text=self.engine_description())
self.issue_label = self.label(engine_card, "", 8, color="danger", wraplength=160,
justify="left")
self.issue_label.pack(fill="x", pady=(6, 0))
self.issue_button = self.button(engine_card, "Open Settings", lambda: self.navigate("Settings"))
self.update_setup_issue()
about = tk.Frame(footer, bg=c["side"], cursor="hand2", height=34)
about.pack(fill="x", padx=12)
about.pack_propagate(False)
about_icon = self.icon(about, "About", c["muted"])
about_icon.pack(side="left", padx=(12, 10))
about_label = self.label(about, "About & Licence", 10, color="muted")
about_label.pack(side="left")
for widget in (about, about_icon, about_label):
widget.bind("<Button-1>", lambda _event: self.navigate("About"))
source = self.label(footer, " GitHub ↗", 10, color="link", cursor="hand2",
image=self.icon_image("github", c["text"]), compound="left")
source.pack(fill="x", padx=24, pady=(8, 18))
source.bind("<Button-1>", lambda _event: webbrowser.open(RELEASES.rsplit("/", 1)[0]))
tk.Frame(side, bg=c["side"]).pack(fill="both", expand=True)
self.content = tk.Frame(self.shell, bg=c["bg"])
self.content.pack(side="left", fill="both", expand=True)
self.header = tk.Frame(self.content, bg=c["bg"])
self.header.pack(fill="x", padx=36, pady=(28, 20))
self.heading_label = self.label(self.header, self.page, 19, weight="bold")
self.heading_label.pack(side="left")
self.body = tk.Frame(self.content, bg=c["bg"])
self.body.pack(fill="both", expand=True, padx=36, pady=(0, 12))
getattr(self, f"show_{self.page.lower()}")()
def engine_description(self):
status = self.model.get("models", {}).get("asr", {}).get("state", "missing")
if status != "ready":
return "Parakeet Redux · " + status.capitalize()
return "Parakeet Redux · " + ("GPU available" if self.model.get("gpu_available") else "CPU mode")
def update_setup_issue(self):
if not hasattr(self, "issue_label") or not self.issue_label.winfo_exists():
return
asr = self.model.get("models", {}).get("asr", {})
error = self.model.get("capture_error") or getattr(self, "setup_error", "")
if asr.get("state") in ("missing", "failed", "paused"):
error = asr.get("error") or "Parakeet is not ready. Open Settings to download or repair it."
self.issue_label.configure(text=error)
if error:
if not self.issue_button.winfo_manager():
self.issue_button.pack(anchor="w", pady=(6, 0))
elif self.issue_button.winfo_manager():
self.issue_button.pack_forget()
def style_nav(self, hover=None):
for page, (row, icon, label) in self.nav_buttons.items():
selected = page == self.page
color = self.colors["button"] if selected or page == hover else self.colors["side"]
for widget in (row, icon, label):
widget.configure(bg=color)
if page == "Shortcuts":
icon.configure(fg=self.colors["text"] if selected else self.colors["muted"])
else:
icon.configure(image=self.icon_image(page, self.colors["text"] if selected else self.colors["muted"]))
label.configure(font=self.font(10, "bold" if selected else "normal"))
def nav_hover(self, page):
row = self.nav_buttons[page][0]
x, y = row.winfo_pointerxy()
inside = (row.winfo_rootx() <= x < row.winfo_rootx() + row.winfo_width()
and row.winfo_rooty() <= y < row.winfo_rooty() + row.winfo_height())
self.style_nav(hover=page if inside else None)
def render_page(self):
self.main.unbind_all("<MouseWheel>")
if hasattr(self, "settings_apply") and self.settings_apply.winfo_exists():
self.settings_apply.destroy()
previous = self.body
self.body = tk.Frame(self.content, bg=self.colors["bg"])
getattr(self, f"show_{self.page.lower()}")()
previous.destroy()
self.body.pack(fill="both", expand=True, padx=36, pady=(0, 12))
if hasattr(self, "notice") and self.notice.winfo_exists() and self.notice.winfo_manager():
self.notice.lift()
def navigate(self, page):
if page == self.page:
self.refresh_page()
return
self.page = page
self.heading_label.configure(text=page)
self.style_nav()
self.render_page()
self.refresh_page()
def refresh_page(self):
if not self.pill.ready:
return
if self.page == "History":
self.pill.request("history_list", self.receive_history, limit=100)
elif self.page == "Dictionary":
self.pill.request("dictionary_get", self.receive_dictionary)
elif self.page == "Shortcuts":
self.pill.request("shortcuts_get", self.receive_shortcuts)
elif self.page == "Settings":
self.pill.request("devices", self.receive_devices)
self.pill.request("model_status", self.receive_model)
def show_setup(self):
box = tk.Frame(self.body, bg=self.colors["card"], padx=28, pady=25)
box.pack(fill="x", pady=12)
self.label(box, "Local dictation, ready for your text box", 16, weight="bold").pack(fill="x", pady=(0, 12))
self.label(box, "Parakeet Redux downloads and verifies on first launch. "
"Open Settings to see progress, pause, or retry. Qwen Smart cleanup is optional. "
"Future dictation works offline after the download.", 11,
wraplength=560, justify="left").pack(fill="x", pady=(0, 16))
tier = "NVIDIA GPU detected" if self.model.get("gpu_available") else "CPU mode available"
self.setup_tier_label = self.label(box, tier + " · Smart cleanup is optional", 11, color="muted")
self.setup_tier_label.pack(fill="x", pady=(0, 22))
self.button(box, "Open model settings", lambda: self.navigate("Settings")).pack(anchor="w", pady=(0, 10))
self.button(box, "Continue to history", self.finish_setup, primary=True).pack(anchor="w")
def finish_setup(self):
if not self.pill.ready:
self.report("Please wait for the engine to finish setup.")
return
self.first_run = False
self.save_preferences()
self.navigate("History")
def receive_history(self, data, error):
if error:
self.report(error)
return
if data != self.history:
self.history = data
if self.page == "History":
self.render_page()
def scroll_area(self, parent):
canvas = tk.Canvas(parent, bg=self.colors["bg"], highlightthickness=0, bd=0)
style = ttk.Style(self.root)
if style.theme_use() != "clam":
style.theme_use("clam")
style.layout("STT.Vertical.TScrollbar", [("Vertical.Scrollbar.trough", {
"sticky": "ns", "children": [("Vertical.Scrollbar.thumb", {"sticky": "nswe", "expand": True})]})])
style.configure("STT.Vertical.TScrollbar", background=self.colors["soft"],
troughcolor=self.colors["bg"], bordercolor=self.colors["bg"],
lightcolor=self.colors["soft"], darkcolor=self.colors["soft"],
arrowsize=8, borderwidth=0)
style.map("STT.Vertical.TScrollbar", background=[("active", self.colors["muted"])])
bar = ttk.Scrollbar(parent, orient="vertical", command=canvas.yview,
style="STT.Vertical.TScrollbar", takefocus=False)
inside = tk.Frame(canvas, bg=self.colors["bg"])
def update_scroll(_event=None):
if not canvas.winfo_exists():
return
canvas.configure(scrollregion=canvas.bbox("all"))
overflowing = inside.winfo_reqheight() > canvas.winfo_height()
if overflowing and not bar.winfo_manager():
bar.pack(side="right", fill="y", padx=(8, 0))
elif not overflowing and bar.winfo_manager():
bar.pack_forget()
canvas.yview_moveto(0)
inside.bind("<Configure>", update_scroll)
canvas.create_window((0, 0), window=inside, anchor="nw", tags="body")
canvas.bind("<Configure>", lambda event: (canvas.itemconfigure("body", width=event.width),
update_scroll()))
canvas.configure(yscrollcommand=bar.set)
canvas.pack(side="left", fill="both", expand=True)
canvas.bind_all("<MouseWheel>", lambda event: canvas.yview_scroll(-int(event.delta / 120), "units"))
return inside
def show_history(self):
if not self.history:
self.label(self.body, "Your dictations and Assistant commands will appear here.", 10,
color="muted").pack(anchor="w")
return
inside = self.scroll_area(self.body)
current_date = None
group = None
for entry in self.history:
if entry.get("date") != current_date:
first_group = current_date is None
current_date = entry.get("date")
self.label(inside, history_heading(current_date).upper(), 8, color="muted",
weight="bold").pack(anchor="w", pady=(0 if first_group else 22, 11))
group = tk.Frame(inside, bg=self.colors["card"],
highlightbackground=self.colors["line"], highlightcolor=self.colors["line"],
highlightthickness=1)
group.pack(fill="x")
elif group.winfo_children():
tk.Frame(group, bg=self.colors["line"], height=1).pack(fill="x", padx=18)
row = tk.Frame(group, bg=self.colors["card"], padx=18, pady=14)
row.pack(fill="x")
stamp = self.label(row, history_time(entry.get("time")), 9, color="muted", width=8)
stamp.pack(side="left", padx=(0, 16))
actions = tk.Frame(row, bg=self.colors["card"], width=28, height=28)
actions.pack(side="right")
actions.pack_propagate(False)
source = tk.Frame(row, bg=self.colors["side"], padx=8, pady=3,
highlightbackground=self.colors["line"], highlightcolor=self.colors["line"],
highlightthickness=1)
source.pack(side="right", padx=(12, 16))
app = self.label(source, entry.get("app") or "", 8, color="muted", style="mono")
app.pack()
content = self.label(row, entry.get("text", ""), 10, wraplength=220, justify="left")
content.pack(side="left", fill="x", expand=True)
content.bind("<Configure>", lambda event, label=content:
label.configure(wraplength=max(120, event.width - 4)))
delete = self.icon(actions, "Delete", self.colors["soft"])
delete.configure(cursor="hand2")
delete.bind("<Button-1>", lambda _event, e=entry: self.delete_history(e))
def show_delete(_event, button=delete):
button.place(relx=.5, rely=.5, anchor="center")
def hide_delete(button=delete, container=row):
if not container.winfo_exists():
return
x, y = container.winfo_pointerxy()
if not (container.winfo_rootx() <= x < container.winfo_rootx() + container.winfo_width()
and container.winfo_rooty() <= y < container.winfo_rooty() + container.winfo_height()):
button.place_forget()
for widget in (row, stamp, actions, source, app, content, delete):
widget.bind("<Enter>", show_delete)
widget.bind("<Leave>", lambda _event, container=row, handler=hide_delete:
container.after(25, handler))
def delete_history(self, entry):
self.pill.request("history_change", lambda _data, error: self.after_history_change(error),
id=entry["id"], action="delete")
def after_history_change(self, error):
if error:
self.report(error)
else:
self.refresh_page()
def receive_dictionary(self, data, error):
if error:
self.report(error)
return
if data != self.dictionary:
self.dictionary = data
if self.page == "Dictionary":
self.render_page()
def show_dictionary(self):
inside = self.scroll_area(self.body)
self.dictionary_forms = {}
self.dictionary_tab = getattr(self, "dictionary_tab", "snippets")
tabs = tk.Frame(inside, bg=self.colors["bg"])
tabs.pack(fill="x", pady=(0, 18))
self.dictionary_tabs = {}
self.dictionary_panels = {}
for kind, title in (("snippets", "Snippet"), ("vocabulary", "Vocabulary")):
tab = tk.Frame(tabs, bg=self.colors["bg"], cursor="hand2")
tab.pack(side="left", padx=(0, 20))
label = self.label(tab, title, 10, color="muted", cursor="hand2")
label.pack(pady=(5, 8))
underline = tk.Frame(tab, bg=self.colors["bg"], height=2)
underline.pack(fill="x")
for widget in (tab, label):
widget.bind("<Button-1>", lambda _event, selected=kind: self.select_dictionary_tab(selected))
self.dictionary_tabs[kind] = label, underline
tk.Frame(inside, bg=self.colors["line"], height=1).pack(fill="x", pady=(0, 20))
banner = tk.Frame(inside, bg=self.colors["banner"], padx=22, pady=18,
highlightbackground=self.colors["banner_line"],
highlightcolor=self.colors["banner_line"], highlightthickness=1)
banner.pack(fill="x", pady=(0, 22))
self.label(banner, "The stuff you shouldn't have to re-type.", 18,
style="serif").pack(fill="x", pady=(0, 5))
self.label(banner, "Save the details you say often. Speak ‘insert my’ followed by a snippet key "
"to expand it instantly.", 10, color="muted", wraplength=650,
justify="left").pack(fill="x")
for kind, heading, helper in (
("snippets", "Snippet", "Say ‘insert my’ followed by the key."),
("vocabulary", "Vocabulary", "Map mishearings to the spelling you want.")):
panel = tk.Frame(inside, bg=self.colors["bg"])
self.dictionary_panels[kind] = panel
self.label(panel, helper, 9, color="muted").pack(fill="x", pady=(0, 12))
form = tk.Frame(panel, bg=self.colors["card"], padx=12, pady=12,
highlightthickness=0)
form.pack(fill="x", pady=(0, 18))
save = self.button(form, "Save", lambda k=kind: self.save_dictionary_form(k), primary=True)
save.pack(side="right", padx=(12, 0))
key_entry = tk.Entry(form, width=20, font=self.font(10), fg=self.colors["text"],
bg=self.colors["side"], relief="flat", bd=0,
insertbackground=self.colors["text"])
key_entry.pack(side="left", padx=(0, 12), ipady=7, ipadx=8)
self.placeholder(key_entry, "Key (e.g. email)" if kind == "snippets" else "Correct spelling")
self.focus_entry(key_entry, self.colors["side"])
value_entry = tk.Entry(form, font=self.font(10), fg=self.colors["text"],
bg=self.colors["side"], relief="flat", bd=0,
insertbackground=self.colors["text"])
value_entry.pack(side="left", fill="x", expand=True, ipady=7, ipadx=8)
self.placeholder(value_entry, "Value (e.g. mail@example.com)" if kind == "snippets"
else "Mishearings, separated by commas")
self.focus_entry(value_entry, self.colors["side"])
self.dictionary_forms[kind] = key_entry, value_entry
def update_form_save(button=save, key=key_entry, value=value_entry):
if not button.winfo_exists():
return
changed = bool(self.entry_text(key).strip() or self.entry_text(value).strip())
if changed and not button.winfo_manager():
button.pack(side="right", before=key, padx=(12, 0))
elif not changed and button.winfo_manager():
button.pack_forget()
for field in (key_entry, value_entry):
variable = tk.StringVar(master=self.root, value=field.get())
field.configure(textvariable=variable)
variable.trace_add("write", lambda *_args, refresh=update_form_save: self.root.after_idle(refresh))
field.form_variable = variable
update_form_save()
list_card = tk.Frame(panel, bg=self.colors["card"],
highlightbackground=self.colors["line"], highlightcolor=self.colors["line"],
highlightthickness=1)
list_card.pack(fill="x")
values = self.dictionary.get(kind, {})
for index, (key, value) in enumerate(values.items()):
if index:
tk.Frame(list_card, bg=self.colors["line"], height=1).pack(fill="x", padx=16)
row = tk.Frame(list_card, bg=self.colors["card"], padx=16, pady=10)
row.pack(fill="x")
rendered = ", ".join(value) if isinstance(value, list) else value
save = self.button(row, "Save", lambda: None, primary=True)
delete = self.icon(row, "Delete", self.colors["soft"])
delete.configure(cursor="hand2")
delete.pack(side="right", padx=(8, 4))
delete.bind("<Button-1>", lambda _event, k=kind, n=key:
self.change_dictionary(k, n, None))
name_var = tk.StringVar(value=key)
text_var = tk.StringVar(value=rendered)
key_entry = tk.Entry(row, width=20, textvariable=name_var,
font=self.font(10, "bold"), fg=self.colors["link"],
bg=self.colors["card"], insertbackground=self.colors["link"],
relief="flat", bd=0, highlightthickness=0)
key_entry.pack(side="left", padx=(0, 10), ipady=5)
self.focus_entry(key_entry, self.colors["card"])
self.label(row, "→", 10, color="soft").pack(side="left", padx=(0, 10))
value_entry = tk.Entry(row, textvariable=text_var,
font=self.font(9, style="mono"), fg=self.colors["text"],
bg=self.colors["value"], insertbackground=self.colors["text"],
relief="flat", bd=0, highlightthickness=0)
value_entry.pack(side="left", fill="x", expand=True, ipady=5, ipadx=7)
self.focus_entry(value_entry, self.colors["value"])
save.configure(command=lambda k=kind, old=key, name=name_var, text=text_var:
self.change_dictionary(k, name.get(), text.get(), original=old))
def update_save(*_args, name=name_var, text=text_var, old=key,
original=rendered, button=save, delete_button=delete):
dirty = name.get() != old or text.get() != original
if dirty and not button.winfo_manager():
button.pack(side="right", before=delete_button, padx=(8, 0), ipady=0)
elif not dirty and button.winfo_manager():
button.pack_forget()
name_var.trace_add("write", update_save)
text_var.trace_add("write", update_save)