Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
5323 lines (4682 loc) · 187 KB
/
Copy path__init__.py
File metadata and controls
5323 lines (4682 loc) · 187 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
# AnkiThemeTwin/__init__.py — Anki 25.x (Qt6/PyQt6) — v1.6.0
# Enhanced theming with keyboard shortcuts, more font sizes, theme presets, and custom theme creator
# Tools > Theme: AnkiThemeTwin | Help > About AnkiThemeTwin
from aqt import mw, gui_hooks
from aqt.qt import (
QAction, QActionGroup, QApplication, QMenu,
QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, Qt,
QSlider, QColorDialog, QLineEdit, QSpinBox, QScrollArea,
QWidget, QGridLayout, QComboBox, QCheckBox, QTextEdit,
QShortcut, QKeySequence, QFrame, QTimeEdit, QButtonGroup,
QRadioButton, QPalette, QColor, QTimer,
QPixmap, QPainter, QPen, QBrush,
)
from aqt.utils import openLink, showInfo, tooltip
import aqt.utils as _aqt_utils
from typing import Literal, Any, Optional
import json
import os
import random
import math
from datetime import datetime, time
VERSION = "1.6.0"
Theme = Literal[
"sepia_word", "sepia_paper", "gray_word", "gray_paper",
"sepia_special", "blue_light", "olive_green",
"high_contrast_light", "high_contrast_dark", "dyslexia_friendly",
"deuteranopia", "protanopia", "tritanopia"
]
THEME_OPTIONS = [
("Sepia (Word-like)", "sepia_word"),
("Sepia (Paper)", "sepia_paper"),
("Sepia (Special • Dr. M)", "sepia_special"),
("Gray (Word-like)", "gray_word"),
("Gray (Paper)", "gray_paper"),
("Blue Light (Evening)", "blue_light"),
("Olive Green (Natural)", "olive_green"),
]
ACCESSIBILITY_THEMES = [
("High Contrast Light", "high_contrast_light"),
("High Contrast Dark", "high_contrast_dark"),
("Dyslexia Friendly", "dyslexia_friendly"),
("Deuteranopia Support", "deuteranopia"),
("Protanopia Support", "protanopia"),
("Tritanopia Support", "tritanopia"),
]
def get_config():
return mw.addonManager.getConfig(__name__) or {}
def write_config(cfg: dict):
mw.addonManager.writeConfig(__name__, cfg)
# ---------------- Palettes (readability-first) ----------------
SEPIA_WORD = {"bg":"#F9F5E9","fg":"#2A2420","muted":"#5C524A","border":"#D9D0C2",
"accent":"#7B5F4B","button":"#EDE5D6","buttonText":"#2A2420",
"input":"#FCF9F1","inputText":"#2A2420","hover":"#E6DECF","selection":"#DACCB7"}
SEPIA_PAPER = {"bg":"#F3E7D3","fg":"#29231F","muted":"#5B4E44","border":"#CFBEA7",
"accent":"#715843","button":"#E9DFC9","buttonText":"#29231F",
"input":"#FBF4E8","inputText":"#29231F","hover":"#E2D5BF","selection":"#D7C6AC"}
GRAY_WORD = {"bg":"#E6E6E6","fg":"#1E1E1E","muted":"#454545","border":"#CFCFCF",
"accent":"#0F5AA6","button":"#F2F2F2","buttonText":"#1E1E1E",
"input":"#FFFFFF","inputText":"#1E1E1E","hover":"#E0E0E0","selection":"#CFCFCF"}
GRAY_PAPER = {"bg":"#D9D9D9","fg":"#1C1C1C","muted":"#3F3F3F","border":"#BFBFBF",
"accent":"#0F5AA6","button":"#E9E9E9","buttonText":"#1C1C1C",
"input":"#F7F7F7","inputText":"#1C1C1C","hover":"#D2D2D2","selection":"#C5C5C5"}
SEPIA_SPECIAL = {"bg":"#EEDFC6","fg":"#201A16","muted":"#54483F","border":"#CDB99F",
"accent":"#6D523F","button":"#E6D3B7","buttonText":"#201A16",
"input":"#FAF2E4","inputText":"#201A16","hover":"#DFC9A9","selection":"#D2BC9C"}
BLUE_LIGHT = {"bg":"#E8F0F8","fg":"#1A2330","muted":"#4A5568","border":"#C5D5E5",
"accent":"#2C5AA0","button":"#DDE8F5","buttonText":"#1A2330",
"input":"#F5F8FC","inputText":"#1A2330","hover":"#D5E3F2","selection":"#C0D8ED"}
OLIVE_GREEN = {"bg":"#EBF0E4","fg":"#2A2F24","muted":"#4F5449","border":"#D0D9C5",
"accent":"#5A7A3C","button":"#E2EAD8","buttonText":"#2A2F24",
"input":"#F5F8F0","inputText":"#2A2F24","hover":"#DDE7D0","selection":"#D0DFBC"}
# Accessibility themes
HIGH_CONTRAST_LIGHT = {"bg":"#FFFFFF","fg":"#000000","muted":"#404040","border":"#000000",
"accent":"#0000FF","button":"#F0F0F0","buttonText":"#000000",
"input":"#FFFFFF","inputText":"#000000","hover":"#E0E0E0","selection":"#FFFF00"}
HIGH_CONTRAST_DARK = {"bg":"#000000","fg":"#FFFFFF","muted":"#C0C0C0","border":"#FFFFFF",
"accent":"#FFFF00","button":"#1A1A1A","buttonText":"#FFFFFF",
"input":"#000000","inputText":"#FFFFFF","hover":"#2A2A2A","selection":"#FFFF00",
"stateNew":"#93C5FD","stateLearn":"#F87171","stateReview":"#4ADE80",
"stateBuried":"#F59E0B","stateSuspended":"#FEF9C3","stateMarked":"#A855F7"}
DYSLEXIA_FRIENDLY = {"bg":"#FFFACD","fg":"#2F2F2F","muted":"#696969","border":"#E6DB8F",
"accent":"#008B8B","button":"#FFF8B0","buttonText":"#2F2F2F",
"input":"#FFFFF0","inputText":"#2F2F2F","hover":"#FFF48F","selection":"#FFE680"}
# Color blindness support themes
DEUTERANOPIA = {"bg":"#F0F0E8","fg":"#003366","muted":"#666699","border":"#9999CC",
"accent":"#CC6600","button":"#E8E8E0","buttonText":"#003366",
"input":"#FAFAF5","inputText":"#003366","hover":"#E0E0D8","selection":"#CCCCBB"}
PROTANOPIA = {"bg":"#EFF5FF","fg":"#004080","muted":"#5577AA","border":"#99BBDD",
"accent":"#CC7700","button":"#E7EDF5","buttonText":"#004080",
"input":"#F7FBFF","inputText":"#004080","hover":"#DFE9F5","selection":"#CCDDFF"}
TRITANOPIA = {"bg":"#FFF0F0","fg":"#330022","muted":"#775566","border":"#CCAACC",
"accent":"#CC3366","button":"#FFE8E8","buttonText":"#330022",
"input":"#FFF8F8","inputText":"#330022","hover":"#FFE0E0","selection":"#FFCCDD"}
PALETTES = {
"sepia_word": SEPIA_WORD,
"sepia_paper": SEPIA_PAPER,
"gray_word": GRAY_WORD,
"gray_paper": GRAY_PAPER,
"sepia_special": SEPIA_SPECIAL,
"blue_light": BLUE_LIGHT,
"olive_green": OLIVE_GREEN,
"high_contrast_light": HIGH_CONTRAST_LIGHT,
"high_contrast_dark": HIGH_CONTRAST_DARK,
"dyslexia_friendly": DYSLEXIA_FRIENDLY,
"deuteranopia": DEUTERANOPIA,
"protanopia": PROTANOPIA,
"tritanopia": TRITANOPIA,
}
def palette_for(theme: Theme) -> dict:
"""Return the color palette dictionary for the given theme."""
return PALETTES.get(theme, PALETTES["sepia_special"])
def normalize_theme(t: str) -> Theme:
legacy = {"sepia":"sepia_word","gray":"gray_word"}
v = legacy.get(t, t)
return v if v in PALETTES else "sepia_special"
def get_active_theme() -> Theme:
"""Return the currently configured theme."""
cfg = get_config()
return normalize_theme(cfg.get("currentTheme", "sepia_special"))
def is_follow_system_theme() -> bool:
"""Return True if the user wants Anki's native theme (no addon override)."""
cfg = get_config()
return cfg.get("followSystemTheme", False)
def set_follow_system_theme(enabled: bool):
"""Enable or disable follow-system-theme mode."""
cfg = get_config()
cfg["followSystemTheme"] = enabled
write_config(cfg)
if enabled:
_restore_system_theme()
else:
apply_theme_everywhere(get_active_theme())
def _restore_system_theme():
"""Remove all addon styling and let Anki/OS control the theme."""
# Clear application-level QSS
app = QApplication.instance()
if app:
try:
app.setStyleSheet("")
except (RuntimeError, AttributeError):
pass
# Clear main window QSS
try:
mw.setStyleSheet("")
except (RuntimeError, AttributeError):
pass
# Reset Anki's theme to follow system
try:
from aqt.theme import theme_manager
theme_manager.night_mode = theme_manager.default_night_mode()
except (ImportError, AttributeError):
pass # Leave night_mode as-is, Anki will fix on next theme change
# Clear QSS from all open top-level widgets
try:
for widget in QApplication.instance().topLevelWidgets():
try:
if widget.isVisible():
widget.setStyleSheet("")
except (RuntimeError, AttributeError):
continue
except (RuntimeError, AttributeError):
pass
# Refresh webviews to remove our injected CSS
_remove_addon_css_from_webviews()
# Restore original tooltip function
_uninstall_tooltip_patch()
# Restore original load_ts_page
_uninstall_ts_page_patch()
# ---------------- CSS / QSS ----------------
_STYLE_ID = "ankithemetwin-style"
def _remove_addon_css_from_webviews():
"""Remove our injected CSS from all open webviews (used when follow-system-theme is on)."""
remove_js = (
"(function(){"
f"var el=document.getElementById('{_STYLE_ID}');"
"if(el){el.remove();}"
"})();"
)
for attr in ("web", "bottomWeb"):
wv = getattr(mw, attr, None)
if wv:
try:
wv.eval(remove_js)
except (RuntimeError, AttributeError):
pass
app = QApplication.instance()
if app:
try:
from aqt.qt import QWebEngineView
for widget in app.topLevelWidgets():
try:
for wv in widget.findChildren(QWebEngineView):
try:
wv.page().runJavaScript(remove_js)
except (RuntimeError, AttributeError):
pass
except (RuntimeError, AttributeError):
pass
except (ImportError, RuntimeError):
pass
def get_font_size() -> int:
"""Get configured font size, default 16px."""
cfg = get_config()
return cfg.get("fontSize", 16)
def get_font_family() -> str:
"""Get configured font family."""
cfg = get_config()
return cfg.get("fontFamily", "Segoe UI,Amiri,Arial,sans-serif")
def get_line_height() -> float:
"""Get configured line height, default 1.58."""
cfg = get_config()
return cfg.get("lineHeight", 1.58)
def get_letter_spacing() -> float:
"""Get configured letter spacing, default 0."""
cfg = get_config()
return cfg.get("letterSpacing", 0.0)
# ====== Feature 1: Pomodoro / Break Reminder ======
def get_pomodoro_settings() -> dict:
"""Get Pomodoro timer settings."""
cfg = get_config()
return cfg.get("pomodoroSettings", {
"enabled": False,
"studyMinutes": 25,
"breakMinutes": 5,
"autoStart": False,
})
def save_pomodoro_settings(settings: dict):
"""Save Pomodoro timer settings."""
cfg = get_config()
cfg["pomodoroSettings"] = settings
write_config(cfg)
def _start_pomodoro_timer():
"""Start (or restart) the Pomodoro study timer."""
settings = get_pomodoro_settings()
if not settings.get("enabled"):
return
study_ms = settings.get("studyMinutes", 25) * 60 * 1000
if not hasattr(mw, "_ankitwin_pomodoro_timer"):
mw._ankitwin_pomodoro_timer = QTimer(mw)
mw._ankitwin_pomodoro_timer.setSingleShot(True)
mw._ankitwin_pomodoro_timer.timeout.connect(_show_break_reminder)
mw._ankitwin_pomodoro_timer.start(study_ms)
mw._ankitwin_pomodoro_studying = True
def _stop_pomodoro_timer():
"""Stop the Pomodoro timer."""
if hasattr(mw, "_ankitwin_pomodoro_timer"):
mw._ankitwin_pomodoro_timer.stop()
mw._ankitwin_pomodoro_studying = False
def _show_break_reminder():
"""Show a break reminder dialog."""
settings = get_pomodoro_settings()
break_min = settings.get("breakMinutes", 5)
theme = get_active_theme()
p = palette_for(theme)
dlg = QDialog(mw)
dlg.setWindowTitle("Break Time!")
dlg.resize(400, 250)
layout = QVBoxLayout(dlg)
dlg.setStyleSheet(f"background:{p['bg']}; color:{p['fg']};")
icon_lbl = QLabel("☕")
icon_lbl.setStyleSheet("font-size:48px;")
icon_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(icon_lbl)
msg = QLabel(
f"<div style='text-align:center;font-size:16px;'>"
f"<b>Time for a {break_min}-minute break!</b><br><br>"
f"Rest your eyes, stretch, and hydrate.<br>"
f"Your study session will continue after.</div>"
)
msg.setWordWrap(True)
layout.addWidget(msg)
def end_break():
dlg.accept()
if settings.get("autoStart", False):
_start_pomodoro_timer()
tooltip("⏱️ Pomodoro: New study session started!", period=2000)
btn = QPushButton(f"I'm Back! (Start Next Session)")
btn.clicked.connect(end_break)
layout.addWidget(btn)
skip_btn = QPushButton("Skip (Don't Restart Timer)")
skip_btn.clicked.connect(dlg.accept)
layout.addWidget(skip_btn)
dlg.exec()
# ====== Feature 2: Blue Light Filter ======
def get_blue_light_filter() -> int:
"""Get blue light filter intensity (0-100)."""
cfg = get_config()
return max(0, min(100, cfg.get("blueLightFilter", 0)))
def set_blue_light_filter(value: int):
"""Set blue light filter intensity (0-100)."""
cfg = get_config()
cfg["blueLightFilter"] = max(0, min(100, value))
write_config(cfg)
apply_theme_everywhere(get_active_theme())
def _get_blue_light_filter_css() -> str:
"""Generate CSS for the blue light filter overlay."""
intensity = get_blue_light_filter()
if intensity <= 0:
return ""
# Scale opacity from 0.0 to 0.35 based on 0-100 slider
opacity = intensity / 100.0 * 0.35
return (
"#ankithemetwin-bluelight-overlay {"
" position:fixed; top:0; left:0; width:100%; height:100%;"
f" background:rgba(255, 180, 50, {opacity});"
" pointer-events:none; z-index:99999; mix-blend-mode:multiply;"
"}"
)
# ====== Feature 3: Theme Sync via collection.media ======
_SYNC_FILENAME = "_ankithemetwin_sync.json"
def get_sync_enabled() -> bool:
"""Check if theme sync is enabled."""
cfg = get_config()
return cfg.get("syncEnabled", False)
def _get_sync_file_path() -> Optional[str]:
"""Get path to sync file in collection.media."""
try:
media_dir = mw.col.media.dir()
return os.path.join(media_dir, _SYNC_FILENAME)
except (AttributeError, Exception):
return None
def sync_config_to_media():
"""Write current config to collection.media for AnkiWeb sync."""
if not get_sync_enabled():
return
path = _get_sync_file_path()
if not path:
return
try:
cfg = get_config()
sync_data = {
"version": VERSION,
"synced_at": datetime.now().isoformat(),
"configuration": cfg,
}
with open(path, "w", encoding="utf-8") as f:
json.dump(sync_data, f, indent=2)
except (OSError, IOError):
pass
def sync_config_from_media():
"""Import config from collection.media if newer than current."""
if not get_sync_enabled():
return
path = _get_sync_file_path()
if not path or not os.path.exists(path):
return
try:
with open(path, "r", encoding="utf-8") as f:
sync_data = json.load(f)
synced_cfg = sync_data.get("configuration", {})
if synced_cfg:
for key, value in synced_cfg.items():
current_cfg = get_config()
current_cfg[key] = value
write_config(current_cfg)
# Reload custom themes
custom_themes = get_custom_themes()
for name, palette in custom_themes.items():
PALETTES[name] = palette
tooltip("🔄 Settings synced from another device!", period=2000)
except (OSError, IOError, json.JSONDecodeError):
pass
# ====== Feature 4: Note-Type Specific Styling ======
def get_note_type_styles() -> dict:
"""Get per-note-type styling overrides."""
cfg = get_config()
return cfg.get("noteTypeStyles", {})
def set_note_type_style(note_type: str, styles: dict):
"""Set styling overrides for a specific note type."""
cfg = get_config()
nts = get_note_type_styles()
nts[note_type] = styles
cfg["noteTypeStyles"] = nts
write_config(cfg)
tooltip(f"Style for '{note_type}' saved!")
def delete_note_type_style(note_type: str):
"""Remove styling overrides for a note type."""
cfg = get_config()
nts = get_note_type_styles()
if note_type in nts:
del nts[note_type]
cfg["noteTypeStyles"] = nts
write_config(cfg)
def _get_note_type_css(note_type_name: str) -> str:
"""Generate CSS overrides for a specific note type."""
styles = get_note_type_styles()
if note_type_name not in styles:
return ""
s = styles[note_type_name]
css = ""
if "fontSize" in s:
css += f".card {{ font-size:{s['fontSize']}px !important; }}"
if "fontFamily" in s:
css += f".card {{ font-family:{s['fontFamily']} !important; }}"
if "lineHeight" in s:
css += f".card {{ line-height:{s['lineHeight']} !important; }}"
if "theme" in s and s["theme"] in PALETTES:
p = PALETTES[s["theme"]]
css += (
f".card {{ background:{p['bg']} !important; color:{p['fg']} !important; }}"
)
return css
# ====== Feature 5: Zen Mode ======
def get_zen_mode() -> bool:
"""Get zen mode state."""
cfg = get_config()
return cfg.get("zenMode", False)
def toggle_zen_mode():
"""Toggle zen mode on/off."""
cfg = get_config()
new_state = not cfg.get("zenMode", False)
cfg["zenMode"] = new_state
write_config(cfg)
apply_theme_everywhere(get_active_theme())
if new_state:
tooltip("🧘 Zen Mode enabled — distraction-free review", period=2000)
else:
tooltip("🧘 Zen Mode disabled", period=2000)
def _get_zen_mode_css() -> str:
"""CSS to hide UI elements for zen mode."""
return (
"/* Zen Mode: hide distracting elements */"
"#header, .header, .toolbar, .deck-info, .deckname, nav,"
"#studycount, #cardcount, .stat, .stattxt {"
" display:none !important;"
"}"
".card, .card1, .card2, .card3 {"
" max-width:800px; margin:40px auto !important;"
" padding:40px !important; min-height:60vh;"
"}"
"#qa { max-width:800px; margin:0 auto; padding:20px; }"
"body { display:flex; flex-direction:column;"
" justify-content:center; min-height:100vh; }"
)
# ====== Feature 6: Theme Rotation ======
def get_rotation_settings() -> dict:
"""Get theme rotation settings."""
cfg = get_config()
return cfg.get("themeRotation", {
"enabled": False,
"themes": [],
"intervalCards": 10,
"intervalMinutes": 0,
})
def save_rotation_settings(settings: dict):
"""Save theme rotation settings."""
cfg = get_config()
cfg["themeRotation"] = settings
write_config(cfg)
def _check_theme_rotation():
"""Check if it's time to rotate the theme (card-based)."""
settings = get_rotation_settings()
if not settings.get("enabled") or not settings.get("themes"):
return
interval = settings.get("intervalCards", 10)
if interval <= 0:
return
count = getattr(mw, "_ankitwin_rotation_count", 0) + 1
mw._ankitwin_rotation_count = count
if count >= interval:
mw._ankitwin_rotation_count = 0
themes = settings["themes"]
# Filter to valid themes
valid = [t for t in themes if t in PALETTES]
if valid:
current = get_active_theme()
choices = [t for t in valid if t != current] or valid
new_theme = random.choice(choices)
set_theme(new_theme)
tooltip(f"🔄 Theme rotated to {new_theme.replace('_', ' ').title()}", period=1500)
def _start_rotation_timer():
"""Start timer-based theme rotation if configured."""
settings = get_rotation_settings()
if not settings.get("enabled"):
return
minutes = settings.get("intervalMinutes", 0)
if minutes <= 0:
return
if not hasattr(mw, "_ankitwin_rotation_timer"):
mw._ankitwin_rotation_timer = QTimer(mw)
mw._ankitwin_rotation_timer.timeout.connect(_rotate_theme_by_timer)
mw._ankitwin_rotation_timer.start(minutes * 60 * 1000)
def _rotate_theme_by_timer():
"""Rotate theme on timer interval."""
settings = get_rotation_settings()
if not settings.get("enabled") or not settings.get("themes"):
return
valid = [t for t in settings["themes"] if t in PALETTES]
if valid:
current = get_active_theme()
choices = [t for t in valid if t != current] or valid
new_theme = random.choice(choices)
set_theme(new_theme)
tooltip(f"🔄 Theme rotated to {new_theme.replace('_', ' ').title()}", period=1500)
# ====== Feature 7: Custom CSS Injection ======
def get_custom_css() -> str:
"""Get user's custom CSS string."""
cfg = get_config()
return cfg.get("customCSS", "")
def set_custom_css(css: str):
"""Set user's custom CSS."""
cfg = get_config()
cfg["customCSS"] = css
write_config(cfg)
apply_theme_everywhere(get_active_theme())
# ====== Feature 9: Ambient Light Auto-Adjust ======
def get_ambient_light_settings() -> dict:
"""Get ambient light auto-adjust settings."""
cfg = get_config()
return cfg.get("ambientLightAuto", {
"enabled": False,
"minFilter": 0,
"maxFilter": 60,
})
def save_ambient_light_settings(settings: dict):
"""Save ambient light settings."""
cfg = get_config()
cfg["ambientLightAuto"] = settings
write_config(cfg)
def _calculate_ambient_filter() -> int:
"""Calculate blue light filter based on time of day (solar position estimate).
Returns a value 0-100 representing blue light filter intensity.
Peaks at night (around midnight), lowest at midday.
"""
settings = get_ambient_light_settings()
if not settings.get("enabled"):
return get_blue_light_filter() # Return manual setting
min_filter = settings.get("minFilter", 0)
max_filter = settings.get("maxFilter", 60)
now = datetime.now()
# Hour as fraction (0-24)
hour_frac = now.hour + now.minute / 60.0
# Cosine curve: peaks at midnight (hour 0/24), valley at noon (hour 12)
# cos(0) = 1 (midnight, max filter), cos(pi) = -1 (noon, min filter)
radians = (hour_frac / 24.0) * 2 * math.pi
factor = (math.cos(radians) + 1) / 2 # Normalized 0-1
filter_value = int(min_filter + factor * (max_filter - min_filter))
return max(0, min(100, filter_value))
def _apply_ambient_light():
"""Apply time-based blue light filter adjustment."""
settings = get_ambient_light_settings()
if not settings.get("enabled"):
return
new_filter = _calculate_ambient_filter()
current = get_blue_light_filter()
if abs(new_filter - current) >= 2: # Only update if meaningful change
cfg = get_config()
cfg["blueLightFilter"] = new_filter
write_config(cfg)
refresh_all_webviews()
# ====== Feature 12: Match Card Background ======
def get_match_card_background() -> bool:
"""Check if match card background is enabled."""
cfg = get_config()
return cfg.get("matchCardBackground", False)
def toggle_match_card_background():
"""Toggle match card background feature."""
cfg = get_config()
new_state = not cfg.get("matchCardBackground", False)
cfg["matchCardBackground"] = new_state
write_config(cfg)
apply_theme_everywhere(get_active_theme())
tooltip(f"Match Card Background: {'enabled' if new_state else 'disabled'}")
# ====== Feature 13: Status Bar Indicator ======
def get_status_bar_enabled() -> bool:
"""Check if status bar indicator is enabled."""
cfg = get_config()
return cfg.get("statusBarIndicator", True)
def _update_status_bar():
"""Update the status bar with current theme info."""
if not get_status_bar_enabled():
return
try:
theme = get_active_theme()
theme_name = theme.replace("_", " ").title()
font_size = get_font_size()
zen = " | 🧘 Zen" if get_zen_mode() else ""
bl = get_blue_light_filter()
bl_text = f" | 🔆 BL:{bl}%" if bl > 0 else ""
msg = f"🎨 {theme_name} | {font_size}px{bl_text}{zen}"
if not hasattr(mw, "_ankitwin_status_label"):
mw._ankitwin_status_label = QLabel()
mw.statusBar().addPermanentWidget(mw._ankitwin_status_label)
mw._ankitwin_status_label.setText(msg)
mw._ankitwin_status_label.setVisible(True)
except (RuntimeError, AttributeError):
pass
def _hide_status_bar():
"""Hide the status bar indicator."""
if hasattr(mw, "_ankitwin_status_label"):
try:
mw._ankitwin_status_label.setVisible(False)
except (RuntimeError, AttributeError):
pass
# ====== Feature 15: Seasonal Themes ======
SEASONAL_THEMES = {
"spring": {"months": [3, 4, 5], "theme": "olive_green", "label": "Spring (March-May)"},
"summer": {"months": [6, 7, 8], "theme": "blue_light", "label": "Summer (June-August)"},
"autumn": {"months": [9, 10, 11], "theme": "sepia_special", "label": "Autumn (September-November)"},
"winter": {"months": [12, 1, 2], "theme": "gray_word", "label": "Winter (December-February)"},
}
def get_seasonal_themes_enabled() -> bool:
"""Check if seasonal themes are enabled."""
cfg = get_config()
return cfg.get("seasonalThemes", {}).get("enabled", False)
def _check_seasonal_theme():
"""Apply seasonal theme if enabled."""
if not get_seasonal_themes_enabled():
return
cfg = get_config()
seasonal_cfg = cfg.get("seasonalThemes", {})
month = datetime.now().month
for season, data in SEASONAL_THEMES.items():
if month in data["months"]:
# Use user-configured theme or fall back to default
target = seasonal_cfg.get(season, data["theme"])
if target not in PALETTES:
target = data["theme"]
current = get_active_theme()
if current != target:
cfg["currentTheme"] = target
write_config(cfg)
apply_theme_everywhere(target)
tooltip(f"🌿 Seasonal theme: {data['label']}", period=2000)
break
# ====== Feature 14: Community Theme Gallery (bundled themes) ======
COMMUNITY_THEMES = {
"Solarized Light": {
"bg": "#FDF6E3", "fg": "#657B83", "muted": "#93A1A1", "border": "#EEE8D5",
"accent": "#268BD2", "button": "#EEE8D5", "buttonText": "#657B83",
"input": "#FDF6E3", "inputText": "#657B83", "hover": "#EEE8D5", "selection": "#D6DBDF",
},
"Nord Light": {
"bg": "#ECEFF4", "fg": "#2E3440", "muted": "#4C566A", "border": "#D8DEE9",
"accent": "#5E81AC", "button": "#E5E9F0", "buttonText": "#2E3440",
"input": "#ECEFF4", "inputText": "#2E3440", "hover": "#D8DEE9", "selection": "#C0C8D8",
},
"Rosé Pine Dawn": {
"bg": "#FAF4ED", "fg": "#575279", "muted": "#9893A5", "border": "#DFDAD9",
"accent": "#D7827E", "button": "#F2E9E1", "buttonText": "#575279",
"input": "#FFFAF3", "inputText": "#575279", "hover": "#F2E9E1", "selection": "#DFDAD9",
},
"Gruvbox Light": {
"bg": "#FBF1C7", "fg": "#3C3836", "muted": "#928374", "border": "#EBDBB2",
"accent": "#D65D0E", "button": "#EBDBB2", "buttonText": "#3C3836",
"input": "#FBF1C7", "inputText": "#3C3836", "hover": "#EBDBB2", "selection": "#D5C4A1",
},
"Catppuccin Latte": {
"bg": "#EFF1F5", "fg": "#4C4F69", "muted": "#9CA0B0", "border": "#CCD0DA",
"accent": "#1E66F5", "button": "#E6E9EF", "buttonText": "#4C4F69",
"input": "#EFF1F5", "inputText": "#4C4F69", "hover": "#CCD0DA", "selection": "#BCC0CC",
},
"Tokyo Night Light": {
"bg": "#D5D6DB", "fg": "#343B58", "muted": "#9699A3", "border": "#C0C1C8",
"accent": "#34548A", "button": "#C8C9D0", "buttonText": "#343B58",
"input": "#D5D6DB", "inputText": "#343B58", "hover": "#C0C1C8", "selection": "#B0B1BA",
},
"Everforest Light": {
"bg": "#FDF6E3", "fg": "#5C6A72", "muted": "#829181", "border": "#E0DCC7",
"accent": "#8DA101", "button": "#EFE8CF", "buttonText": "#5C6A72",
"input": "#FDF6E3", "inputText": "#5C6A72", "hover": "#E0DCC7", "selection": "#D4CCAD",
},
"Dracula Light": {
"bg": "#F8F8F2", "fg": "#282A36", "muted": "#6272A4", "border": "#E0E0E0",
"accent": "#BD93F9", "button": "#E8E8E4", "buttonText": "#282A36",
"input": "#F8F8F2", "inputText": "#282A36", "hover": "#E0E0E0", "selection": "#D0D0CE",
},
}
def css_vars(p):
"""Generate comprehensive CSS for all webview contexts."""
font_size = get_font_size()
font_family = get_font_family()
line_height = get_line_height()
letter_spacing = get_letter_spacing()
anim_settings = get_animation_settings()
# Animation CSS based on settings
transitions = ""
if anim_settings.get("enabled", True):
duration = anim_settings.get("duration", 300)
style = anim_settings.get("style", "fade")
if style == "fade":
transitions = f"transition: all {duration}ms ease-in-out;"
elif style == "slide":
transitions = f"transition: all {duration}ms cubic-bezier(0.4, 0, 0.2, 1);"
elif style == "morph":
transitions = f"transition: all {duration}ms cubic-bezier(0.68, -0.55, 0.265, 1.55);"
elif style == "zoom":
transitions = f"transition: all {duration}ms cubic-bezier(0.175, 0.885, 0.32, 1.275);"
else:
transitions = f"transition: all {duration}ms ease-in-out;"
# Blue light filter CSS
blue_light_css = _get_blue_light_filter_css()
# Custom user CSS
user_css = get_custom_css()
# Zen mode CSS
zen_css = _get_zen_mode_css() if get_zen_mode() else ""
# Card template helper variables (--att-* prefix)
template_helper_css = (
f" --att-bg: {p['bg']};"
f" --att-fg: {p['fg']};"
f" --att-muted: {p['muted']};"
f" --att-border: {p['border']};"
f" --att-accent: {p['accent']};"
f" --att-button: {p['button']};"
f" --att-button-text: {p['buttonText']};"
f" --att-input: {p['input']};"
f" --att-input-text: {p['inputText']};"
f" --att-hover: {p['hover']};"
f" --att-selection: {p['selection']};"
f" --att-font-size: {font_size}px;"
f" --att-font-family: {font_family};"
f" --att-line-height: {line_height};"
f" --att-letter-spacing: {letter_spacing}px;"
)
return (
# ── CSS Custom Properties ──────────────────────────────────────
# These are the ONLY official Anki CSS variables (from _vars.scss).
# Anki's Svelte components read these variables to style themselves.
# Using !important ensures our values win over Anki's default :root.
# We do NOT directly style HTML elements with !important, because
# that would override the Svelte component styles.
":root {"
# Canvas (backgrounds)
f" --canvas: {p['bg']} !important;"
f" --canvas-elevated: {p['input']} !important;"
f" --canvas-overlay: {p['bg']} !important;"
f" --canvas-inset: {p['input']} !important;"
f" --canvas-glass: {p['bg']}ee !important;"
f" --canvas-code: {p['input']} !important;"
# Foreground (text)
f" --fg: {p['fg']} !important;"
f" --fg-subtle: {p['muted']} !important;"
f" --fg-disabled: {p['muted']} !important;"
f" --fg-faint: {p['border']} !important;"
f" --fg-link: {p['accent']} !important;"
# Shadows
f" --shadow: {p['border']} !important;"
f" --shadow-inset: {p['muted']} !important;"
f" --shadow-subtle: {p['hover']} !important;"
f" --shadow-focus: {p['accent']} !important;"
# Borders
f" --border: {p['border']} !important;"
f" --border-subtle: {p['border']} !important;"
f" --border-strong: {p['muted']} !important;"
f" --border-focus: {p['accent']} !important;"
# Buttons
f" --button-bg: {p['button']} !important;"
f" --button-gradient-start: {p['button']} !important;"
f" --button-gradient-end: {p['hover']} !important;"
f" --button-hover-border: {p['accent']} !important;"
f" --button-disabled: {p['border']} !important;"
# Primary button — fg must be white for readability on colored bg
f" --button-primary-bg: {p['accent']} !important;"
f" --button-primary-gradient-start: {p['accent']} !important;"
f" --button-primary-gradient-end: {p['accent']} !important;"
f" --button-primary-disabled: {p['muted']} !important;"
# Scrollbar
f" --scrollbar-bg: {p['border']} !important;"
f" --scrollbar-bg-hover: {p['muted']} !important;"
f" --scrollbar-bg-active: {p['accent']} !important;"
# Accent colors — card (blue) and note (green) are distinct in Anki
f" --accent-card: {p['accent']} !important;"
f" --accent-note: {p.get('accentNote', '#16A34A')} !important;"
f" --accent-danger: #E74C3C !important;"
# Highlight and selection
f" --highlight-bg: {p['selection']} !important;"
f" --highlight-fg: {p['fg']} !important;"
f" --selected-bg: {p['selection']} !important;"
f" --selected-fg: {p['fg']} !important;"
# Flags
f" --flag-1: #E74C3C !important;"
f" --flag-2: #E67E22 !important;"
f" --flag-3: #2ECC71 !important;"
f" --flag-4: #3498DB !important;"
f" --flag-5: #FF69B4 !important;"
f" --flag-6: #40E0D0 !important;"
f" --flag-7: #9B59B6 !important;"
# Card state colors
f" --state-new: {p.get('stateNew', '#3B82F6')} !important;"
f" --state-learn: {p.get('stateLearn', '#DC2626')} !important;"
f" --state-review: {p.get('stateReview', '#16A34A')} !important;"
f" --state-buried: {p.get('stateBuried', '#D97706')} !important;"
f" --state-suspended: {p.get('stateSuspended', '#EAB308')} !important;"
f" --state-marked: {p.get('stateMarked', '#6366F1')} !important;"
# Non-color properties from Anki's _vars.scss
f" --font-size: {font_size}px !important;"
f" --border-radius: 5px !important;"
f" --border-radius-medium: 12px !important;"
f" --border-radius-large: 15px !important;"
f" --transition: 180ms !important;"
f" --transition-medium: 500ms !important;"
f" --transition-slow: 1000ms !important;"
f" --blur: 20px !important;"
# Feature 8: Theme-aware card template helper variables (--att-* prefix)
+ template_helper_css +
"}"
# ── Minimal direct styles ──────────────────────────────────────
# Only html/body and .card get direct styling. Everything else is
# handled by Anki's Svelte components reading the CSS variables above.
# We do NOT use !important on element styles so that Svelte components
# and card templates can override them with their own specific styles.
"html, body {"
f" background: var(--canvas, {p['bg']});"
f" color: var(--fg, {p['fg']});"
f' font-family:{font_family};'
f" line-height:{line_height}; font-size:{font_size}px;"
f" letter-spacing:{letter_spacing}px;"
" -webkit-font-smoothing:antialiased; text-rendering:optimizeLegibility;"
"}"
# Card content — only background and color, like native Anki.
# Card templates control their own layout, fonts, and element styling.
f".card, .card1, .card2, .card3 {{"
f" background: var(--canvas, {p['bg']}); color: var(--fg, {p['fg']});"
"}}"
f"::selection {{ background:{p['selection']}; color:{p['fg']}; }}"
# Scrollbar theming (doesn't conflict with Svelte)
f"::-webkit-scrollbar {{ width:12px; height:12px; }}"
f"::-webkit-scrollbar-track {{ background: var(--canvas, {p['bg']}); }}"
f"::-webkit-scrollbar-thumb {{"
f" background: var(--scrollbar-bg, {p['border']});"
f" border-radius:6px; border:2px solid var(--canvas, {p['bg']});"
"}}"
f"::-webkit-scrollbar-thumb:hover {{"
f" background: var(--scrollbar-bg-hover, {p['muted']});"
"}}"
# Night mode fallback — ensure our background/color wins when Anki
# adds nightMode/night_mode class in dark mode scenarios
f"body.nightMode, body.night_mode {{"
f" background: var(--canvas, {p['bg']}) !important;"
f" color: var(--fg, {p['fg']}) !important;"
"}}"
f".nightMode .card, .night_mode .card {{"
f" background: var(--canvas, {p['bg']}) !important;"
f" color: var(--fg, {p['fg']}) !important;"
"}}"
# Animation keyframes (Feature 11 — only definitions, not applied)
"@keyframes slideIn {"
" from { opacity:0; transform:translateX(-20px); }"
" to { opacity:1; transform:translateX(0); }"
"}"
"@keyframes zoomIn {"
" from { opacity:0; transform:scale(0.8); }"
" to { opacity:1; transform:scale(1); }"
"}"
"@keyframes morphIn {"
" 0% { opacity:0; transform:scale(0.95) rotate(-1deg); }"
" 50% { opacity:0.8; transform:scale(1.02) rotate(0.5deg); }"
" 100% { opacity:1; transform:scale(1) rotate(0); }"
"}"
# Blue light filter overlay (Feature 2)
+ blue_light_css
# Zen mode CSS (Feature 5)
+ zen_css
# User custom CSS (Feature 7)
+ user_css
)
def inject_css(web_content, ctx):
"""Inject CSS into webviews with context-specific enhancements."""
if is_follow_system_theme():
return
theme = get_active_theme()
p = palette_for(theme)
# Base CSS for all contexts
base_css = css_vars(p)
# Add background pattern CSS if enabled
pattern = get_background_pattern()
pattern_css = get_pattern_css(p, pattern)
# Context-specific CSS additions
context_css = ""
# Check context type and add specific styling
ctx_name = ctx.__class__.__name__ if hasattr(ctx, '__class__') else str(ctx)
# DeckBrowser - main deck list (plain HTML, not Svelte — needs element styling)
if "DeckBrowser" in ctx_name:
context_css += f"""
/* Deck browser specific — this is plain HTML, not Svelte components */
a {{ color:{p['accent']}; }}
table {{ background:{p['bg']}; color:{p['fg']}; }}
td {{ color:{p['fg']}; padding:6px; }}
th {{ background:{p['button']}; color:{p['buttonText']}; padding:8px; }}
tr:hover {{ background:{p['hover']}; }}
.deck {{ color:{p['fg']}; }}
.deck-current {{ background:{p['hover']}; }}
tr.deck td {{ padding:8px; color:{p['fg']}; }}
.collapse {{ color:{p['muted']}; }}
.filtered {{ color:{p['accent']}; }}
.gears {{ color:{p['muted']}; }}
button {{ background:{p['button']}; color:{p['buttonText']}; border:1px solid {p['border']}; border-radius:5px; padding:6px 12px; }}
button:hover {{ background:{p['hover']}; }}
"""
# Reviewer - card display
elif "Reviewer" in ctx_name or "Review" in ctx_name:
context_css += f"""
/* Reviewer specific — style the page and Anki UI elements.
Card content inherits color from .card which is set in base CSS.
We do NOT force color on generic elements (p, span, div, li)
because user card templates control their own formatting. */
#qa {{ background: var(--canvas, {p['bg']}); }}
.replay-button {{ background:{p['button']}; border:1px solid {p['border']}; }}
.typeGood {{ color:{p['accent']}; }}
.typeBad {{ color:#E74C3C; }}
.typeMissed {{ color:#F39C12; }}
/* Bottom bar answer buttons and stats */
.stattxt {{ color: var(--fg, {p['fg']}); }}
"""
# Editor or AddCards - note editing
elif "Editor" in ctx_name or "AddCards" in ctx_name or "NoteEditor" in ctx_name:
context_css += f"""
/* Editor specific */
.fname {{ color:{p['muted']} !important; font-size:12px; }}
.field {{ min-height:60px !important; background:{p['input']} !important; color:{p['inputText']} !important; }}