forked from Arthur-Milchior/anki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowser.py
2555 lines (2213 loc) · 94.9 KB
/
browser.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
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import html
import json
import operator
import re
import sre_constants
import time
import unicodedata
from operator import itemgetter
import anki
import aqt.forms
from anki.consts import *
from anki.decks import DeckManager
from anki.hooks import addHook, remHook, runFilter, runHook
from anki.lang import _, ngettext
from anki.sound import allSounds, clearAudioQueue, play
from anki.utils import (bodyClass, fmtTimeSpan, htmlToTextLine, ids2str,
intTime, isMac, isWin)
from aqt.browserColumn import (ColumnAttribute, ColumnByMethod,
DateColumnFromQuery, TimeColumnFromQuery,
UselessColumn)
from aqt.exporting import ExportDialog
from aqt.main import \
AnkiQt # used to be `from aqt import AnkiQt` but this lead to import in errors
from aqt.qt import *
from aqt.utils import (MenuList, SubMenu, askUser, getOnlyText, getTag,
getText, mungeQA, openHelp, qtMenuShortcutWorkaround,
restoreGeom, restoreHeader, restoreSplitter,
restoreState, saveGeom, saveHeader, saveSplitter,
saveState, shortcut, showInfo, showWarning, tooltip)
from aqt.webview import AnkiWebView
# Data model
##########################################################################
class DataModel(QAbstractTableModel):
"""
The model for the table, showing informations on a list of cards in the browser.
Implemented as a separate class because that is how QT show those tables.
sortKey -- never used
activeCols -- the list of name of columns to display in the browser
cards -- the set of cards corresponding to current browser's search
cardObjs -- dictionnady from card's id to the card object. It
allows to avoid reloading cards already seen since browser was
opened. If a nose is «refreshed» then it is remove from the
dic. It is emptied during reset.
focusedCard -- the last thing focused, assuming it was a single line. Used to restore a selection after edition/deletion.
selectedCards -- a dictionnary containing the set of selected card's id, associating them to True. Seems that the associated value is never used. Used to restore a selection after some edition
minutes -- whether to show minutes in the columns
"""
def __init__(self, browser, focusedCard=None, selectedCards=None):
QAbstractTableModel.__init__(self)
self.browser = browser
self.col = browser.col
self.sortKey = None
self.activeCols = self.col.conf.get(
"activeCols", ["noteFld", "template", "cardDue", "deck"])
self.advancedColumns = self.col.conf.get("advancedColumnsInBrowser", False)
self.fieldsTogether = self.col.conf.get("fieldsTogether", False)
self.setupColumns()
self.cards = []
self.cardObjs = {}
self.minutes = self.col.conf.get("minutesInBrowser", False)
self.focusedCard = focusedCard
self.selectedCards = selectedCards
def getCard(self, index):
"""The card object at position index in the list"""
id = self.cards[index.row()]
if not id in self.cardObjs:
self.cardObjs[id] = self.col.getCard(id)
return self.cardObjs[id]
def refreshNote(self, note):
"""Remove cards of this note from cardObjs, and potentially signal
that the layout need to be changed if one cards was in this dict."""
refresh = False
for card in note.cards():
if card.id in self.cardObjs:
del self.cardObjs[card.id]
refresh = True
if refresh:
self.layoutChanged.emit()
# Model interface
######################################################################
def rowCount(self, parent):
"""The number of cards in the browser.
Or 0 if parent is a valid index, as requested by QAbstractTableModel
parent -- a QModelIndex
"""
if parent and parent.isValid():
return 0
return len(self.cards)
def columnCount(self, parent):
"""The number of columns to display in the browser.
Or 0 if parent is a valid index, as requested by QAbstractTableModel
parent -- a QModelIndex
"""
if parent and parent.isValid():
return 0
return len(self.activeCols)
def data(self, index, role):
"""Some information to display the content of the table, at index
`index` for role `role`, as defined by QAbstractTableModel.
index -- a QModelIndex, i.e. a pair row,column
role -- a value of ItemDataRole; stating which information is requested to display this cell.
"""
if not index.isValid():
return
if role == Qt.FontRole:
# The font used for items rendered with the default delegate.
if self.activeCols[index.column()] not in (
"question", "answer", "noteFld"):
return
row = index.row()
card = self.getCard(index)
template = card.template()
if not template.get("bfont"):
return
font = QFont()
font.setFamily(template.get("bfont", "arial"))
font.setPixelSize(template.get("bsize", 12))
return font
elif role == Qt.TextAlignmentRole:
#The alignment of the text for items rendered with the default delegate.
align = Qt.AlignVCenter
if self.activeCols[index.column()] not in ("question", "answer",
"template", "deck", "noteFld", "note"):
align |= Qt.AlignHCenter
return align
elif role == Qt.DisplayRole or role == Qt.EditRole:
#The key data to be rendered in the form of text.
return self.columnData(index)
else:
return
def headerData(self, section, orientation, role):
"""The localized name of the header of column `section`.
Assuming role is displayrole, orientation is vertical, and
section is a valid column. Otherwise, return Nothing.
If the column exists but its local name is not known, return
the first name in alphabetical order (Not clear why this
choice)
"""
if orientation == Qt.Vertical:
return
elif role == Qt.DisplayRole and section < len(self.activeCols):
type = self.columnType(section)
# handle case where extension has set an invalid column type
return self.columns.get(type, list(self.columns.values())[0]).name
else:
return
def flags(self, index):
"""Required by QAbstractTableModel. State that interaction is possible
and it can be selected (not clear what it means right now)
"""
return Qt.ItemFlag(Qt.ItemIsEnabled |
Qt.ItemIsSelectable)
# Filtering
######################################################################
def search(self, txt):
"""Given a query `txt` entered in the search browser, set self.cards
to the result of the query, warn if the search is invalid, and
reset the display.
"""
self.beginReset()
startTime = time.time()
# the db progress handler may cause a refresh, so we need to zero out
# old data first
self.cards = []
invalid = False
try:
type = self.col.conf['sortType']
sortColumn = self.columns[type]
sort = sortColumn.getSort()
self.cards = self.col.findCards(txt, order=sort, oneByNote=self.browser.showNotes)
if self.browser.sortBackwards:
self.cards.reverse()
except Exception as e:
if str(e) == "invalidSearch":
self.cards = []
invalid = True
else:
raise
#print "fetch cards in %dms" % ((time.time() - startTime)*1000)
self.endReset()
if invalid:
showWarning(_("Invalid search - please check for typing mistakes."))
def reset(self):
self.beginReset()
self.endReset()
# caller must have called editor.saveNow() before calling this or .reset()
def beginReset(self):
self.browser.editor.setNote(None, hide=False)
self.browser.mw.progress.start()
self.saveSelection()
self.beginResetModel()
self.cardObjs = {}
def endReset(self):
self.endResetModel()
self.restoreSelection()
self.browser.mw.progress.finish()
def reverse(self):
"""Save the current note, reverse the list of cards and update the display"""
self.browser.editor.saveNow(self._reverse)
def _reverse(self):
"""Reverse the list of cards and update the display"""
self.beginReset()
self.cards.reverse()
self.browser.sortBackwards = not self.browser.sortBackwards
self.endReset()
def saveSelection(self):
"""Set selectedCards and focusedCards according to what their represent"""
cards = self.browser.selectedCards()
self.selectedCards = dict([(id, True) for id in cards])
if getattr(self.browser, 'card', None):
self.focusedCard = self.browser.card.id
else:
self.focusedCard = None
def restoreSelection(self):
""" Restore main selection as either:
* focusedCard (which is set to None)
* or first selected card in the list of cards
If there are less than 500 selected card, select them back.
"""
if not self.cards:
return
sm = self.browser.form.tableView.selectionModel()
sm.clear()
# restore selection
items = QItemSelection()
count = 0
firstIdx = None
focusedIdx = None
for row, id in enumerate(self.cards):
# if the id matches the focused card, note the index
if self.focusedCard == id:
focusedIdx = self.index(row, 0)
items.select(focusedIdx, focusedIdx)
self.focusedCard = None
# if the card was previously selected, select again
if id in self.selectedCards:
count += 1
idx = self.index(row, 0)
items.select(idx, idx)
# note down the first card of the selection, in case we don't
# have a focused card
if not firstIdx:
firstIdx = idx
# focus previously focused or first in selection
idx = focusedIdx or firstIdx
tv = self.browser.form.tableView
if idx:
tv.selectRow(idx.row())
# scroll if the selection count has changed
if count != len(self.selectedCards):
# we save and then restore the horizontal scroll position because
# scrollTo() also scrolls horizontally which is confusing
horizontalScroll = tv.horizontalScrollBar().value()
tv.scrollTo(idx, tv.PositionAtCenter)
tv.horizontalScrollBar().setValue(horizontalScroll)
if count < 500:
# discard large selections; they're too slow
sm.select(items, QItemSelectionModel.SelectCurrent |
QItemSelectionModel.Rows)
else:
tv.selectRow(0)
# Column data
######################################################################
def setupColumns(self):
"""Set self.columns"""
#type -> columns
columns = {}
def add(column):
"""Add a column in columns. If the column is new, add it. Otherwise,
simply add the menu path to the column already present in
the dict
"""
type = column.type
present = columns.get(type)
if present is not None:
present = columns[type]
assert column == present
menus = column.menus
assert len(menus)==1
present.addMenu(menus[0])
else:
columns[type] = column
for column in [
ColumnByMethod('question', _("Question"), "questionContentByCid(card.id)"),
ColumnByMethod('answer', _("Answer"), "answerContentByCid(card.id)"),
ColumnByMethod('template', _("Card"), "nameByMidOrd(note.mid, card.ord)"),
ColumnByMethod('deck', _("Deck"), "nameForDeck(card.did)"),
ColumnByMethod('noteFld', _("Sort Field"), "note.sfld collate nocase, card.ord"),
DateColumnFromQuery('noteCrt', _("Created"), "note.id/1000.0", self),
DateColumnFromQuery('noteMod', _("Edited"), "note.mod", self),
DateColumnFromQuery('cardMod', _("Changed"), "card.mod", self),
ColumnByMethod('cardDue', _("Due"), "card.type, card.due"),
ColumnByMethod('cardIvl', _("Interval"), "card.ivl"),
ColumnByMethod('cardEase', _("Ease"), "(card.type == 0), card.factor"),
ColumnByMethod('cardReps', _("Reviews"), "card.reps"),
ColumnByMethod('cardLapses', _("Lapses"), "card.lapses"),
ColumnByMethod('noteTags', _("Tags"), "note.tags", "stringTags"),
ColumnByMethod('note', _("Note"), "nameByMid(note.mid)", "noteTypeBrowserColumn"),
TimeColumnFromQuery('cardFirstReview', _("First Review"), "min(id)"),
TimeColumnFromQuery('cardLastReview', _("Last Review"), "max(id)"),
TimeColumnFromQuery('cardAverageTime', _('Average time'), "avg(time)/1000.0"),
TimeColumnFromQuery('cardTotalTime', _('Total time'), "sum(time)/1000.0"),
TimeColumnFromQuery('cardFastestTime', _('Fastest review'), "time/1000.0", True),
TimeColumnFromQuery('cardSlowestTime', _('Slowest review'), "time/1000.0", True),
ColumnByMethod("cardPreviousIvl", _("Previous interval"), """(select ivl from revlog where cid = card.id order by id desc limit 1 offset 1)"""),
ColumnByMethod("cardPercentCorrect", _("Percent correct"), "cast(card.lapses as real)/card.reps"),
ColumnByMethod("cardPreviousDuration", _("Previous duration"), """(select time/1000.0 from revlog where cid = card.idy order by id desc limit 1)"""),
ColumnAttribute("nid", _("Note id")),
ColumnAttribute("nguid", _("Note guid")),
ColumnAttribute("nmid", _("mid")),
ColumnAttribute("nusn", _("note usn")),
ColumnByMethod("nfields", _("Note fields"), "note.flds", methodName="joinedFields", note=True),
ColumnAttribute("nflags", _("Note flags")),
ColumnAttribute("ndata", _("Note data")),
ColumnAttribute("cid", _("Card Id")),
ColumnAttribute("cdid", _("Deck Id")),
ColumnAttribute("codid", _("Deck Original id")),
ColumnAttribute("cord", _("Card Ord")),
ColumnAttribute("cusn", _("Card Usn")),
ColumnAttribute("ctype", _("Card type")),
ColumnAttribute("cqueue", _("Card queue")),
ColumnAttribute("cleft", _("Card left")),
ColumnAttribute("codue", _("Card odue")),
ColumnAttribute("cflags", _("Card flags")),
ColumnByMethod("cardOverdueIvl", _("Overdue interval"), f"""(
select
(case
when odid then ""
when queue =1 then ""
when queue = 0 then ""
when type=0 then ""
when due<{self.col.sched.today} and (queue in (2, 3) or (type=2 and queue<0))
then {self.col.sched.today}-due
else ""
end)
from cards where id = card.id)"""),
]:
add(column)
for model in self.col.models.all():
modelName = model.getName()
for field in model['flds']:
fieldName = field.getName()
type = f'_field_{fieldName}'
if self.fieldsTogether:
menu = ['Fields']
else:
menu = ['Fields', modelName]
column = ColumnByMethod(type, fieldName, "valueForField(note.mid, note.flds, '{fieldName}')", "get", menu, True, fieldName)
add(column)
for type in self.activeCols:
if type not in columns:
column = UselessColumn(type)
add(column)
# allow to sort by alphabetical order in he local language
self.columns = {column.type: column
for column in sorted(columns.values(), key=operator.attrgetter('name'))
}
def columnType(self, column):
"""The name of the column in position `column`"""
return self.activeCols[column]
def columnData(self, index):
"""Return the text of the cell at a precise index.
Only called from data. It does the computation for data, in
the case where the content of a cell is asked.
It is kept by compatibility with original anki, but could be incorporated in it.
"""
row = index.row()
col = index.column()
type = self.columnType(col)
card = self.getCard(index)
return self.columns[type].content(card)
def isRTL(self, index):
col = index.column()
type = self.columnType(col)
if type != "noteFld":
return False
row = index.row()
card = self.getCard(index)
nt = card.note().model()
return nt['flds'][nt.sortIdx()]['rtl']
# Line painter
######################################################################
class StatusDelegate(QItemDelegate):
"""Similar to QItemDelegate and ensure that the row is colored
according to flag, marked or suspended."""
def __init__(self, browser, model):
QItemDelegate.__init__(self, browser)
self.browser = browser
self.model = model
def paint(self, painter, option, index):
self.browser.mw.progress.blockUpdates = True
try:
card = self.model.getCard(index)
except:
# in the the middle of a reset; return nothing so this row is not
# rendered until we have a chance to reset the model
return
finally:
self.browser.mw.progress.blockUpdates = True
if self.model.isRTL(index):
option.direction = Qt.RightToLeft
col = None
if card.userFlag() > 0:
col = flagColours[card.userFlag()]
elif card.note().hasTag("Marked"):
col = COLOUR_MARKED
elif card.queue == QUEUE_SUSPENDED:
col = COLOUR_SUSPENDED
if col:
brush = QBrush(QColor(col))
painter.save()
painter.fillRect(option.rect, brush)
painter.restore()
return QItemDelegate.paint(self, painter, option, index)
# Browser window
######################################################################
# fixme: respond to reset+edit hooks
class Browser(QMainWindow):
"""model: the data model (and not a card model !)
card -- the card in the reviewer when the browser was opened, or the last selected card.
columns -- A list of pair of potential columns, with their internal name and their local name.
card -- card selected if there is a single one
_previewTimer -- progamming a call to _renderScheduledPreview,
with a new card, at least 500 ms after the last call to this
method
_lastPreviewRender -- when was the last call to _renderScheduledPreview
"""
def __init__(self, mw: AnkiQt, search=None, focusedCard=None, selectedCards=None):
"""
search -- the search query to use when opening the browser
focusedCard, selectedCards -- as in DataModel
"""
QMainWindow.__init__(self, None, Qt.Window)
self.mw = mw
self.col = self.mw.col
self.showNotes = self.mw.col.conf.get("advbrowse_uniqueNote",False)
self.sortBackwards = self.col.conf['sortBackwards']
self.lastFilter = ""
self.focusTo = None
self._previewWindow = None
self._closeEventHasCleanedUp = False
self.form = aqt.forms.browser.Ui_Dialog()
self.form.setupUi(self)
self.setupSidebar()
restoreGeom(self, "editor", 0)
restoreState(self, "editor")
restoreSplitter(self.form.splitter, "editor3")
self.form.splitter.setChildrenCollapsible(False)
self.card = None
self.setupTable()
self.setupMenus()
self.setupHeaders()
self.setupHooks()
self.setupEditor()
self.updateFont()
self.onUndoState(self.mw.form.actionUndo.isEnabled())
self.setupSearch(search=search, focusedCard=focusedCard, selectedCards=selectedCards)
self.show()
def dealWithShowNotes(self, showNotes):
self.editor.saveNow(lambda:self._dealWithShowNotes(showNotes))
def _dealWithShowNotes(self, showNotes):
self.mw.col.conf["advbrowse_uniqueNote"] = showNotes
self.showNotes = showNotes
self.form.menu_Cards.setEnabled(not showNotes)
self.model.reset()
self.search()
def warnOnShowNotes(self, what):
"""Return self.showNotes. If we show note, then warn that action what
is impossible.
"""
if self.showNotes:
tooltip(_(f"You can't {what} a note. Please switch to card mode before doing this action."))
return self.showNotes
def setupMenus(self):
# pylint: disable=unnecessary-lambda
# actions
self.form.previewButton.clicked.connect(self.onTogglePreview)
self.form.previewButton.setToolTip(_("Preview Selected Card (%s)") %
shortcut(_("Ctrl+Shift+P")))
self.form.filter.clicked.connect(self.onFilterButton)
# edit
self.form.actionUndo.triggered.connect(self.mw.onUndo)
self.form.actionInvertSelection.triggered.connect(self.invertSelection)
self.form.actionSelectNotes.triggered.connect(self.selectNotes)
if not isMac:
self.form.actionClose.setVisible(False)
self.form.actionRefresh.triggered.connect(self.onSearchActivated)
# notes
self.form.actionAdd.triggered.connect(self.mw.onAddCard)
self.form.actionAdd_Tags.triggered.connect(lambda: self.addTags())
self.form.actionRemove_Tags.triggered.connect(lambda: self.deleteTags())
self.form.actionClear_Unused_Tags.triggered.connect(self.clearUnusedTags)
self.form.actionToggle_Mark.triggered.connect(lambda: self.onMark())
self.form.actionChangeModel.triggered.connect(self.onChangeModel)
self.form.actionFindDuplicates.triggered.connect(self.onFindDupes)
self.form.actionFindReplace.triggered.connect(self.onFindReplace)
self.form.actionBatchEdit.triggered.connect(self.onBatchEdit)
self.form.actionManage_Note_Types.triggered.connect(self.mw.onNoteTypes)
self.form.actionDelete.triggered.connect(self.deleteNotes)
self.form.actionCopy.triggered.connect(self.actionCopy)
# cards
self.form.actionChange_Deck.triggered.connect(self.setDeck)
self.form.action_Info.triggered.connect(self.showCardInfo)
self.form.sort_new_card.triggered.connect(self.sort)
self.form.actionReposition.triggered.connect(self.reposition)
self.form.actionReschedule.triggered.connect(self.reschedule)
self.form.actionToggle_Suspend.triggered.connect(self.onSuspend)
self.form.actionRed_Flag.triggered.connect(lambda: self.onSetFlag(1))
self.form.actionOrange_Flag.triggered.connect(lambda: self.onSetFlag(2))
self.form.actionGreen_Flag.triggered.connect(lambda: self.onSetFlag(3))
self.form.actionBlue_Flag.triggered.connect(lambda: self.onSetFlag(4))
self.form.action_Export.triggered.connect(lambda: ExportDialog(self.mw, cids=self.selectedCards()))
self.form.actionPostpone_reviews.triggered.connect(self.onPostpone_reviews)
# jumps
self.form.actionPreviousCard.triggered.connect(self.onPreviousCard)
self.form.actionNextCard.triggered.connect(self.onNextCard)
self.form.actionFirstCard.triggered.connect(self.onFirstCard)
self.form.actionLastCard.triggered.connect(self.onLastCard)
self.form.actionFind.triggered.connect(self.onFind)
self.form.actionNote.triggered.connect(self.onNote)
self.form.actionTags.triggered.connect(self.onFilterButton)
self.form.actionSidebar.triggered.connect(self.focusSidebar)
self.form.actionCardList.triggered.connect(self.onCardList)
# Columns
self.form.actionShow_Hours_and_Minutes.triggered.connect(self.toggleHoursAndMinutes)
self.form.actionShow_Hours_and_Minutes.setChecked(self.model.minutes)
self.form.actionShow_Advanced_Columns.triggered.connect(self.toggleAdvancedColumns)
self.form.actionShow_Advanced_Columns.setCheckable(True)
self.form.actionShow_Advanced_Columns.setChecked(self.model.advancedColumns)
# decks
self.form.addPrefix.triggered.connect(self.addPrefix)
self.addPrefixShortcut = QShortcut(QKeySequence("Ctrl+Alt+P"), self)
self.addPrefixShortcut.activated.connect(self.addPrefix)
self.removePrefixShortcut = QShortcut(QKeySequence("Ctrl+Alt+Shift+P"), self)
self.removePrefixShortcut.activated.connect(self.removePrefix)
self.form.removePrefix.triggered.connect(self.removePrefix)
# help
self.form.actionGuide.triggered.connect(self.onHelp)
self.form.actionShowNotesCards.triggered.connect(lambda:self.dealWithShowNotes(not self.showNotes))
# keyboard shortcut for shift+home/end
self.pgUpCut = QShortcut(QKeySequence("Shift+Home"), self)
self.pgUpCut.activated.connect(self.onFirstCard)
self.pgDownCut = QShortcut(QKeySequence("Shift+End"), self)
self.pgDownCut.activated.connect(self.onLastCard)
# add-on hook
runHook('browser.setupMenus', self)
self.mw.maybeHideAccelerators(self)
# context menu
self.form.tableView.setContextMenuPolicy(Qt.CustomContextMenu)
self.form.tableView.customContextMenuRequested.connect(self.onContextMenu)
def dealWithFieldsTogether(self, fieldsTogether):
self.editor.saveNow(lambda:self._dealWithFieldsTogether(fieldsTogether))
def _dealWithFieldsTogether(self, fieldsTogether):
self.mw.col.conf["advbrowse_uniqueNote"] = fieldsTogether
self.model.fieldsTogether = fieldsTogether
self.search()
def onContextMenu(self, _point):
"""Open, where mouse is, the context menu, with the content of menu
cards, menu notes.
This list can be changed by the hook browser.onContextMenu.
_point -- not used
"""
menu = QMenu()
for act in self.form.menu_Cards.actions():
menu.addAction(act)
menu.addSeparator()
for act in self.form.menu_Notes.actions():
menu.addAction(act)
runHook("browser.onContextMenu", self, menu)
qtMenuShortcutWorkaround(menu)
menu.exec_(QCursor.pos())
def updateFont(self):
"""Size for the line heights. 6 plus the max of the size of font of
all models. At least 22."""
# we can't choose different line heights efficiently, so we need
# to pick a line height big enough for any card template
curmax = 16
for model in self.col.models.all():
for template in model['tmpls']:
bsize = template.get("bsize", 0)
if bsize > curmax:
curmax = bsize
self.form.tableView.verticalHeader().setDefaultSectionSize(
curmax + 6)
def closeEvent(self, evt):
if self._closeEventHasCleanedUp:
evt.accept()
return
self.editor.saveNow(self._closeWindow)
evt.ignore()
def _closeWindow(self):
self._cancelPreviewTimer()
self.editor.cleanup()
saveSplitter(self.form.splitter, "editor3")
saveGeom(self, "editor")
saveState(self, "editor")
saveHeader(self.form.tableView.horizontalHeader(), "editor")
self.col.conf['activeCols'] = self.model.activeCols
self.col.setMod()
self.teardownHooks()
self.mw.maybeReset()
aqt.dialogs.markClosed("Browser")
self._closeEventHasCleanedUp = True
self.col.conf['sortBackwards'] = self.sortBackwards
self.mw.gcWindow(self)
self.close()
def closeWithCallback(self, onsuccess):
def callback():
self._closeWindow()
onsuccess()
self.editor.saveNow(callback)
def keyPressEvent(self, evt):
"""Ensure that window close on escape. Send other event to parent"""
if evt.key() == Qt.Key_Escape:
self.close()
else:
super().keyPressEvent(evt)
# Searching
######################################################################
@staticmethod
def _defaultPrompt():
return _("<type here to search; hit enter to show current deck>")
def setupSearch(self, search=None, focusedCard=None, selectedCards=None):
self.form.searchButton.clicked.connect(self.onSearchActivated)
self.form.searchEdit.lineEdit().returnPressed.connect(self.onSearchActivated)
self.form.searchEdit.setCompleter(None)
searchLineOnOpen = search or self._defaultPrompt()
self.form.searchEdit.addItems([searchLineOnOpen] + self.mw.pm.profile['searchHistory'])
self._lastSearchTxt = search or "is:current"
self.card = focusedCard
self.model.selectedCards = selectedCards
self.search()
# then replace text for easily showing the deck
self.form.searchEdit.lineEdit().setText(searchLineOnOpen)
self.form.searchEdit.lineEdit().selectAll()
self.form.searchEdit.setFocus()
# search triggered by user
def onSearchActivated(self):
self.editor.saveNow(self._onSearchActivated)
def _onSearchActivated(self):
# convert guide text before we save history
if self.form.searchEdit.lineEdit().text() == self._defaultPrompt():
self.form.searchEdit.lineEdit().setText("deck:current ")
# grab search text and normalize
txt = self.form.searchEdit.lineEdit().text()
txt = unicodedata.normalize("NFC", txt)
# update history
sh = self.mw.pm.profile['searchHistory']
if txt in sh:
sh.remove(txt)
sh.insert(0, txt)
sh = sh[:30]
self.form.searchEdit.clear()
self.form.searchEdit.addItems(sh)
self.mw.pm.profile['searchHistory'] = sh
# keep track of search string so that we reuse identical search when
# refreshing, rather than whatever is currently in the search field
self._lastSearchTxt = txt
self.search()
# search triggered programmatically. caller must have saved note first.
def search(self):
"""Search in the model, either reviewer's note if there is one and
_lastSearchTxt contains "is:current", or otherwise the
_lastSearchTxt query.
"""
if "is:current" in self._lastSearchTxt:
# show current card if there is one
card = self.mw.reviewer.card
if self.card is None:
self.card = card
nid = card and card.nid or 0
self.model.search("nid:%d"%nid)
else:
self.model.search(self._lastSearchTxt)
if not self.model.cards:
# no row change will fire
self._onRowChanged(None, None)
def updateTitle(self):
"""Set the browser's window title, to take into account the number of
cards and of selected cards"""
selected = len(self.form.tableView.selectionModel().selectedRows())
cur = len(self.model.cards)
what = "note" if self.showNotes else "card"
self.setWindowTitle(ngettext(f"Browse (%(cur)d {what} shown; %(sel)s)",
f"Browse (%(cur)d {what}s shown; %(sel)s)",
cur) % {
"cur": cur,
"sel": ngettext("%d selected", "%d selected", selected) % selected
})
return selected
def onReset(self):
"""Remove the note from the browser's editor window. Redo the
search"""
self.editor.setNote(None)
self.search()
# Table view & editor
######################################################################
def setupTable(self):
self.model = DataModel(self)
self.form.tableView.setSortingEnabled(True)
self.form.tableView.setModel(self.model)
self.form.tableView.selectionModel()
self.form.tableView.setItemDelegate(StatusDelegate(self, self.model))
self.form.tableView.selectionModel().selectionChanged.connect(self.onRowChanged)
self.form.tableView.setStyleSheet("QTableView{ selection-background-color: rgba(127, 127, 127, 50); }")
self.singleCard = False
def setupEditor(self):
self.editor = aqt.editor.Editor(
self.mw, self.form.fieldsArea, self)
def onRowChanged(self, current, previous):
"""Save the note. Hide or show editor depending on which cards are
selected."""
self.editor.saveNow(lambda: self._onRowChanged(current, previous))
def _onRowChanged(self, current, previous):
"""Hide or show editor depending on which cards are selected."""
update = self.updateTitle()
show = self.model.cards and update == 1
self.form.splitter.widget(1).setVisible(not not show)
idx = self.form.tableView.selectionModel().currentIndex()
if idx.isValid():
self.card = self.model.getCard(idx)
if not show:
self.editor.setNote(None)
self.singleCard = False
else:
self.editor.setNote(self.card.note(reload=True), focusTo=self.focusTo)
self.focusTo = None
self.editor.card = self.card
self.singleCard = True
self._updateFlagsMenu()
runHook("browser.rowChanged", self)
self._renderPreview(True)
def refreshCurrentCard(self, note):
self.model.refreshNote(note)
self._renderPreview(False)
def onLoadNote(self, editor):
self.refreshCurrentCard(editor.note)
def refreshCurrentCardFilter(self, flag, note, fidx):
self.refreshCurrentCard(note)
return flag
def currentRow(self):
idx = self.form.tableView.selectionModel().currentIndex()
return idx.row()
# Headers & sorting
######################################################################
def setupHeaders(self):
vh = self.form.tableView.verticalHeader()
hh = self.form.tableView.horizontalHeader()
if not isWin:
vh.hide()
hh.show()
restoreHeader(hh, "editor")
hh.setHighlightSections(False)
hh.setMinimumSectionSize(50)
hh.setSectionsMovable(True)
self.setColumnSizes()
hh.setContextMenuPolicy(Qt.CustomContextMenu)
hh.customContextMenuRequested.connect(self.onHeaderContext)
self.setSortIndicator()
hh.sortIndicatorChanged.connect(self.onSortChanged)
hh.sectionMoved.connect(self.onColumnMoved)
def onSortChanged(self, idx, ord):
ord = bool(ord)
self.editor.saveNow(lambda: self._onSortChanged(idx, ord))
def _onSortChanged(self, idx, ord):
type = self.model.activeCols[idx]
if self.col.conf['sortType'] != type:
self.col.conf['sortType'] = type
# default to descending for non-text fields
if type == "noteFld":
ord = not ord
self.sortBackwards = ord
self.search()
else:
if self.sortBackwards != ord:
self.sortBackwards = ord
self.model.reverse()
self.setSortIndicator()
def setSortIndicator(self):
"""Add the arrow indicating which column is used to sort, and
in which order, in the column header"""
hh = self.form.tableView.horizontalHeader()
type = self.col.conf['sortType']
if type not in self.model.activeCols:
hh.setSortIndicatorShown(False)
return
idx = self.model.activeCols.index(type)
if self.sortBackwards:
ord = Qt.DescendingOrder
else:
ord = Qt.AscendingOrder
hh.blockSignals(True)
hh.setSortIndicator(idx, ord)
hh.blockSignals(False)
hh.setSortIndicatorShown(True)
def onHeaderContext(self, pos):
"""Open the context menu related to the list of column.
There is a button by potential column.
"""
gpos = self.form.tableView.mapToGlobal(pos) # the position,
# usable from the browser
topMenu = QMenu()
menuDict = dict()
for column in self.model.columns.values():
for menu in column.menus:
currentDict = menuDict
currentMenu = topMenu
for submenuName in menu:
if submenuName in currentDict:
currentDict, currentMenu = currentDict[submenuName]
else:
newDict = dict()
newMenu = currentMenu.addMenu(submenuName)
currentDict[submenuName] = newDict, newMenu
currentMenu = newMenu
currentDict = newDict
action = currentMenu.addAction(column.name)
action.setCheckable(True)
action.setChecked(column.type in self.model.activeCols)
action.toggled.connect(lambda button, type=column.type: self.toggleField(type))
# toggle note/card
a = topMenu.addAction(_("Use Note mode"))
a.setCheckable(True)
a.setChecked(self.showNotes)
a.toggled.connect(lambda:self.dealWithShowNotes(not self.showNotes))
#
a = topMenu.addAction(_("Show advanced fields"))
a.setCheckable(True)
a.setChecked(self.col.conf.get("advancedColumnsInBrowser", False))
a.toggled.connect(self.toggleAdvancedColumns)
a = topMenu.addAction(_("All Fields Together"))
a.setCheckable(True)
a.setChecked(self.model.fieldsTogether)
a.toggled.connect(lambda:self.dealWithFieldsTogether(not self.model.fieldsTogether))
topMenu.exec_(gpos)
def addMenu(self, menu):
self.menus.append(menu)
def toggleHoursAndMinutes(self):
"""
Save the note in the editor
Show/hide hours and minutes
"""
self.editor.saveNow(lambda: self._toggleHoursAndMinutes())
def _toggleHoursAndMinutes(self):
self.model.minutes = not self.model.minutes
self.col.conf["minutesInBrowser"] = self.model.minutes
self.model.reset()
def toggleField(self, type):
"""
Save the note in the editor
Add or remove column type. If added, scroll to it. Can't
remove if there are less than two columns.
"""
self.editor.saveNow(lambda: self._toggleField(type))
def _toggleField(self, type):
"""
Add or remove column type. If added, scroll to it. Can't
remove if there are less than two columns.
"""
self.model.beginReset()
if type in self.model.activeCols:
if len(self.model.activeCols) < 2:
self.model.endReset()
return showInfo(_("You must have at least one column."))
self.model.activeCols.remove(type)
self.model.setupColumns() #in case we removed a column which should disappear
adding=False
else:
self.model.activeCols.append(type)
adding=True
# sorted field may have been hidden