-
Notifications
You must be signed in to change notification settings - Fork 1
/
_Again_Good_HUGE_extra_buttons.py
3381 lines (2811 loc) · 115 KB
/
_Again_Good_HUGE_extra_buttons.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
# -*- mode: Python ; coding: utf-8 -*-
# • Again Good HUGE buttons
# https://ankiweb.net/shared/info/2074653746
# https://github.com/ankitest/anki-musthave-addonz-by-ankitest
# -- tested with Anki 2.0.44 under Windows 7 SP1
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
# Copyright (c) 2016-2017 Dmitry Mikheev, http://finpapa.ucoz.net/
# No support. Use it AS IS on your own risk.
"""
Show 2 buttons: Again and (Hard or Good or Easy) buttons
so wide as Anki window.
Or usual 4 buttons: it's on user's choice.
Good button always takes place of Hard and Easy buttons,
if they are absent on the card.
4 wide color buttons only with smiles
instead of words and with a bigger font on them.
-- In 2-buttons mode hotkeys are:
Hotkey 1 means AGAIN in any case.
Hotkeys 2,3,4 means the same:
it is Hard, Good or Easy (on user's choice)
-- In 3-4-buttons mode hotkeys are:
Hotkey 1 means AGAIN in any case.
Hotkey 2 means HARD when available otherwise it mean GOOD.
Hotkey 3 means GOOD anyway.
Hotkey 4 means maximum available easiness anyhow
(it is Good for 2 buttons and Easy for 3 or 4 buttons).
Adds 1-4 (4 by default) extra answer buttons with regular intervals.
No answer on that card will be given, just setup additional interval.
You can assign you own intervals, labels (by editing source).
Hotkeys are 6, 7, 8, 9.
You can use intervals as button labels
View - Answer buttons without labels or Ctrl+Alt+Shift+L
On Cards - Later, Not Now menu click (Escape hotkey):
No answer will be given, next card will be shown.
Card stays on its place in queue,
you'll see it next time you study the deck
or immediatly after reset of cards' queue.
• Flip-flop card: Show FrontSide/BackSide
by Ctrl+Up/Control+Down or ^8/^2 or Insert/0
To modify a single card so the front and back are inverted
use F12 in Card Reviewer.
You can easily add your own field name pairs in existing list.
Pairs higher in the list take precedence over lower
if some of them exist in the same note simultaneously.
2B cont...
"""
from __future__ import unicode_literals
from __future__ import division
"""
Inspired by Duplicate Selected Notes
https://ankiweb.net/shared/info/2126361512
and Create Copy of Selected Cards
https://ankiweb.net/shared/info/787914845
It puts the stats when you finish a timebox in a tooltip message
that goes away after a few seconds.
Based on Decks Total https://ankiweb.net/shared/info/1421528223
Some hotkeys:
Check Database... Ctrl+Delete
Check Media... Alt+Shift+Delete
Empty Cards... Ctrl+Shift+Delete
Add-ons Browse and Install... Ctrl+Shift+Ins
rated:90:1 will be available with this addon.
You can enter more than one addon number in install dialog
with spaces: 1238745 2378903 9875237
You can add some {{info:...}} stencil in your templates.
This is a simple monkey patch add-on that inserts day learning cards
(learning cards with intervals that crossed the day turnover)
always before new cards without depending due reviews.
By default Anki do so:
learning; new if before; due; day learning; new if after
With this add-on card will be displayed in the following order:
learning; (day learning; new) if before; due; (day learning; new) if after
Normally these cards go after due, but I want them to go before new.
If Tools -> Preferences... -> Basic -> Show new cards before reviews
learning; day learning; new; due
If Tools -> Preferences... -> Basic -> Show new cards after reviews
learning; due; day learning; new
How to make Anki insensitive case when using {{type:field}}
Upper case, lower case and {{type:}} /monkey patch/
You can use it together with
Multiple type fields on card
https://ankiweb.net/shared/info/689574440
Inspired by
Select Buttons Automatically If Correct Answer, Wrong Answer or Nothing
https://ankiweb.net/shared/info/2074758752
"""
import datetime
import random
import json
import time
import sys
import os
import re
import copy
import unicodedata
import HTMLParser
import anki # ' Addons Install Tooltip
import aqt
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import anki.hooks
import anki.utils
import anki.sound
import aqt.main
import aqt.utils
import aqt.qt
import aqt.reviewer
import aqt.editor
import aqt.fields
import aqt.deckconf
import aqt.forms
import aqt.customstudy
import anki.sched # why?
from anki.collection import _Collection
from aqt.qt import *
from aqt.clayout import CardLayout
from anki.consts import MODEL_STD, MODEL_CLOZE
from anki.consts import *
# Get language class
# import anki.lang
lang = anki.lang.getLang()
extra_buttons = [ # should start from 6 anyway
{'Description': '5-7d',
'Label': '!!!',
'ShortCut': '6',
'ReschedMin': 5,
'ReschedMax': 7},
{'Description': '8-15d',
'Label': 'Veni',
'ShortCut': '7',
'ReschedMin': 8,
'ReschedMax': 15},
{'Description': '3-4w',
'Label': 'Vidi',
'ShortCut': '8',
'ReschedMin': 15,
'ReschedMax': 30},
{'Description': '2-3mo',
'Label': 'Vici',
'ShortCut': '9',
'ReschedMin': 31,
'ReschedMax': 90},
]
MSG = {
'en': {
'later': _('later'),
'not now': _('not now'),
'Later, not now': _('&Later, not now'),
'View': _('&View'),
'Cards': _('&Cards'),
'Sound': _('&Sound'),
'Go': _('&Go'),
'HardGoodEasy':
_('Again')+', '+_('Hard')+', '+_('Good')+', '+_('Easy'),
'Again': '&'+_('Again'),
'AgainHard': _('Again')+', &'+_('Hard'),
'AgainGood': _('Again')+', &'+_('Good'),
'AgainEasy': _('Again')+', &'+_('Easy'),
'no_smiles': _('No smiles'),
'no_styles': _('No big buttons'),
'no_labels': _('Next Interva&L — on answer buttons'),
'later_not_now': _(' not now '),
'no_extra_buttons': _('Hide &Extra buttons'),
'Hide button: ': _('&Hide button: '),
'Edit': _('Edit'),
'More': _('More'),
'Hide buttons': _('Hide buttons: '),
'Edit': _('&Edit...'),
'Edit Layout': _('Edi&t Layout...'),
'Edit Fields': _('Edit &Fields...'),
'flat_buttons': _('&Flat buttons'),
'HUGE_buttons': _('&HUGE buttons options'),
'aa': _('About addon '),
'showFrontSide': _('Show &FrontSide'),
'showBackSide': _('Show &BackSide'),
'viewFrontSide': _('&FrontSide'),
'viewBackSide': _('&BackSide'),
'cardFrontSide': _("Card's &FrontSide"),
'cardBackSide': _("Card's &BackSide"),
'gotoFrontSide': _('Goto &FrontSide'),
'gotoBackSide': _('Goto &BackSide'),
'goFrontSide': _('to &FrontSide'),
'goBackSide': _('to &BackSide'),
'swap_fields': _('S&wap %s and %s fields'),
'fields_swapped': _('<b>%s</b> and <b>%s</b> swapped.'),
'swapping': _('Swap fields'),
'duplicate': _('Duplicate notes and Swap fields'),
'target_deck': _('Enter the name of target deck:'),
'till next': _('Number of days until next review'),
'current': _('actual interval'),
'card ease': _('Card ease'),
'days interval': _('&Prompt and Set ... days interval'),
'search in browser': 'Search Anki Browser for %s...',
'delete note': 'Delete note?',
'autoshow': _("Autoshow answer/next question"),
'autoshow Answer': _("Automatically show answer after"),
'autoshow Question': _("Automatically show next question after"),
'AUTOSHOW_STATE is on':
"<b>Auto</b> show Q-and-A is <b style=color:blue;>ON</b> now",
'AUTOSHOW_STATE is off':
"<b>Auto</b> show QandA is <b style=color:red;>OFF</b> now",
'show_install': _("Show Browse and Install... &Again"),
'open_ankiweb': _("Open Anki&Web shared add-ons site"),
'exact': 'type: compare exactly',
},
'ru': {
'later': 'позже',
'not now': 'не сейчас',
'Later, not now': 'Поз&же, не сейчас',
'View': '&Вид',
'Cards': '&Карточки',
'Sound': '&Звук',
'Go': 'П&ереход',
'HardGoodEasy':
_('Again')+', '+_('Hard')+', '+_('Good')+', '+_('Easy'),
'Again': '&'+_('Again'),
'AgainHard': _('Again')+', &'+_('Hard'),
'AgainGood': _('Again')+', &'+_('Good'),
'AgainEasy': _('Again')+', &'+_('Easy'),
'no_smiles': '&Без смайликов',
'no_styles': '&Обычная высота кнопок',
'no_labels': 'На кнопках о&ценок - следующий интервал',
'later_not_now': ' не сейчас ',
'Hide button: ': 'Скрыть кнопку: ',
'no_extra_buttons': 'Скрыть кнопки &интервалов',
'Edit': 'Правка',
'More': 'Ещё',
'Hide buttons': 'Скрыть кнопки: ',
'Edit': 'Ре&дактирование...',
'Edit Layout': '&Шаблоны карточек...',
'Edit Fields': '&Список полей...',
'flat_buttons': '&Плоские кнопки',
'HUGE_buttons': '&Настройка кнопок ответа',
'aa': 'О дополнении ',
'showFrontSide': 'Перейти на &Лицевую Сторону карточки',
'showBackSide': 'Перейти на &Оборотную Сторону карточки',
'viewFrontSide': 'Показать &Лицевую Сторону карточки',
'viewBackSide': 'Показать &Оборотную Сторону карточки',
'swap_fields': 'О&бмен полей %s и %s',
'fields_swapped':
'Выполнен обмен значений ' +
'между полями <b>%s</b> и <b>%s</b>.',
'swapping': 'Обмен полей',
'duplicate': 'Дублировать записи и обменять поля',
'target_deck': 'Введите имя целевой папки для дублируемых карточек:',
'till next': 'Дней до следующего просмотра карточки',
'current': 'фактический интервал',
'card ease': 'Лёгкость карточки',
'days interval': '&Через ... дней',
'search in browser': 'Поиск в Обозревателе Anki: %s...',
'delete note': "Удалить запись?",
'autoshow': "Автопоказ ответа/следующего вопроса",
'autoshow Answer': "Автоматически показывать ответ на вопрос через",
'autoshow Question': "Автоматически показывать следующий вопрос через",
'AUTOSHOW_STATE is on':
"<b style=color:blue;>Включён</b> <b>автопоказ</b> " +
"вопросов и ответов",
'AUTOSHOW_STATE is off':
"<b>Автопоказ</b> вопросов и ответов " +
"<b style=color:red;>отключён</b>",
'show_install': "Показывать Обзор и установка... &Снова",
'open_ankiweb': 'Открыть сайт AnkiWeb с &дополнениями',
'exact': 'type: точное сравнение при проверке',
}
}
try:
MSG[lang]
except KeyError:
lang = 'en'
# 'позже' if lang == 'ru' else _('later')
# 'не сейчас' if lang == 'ru' else _('not now')
# _(u'&Карточки') if lang == 'ru' else _(u'&Cards')
# u'Позж&е, не сейчас' if lang == 'ru' else _(u'&Later, not now')
# _('&Вид') if lang == 'ru' else _('&View')
# '&Кнопки оценок - без меток' if lang == 'ru'
# else _('&Answer buttons without labels')
# ' не сейчас '
# if lang == 'ru' else _(' not now ')
HOTKEY = {
'no_smiles': QKeySequence('Ctrl+Alt+Shift+O'),
'no_styles': QKeySequence('Ctrl+Alt+Shift+B'),
'no_labels': QKeySequence('Ctrl+Alt+Shift+L'),
'later_not_now': 'Escape',
'hide_later': QKeySequence('Ctrl+Alt+Shift+Esc'),
'HideButtons': QKeySequence('Ctrl+Alt+Shift+M'),
'no_extra_buttons': QKeySequence('Ctrl+Alt+Shift+N'),
'All': QKeySequence('Ctrl+Alt+Shift+0'),
'Again': QKeySequence('Ctrl+Alt+Shift+1'),
'Hard': QKeySequence('Ctrl+Alt+Shift+2'),
'Good': QKeySequence('Ctrl+Alt+Shift+3'),
'Easy': QKeySequence('Ctrl+Alt+Shift+4'),
'flat_buttons': 'Ctrl+Alt+Shift+F',
"next_cloze": 'Ctrl+Space',
"same_cloze": 'Ctrl+Alt+Space',
'same_without_Alt': 'F1',
"next_closure": 'F2', # 'Ctrl+Shift+C'
"same_closure": 'Alt+F2', # 'Ctrl+Alt+Shift+C' -- old style
# Ctrl+F11 does not work
"LaTeX": 'Alt+F11', # "Ctrl+T, T"
"LaTeX$": 'F11', # "Ctrl+T, E"
"LaTeX$$": 'Shift+F11', # "Ctrl+T, M"
'showFrontSide': "Ctrl+Up",
'showBackSide': "Ctrl+Down",
'viewFrontSide': "Ctrl+8",
'viewBackSide': "Ctrl+2",
'swap': 'F12',
'dupe': 'Shift+F12',
'timebox': "Ctrl+Shift+T",
'prompt_popup': 'Alt+Shift+Space',
'autoshow': 'Ctrl+Shift+F5',
'Install': QKeySequence('Ctrl+Shift+Insert'),
}
# It is a part of '• Must Have' addon's functionality:
# --musthave.py
# https://ankiweb.net/shared/info/67643234
# based on
# _Again_Hard.py
# https://ankiweb.net/shared/info/1996229983
# old name of this one
# _Later_not_now_button.py
# https://ankiweb.net/shared/info/777151722
# ' Again Hard Good Easy wide big buttons
# https://ankiweb.net/shared/info/1508882486
# inspired by
# Answer_Key_Remap.py
# https://ankiweb.net/shared/info/1446503737
# Bigger Show Answer Button
# https://ankiweb.net/shared/info/1867966335
# Button Colours (Good, Again)
# https://ankiweb.net/shared/info/2494384865
# Bigger Show All Answer Buttons
# https://ankiweb.net/shared/info/2034935033
# More_Answer_Buttons_for_New_Cards.py
# https://ankiweb.net/shared/info/468253198 invalid id
# https://ankiweb.net/shared/info/153603893
# Low Key Anki: Pass/Fail
# https://ankiweb.net/shared/info/477405355
black = 'none' # Night_Mode compatibility
orange = '#c90' # darkgoldenrod
red = '#c33' # #c33
green = '#3c3' # #090
blue = '#69f' # #66f
remap = 'All'
remaps = {'Again':
{1: [None, 1, 1, 1, 1], # nil Again Again Again Again
2: [None, 1, 1, 1, 1], # nil Again Again Again Again
3: [None, 1, 1, 1, 1], # nil Again Again Again Again
4: [None, 1, 1, 1, 1]}, # nil Again Again Again Again
'Hard':
{1: [None, 1, 1, 1, 1], # nil Again Again Again Again
2: [None, 1, 2, 2, 2], # nil Again Good Good Good
3: [None, 1, 2, 2, 2], # nil Again Good Good Good
4: [None, 1, 2, 2, 2]}, # nil Again Hard Hard Hard
'Good':
{1: [None, 1, 1, 1, 1], # nil Again Again Again Again
2: [None, 1, 2, 2, 2], # nil Again Good Good Good
3: [None, 1, 2, 2, 2], # nil Again Good Good Good
4: [None, 1, 3, 3, 3]}, # nil Again Good Good Good
'Easy':
{1: [None, 1, 1, 1, 1], # nil Again Again Again Again
2: [None, 1, 2, 2, 2], # nil Again Good Good Good
3: [None, 1, 3, 3, 3], # nil Again Easy Easy Easy
4: [None, 1, 4, 4, 4]}, # nil Again Easy Easy Easy
'All':
{1: [None, 1, 1, 1, 1], # nil Again Again Again Again
2: [None, 1, 2, 2, 2], # nil Again Good Good Good
3: [None, 1, 2, 2, 3], # nil Again Good Good Easy
4: [None, 1, 2, 3, 4]}} # nil Again Hard Good Easy
# -- width of Show Answer button, triple, double and single answers buttons
BEAMS4 = '99%'
BEAMS3 = '74%'
BEAMS2 = '48%'
BEAMS1 = '24%'
USE_INTERVALS_AS_LABELS = False # True #
EDIT_MORE_BUTTONS = True # False #
HIDE_LATER = False # True #
swAdded = True # False #
NO_SMILES = False # True #
NO_STYLES = False # True #
##
BUTTON_COLOR = {'Again': [black, red, red, red, red],
'Hard': [black, red, orange, orange, orange],
'Good': [black, red, green, green, green],
'Easy': [black, red, blue, blue, blue],
'All': [black, red, orange, green, blue]}
BTN_CLR = {'Again': red, 'Hard': orange, 'Good': green, 'Easy': blue}
BUTTON_LABEL = {'Again': '<span style="color:' + red + ';">o_0</span>',
'Hard': '<b style="color:' + orange + ';">:-(</b>',
'Good': '<b style="color:' + green + ';">:-|</b>',
'Easy': '<b style="color:' + blue + ';">:-)</b>'}
BTN_LABL = {
'en': {
'Again': _('Again').upper(),
'Hard': _('Hard').upper(),
'Good': _('Good').upper(),
'Easy': _('Easy').upper(),
},
'ru': {
'Again': 'СНОВА',
'Hard': 'ТРУДНО',
'Good': 'ХОРОШО',
'Easy': 'ЛЕГКО',
}
}
try:
import Night_Mode
Night_Mode.nm_css_bottom = Night_Mode.nm_css_buttons \
+ Night_Mode.nm_css_color_replacer + \
"""
body {
background:-webkit-gradient(linear,
left top, left bottom, from(#333), to(#222));
border-top-color: #000;
}
.stattxt {
color: #ccc;
}
"""
except ImportError:
pass
FLIP_FLOP = True
# FLIP_FLOP = False
ANKI_MENU_ICONS = True
# ANKI_MENU_ICONS = False
try:
MUSTHAVE_COLOR_ICONS = os.path.join(
aqt.mw.pm.addonFolder(), 'handbook')
except:
MUSTHAVE_COLOR_ICONS = ''
ZERO_KEY_TO_SHOW_ANSWER = True
# ZERO_KEY_TO_SHOW_ANSWER = False
##
CASE_SENSITIVE = True # False #
SWAP_TAG = False
# SWAP_TAG = datetime.datetime.now().strftime(
# 'swapped::swap-%Y-%m-%d') #-%H:%M:%S')
# SWAP_TAG = datetime.datetime.now().strftime('sw-%y-%m-%d')
DUPE_TAG = False
# DUPE_TAG = datetime.datetime.now().strftime(
# 'double::dupe-%Y-%m-%d') # -%H:%M:%S')
# DUPE_TAG = datetime.datetime.now().strftime('dp-%y-%m-%d')
fldlst = [
['En', 'Ru'],
['Eng', 'Rus'],
['English', 'Russian'],
['по-английски', 'по-русски'],
['Q', 'A'], ['В', 'О'],
['Question', 'Answer'],
[_('Question'), _('Answer')],
['Front', 'Back'],
[_('Front'), _('Back')], # Вопрос, Ответ
]
# Anki uses a single digit to track which button has been clicked.
NOT_NOW_BASE = 5
# We will use shortcut number from the first extra button
# and above to track the extra buttons.
INTERCEPT_EASE_BASE = 6
# Must be four or less
assert len(extra_buttons) <= 4
SWAP_TAG = False
# SWAP_TAG = datetime.datetime.now().strftime(
# 'rescheduled::re-%Y-%m-%d::re-card')
# SWAP_TAG = datetime.datetime.now().strftime('re-%y-%m-%d-c')
USE_INTERVALS_AS_LABELS = False # True #
FLAT_BUTTONS = True # False #
AUTOSHOW_STATE = False # True #
install_tooltip = True # False #
install_hotkeys = True # False #
install_again = False # True #
install_menu = True # False #
#
__addon__ = "'" + __name__.replace('_', ' ')
__version__ = "2.0.44a"
if __name__ == '__main__':
print("This is _Again_Good_HUGE_extra_buttons" +
" add-on for the Anki program" +
"and it can't be run directly.")
print('Please download Anki 2.0 from https://apps.ankiweb.net/')
sys.exit()
else:
pass
if sys.version[0] == '2': # Python 3 is utf8 only already.
if hasattr(sys, 'setdefaultencoding'):
sys.setdefaultencoding('utf8')
##
old_addons = (
'Answer_Key_Remap.py',
'Bigger_Show_Answer_Button.py',
'Button_Colours_Good_Again.py',
'Bigger_Show_All_Answer_Buttons.py',
'More_Answer_Buttons_for_New_Cards.py',
'_Again_Hard.py',
# '_Editor_Fontsize.py',
'_Again_Hard_Good_Easy_wide_big_buttons.py',
'_Alternative_hotkeys_to_cloze_selected_text_in_Add_or_Editor_window.py',
'_Later_not_now_button.py',
'More_Answer_Buttons_for_New_Cards.py',
'_More_Answer_Buttons_for_ALL_Cards.py',
'Low_Key_Anki_PassFail.py',
'_Flip-flop.py',
'_Duplicate_notes_and_Swap_fields.py',
'_Swap.py',
'_Swap_fields.py',
'Create_Copy_of_Selected_Cards.py',
'Create_Duplicate_Notes.py',
'Duplicate_Selected_Notes.py',
'anki-browser-create-duplicate.py',
'_Prompt_and_set_days_interval_and_card_ease.py',
'Automatically_show_answer_after_X_seconds.py',
'_Addons_Install_Tooltip.py',
)
old_addons2delete = ''
for old_addon in old_addons:
if len(old_addon) > 0:
old_filename = os.path.join(aqt.mw.pm.addonFolder(), old_addon)
if os.path.exists(old_filename):
old_addons2delete += old_addon[:-3] + ' \n'
if old_addons2delete != '':
if lang == 'ru':
aqt.utils.showText(
'В каталоге\n\n ' + aqt.mw.pm.addonFolder() +
'\n\nнайдены дополнения, которые уже включены в дополнение\n' +
" Again Good HUGE buttons \n" +
'и поэтому будут конфликтовать с ним.\n\n' +
old_addons2delete +
'\nУдалите эти дополнения и перезапустите Anki.')
else:
aqt.utils.showText(
'<big>There are some add-ons in the folder <br>\n<br>\n' +
' ' + aqt.mw.pm.addonFolder() +
'<pre>' + old_addons2delete + '</pre>' +
'They are already part of<br>\n' +
" <b> Again Good HUGE buttons</b>" +
' addon.<br>\n' +
'Please, delete them and restart Anki.</big>', type="html")
act = [None, None, None, None, None]
# --------------------------
# hotkeys does not work on context menu
# for information purpose only (exploratory testing is anticipated)
def ask_delete():
"""Delete a note after asking the user."""
if aqt.mw.state != 'review':
return
if aqt.utils.askUser(MSG[lang]['delete note']): # , defaultno=True):
aqt.mw.reviewer.onDelete()
# -- Disable the delete key in reviews
aqt.mw.disconnect(aqt.mw.reviewer.delShortcut, aqt.qt.SIGNAL(
"activated()"), aqt.mw.reviewer.onDelete)
# дисконнект нужен обязательно, иначе продолжают работать вместе
aqt.mw.connect(aqt.mw.reviewer.delShortcut,
aqt.qt.SIGNAL("activated()"), ask_delete)
opts = [
[_("Mark Note"), "*", aqt.mw.reviewer.onMark],
None,
[_("Bury Card"), "-", aqt.mw.reviewer.onBuryCard],
[_("Bury Note"), "=", aqt.mw.reviewer.onBuryNote],
[_("Suspend Card"), "@", aqt.mw.reviewer.onSuspendCard],
[_("Suspend Note"), "!", aqt.mw.reviewer.onSuspend],
[_("Delete Note"), "Delete", ask_delete], # aqt.mw.reviewer.onDelete],
None,
[_("Options"), "o", aqt.mw.reviewer.onOptions],
]
opts.extend([
None,
[_("Replay Audio"), "r", aqt.mw.reviewer.replayAudio],
None,
])
opts.append(
[_("Record Own Voice"), "Shift+v", aqt.mw.reviewer.onRecordVoice],
)
opts.append(
[_("Replay Own Voice"), "v", aqt.mw.reviewer.onReplayRecorded],
)
class BrowserLookup:
def get_selected(self, view):
"""Copy selected text"""
return view.page().selectedText()
def lookup_action(self, view):
browser = aqt.dialogs.open("Browser", aqt.mw)
browser.form.searchEdit.lineEdit().setText(self.get_selected(view))
browser.onSearch()
def add_action(self, view, menu, action):
"""Add 'lookup' action to context menu."""
if self.get_selected(view):
action = menu.addAction(action)
action.connect(action, SIGNAL('triggered()'),
lambda view=view: self.lookup_action(view))
def context_lookup_action(self, view, menu):
if aqt.mw.state != 'review':
return
edit_current_action = menu.addAction(MSG[lang]["Edit"])
edit_current_action.connect(
edit_current_action, SIGNAL("triggered()"), go_edit_current)
more_menu = QMenu(MSG[lang]["More"], menu)
menu.addMenu(more_menu)
for row in opts:
if not row:
more_menu.addSeparator()
continue
label, scut, func = row
a = more_menu.addAction(label)
a.setShortcut(QKeySequence(scut))
a.connect(a, SIGNAL("triggered()"), func)
"""Browser Lookup action"""
self.add_action(
view, menu,
MSG[lang]['search in browser'] % self.get_selected(view)[:20])
# Add lookup actions to context menu
browser_lookup = BrowserLookup()
anki.hooks.addHook(
"AnkiWebView.contextMenuEvent",
browser_lookup.context_lookup_action)
"""
# Bigger Show Answer Button
For people who do their reps with a mouse.
Makes the show answer button wide enough to cover all 4 of the review buttons.
"""
def newRemaining(self):
if not self.mw.col.conf['dueCounts']:
return 0
idx = self.mw.col.sched.countIdx(self.card)
if self.hadCardQueue:
# if it's come from the undo queue, don't count it separately
counts = list(self.mw.col.sched.counts())
else:
counts = list(self.mw.col.sched.counts(self.card))
return (idx == 0 and counts[0] < 1)
def laterNotNow(self, showAnswer):
ret = '<style>td{vertical-align:bottom;}' +\
'html, body, table { width: 100%; height: 100%;' +\
' margin: 0px; padding: 0px; box-sizing: content-box; }' +\
'/*html,*/ body { overflow: hidden; } ' +\
'</style>'
if not NO_STYLES:
ret += '<style>' +\
'td button{font-size:large;}' +\
'td.x button{font-size:x-large;color:#888;}' +\
'td.xx button{font-size:xx-large;}' +\
'</style>'
if not NO_STYLES and FLAT_BUTTONS:
ret += '<style>' +\
'td.esc,td.xxx,td.stat{border:none;}' +\
'td.esc button, td.xxx button, td.stat button {border:none;}' +\
'/*td.stat,td.stat button{background-color:Ivory;}*/' +\
'td.xxx, td.xxx button {background-color:aliceblue;}' +\
'td.esc, td.esc button {background-color:whitesmoke;}' +\
'td.but1, td.but1 button {background-color:#D72D2E;}' +\
'td.but2, td.but2 button {background-color:#465A65;}' +\
'td.but3, td.but3 button {background-color:#4CB050;}' +\
'td.but4, td.but4 button {background-color:#03A9F5;}' +\
'td.but button span, td.but button b, td.but, ' +\
'td.but button {color:#ffFFff!important;border:none;}' +\
'td.but button:focus {outline: orange 1px dashed;}' +\
'</style>'
if not NO_STYLES and FLAT_BUTTONS and (swAdded or not HIDE_LATER):
ret += '<style>' +\
'td.esc,td.xxx,td.stat{border-left:solid 1px silver;}' +\
'td:first-child.stat{border-left:none;}' +\
'</style>'
if not NO_STYLES and USE_INTERVALS_AS_LABELS and FLAT_BUTTONS:
ret += '<style>' +\
'.stattxt, .nobold {display:none;}' +\
' button { width: 100%; height: 100%;} ' +\
'</style>'
ret += '<table cellpadding=0 cellspacing=0 width=100%><tr>'
if HIDE_LATER:
return ret
ret = ret.replace('%', '%%') +\
'<td align=center class="x esc" style="padding-right:.35em;" ' +\
"""onclick="py.link('ease%d');"><span class="stattxt">%s</span>""" +\
'''<button title=" %s " onclick="py.link('ease%d');" ''' +\
'style="width:99%%;%s">%s</button></td>' # <td> </td>
if showAnswer:
if self.mw.col.conf['dueCounts']:
retv = True
else:
retv = False
else:
if self.mw.col.conf['estTimes']:
retv = True
else:
retv = False
if USE_INTERVALS_AS_LABELS:
retv = False
if retv:
return ret % (NOT_NOW_BASE, MSG[lang]['later'],
_("Shortcut key: %s") % (HOTKEY['later_not_now']),
NOT_NOW_BASE,
'color:' + black + ';', (MSG[lang]['later_not_now']))
else:
return ret % (NOT_NOW_BASE, "",
_("Shortcut key: %s") % (HOTKEY['later_not_now']),
NOT_NOW_BASE,
'color:' + black + ';', (MSG[lang]['later']))
def myShowAnswerButton(self, _old):
_old(self)
set_timeoutA(self)
if newRemaining(self):
self.mw.moveToState('overview')
self._bottomReady = True
if not self.typeCorrect:
self.bottom.web.setFocus()
if USE_INTERVALS_AS_LABELS:
middle = laterNotNow(self, True) + (
'<td align=center style="width:%s;" class="xx xxx"' +
''' onclick="py.link('ans');"><span''' +
' class="stattxt"> </span><button %s id=ansbut ' +
'''style="width:100%%;%s" onclick="py.link('ans');" ''' +
'>%s</button></td>' +
'</tr></table>') % (
BEAMS4,
' title=" ' + (_('Shortcut key: %s') % _('Space')) + ' " ',
' color:' + black + ';', self._remaining())
else:
middle = laterNotNow(self, True) + (
'<td align=center style="width:%s;" class="xx xxx"' +
' onclick="py.link(\'ans\');"><span' +
' class="stattxt">%s</span><button %s id=ansbut ' +
'''style="width:100%%;%s" onclick="py.link('ans');" ''' +
'>%s</button></td>' +
'</tr></table>') % (
BEAMS4, self._remaining(),
' title=" ' + (_('Shortcut key: %s') % _('Space')) + ' " ',
' color:' + black + ';', _('Show Answer'))
# place it in a table so it has the same top margin as the ease buttons
# middle = '<!div align=center style='width:%s!important;'>%s</div>' %
# (BEAMS4, middle)
if self.card.shouldShowTimer():
maxTime = self.card.timeLimit() / 1000
else:
maxTime = 0
self.bottom.web.eval('showQuestion(%s,%d);' % (
json.dumps(middle), maxTime))
return True
if old_addons2delete == '':
aqt.reviewer.Reviewer._showAnswerButton = anki.hooks.wrap(
aqt.reviewer.Reviewer._showAnswerButton, myShowAnswerButton, 'around')
# This wraps existing Reviewer._answerCard function.
def answer_card_intercepting(self, actual_ease, _old):
ease = actual_ease
if actual_ease == NOT_NOW_BASE:
self.nextCard()
return True
elif actual_ease < NOT_NOW_BASE:
count = self.mw.col.sched.answerButtons(self.card)
try:
ease = remaps[remap][count][ease]
except (KeyError, IndexError):
pass
return _old(self, ease)
else:
was_new_card = self.card.type in (0, 1, 2, 3)
is_extra_button = was_new_card and \
actual_ease >= INTERCEPT_EASE_BASE
if is_extra_button:
# Make sure this is as expected.
# assert self.mw.col.sched.answerButtons(self.card) == 3
# So this is one of our buttons.
# First answer the card as if 'Easy' clicked.
ease = 3
# We will need this to reschedule it.
prev_card_id = self.card.id
prev_card_factor = self.card.factor
#
buttonItem = extra_buttons[actual_ease - INTERCEPT_EASE_BASE]
# Do the reschedule.
self.mw.checkpoint(_('Reschedule card'))
# self.mw.col.sched.reschedCards([prev_card_id],
# buttonItem['ReschedMin'], buttonItem['ReschedMax'])
_reschedCards(
self.mw.col.sched, [prev_card_id],
buttonItem['ReschedMin'], buttonItem['ReschedMax'],
indi=prev_card_factor)
aqt.utils.tooltip(
'<center>Rescheduled:' + '<br>' +
buttonItem['Description'] + '</center>')
SwapTag = SWAP_TAG
if SwapTag:
SwapTag += unicode(self.mw.reviewer.card.ord + 1)
note = self.mw.reviewer.card.note()
if not note.hasTag(SwapTag):
note.addTag(SwapTag)
note.flush() # never forget to flush
self.mw.reset()
return True
else:
ret = _old(self, ease)
return ret
aqt.reviewer.Reviewer._answerCard = anki.hooks.wrap(
aqt.reviewer.Reviewer._answerCard,
answer_card_intercepting, 'around')
# 'before' does not working as intended cause ease is changing inside AKR
# to remove <span class=nobold>
def _bottomTimes(self, i):
if not self.mw.col.conf['estTimes']:
return ' '
txt = self.mw.col.sched.nextIvlStr(self.card, i, True) or ' '
return txt.replace("<", "<")
# always show interval despite user's preferences
def _bottomTime(self, i):
# if not self.mw.col.conf['estTimes']:
# return ' '
txt = self.mw.col.sched.nextIvlStr(self.card, i, True) or ' '
return txt.replace("<", "<")
def BTN_LBL(title):
if NO_STYLES:
return '<b style="color:%s;">' % (BTN_CLR[title]) + \
_(title) + '</b>'
elif NO_SMILES:
return '<span style="color:%s;">' % (BTN_CLR[title]) + \
BTN_LABL[lang][title] + '</span>'
else:
return BUTTON_LABEL[title]
# Replace _answerButtonList method
def answerButtonList(self):
if remap == 'All':
l = ((1, '' + BTN_LBL('Again') + '', BEAMS1),)
cnt = self.mw.col.sched.answerButtons(self.card)
elif remap == 'Again':
l = ((1, '' + BTN_LBL('Again') + '', BEAMS4),)
cnt = 1
return l
else:
l = ((1, '' + BTN_LBL('Again') + '', BEAMS2),)
cnt = 2
if cnt == 2:
if remap == 'All':
return l + ((2, '' + BTN_LBL('Good') + '', BEAMS3),)
else:
return l + ((2, '' + BTN_LBL(remap) + '', BEAMS2),)
# the comma at the end is mandatory, a subtle bug occurs without it
elif cnt == 3:
return l + ((2, '' + BTN_LBL('Good') + '', BEAMS2),
(3, '' + BTN_LBL('Easy') + '', BEAMS1))
else:
return l + ((2, '' + BTN_LBL('Hard') + '', BEAMS1),
(3, '' + BTN_LBL('Good') + '', BEAMS1),
(4, '' + BTN_LBL('Easy') + '', BEAMS1))
# all buttons are with coloured text
# and have an equal width with buttons in Night Mode
def answerCard_tooltip(self, ease):
l = self._answerButtonList()
a = [item for item in l if item[0] == ease]
if len(a) > 0:
return a[0][1]