-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathmain.py
1849 lines (1540 loc) · 62.2 KB
/
main.py
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
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations
import enum
import gc
import os
import re
import signal
import sys
import traceback
import weakref
from argparse import Namespace
from collections.abc import Callable, Sequence
from concurrent.futures import Future
from typing import Any, Literal, TypeVar, cast
import anki
import anki.cards
import anki.sound
import aqt
import aqt.forms
import aqt.mediasrv
import aqt.mpv
import aqt.operations
import aqt.progress
import aqt.sound
import aqt.stats
import aqt.toolbar
import aqt.webview
from anki import hooks
from anki._backend import RustBackend as _RustBackend
from anki._legacy import deprecated
from anki.collection import Collection, Config, OpChanges, UndoStatus
from anki.decks import DeckDict, DeckId
from anki.hooks import runHook
from anki.notes import NoteId
from anki.sound import AVTag, SoundOrVideoTag
from anki.utils import (
dev_mode,
ids2str,
int_time,
int_version,
is_lin,
is_mac,
is_win,
split_fields,
)
from aqt import gui_hooks
from aqt.addons import DownloadLogEntry, check_and_prompt_for_updates, show_log_to_user
from aqt.dbcheck import check_db
from aqt.debug_console import show_debug_console
from aqt.emptycards import show_empty_cards
from aqt.flags import FlagManager
from aqt.import_export.exporting import ExportDialog
from aqt.import_export.importing import (
import_collection_package_op,
import_file,
prompt_for_file_then_import,
)
from aqt.legacy import install_pylib_legacy
from aqt.mediacheck import check_media_db
from aqt.mediasync import MediaSyncer
from aqt.operations import QueryOp
from aqt.operations.collection import redo, undo
from aqt.operations.deck import set_current_deck
from aqt.profiles import ProfileManager as ProfileManagerType
from aqt.qt import *
from aqt.qt import sip
from aqt.sync import sync_collection, sync_login
from aqt.taskman import TaskManager
from aqt.theme import Theme, theme_manager
from aqt.toolbar import BottomWebView, Toolbar, TopWebView
from aqt.undo import UndoActionsInfo
from aqt.utils import (
HelpPage,
KeyboardModifiersPressed,
askUser,
checkInvalidFilename,
current_window,
disallow_full_screen,
getFile,
getOnlyText,
openHelp,
openLink,
restoreGeom,
restoreState,
saveGeom,
saveState,
showInfo,
showWarning,
tooltip,
tr,
)
from aqt.webview import AnkiWebView, AnkiWebViewKind
install_pylib_legacy()
MainWindowState = Literal[
"startup", "deckBrowser", "overview", "review", "resetRequired", "profileManager"
]
T = TypeVar("T")
class MainWebView(AnkiWebView):
def __init__(self, mw: AnkiQt) -> None:
AnkiWebView.__init__(self, kind=AnkiWebViewKind.MAIN)
self.mw = mw
self.setFocusPolicy(Qt.FocusPolicy.WheelFocus)
self.setMinimumWidth(400)
self.setAcceptDrops(True)
# Importing files via drag & drop
##########################################################################
def dragEnterEvent(self, event: QDragEnterEvent) -> None:
if self.mw.state != "deckBrowser":
return super().dragEnterEvent(event)
mime = event.mimeData()
if not mime.hasUrls():
return
for url in mime.urls():
path = url.toLocalFile()
if not os.path.exists(path) or os.path.isdir(path):
return
event.accept()
def dropEvent(self, event: QDropEvent) -> None:
import aqt.importing
if self.mw.state != "deckBrowser":
return super().dropEvent(event)
mime = event.mimeData()
paths = [url.toLocalFile() for url in mime.urls()]
deck_paths = filter(lambda p: not p.endswith(".colpkg"), paths)
for path in deck_paths:
if not self.mw.pm.legacy_import_export():
import_file(self.mw, path)
else:
aqt.importing.importFile(self.mw, path)
# importing continues after the above call returns, so it is not
# currently safe for us to import more than one file at once
return
# Main webview specific event handling
def eventFilter(self, obj, evt):
if handled := super().eventFilter(obj, evt):
return handled
if evt.type() == QEvent.Type.Leave:
# Show menubar when mouse moves outside main webview in fullscreen
if self.mw.fullscreen:
self.mw.show_menubar()
# Show toolbar when mouse moves outside main webview
# and automatically hide it with delay after mouse has entered again
# The toolbar's hide timer will also trigger menubar hiding when in fullscreen mode
if self.mw.pm.hide_top_bar() or self.mw.pm.hide_bottom_bar():
self.mw.toolbarWeb.show()
self.mw.bottomWeb.show()
return True
if evt.type() == QEvent.Type.Enter:
self.mw.toolbarWeb.hide_timer.start()
self.mw.bottomWeb.hide_timer.start()
return True
return False
class AnkiQt(QMainWindow):
col: Collection
pm: ProfileManagerType
web: MainWebView
bottomWeb: BottomWebView
def __init__(
self,
app: aqt.AnkiApp,
profileManager: ProfileManagerType,
backend: _RustBackend,
opts: Namespace,
args: list[Any],
) -> None:
QMainWindow.__init__(self)
self.backend = backend
self.state: MainWindowState = "startup"
self.opts = opts
self.col: Collection | None = None
self.taskman = TaskManager(self)
self.media_syncer = MediaSyncer(self)
aqt.mw = self
self.app = app
self.pm = profileManager
self.fullscreen = False
# init rest of app
self.safeMode = (
bool(self.app.queryKeyboardModifiers() & Qt.KeyboardModifier.ShiftModifier)
or self.opts.safemode
)
try:
self.setupUI()
self.setupAddons(args)
self.finish_ui_setup()
except Exception:
showInfo(tr.qt_misc_error_during_startup(val=traceback.format_exc()))
sys.exit(1)
# must call this after ui set up
if self.safeMode:
tooltip(tr.qt_misc_shift_key_was_held_down_skipping())
# were we given a file to import?
if args and args[0] and not self._isAddon(args[0]):
self.onAppMsg(args[0])
# Load profile in a timer so we can let the window finish init and not
# close on profile load error.
if is_win:
fn = self.setupProfileAfterWebviewsLoaded
else:
fn = self.setupProfile
def on_window_init() -> None:
fn()
gui_hooks.main_window_did_init()
self.progress.single_shot(10, on_window_init, False)
def setupUI(self) -> None:
self.col = None
self.disable_automatic_garbage_collection()
self.setupAppMsg()
self.setupKeys()
self.setupThreads()
self.setupMediaServer()
self.setupSpellCheck()
self.setupProgress()
self.setupStyle()
self.setupMainWindow()
self.setupSystemSpecific()
self.setupMenus()
self.setupErrorHandler()
self.setupSignals()
self.setupHooks()
self.setup_timers()
self.updateTitleBar()
self.setup_focus()
# screens
self.setupDeckBrowser()
self.setupOverview()
self.setupReviewer()
def finish_ui_setup(self) -> None:
"Actions that are deferred until after add-on loading."
self.toolbar.draw()
# add-ons are only available here after setupAddons
gui_hooks.reviewer_did_init(self.reviewer)
def setupProfileAfterWebviewsLoaded(self) -> None:
for w in (self.web, self.bottomWeb):
if not w._domDone:
self.progress.single_shot(
10,
self.setupProfileAfterWebviewsLoaded,
False,
)
return
else:
w.requiresCol = True
self.setupProfile()
def weakref(self) -> AnkiQt:
"Shortcut to create a weak reference that doesn't break code completion."
return weakref.proxy(self) # type: ignore
def setup_focus(self) -> None:
qconnect(self.app.focusChanged, self.on_focus_changed)
def on_focus_changed(self, old: QWidget, new: QWidget) -> None:
gui_hooks.focus_did_change(new, old)
# Profiles
##########################################################################
class ProfileManager(QMainWindow):
onClose = pyqtSignal()
closeFires = True
def closeEvent(self, evt: QCloseEvent) -> None:
if self.closeFires:
self.onClose.emit() # type: ignore
evt.accept()
def closeWithoutQuitting(self) -> None:
self.closeFires = False
self.close()
self.closeFires = True
def setupProfile(self) -> None:
if self.pm.meta["firstRun"]:
# load the new deck user profile
self.pm.load(self.pm.profiles()[0])
self.pm.meta["firstRun"] = False
self.pm.save()
self.pendingImport: str | None = None
self.restoring_backup = False
# - if a valid profile was provided on commandline, we load it
# - if an invalid profile was provided, we skip this step and show the picker
# - if no profile was provided, we use this step
if not self.pm.name and not self.pm.invalid_profile_provided_on_commandline:
profs = self.pm.profiles()
name = self.pm.last_loaded_profile_name()
if len(profs) == 1:
self.pm.load(profs[0])
elif name in profs:
self.pm.load(name)
if not self.pm.name:
self.showProfileManager()
else:
self.loadProfile()
def showProfileManager(self) -> None:
self.pm.profile = None
self.moveToState("profileManager")
d = self.profileDiag = self.ProfileManager()
f = self.profileForm = aqt.forms.profiles.Ui_MainWindow()
f.setupUi(d)
qconnect(f.login.clicked, self.onOpenProfile)
qconnect(f.profiles.itemDoubleClicked, self.onOpenProfile)
qconnect(f.openBackup.clicked, self.onOpenBackup)
qconnect(f.quit.clicked, d.close)
qconnect(d.onClose, self.cleanupAndExit)
qconnect(f.add.clicked, self.onAddProfile)
qconnect(f.rename.clicked, self.onRenameProfile)
qconnect(f.delete_2.clicked, self.onRemProfile)
qconnect(f.profiles.currentRowChanged, self.onProfileRowChange)
f.statusbar.setVisible(False)
qconnect(f.downgrade_button.clicked, self._on_downgrade)
f.downgrade_button.setText(tr.profiles_downgrade_and_quit())
# enter key opens profile
QShortcut(QKeySequence("Return"), d, activated=self.onOpenProfile) # type: ignore
self.refreshProfilesList()
# raise first, for osx testing
d.show()
d.activateWindow()
d.raise_()
def refreshProfilesList(self) -> None:
f = self.profileForm
f.profiles.clear()
profs = self.pm.profiles()
f.profiles.addItems(profs)
try:
idx = profs.index(self.pm.name)
except Exception:
idx = 0
f.profiles.setCurrentRow(idx)
def onProfileRowChange(self, n: int) -> None:
if n < 0:
# called on .clear()
return
name = self.pm.profiles()[n]
self.pm.load(name)
def openProfile(self) -> None:
name = self.pm.profiles()[self.profileForm.profiles.currentRow()]
self.pm.load(name)
return
def onOpenProfile(self, *, callback: Callable[[], None] | None = None) -> None:
def on_done() -> None:
self.profileDiag.closeWithoutQuitting()
if callback:
callback()
self.profileDiag.hide()
# code flow is confusing here - if load fails, profile dialog
# will be shown again
self.loadProfile(on_done)
def profileNameOk(self, name: str) -> bool:
return not checkInvalidFilename(name) and name != "addons21"
def onAddProfile(self) -> None:
name = getOnlyText(tr.actions_name()).strip()
if name:
if name in self.pm.profiles():
showWarning(tr.qt_misc_name_exists())
return
if not self.profileNameOk(name):
return
self.pm.create(name)
self.pm.name = name
self.refreshProfilesList()
def onRenameProfile(self) -> None:
name = getOnlyText(tr.actions_new_name(), default=self.pm.name).strip()
if not name:
return
if name == self.pm.name:
return
if name in self.pm.profiles():
showWarning(tr.qt_misc_name_exists())
return
if not self.profileNameOk(name):
return
self.pm.rename(name)
self.refreshProfilesList()
def onRemProfile(self) -> None:
profs = self.pm.profiles()
if len(profs) < 2:
showWarning(tr.qt_misc_there_must_be_at_least_one())
return
# sure?
if not askUser(
tr.qt_misc_all_cards_notes_and_media_for2(name=self.pm.name),
msgfunc=QMessageBox.warning,
defaultno=True,
):
return
self.pm.remove(self.pm.name)
self.refreshProfilesList()
def _handle_load_backup_success(self) -> None:
"""
Actions that occur when profile backup has been loaded successfully
"""
if self.state == "profileManager":
self.profileDiag.closeWithoutQuitting()
self.loadProfile()
def _handle_load_backup_failure(self, error: Exception) -> None:
"""
Actions that occur when a profile has loaded unsuccessfully
"""
showWarning(str(error))
if self.state != "profileManager":
self.loadProfile()
def onOpenBackup(self) -> None:
def do_open(path: str) -> None:
if not askUser(
tr.qt_misc_replace_your_collection_with_an_earlier2(
os.path.basename(path)
),
msgfunc=QMessageBox.warning,
defaultno=True,
):
return
showInfo(tr.qt_misc_automatic_syncing_and_backups_have_been())
# Collection is still loaded if called from main window, so we unload. This is already
# unloaded if called from the ProfileManager window.
if self.col:
self.unloadProfile(lambda: self._start_restore_backup(path))
return
self._start_restore_backup(path)
getFile(
self.profileDiag if self.state == "profileManager" else self,
tr.qt_misc_revert_to_backup(),
cb=do_open, # type: ignore
filter="*.colpkg",
dir=self.pm.backupFolder(),
)
def _start_restore_backup(self, path: str):
self.restoring_backup = True
import_collection_package_op(
self, path, success=self._handle_load_backup_success
).failure(self._handle_load_backup_failure).run_in_background()
def _on_downgrade(self) -> None:
self.progress.start()
profiles = self.pm.profiles()
def downgrade() -> list[str]:
return self.pm.downgrade(profiles)
def on_done(future: Future) -> None:
self.progress.finish()
problems = future.result()
if not problems:
showInfo("Profiles can now be opened with an older version of Anki.")
else:
showWarning(
"The following profiles could not be downgraded: {}".format(
", ".join(problems)
)
)
return
self.profileDiag.close()
self.taskman.run_in_background(downgrade, on_done)
def loadProfile(self, onsuccess: Callable | None = None) -> None:
if not self.loadCollection():
return
self.setup_sound()
self.flags = FlagManager(self)
# show main window
restoreGeom(self, "mainWindow")
restoreState(self, "mainWindow")
# titlebar
self.setWindowTitle(f"{self.pm.name} - Anki")
# show and raise window for osx
self.show()
self.activateWindow()
self.raise_()
# import pending?
if self.pendingImport:
if self._isAddon(self.pendingImport):
self.installAddon(self.pendingImport)
else:
self.handleImport(self.pendingImport)
self.pendingImport = None
def _onsuccess(synced: bool) -> None:
if synced:
self._refresh_after_sync()
if onsuccess:
onsuccess()
if not self.safeMode:
self.maybe_check_for_addon_updates(self.setup_auto_update)
last_day_cutoff = self.col.sched.day_cutoff
def refresh_reviewer_on_day_rollover_change():
from aqt.reviewer import RefreshNeeded
# need to refresh?
nonlocal last_day_cutoff
current_cutoff = self.col.sched.day_cutoff
if self.state == "review" and last_day_cutoff != current_cutoff:
last_day_cutoff = self.col.sched.day_cutoff
self.reviewer._refresh_needed = RefreshNeeded.QUEUES
self.reviewer.refresh_if_needed()
# schedule another check
secs_until_cutoff = current_cutoff - int_time()
self._reviewer_refresh_timer = self.progress.timer(
secs_until_cutoff * 1000,
refresh_reviewer_on_day_rollover_change,
repeat=False,
parent=self,
)
refresh_reviewer_on_day_rollover_change()
gui_hooks.profile_did_open()
self.maybe_auto_sync_on_open_close(_onsuccess)
def unloadProfile(self, onsuccess: Callable) -> None:
def callback() -> None:
self._unloadProfile()
onsuccess()
gui_hooks.profile_will_close()
self.unloadCollection(callback)
def _unloadProfile(self) -> None:
self.cleanup_sound()
saveGeom(self, "mainWindow")
saveState(self, "mainWindow")
self.pm.save()
self.hide()
self.restoring_backup = False
# at this point there should be no windows left
self._checkForUnclosedWidgets()
self._reviewer_refresh_timer.deleteLater()
def _checkForUnclosedWidgets(self) -> None:
for w in self.app.topLevelWidgets():
if w.isVisible():
# windows with this property are safe to close immediately
if getattr(w, "silentlyClose", None):
w.close()
else:
print(f"Window should have been closed: {w}")
def unloadProfileAndExit(self) -> None:
self.unloadProfile(self.cleanupAndExit)
def unloadProfileAndShowProfileManager(self) -> None:
self.unloadProfile(self.showProfileManager)
def cleanupAndExit(self) -> None:
self.errorHandler.unload()
self.mediaServer.shutdown()
# Rust background jobs are not awaited implicitly
self.backend.await_backup_completion()
self.deleteLater()
app = self.app
app._unset_windows_shutdown_block_reason()
def exit():
# try to ensure Qt objects are deleted in a logical order,
# to prevent crashes on shutdown
gc.collect()
app.exit(0)
self.progress.single_shot(100, exit, False)
# Sound/video
##########################################################################
def setup_sound(self) -> None:
aqt.sound.setup_audio(self.taskman, self.pm.base, self.col.media.dir())
def cleanup_sound(self) -> None:
aqt.sound.cleanup_audio()
def _add_play_buttons(self, text: str) -> str:
"Return card text with play buttons added, or stripped."
if self.col.get_config_bool(Config.Bool.HIDE_AUDIO_PLAY_BUTTONS):
return anki.sound.strip_av_refs(text)
else:
return aqt.sound.av_refs_to_play_icons(text)
def prepare_card_text_for_display(self, text: str) -> str:
text = self.col.media.escape_media_filenames(text)
text = self._add_play_buttons(text)
return text
# Collection load/unload
##########################################################################
def loadCollection(self) -> bool:
try:
self._loadCollection()
except Exception as e:
if "FileTooNew" in str(e):
showWarning(
"This profile requires a newer version of Anki to open. Did you forget to use the Downgrade button prior to switching Anki versions?"
)
else:
showWarning(
f"{tr.errors_unable_open_collection()}\n{traceback.format_exc()}"
)
# clean up open collection if possible
try:
self.backend.close_collection(downgrade_to_schema11=False)
except Exception as e:
print("unable to close collection:", e)
self.col = None
# return to profile manager
self.hide()
self.showProfileManager()
return False
# make sure we don't get into an inconsistent state if an add-on
# has broken the deck browser or the did_load hook
try:
self.update_undo_actions()
gui_hooks.collection_did_load(self.col)
self.apply_collection_options()
self.moveToState("deckBrowser")
except Exception as e:
# dump error to stderr so it gets picked up by errors.py
traceback.print_exc()
return True
def _loadCollection(self) -> None:
cpath = self.pm.collectionPath()
self.col = Collection(cpath, backend=self.backend)
self.setEnabled(True)
def reopen(self, after_full_sync: bool = False) -> None:
self.col.reopen(after_full_sync=after_full_sync)
gui_hooks.collection_did_temporarily_close(self.col)
def unloadCollection(self, onsuccess: Callable) -> None:
def after_media_sync() -> None:
self._unloadCollection()
onsuccess()
def after_sync(synced: bool) -> None:
self.media_syncer.show_diag_until_finished(after_media_sync)
def before_sync() -> None:
self.setEnabled(False)
self.maybe_auto_sync_on_open_close(after_sync)
self.closeAllWindows(before_sync)
def _unloadCollection(self) -> None:
if not self.col:
return
label = (
tr.qt_misc_closing() if self.restoring_backup else tr.qt_misc_backing_up()
)
self.progress.start(label=label)
corrupt = False
try:
self.maybeOptimize()
if not dev_mode:
corrupt = self.col.db.scalar("pragma quick_check") != "ok"
except Exception:
corrupt = True
try:
if not corrupt and not dev_mode and not self.restoring_backup:
try:
# default 5 minute throttle
self.col.create_backup(
backup_folder=self.pm.backupFolder(),
force=False,
wait_for_completion=False,
)
except Exception:
print("backup on close failed")
self.col.close(downgrade=False)
except Exception as e:
print(e)
corrupt = True
finally:
self.col = None
self.progress.finish()
if corrupt:
showWarning(tr.qt_misc_your_collection_file_appears_to_be())
def apply_collection_options(self) -> None:
"Setup audio after collection loaded."
aqt.sound.av_player.interrupt_current_audio = self.col.get_config_bool(
Config.Bool.INTERRUPT_AUDIO_WHEN_ANSWERING
)
# Auto-optimize
##########################################################################
def maybeOptimize(self) -> None:
# have two weeks passed?
if (last_optimize := self.pm.profile.get("lastOptimize")) is not None:
if (int_time() - last_optimize) < 86400 * 14:
return
self.progress.start(label=tr.qt_misc_optimizing())
self.col.optimize()
self.pm.profile["lastOptimize"] = int_time()
self.pm.save()
self.progress.finish()
# Tracking main window state (deck browser, reviewer, etc)
##########################################################################
def moveToState(self, state: MainWindowState, *args: Any) -> None:
# print("-> move from", self.state, "to", state)
oldState = self.state
cleanup = getattr(self, f"_{oldState}Cleanup", None)
if cleanup:
# pylint: disable=not-callable
cleanup(state)
self.clearStateShortcuts()
self.state = state
gui_hooks.state_will_change(state, oldState)
getattr(self, f"_{state}State", lambda *_: None)(oldState, *args)
if state != "resetRequired":
self.bottomWeb.adjustHeightToFit()
gui_hooks.state_did_change(state, oldState)
def _deckBrowserState(self, oldState: MainWindowState) -> None:
self.deckBrowser.show()
def _selectedDeck(self) -> DeckDict | None:
did = self.col.decks.selected()
if not self.col.decks.name_if_exists(did):
showInfo(tr.qt_misc_please_select_a_deck())
return None
return self.col.decks.get(did)
def _overviewState(self, oldState: MainWindowState) -> None:
if not self._selectedDeck():
return self.moveToState("deckBrowser")
self.overview.show()
def _reviewState(self, oldState: MainWindowState) -> None:
self.reviewer.show()
if self.fullscreen:
self.hide_menubar()
if self.pm.hide_top_bar():
self.toolbarWeb.hide_timer.setInterval(500)
self.toolbarWeb.hide_timer.start()
else:
self.toolbarWeb.flatten()
if self.pm.hide_bottom_bar():
self.bottomWeb.hide_timer.setInterval(500)
self.bottomWeb.hide_timer.start()
def _reviewCleanup(self, newState: MainWindowState) -> None:
if newState != "resetRequired" and newState != "review":
self.reviewer.auto_advance_enabled = False
self.reviewer.cleanup()
self.toolbarWeb.elevate()
self.toolbarWeb.show()
self.bottomWeb.show()
# Resetting state
##########################################################################
def _increase_background_ops(self) -> None:
if not self._background_op_count:
gui_hooks.backend_will_block()
self._background_op_count += 1
def _decrease_background_ops(self) -> None:
self._background_op_count -= 1
if not self._background_op_count:
gui_hooks.backend_did_block()
if self._background_op_count < 0:
raise Exception("no background ops active")
def _synthesize_op_did_execute_from_reset(self) -> None:
"""Fire the `operation_did_execute` hook with everything marked as changed,
after legacy code has called .reset()"""
op = OpChanges()
for field in op.DESCRIPTOR.fields:
if field.name != "kind":
setattr(op, field.name, True)
gui_hooks.operation_did_execute(op, None)
def on_operation_did_execute(
self, changes: OpChanges, handler: object | None
) -> None:
"Notify current screen of changes."
focused = current_window() == self
if self.state == "review":
dirty = self.reviewer.op_executed(changes, handler, focused)
elif self.state == "overview":
dirty = self.overview.op_executed(changes, handler, focused)
elif self.state == "deckBrowser":
dirty = self.deckBrowser.op_executed(changes, handler, focused)
else:
dirty = False
if not focused and dirty:
self.fade_out_webview()
if changes.mtime:
self.toolbar.update_sync_status()
def on_focus_did_change(
self, new_focus: QWidget | None, _old: QWidget | None
) -> None:
"If main window has received focus, ensure current UI state is updated."
if new_focus and new_focus.window() == self:
if self.state == "review":
self.reviewer.refresh_if_needed()
elif self.state == "overview":
self.overview.refresh_if_needed()
elif self.state == "deckBrowser":
self.deckBrowser.refresh_if_needed()
def fade_out_webview(self) -> None:
self.web.eval("document.body.style.opacity = 0.3")
def fade_in_webview(self) -> None:
self.web.eval("document.body.style.opacity = 1")
def reset(self, unused_arg: bool = False) -> None:
"""Legacy method of telling UI to refresh after changes made to DB.
New code should use CollectionOp() instead."""
if self.col:
# fire new `operation_did_execute` hook first. If the overview
# or review screen are currently open, they will rebuild the study
# queues (via mw.col.reset())
self._synthesize_op_did_execute_from_reset()
# fire the old reset hook
gui_hooks.state_did_reset()
self.update_undo_actions()
# legacy
def requireReset(
self,
modal: bool = False,
reason: Any | None = None,
context: Any | None = None,
) -> None:
traceback.print_stack(file=sys.stdout)
print("requireReset() is obsolete; please use CollectionOp()")
self.reset()
def maybeReset(self) -> None:
pass
def delayedMaybeReset(self) -> None:
pass
def _resetRequiredState(self, oldState: MainWindowState) -> None:
pass
# HTML helpers
##########################################################################
def button(
self,
link: str,
name: str,
key: str | None = None,
class_: str = "",
id: str = "",
extra: str = "",
) -> str:
class_ = f"but {class_}"
if key:
key = tr.actions_shortcut_key(val=key)
else:
key = ""
return """
<button id="{}" class="{}" onclick="pycmd('{}');return false;"
title="{}" {}>{}</button>""".format(
id,
class_,
link,
key,
extra,
name,
)
# Main window setup
##########################################################################
def setupMainWindow(self) -> None:
# main window
self.form = aqt.forms.main.Ui_MainWindow()
self.form.setupUi(self)
# toolbar
tweb = self.toolbarWeb = TopWebView(self)
self.toolbar = Toolbar(self, tweb)
# main area
self.web = MainWebView(self)
# bottom area
sweb = self.bottomWeb = BottomWebView(self)
sweb.setFocusPolicy(Qt.FocusPolicy.WheelFocus)
sweb.disable_zoom()
# add in a layout
self.mainLayout = QVBoxLayout()
self.mainLayout.setContentsMargins(0, 0, 0, 0)
self.mainLayout.setSpacing(0)
self.mainLayout.addWidget(tweb)
self.mainLayout.addWidget(self.web)
self.mainLayout.addWidget(sweb)
self.form.centralwidget.setLayout(self.mainLayout)
# force webengine processes to load before cwd is changed
if is_win:
for webview in self.web, self.bottomWeb:
webview.force_load_hack()
gui_hooks.card_review_webview_did_init(self.web, AnkiWebViewKind.MAIN)
def closeAllWindows(self, onsuccess: Callable) -> None:
aqt.dialogs.closeAll(onsuccess)
# Components
##########################################################################
def setupSignals(self) -> None:
signal.signal(signal.SIGINT, self.onUnixSignal)
signal.signal(signal.SIGTERM, self.onUnixSignal)
def onUnixSignal(self, signum: Any, frame: Any) -> None:
def quit() -> None:
self.close()
self.progress.single_shot(100, quit)
def setupProgress(self) -> None:
self.progress = aqt.progress.ProgressManager(self)
def setupErrorHandler(self) -> None:
import aqt.errors
self.errorHandler = aqt.errors.ErrorHandler(self)
def setupAddons(self, args: list | None) -> None: