-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdictee-cheatsheet
More file actions
executable file
·1455 lines (1314 loc) · 53.7 KB
/
Copy pathdictee-cheatsheet
File metadata and controls
executable file
·1455 lines (1314 loc) · 53.7 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
dictee-cheatsheet — Floating voice-commands cheatsheet card for dictee.
Singleton: only one instance per UID. Subsequent invocations route
their CLI command (toggle/close/open/first-run) over a QLocalSocket
to the running instance and exit.
"""
import argparse
import locale
import os
import sys
from functools import partial
from pathlib import Path
from PyQt6.QtCore import Qt, QEvent, QFileSystemWatcher, QRect, QSettings, QTimer
from PyQt6.QtGui import QColor, QGuiApplication, QKeySequence, QPainter, QShortcut
from PyQt6.QtNetwork import QLocalServer, QLocalSocket
from PyQt6.QtWidgets import (
QApplication,
QFrame,
QGridLayout,
QHBoxLayout,
QLabel,
QPushButton,
QScrollArea,
QSizePolicy,
QVBoxLayout,
QWidget,
)
SERVER_NAME = f"dictee-cheatsheet-{os.getuid()}"
VALID_COMMANDS = ("open", "toggle", "close", "first-run")
# Config files read at render time.
DICTEE_CONF = Path.home() / ".config" / "dictee.conf"
CONTINUATION_CONF = Path.home() / ".config" / "dictee" / "continuation.conf"
# First-run marker — created on first close after --first-run was used,
# so the tray auto-show logic (Task 14) does not re-trigger the banner.
FIRSTRUN_MARKER = Path.home() / ".local" / "state" / "dictee" / "cheatsheet-firstrun.done"
# Visibility state file — read by the tray/plasmoid to know if the card
# is currently shown. Written on every showEvent/hideEvent.
STATE_FILE = Path(f"/dev/shm/.dictee_cheatsheet-{os.getuid()}")
# Languages supported by the cheatsheet (must match COMMAND_TABLE / CATEGORY_LABELS).
SUPPORTED_LANGS = ("fr", "en", "de", "es", "it", "pt", "uk")
# Zoom settings — body text point size, clamped to [MIN, MAX].
DEFAULT_ZOOM_PT = 12.0
MIN_ZOOM_PT = 9.0
MAX_ZOOM_PT = 22.0
ZOOM_STEP = 0.5
# Window opacity — adjusted via mouse wheel on the header.
DEFAULT_OPACITY = 1.0
MIN_OPACITY = 0.05
MAX_OPACITY = 1.0
# Mouse wheel: continuous, scaled by angleDelta so a full notch on a regular
# mouse (~120 units) = OPACITY_STEP, while a touchpad swipe (smaller deltas)
# produces proportionally smaller changes — feels smooth.
OPACITY_STEP = 0.05
# Header button click: jump 10% per click for fast manual cycling.
OPACITY_BUTTON_STEP = 0.10
# Fallback values when the user has not customized their config.
# DICTEE_COMMAND_SUFFIX_<LANG> in dictee.conf — kept verbatim (regex form).
_DEFAULT_SUFFIX = {
"fr": "finale?s?",
"en": "done",
"de": "weiter",
"es": "listo",
"it": "seguito",
"pt": "pronto",
"uk": "далі",
}
# First alias of CONTINUATION_WORDS_<LANG> from continuation.conf.
_DEFAULT_CONT = {
"fr": "minuscule",
"en": "lowercase",
"de": "kleinschreibung",
"es": "minúscula",
"it": "minuscola",
"pt": "minúscula",
"uk": "рядкова",
}
# Categories rendered in this order. First 4 are expanded by default.
CATEGORY_ORDER = (
"continuation_reset",
"sauts_de_ligne",
"ponctuation",
"brackets",
"markdown",
"caracteres_speciaux",
"hotkeys",
)
DEFAULT_EXPANDED = frozenset({
"continuation_reset",
"sauts_de_ligne",
"ponctuation",
"brackets",
})
# Localized section labels per language.
CATEGORY_LABELS = {
"fr": {
"continuation_reset": "Continuation et reset",
"sauts_de_ligne": "Sauts de ligne",
"ponctuation": "Ponctuation",
"brackets": "Guillemets et parenthèses",
"markdown": "Markdown",
"caracteres_speciaux": "Caractères spéciaux",
"hotkeys": "Raccourcis vocaux",
},
"en": {
"continuation_reset": "Continuation and reset",
"sauts_de_ligne": "Line breaks",
"ponctuation": "Punctuation",
"brackets": "Quotes and brackets",
"markdown": "Markdown",
"caracteres_speciaux": "Special characters",
"hotkeys": "Voice hotkeys",
},
"de": {
"continuation_reset": "Fortsetzung und Reset",
"sauts_de_ligne": "Zeilenumbrüche",
"ponctuation": "Interpunktion",
"brackets": "Klammern",
"markdown": "Markdown",
"caracteres_speciaux": "Sonderzeichen",
"hotkeys": "Sprachbefehle",
},
"es": {
"continuation_reset": "Continuación y reinicio",
"sauts_de_ligne": "Saltos de línea",
"ponctuation": "Puntuación",
"brackets": "Comillas y paréntesis",
"markdown": "Markdown",
"caracteres_speciaux": "Caracteres especiales",
"hotkeys": "Atajos de voz",
},
"it": {
"continuation_reset": "Continuazione e reset",
"sauts_de_ligne": "A capo",
"ponctuation": "Punteggiatura",
"brackets": "Virgolette e parentesi",
"markdown": "Markdown",
"caracteres_speciaux": "Caratteri speciali",
"hotkeys": "Comandi vocali",
},
"pt": {
"continuation_reset": "Continuação e reset",
"sauts_de_ligne": "Quebras de linha",
"ponctuation": "Pontuação",
"brackets": "Aspas e parênteses",
"markdown": "Markdown",
"caracteres_speciaux": "Caracteres especiais",
"hotkeys": "Atalhos de voz",
},
"uk": {
"continuation_reset": "Продовження та скидання",
"sauts_de_ligne": "Розриви рядків",
"ponctuation": "Пунктуація",
"brackets": "Лапки та дужки",
"markdown": "Markdown",
"caracteres_speciaux": "Спеціальні символи",
"hotkeys": "Голосові скорочення",
},
}
# Window title per language.
TITLE_BY_LANG = {
"fr": "Commandes vocales (FR)",
"en": "Voice commands (EN)",
"de": "Sprachbefehle (DE)",
"es": "Comandos de voz (ES)",
"it": "Comandi vocali (IT)",
"pt": "Comandos de voz (PT)",
"uk": "Голосові команди (UK)",
}
# First-run onboarding banner text per language. {shortcut} is replaced at
# render time by the actual keyboard combo (e.g. "Ctrl+F9", "Meta+H") or
# omitted entirely (FIRSTRUN_BANNER_NO_SHORTCUT) when the user has no
# cheatsheet shortcut configured.
FIRSTRUN_BANNER_TEXTS = {
"fr": "Bienvenue. Cette aide reste accessible via {shortcut} ou le menu tray. Glisser pour déplacer.",
"en": "Welcome. This card stays accessible via {shortcut} or the tray menu. Drag to move.",
"de": "Willkommen. Diese Hilfe bleibt über {shortcut} oder das Tray-Menü erreichbar. Zum Verschieben ziehen.",
"es": "Bienvenido. Esta ayuda sigue accesible mediante {shortcut} o el menú de la bandeja. Arrastrar para mover.",
"it": "Benvenuto. Questa guida resta accessibile tramite {shortcut} o il menu del vassoio. Trascina per spostare.",
"pt": "Bem-vindo. Esta ajuda permanece acessível via {shortcut} ou pelo menu da bandeja. Arrastar para mover.",
"uk": "Вітаємо. Ця довідка лишається доступною через {shortcut} або меню в треї. Перетягніть, щоб перемістити.",
}
FIRSTRUN_BANNER_NO_SHORTCUT = {
"fr": "Bienvenue. Cette aide reste accessible via le menu tray. Glisser pour déplacer.",
"en": "Welcome. This card stays accessible via the tray menu. Drag to move.",
"de": "Willkommen. Diese Hilfe bleibt über das Tray-Menü erreichbar. Zum Verschieben ziehen.",
"es": "Bienvenido. Esta ayuda sigue accesible mediante el menú de la bandeja. Arrastrar para mover.",
"it": "Benvenuto. Questa guida resta accessibile tramite il menu del vassoio. Trascina per spostare.",
"pt": "Bem-vindo. Esta ajuda permanece acessível pelo menu da bandeja. Arrastar para mover.",
"uk": "Вітаємо. Ця довідка лишається доступною через меню в треї. Перетягніть, щоб перемістити.",
}
# Display name per Linux input keycode for keys we expect to see as PTT
# (function row + a few extras). Used by _format_cheatsheet_shortcut() to
# build a readable "Mod+Key" string for the first-run banner.
LINUX_KEYCODE_NAMES = {
1: "Esc",
15: "Tab",
28: "Enter",
57: "Space",
59: "F1", 60: "F2", 61: "F3", 62: "F4", 63: "F5", 64: "F6",
65: "F7", 66: "F8", 67: "F9", 68: "F10", 87: "F11", 88: "F12",
100: "RightAlt",
119: "Pause",
}
# Curated voice commands per language × category.
# Templates: {cont} = continuation keyword, {suffix} = SUFFIX_<LANG>.
# One canonical form per command — variants live in the wiki.
COMMAND_TABLE = {
"fr": {
"continuation_reset": [
("{cont}", "continue"),
("nouvelle phrase", "reset"),
],
"sauts_de_ligne": [
("à la ligne", "↵"),
("retour à la ligne", "↵"),
("nouveau paragraphe", "↵↵"),
("point à la ligne", ".↵"),
("virgule à la ligne", ",↵"),
("deux points à la ligne", ":↵"),
],
"ponctuation": [
("virgule", ","),
("point {suffix}", "."),
("deux points {suffix}", ": "),
("point virgule", "; "),
("point d'interrogation", "?"),
("point d'exclamation", "!"),
("points de suspension", "…"),
("apostrophe", "'"),
],
"brackets": [
("ouvrir guillemets", "« "),
("fermer guillemets", " »"),
("ouvrir parenthèse", " ("),
("fermer parenthèse", ") "),
],
"markdown": [
("dièse espace", "# "),
("double dièse", "## "),
("triple dièse", "### "),
],
"caracteres_speciaux": [
("tabulation", "\\t"),
("tiret", "- "),
("tiret bas", "_"),
("tiret du six", "-"),
],
"hotkeys": [
("contrôle j", "Ctrl+J"),
],
},
"en": {
"continuation_reset": [
("{cont}", "continue"),
("new sentence", "reset"),
],
"sauts_de_ligne": [
("new line", "↵"),
("new paragraph", "↵↵"),
("period new line", ".↵"),
("comma new line", ",↵"),
("colon new line", ":↵"),
("question mark new line", "?↵"),
],
"ponctuation": [
("comma", ", "),
("period {suffix}", "."),
("colon {suffix}", ": "),
("semicolon", "; "),
("question mark", "? "),
("exclamation mark", "! "),
("ellipsis", "… "),
],
"brackets": [
("open quote", "\""),
("close quote", "\""),
("open paren", " ("),
("close paren", ") "),
],
"markdown": [
("hash space", "# "),
("hash hash space", "## "),
("hash hash hash space", "### "),
],
"caracteres_speciaux": [
("tab", "\\t"),
("hyphen", "- "),
],
"hotkeys": [],
},
"de": {
"continuation_reset": [
("{cont}", "continue"),
("neuer Satz", "reset"),
],
"sauts_de_ligne": [
("neue Zeile", "↵"),
("neuer Absatz", "↵↵"),
("Punkt neue Zeile", ".↵"),
("Komma neue Zeile", ",↵"),
("Doppelpunkt neue Zeile", ":↵"),
("Fragezeichen neue Zeile", "?↵"),
],
"ponctuation": [
("Komma", ", "),
("Punkt {suffix}", "."),
("Doppelpunkt", ": "),
("Semikolon", "; "),
("Fragezeichen", "?"),
("Ausrufezeichen", "!"),
("Auslassungspunkte", "…"),
],
"brackets": [
("Anführungszeichen auf", "\""),
("Anführungszeichen zu", "\""),
("Klammer auf", "("),
("Klammer zu", ")"),
],
"markdown": [],
"caracteres_speciaux": [
("Tabulator", "\\t"),
("Bindestrich", "- "),
],
"hotkeys": [],
},
"es": {
"continuation_reset": [
("{cont}", "continue"),
("nueva frase", "reset"),
],
"sauts_de_ligne": [
("nueva línea", "↵"),
("nuevo párrafo", "↵↵"),
("coma nueva línea", ",↵"),
("dos puntos nueva línea", ":↵"),
("signo de interrogación nueva línea", "?↵"),
("signo de exclamación nueva línea", "!↵"),
],
"ponctuation": [
("coma {suffix}", ", "),
("punto {suffix}", "."),
("dos puntos", ": "),
("punto y coma", "; "),
("signo de interrogación", "?"),
("signo de exclamación", "!"),
("puntos suspensivos", "…"),
],
"brackets": [
("abrir comillas", "\""),
("cerrar comillas", "\""),
("abrir paréntesis", "("),
("cerrar paréntesis", ")"),
],
"markdown": [],
"caracteres_speciaux": [
("tabulación", "\\t"),
("guión", "- "),
],
"hotkeys": [],
},
"it": {
"continuation_reset": [
("{cont}", "continue"),
("nuova frase", "reset"),
],
"sauts_de_ligne": [
("a capo", "↵"),
("nuovo paragrafo", "↵↵"),
("virgola a capo", ",↵"),
("due punti a capo", ":↵"),
("punto interrogativo a capo", "?↵"),
("punto esclamativo a capo", "!↵"),
],
"ponctuation": [
("virgola", ", "),
("punto {suffix}", "."),
("due punti", ": "),
("punto e virgola", "; "),
("punto interrogativo", "?"),
("punto esclamativo", "!"),
("puntini di sospensione", "…"),
],
"brackets": [
("apri virgolette", "\""),
("chiudi virgolette", "\""),
("apri parentesi", "("),
("chiudi parentesi", ")"),
],
"markdown": [],
"caracteres_speciaux": [
("tabulazione", "\\t"),
("trattino", "- "),
],
"hotkeys": [],
},
"pt": {
"continuation_reset": [
("{cont}", "continue"),
("nova frase", "reset"),
],
"sauts_de_ligne": [
("nova linha", "↵"),
("novo parágrafo", "↵↵"),
("vírgula nova linha", ",↵"),
("dois pontos nova linha", ":↵"),
("ponto de interrogação nova linha", "?↵"),
("ponto de exclamação nova linha", "!↵"),
],
"ponctuation": [
("vírgula", ", "),
("ponto {suffix}", "."),
("dois pontos", ": "),
("ponto e vírgula", "; "),
("ponto de interrogação", "?"),
("ponto de exclamação", "!"),
("reticências", "…"),
],
"brackets": [
("abrir aspas", "\""),
("fechar aspas", "\""),
("abrir parênteses", "("),
("fechar parênteses", ")"),
],
"markdown": [],
"caracteres_speciaux": [
("tabulação", "\\t"),
("hífen", "- "),
],
"hotkeys": [],
},
"uk": {
"continuation_reset": [
("{cont}", "continue"),
("нове речення", "reset"),
],
"sauts_de_ligne": [
("новий рядок", "↵"),
("новий абзац", "↵↵"),
("кома новий рядок", ",↵"),
("двокрапка новий рядок", ":↵"),
("знак питання новий рядок", "?↵"),
("знак оклику новий рядок", "!↵"),
],
"ponctuation": [
("кома {suffix}", ", "),
("крапка {suffix}", "."),
("двокрапка", ": "),
("крапка з комою", "; "),
("знак питання", "?"),
("знак оклику", "!"),
("три крапки", "…"),
],
"brackets": [
("відкрити лапки", "\""),
("закрити лапки", "\""),
("відкрити дужки", "("),
("закрити дужки", ")"),
],
"markdown": [],
"caracteres_speciaux": [
("табуляція", "\\t"),
("дефіс", "- "),
],
"hotkeys": [],
},
}
def _read_kv_file(path):
"""Parse a simple KEY=VALUE file. Skip blanks and comments. Return dict."""
if not path.exists():
return {}
out = {}
try:
for line in path.read_text(encoding="utf-8").splitlines():
s = line.strip()
if not s or s.startswith("#"):
continue
if "=" not in s:
continue
k, v = s.split("=", 1)
out[k.strip()] = v.strip().strip('"').strip("'")
except OSError:
pass
return out
def _detect_lang():
"""Resolve the current source language: dictee.conf -> system locale -> 'en'."""
cfg = _read_kv_file(DICTEE_CONF)
val = cfg.get("DICTEE_LANG_SOURCE", "").strip().lower()
if val in SUPPORTED_LANGS:
return val
try:
loc = locale.getlocale()[0]
if loc:
short = loc.split("_")[0].lower()
if short in SUPPORTED_LANGS:
return short
except (ValueError, TypeError):
pass
return "en"
def _format_cheatsheet_shortcut():
"""Return the user-facing cheatsheet shortcut string, or None if
disabled/unset.
Reads dictee.conf for DICTEE_CHEATSHEET_MOD and DICTEE_PTT_KEY (or
DICTEE_CHEATSHEET_KEY_SEQ for the "Separate key" mode), and rebuilds
a readable combo like "Ctrl+F9", "Super+F9", or "Meta+H".
- "same_X" modes → "<X>+<key_name>" using DICTEE_PTT_KEY
- "separate" → DICTEE_CHEATSHEET_KEY_SEQ verbatim
- "disabled"/"" → None
- unknown keycode → None (better no shortcut than a misleading "Ctrl+Key 67")
"""
cfg = _read_kv_file(DICTEE_CONF)
mode = cfg.get("DICTEE_CHEATSHEET_MOD", "").strip()
if not mode or mode == "disabled":
return None
if mode == "separate":
seq = cfg.get("DICTEE_CHEATSHEET_KEY_SEQ", "").strip()
return seq or None
# "same_<modname>" pattern: rebuild "<Mod>+<KeyName>"
mod_label = {
"same_alt": "Alt",
"same_ctrl": "Ctrl",
"same_super": "Super",
"same_shift": "Shift",
}.get(mode)
if not mod_label:
return None
try:
ptt_key = int(cfg.get("DICTEE_PTT_KEY", "").strip())
except (TypeError, ValueError):
return None
key_name = LINUX_KEYCODE_NAMES.get(ptt_key)
if not key_name:
return None
return f"{mod_label}+{key_name}"
def _humanize_suffix(regex_form):
"""Turn a regex-form suffix (e.g. 'finale?s?') into a readable canonical
word for display in the cheatsheet (e.g. 'finale').
Strategy: drop optional-marker '?' chars together with the single ASCII
letter that precedes them. So 'finale?s?' → 'final', 'final?' → 'fina'.
For better UX we keep the bare-letter form before the last '?' (the most
common Latin-language pattern is `<root>e?s?` to match singular/plural):
after stripping the trailing '?' tokens, restore the canonical 'e' if
the original had 'e?' so users see 'finale' not 'final'."""
import re
# Special-case the common 'e?s?' Latin pattern → keep the 'e'
if regex_form.endswith("e?s?"):
return regex_form[:-len("e?s?")] + "e"
if regex_form.endswith("s?"):
return regex_form[:-len("s?")]
# Fallback: strip every '<letter>?' token
return re.sub(r"[A-Za-zÀ-ÿ]\?", "", regex_form)
def _read_suffix(lang):
"""Read DICTEE_COMMAND_SUFFIX_<LANG> from dictee.conf, fallback to default.
The on-disk value may be a regex (e.g. 'finale?s?'); humanize it for
display so the user sees 'finale' rather than the raw regex."""
cfg = _read_kv_file(DICTEE_CONF)
key = f"DICTEE_COMMAND_SUFFIX_{lang.upper()}"
val = cfg.get(key, "").strip()
if not val:
val = _DEFAULT_SUFFIX.get(lang, "")
return _humanize_suffix(val)
def _read_continuation_word(lang):
"""Read first alias from `[keyword:<lang>] word1, word2, ...` in continuation.conf."""
if not CONTINUATION_CONF.exists():
return _DEFAULT_CONT.get(lang, lang)
prefix = f"[keyword:{lang}]"
try:
for line in CONTINUATION_CONF.read_text(encoding="utf-8").splitlines():
s = line.strip()
if s.startswith(prefix):
rest = s[len(prefix):].strip()
if not rest:
return _DEFAULT_CONT.get(lang, lang)
first = rest.split(",")[0].strip()
return first or _DEFAULT_CONT.get(lang, lang)
except OSError:
pass
return _DEFAULT_CONT.get(lang, lang)
def _write_state_file(value: str) -> None:
"""Write '0' or '1' to STATE_FILE so the tray/plasmoid can poll visibility."""
try:
STATE_FILE.write_text(value + "\n")
except OSError:
pass
def _parse_args(argv):
p = argparse.ArgumentParser(prog="dictee-cheatsheet", add_help=True)
g = p.add_mutually_exclusive_group()
g.add_argument("--toggle", action="store_const", const="toggle", dest="cmd")
g.add_argument("--close", action="store_const", const="close", dest="cmd")
g.add_argument("--first-run", action="store_const", const="first-run", dest="cmd")
args = p.parse_args(argv)
return args.cmd or "open"
def _try_send_to_existing(command):
"""Try to deliver the command to a running instance.
Returns True if delivered (this process should exit), False otherwise."""
sock = QLocalSocket()
sock.connectToServer(SERVER_NAME)
if not sock.waitForConnected(200):
return False
sock.write(command.encode("utf-8"))
sock.flush()
sock.waitForBytesWritten(200)
sock.disconnectFromServer()
if sock.state() != QLocalSocket.LocalSocketState.UnconnectedState:
sock.waitForDisconnected(200)
return True
class CheatsheetCard(QWidget):
"""Frameless top-most floating card with draggable header."""
def __init__(self):
super().__init__()
self.setObjectName("CheatsheetCard")
self.setWindowFlags(
Qt.WindowType.FramelessWindowHint
| Qt.WindowType.WindowStaysOnTopHint
| Qt.WindowType.Tool
)
self.setWindowTitle("dictee-cheatsheet")
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
# Translucent backing surface so the QSS rgba(...) alpha is honored
# by the compositor (KWin Wayland ignores setWindowOpacity for
# frameless Qt.Tool windows, so we drive opacity via QSS instead).
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.resize(320, 480)
self.setMinimumSize(240, 280)
# Drag state.
self._drag_start = None
self._win_start = None
# Tracks whether we have pushed a resize cursor onto the override
# stack so we never call restoreOverrideCursor() spuriously.
self._edge_cursor_active = False
# Current zoom (body text point size).
self._zoom_pt = DEFAULT_ZOOM_PT
# Window opacity (0.40 - 1.00). Adjusted by wheel on header.
self._opacity = DEFAULT_OPACITY
# Per-category expand/collapse state.
self._cat_state = {cat: (cat in DEFAULT_EXPANDED) for cat in CATEGORY_ORDER}
# First-run onboarding banner (created on demand by show_firstrun_banner).
self._firstrun_banner = None
# Restore persisted zoom + cat_state early (before first render).
# Geometry is restored via QTimer.singleShot to ensure the window
# is fully constructed and screen() is reliable.
self._restore_state()
# Root layout: header / body / footer.
root = QVBoxLayout(self)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
self._header = self._build_header()
root.addWidget(self._header)
# Body wrapped in QScrollArea so accordion expand and zoom never
# resize the window — overflow becomes a vertical/horizontal scroll.
self._body = QFrame()
self._body.setObjectName("CheatsheetBody")
self._body_layout = QVBoxLayout(self._body)
self._body_layout.setContentsMargins(8, 8, 8, 8)
self._body_layout.setSpacing(2)
self._scroll = QScrollArea()
self._scroll.setObjectName("CheatsheetScroll")
self._scroll.setWidgetResizable(True)
self._scroll.setFrameShape(QFrame.Shape.NoFrame)
self._scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
self._scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
self._scroll.setWidget(self._body)
root.addWidget(self._scroll, 1)
self._footer = QFrame()
self._footer.setObjectName("CheatsheetFooter")
self._footer.setFixedHeight(0)
root.addWidget(self._footer)
self._apply_stylesheet()
# Forward wheel events from child widgets to the card so opacity
# adjustment works regardless of where the cursor is.
self._install_wheel_filter()
# Live update: re-render body whenever a watched config file changes.
self._watcher = QFileSystemWatcher(self)
for path in (DICTEE_CONF, CONTINUATION_CONF):
if path.exists():
self._watcher.addPath(str(path))
self._watcher.fileChanged.connect(self._on_config_changed)
self._connect_zoom_buttons()
self._register_shortcuts()
self._render_body()
def _on_config_changed(self, path: str):
"""Re-render when watched config files change. Re-add the path
if QFileSystemWatcher dropped it after an atomic rename
(vim, dictee-setup save, etc.)."""
if path not in self._watcher.files():
self._watcher.addPath(path)
self._render_body()
def _build_header(self):
header = QFrame()
header.setObjectName("CheatsheetHeader")
header.setFixedHeight(40)
layout = QHBoxLayout(header)
layout.setContentsMargins(0, 0, 6, 0)
layout.setSpacing(2)
self._title_label = QLabel("\U0001F3A4 Commandes vocales (FR)")
self._title_label.setObjectName("CheatsheetTitle")
layout.addWidget(self._title_label)
layout.addStretch(1)
self._btn_opacity = QPushButton("◐")
self._btn_opacity.setObjectName("CheatsheetHeaderBtn")
self._btn_opacity.setToolTip("Cycle window opacity")
self._btn_opacity.clicked.connect(self.cycle_opacity)
layout.addWidget(self._btn_opacity)
self._btn_zoom_out = QPushButton("−")
self._btn_zoom_out.setObjectName("CheatsheetHeaderBtn")
self._btn_zoom_out.setToolTip("Zoom out")
layout.addWidget(self._btn_zoom_out)
self._btn_zoom_in = QPushButton("+")
self._btn_zoom_in.setObjectName("CheatsheetHeaderBtn")
self._btn_zoom_in.setToolTip("Zoom in")
layout.addWidget(self._btn_zoom_in)
self._btn_close = QPushButton("×")
self._btn_close.setObjectName("CheatsheetHeaderBtn")
self._btn_close.setToolTip("Close")
self._btn_close.clicked.connect(self.hide)
layout.addWidget(self._btn_close)
return header
def _build_stylesheet(self, zoom_pt: float) -> str:
# All font sizes scale with zoom_pt (body size). Title was 11pt at the
# 12pt default; keep that ratio. Header buttons scale roughly with body.
body_pt = zoom_pt
title_pt = zoom_pt * 11.0 / 12.0
btn_min_size = max(int(zoom_pt * 28 / 12), 24)
# NOTE: the card background and rounded border are painted in
# paintEvent() rather than via QSS; Qt aggressively caches stylesheet
# rules and rgba alpha changes were not always re-applied on Wayland.
return f"""
QWidget#CheatsheetCard {{
background: transparent;
}}
QFrame#CheatsheetHeader {{
background-color: rgba(255, 255, 255, 18);
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}}
QFrame#CheatsheetBody {{
background: transparent;
}}
QFrame#CheatsheetFooter {{
background: transparent;
}}
QLabel#CheatsheetTitle {{
color: #e0e0e0;
font-size: {title_pt}pt;
font-weight: 600;
padding: 8px 12px;
}}
QPushButton#CheatsheetHeaderBtn {{
background: transparent;
color: #b0b0b0;
border: none;
font-size: {body_pt}pt;
min-width: {btn_min_size}px;
min-height: {btn_min_size}px;
}}
QPushButton#CheatsheetHeaderBtn:hover {{
background-color: rgba(255, 255, 255, 26);
border-radius: 4px;
color: #ffffff;
}}
QPushButton#CheatsheetCategoryTitle {{
background: transparent;
color: #8ec5ff;
border: none;
font-size: {title_pt}pt;
font-weight: 600;
text-align: left;
padding: 6px 8px;
}}
QPushButton#CheatsheetCategoryTitle:hover {{
background-color: rgba(255, 255, 255, 13);
border-radius: 4px;
}}
QLabel#CheatsheetCmd {{
color: rgba(224, 224, 224, 217);
font-size: {body_pt}pt;
}}
QLabel#CheatsheetResult {{
color: rgba(224, 224, 224, 128);
font-size: {body_pt}pt;
font-family: "JetBrains Mono", "Fira Code", monospace;
}}
QFrame#CheatsheetFirstRunBanner {{
background-color: rgba(94, 140, 240, 38);
border: 1px solid rgba(94, 140, 240, 76);
border-radius: 6px;
margin: 4px 8px 0 8px;
}}
QLabel#CheatsheetFirstRunText {{
color: #d8e3ff;
font-size: {body_pt}pt;
}}
QScrollArea#CheatsheetScroll {{
background: transparent;
border: none;
}}
QScrollBar:vertical, QScrollBar:horizontal {{
background: transparent;
margin: 0;
}}
QScrollBar:vertical {{
width: 6px;
}}
QScrollBar:horizontal {{
height: 6px;
}}
QScrollBar::handle:vertical, QScrollBar::handle:horizontal {{
background: rgba(255, 255, 255, 51);
border-radius: 3px;
min-width: 20px;
min-height: 20px;
}}
QScrollBar::handle:vertical:hover, QScrollBar::handle:horizontal:hover {{
background: rgba(255, 255, 255, 102);
}}
QScrollBar::add-line, QScrollBar::sub-line,
QScrollBar::add-page, QScrollBar::sub-page {{
background: none;
border: none;
width: 0;
height: 0;
}}
"""
def _apply_stylesheet(self):
self.setStyleSheet(self._build_stylesheet(self._zoom_pt))
# The card background is painted in paintEvent based on self._opacity,
# so trigger a repaint when stylesheet or opacity changes.
self.update()
def paintEvent(self, event):
# Draw the card background ourselves — Qt's stylesheet rgba caching
# was unreliable on Wayland, so the alpha lives in self._opacity and
# is re-rendered every paint.
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
alpha = max(0, min(255, int(round(self._opacity * 255))))
bg = QColor(28, 30, 35, alpha)
border = QColor(255, 255, 255, min(60, alpha))
rect = self.rect().adjusted(0, 0, -1, -1)
painter.setPen(border)
painter.setBrush(bg)
painter.drawRoundedRect(rect, 8, 8)
painter.end()
super().paintEvent(event)
def _connect_zoom_buttons(self):
self._btn_zoom_out.clicked.connect(self.zoom_out)
self._btn_zoom_in.clicked.connect(self.zoom_in)
def _register_shortcuts(self):
# Ctrl++ and Ctrl+= both zoom in (Ctrl+= avoids needing Shift on US layouts).
QShortcut(QKeySequence("Ctrl++"), self, activated=self.zoom_in)
QShortcut(QKeySequence("Ctrl+="), self, activated=self.zoom_in)
QShortcut(QKeySequence("Ctrl+-"), self, activated=self.zoom_out)
QShortcut(QKeySequence("Ctrl+0"), self, activated=self.zoom_reset)
QShortcut(QKeySequence("Ctrl+W"), self, activated=self.hide)
QShortcut(QKeySequence("Escape"), self, activated=self.hide)
def zoom_in(self):
self._zoom_pt = min(self._zoom_pt + ZOOM_STEP, MAX_ZOOM_PT)
self._apply_zoom()
def zoom_out(self):
self._zoom_pt = max(self._zoom_pt - ZOOM_STEP, MIN_ZOOM_PT)
self._apply_zoom()
def zoom_reset(self):
self._zoom_pt = DEFAULT_ZOOM_PT
self._apply_zoom()
def _apply_zoom(self):
# Update the stylesheet — font-sizes propagate to existing widgets.
# Window size stays as-is; body overflow becomes a scroll inside
# the QScrollArea wrapper.
self._apply_stylesheet()
def _render_body(self):
"""Clear and re-build the body content based on current expand state."""
# Clear existing children of the body layout.
while self._body_layout.count():
item = self._body_layout.takeAt(0)
w = item.widget()
if w is not None:
w.setParent(None)
w.deleteLater()
# Resolve current lang + dynamic template values from user config.
lang = _detect_lang()
if lang not in COMMAND_TABLE:
lang = "en"
cont_word = _read_continuation_word(lang)
suffix = _read_suffix(lang)
# Update window title to match current lang.
if hasattr(self, "_title_label"):
self._title_label.setText(f"\U0001F3A4 {TITLE_BY_LANG[lang]}")
labels = CATEGORY_LABELS[lang]
table = COMMAND_TABLE[lang]
for cat in CATEGORY_ORDER:
items = table.get(cat, [])
if not items:
# Skip empty categories (e.g. markdown for non-fr/en).
continue
is_open = self._cat_state[cat]
arrow = "▾" if is_open else "▸"
title_btn = QPushButton(f"{arrow} {labels[cat]}")
title_btn.setObjectName("CheatsheetCategoryTitle")
title_btn.setCursor(Qt.CursorShape.PointingHandCursor)
title_btn.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Fixed)
title_btn.clicked.connect(partial(self._toggle_category, cat))
# Row keeps the button at its natural width and reserves the
# remaining horizontal space for window-drag/resize events.
title_row = QHBoxLayout()
title_row.setContentsMargins(0, 0, 0, 0)
title_row.setSpacing(0)
title_row.addWidget(title_btn)
title_row.addStretch(1)
title_container = QWidget()
title_container.setLayout(title_row)
self._body_layout.addWidget(title_container)
if is_open: