forked from Ramblurr/Anki-Android
-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathSched.java
2839 lines (2521 loc) · 93.1 KB
/
Sched.java
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 (c) 2011 Norbert Nagold <[email protected]> *
* Copyright (c) 2012 Kostas Spyropoulos <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General private License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General private License for more details. *
* *
* You should have received a copy of the GNU General private License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.util.Log;
import com.ichi2.anki.AnkiDroidApp;
import com.ichi2.anki.Pair;
import com.ichi2.anki.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.TreeSet;
public class Sched {
// whether new cards should be mixed with reviews, or shown first or last
public static final int NEW_CARDS_DISTRIBUTE = 0;
public static final int NEW_CARDS_LAST = 1;
public static final int NEW_CARDS_FIRST = 2;
// new card insertion order
public static final int NEW_CARDS_RANDOM = 0;
public static final int NEW_CARDS_DUE = 1;
// review card sort order
public static final int REV_CARDS_RANDOM = 0;
public static final int REV_CARDS_OLD_FIRST = 1;
public static final int REV_CARDS_NEW_FIRST = 2;
// removal types
public static final int REM_CARD = 0;
public static final int REM_NOTE = 1;
public static final int REM_DECK = 2;
// count display
public static final int COUNT_ANSWERED = 0;
public static final int COUNT_REMAINING = 1;
// media log
public static final int MEDIA_ADD = 0;
public static final int MEDIA_REM = 1;
// dynamic deck order
public static final int DYN_OLDEST = 0;
public static final int DYN_RANDOM = 1;
public static final int DYN_SMALLINT = 2;
public static final int DYN_BIGINT = 3;
public static final int DYN_LAPSES = 4;
public static final int DYN_ADDED = 5;
public static final int DYN_DUE = 6;
public static final int DYN_REVADDED = 7;
// model types
public static final int MODEL_STD = 0;
public static final int MODEL_CLOZE = 1;
private static final String[] REV_ORDER_STRINGS = { "ivl DESC", "ivl" };
private static final int[] FACTOR_ADDITION_VALUES = { -150, 0, 150 };
// not in libanki
public static final int DECK_INFORMATION_NAMES = 0;
public static final int DECK_INFORMATION_SIMPLE_COUNTS = 1;
public static final int DECK_INFORMATION_EXTENDED_COUNTS = 2;
private Collection mCol;
private String mName = "std";
private int mQueueLimit;
private int mReportLimit;
public int mReps;
private boolean mHaveQueues;
private int mToday;
public long mDayCutoff;
private boolean mHaveCustomStudy;
private boolean mSpreadRev = true;
private int mNewCount;
private int mLrnCount;
private int mRevCount;
private int mNewCardModulus;
private double[] mEtaCache = new double[] { -1, -1, -1, -1 };
// Queues
private LinkedList<long[]> mNewQueue;
private LinkedList<long[]> mLrnQueue;
private LinkedList<long[]> mLrnDayQueue;
private LinkedList<long[]> mRevQueue;
private LinkedList<Long> mNewDids;
private LinkedList<Long> mLrnDids;
private LinkedList<Long> mRevDids;
private TreeMap<Integer, Integer> mGroupConfs;
private TreeMap<Integer, JSONObject> mConfCache;
private HashMap<Long, Pair<String[], long[]>> mCachedDeckCounts;
/**
* queue types: 0=new/cram, 1=lrn, 2=rev, 3=day lrn, -1=suspended, -2=buried revlog types: 0=lrn, 1=rev, 2=relrn,
* 3=cram positive intervals are in positive revlog intervals are in days (rev), negative in seconds (lrn)
*/
public Sched(Collection col) {
mCol = col;
mQueueLimit = 50;
mReportLimit = 1000;
mReps = 0;
mHaveCustomStudy = true;
mHaveQueues = false;
_updateCutoff();
// Initialise queues
mNewQueue = new LinkedList<long[]>();
mLrnQueue = new LinkedList<long[]>();
mLrnDayQueue = new LinkedList<long[]>();
mRevQueue = new LinkedList<long[]>();
}
/**
* Pop the next card from the queue. None if finished.
*/
public Card getCard() {
_checkDay();
if (!mHaveQueues) {
reset();
}
Card card = _getCard();
if (card != null) {
mReps += 1;
card.startTimer();
}
return card;
}
/* NOT IN LIBANKI */
public void decrementCounts(Card card) {
int type = card.getQueue();
switch (type) {
case 0:
mNewCount--;
break;
case 1:
mLrnCount -= card.getLeft() / 1000;
break;
case 2:
mRevCount--;
break;
case 3:
mLrnCount--;
break;
}
}
public void reset() {
_updateCutoff();
_resetLrn();
_resetRev();
_resetNew();
mHaveQueues = true;
}
public boolean answerCard(Card card, int ease) {
Log.i(AnkiDroidApp.TAG, "answerCard - ease:" + ease);
boolean isLeech = false;
mCol.markUndo(Collection.UNDO_REVIEW, new Object[]{card});
card.setReps(card.getReps() + 1);
// former is for logging new cards, latter also covers filt. decks
card.setWasNew((card.getType() == 0));
boolean wasNewQ = (card.getQueue() == 0);
if (wasNewQ) {
// came from the new queue, move to learning
card.setQueue(1);
// if it was a new card, it's now a learning card
if (card.getType() == 0) {
card.setType(1);
}
// init reps to graduation
card.setLeft(_startingLeft(card));
// dynamic?
if (card.getODid() != 0 && card.getType() == 2) {
if (_resched(card)) {
// reviews get their ivl boosted on first sight
card.setIvl(_dynIvlBoost(card));
card.setODue(mToday + card.getIvl());
}
}
_updateStats(card, "new");
}
if (card.getQueue() == 1 || card.getQueue() == 3) {
_answerLrnCard(card, ease);
if (!wasNewQ) {
_updateStats(card, "lrn");
}
} else if (card.getQueue() == 2) {
isLeech = _answerRevCard(card, ease);
_updateStats(card, "rev");
} else {
throw new RuntimeException("Invalid queue");
}
_updateStats(card, "time", card.timeTaken());
card.setMod(Utils.intNow());
card.setUsn(mCol.usn());
card.flushSched();
return isLeech;
}
public int[] counts() {
return counts(null);
}
public int[] counts(Card card) {
int[] counts = new int[3];
counts[0] = mNewCount;
counts[1] = mLrnCount;
counts[2] = mRevCount;
if (card != null) {
int idx = countIdx(card);
if (idx == 1) {
counts[1] += card.getLeft() / 1000;
} else {
counts[idx] += 1;
}
}
return counts;
}
/**
* Return counts over next DAYS. Includes today.
*/
public int dueForecast() {
return dueForecast(7);
}
public int dueForecast(int days) {
// TODO:...
return 0;
}
public int countIdx(Card card) {
if (card.getQueue() == 3) {
return 1;
}
return card.getQueue();
}
public int answerButtons(Card card) {
if (card.getODue() != 0) {
// normal review in dyn deck?
if (card.getODid() != 0 && card.getQueue() == 2) {
return 4;
}
JSONObject conf = _lapseConf(card);
try {
if (card.getType() == 0 || conf.getJSONArray("delays").length() > 1) {
return 3;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return 2;
} else if (card.getQueue() == 2) {
return 4;
} else {
return 3;
}
}
/**
* Unbury cards when closing.
*/
public void unburyCards() {
boolean mod = mCol.getDb().getMod();
mCol.getDb().execute("UPDATE cards SET queue = type WHERE queue = -2");
mCol.getDb().setMod(mod);
}
// /**
// * A very rough estimate of time to review.
// */
// public int eta() {
// Cursor cur = null;
// int cnt = 0;
// int sum = 0;
// try {
// cur = mDb.getDatabase().rawQuery(
// "SELECT count(), sum(taken) FROM (SELECT * FROM revlog " +
// "ORDER BY time DESC LIMIT 10)", null);
// if (cur.moveToFirst()) {
// cnt = cur.getInt(0);
// sum = cur.getInt(1);
// }
// } finally {
// if (cur != null && !cur.isClosed()) {
// cur.close();
// }
// }
// if (cnt == 0) {
// return 0;
// }
// double avg = sum / ((float) cnt);
// int[] c = counts();
// return (int) ((avg * c[0] * 3 + avg * c[1] * 3 + avg * c[2]) / 1000.0);
// }
/**
* Rev/lrn/time daily stats *************************************************
* **********************************************
*/
private void _updateStats(Card card, String type) {
_updateStats(card, type, 1);
}
public void _updateStats(Card card, String type, long l) {
String key = type + "Today";
long did = card.getDid();
ArrayList<JSONObject> list = mCol.getDecks().parents(did);
list.add(mCol.getDecks().get(did));
for (JSONObject g : list) {
try {
JSONArray a = g.getJSONArray(key);
// add
a.put(1, a.getLong(1) + l);
} catch (JSONException e) {
throw new RuntimeException(e);
}
mCol.getDecks().save(g);
}
}
public void extendLimits(int newc, int rev) {
JSONObject cur = mCol.getDecks().current();
ArrayList<JSONObject> decks = new ArrayList<JSONObject>();
decks.add(cur);
try {
decks.addAll(mCol.getDecks().parents(cur.getLong("id")));
for (long did : mCol.getDecks().children(cur.getLong("id")).values()) {
decks.add(mCol.getDecks().get(did));
}
for (JSONObject g : decks) {
// add
JSONArray ja = g.getJSONArray("newToday");
ja.put(1, ja.getInt(1) - newc);
g.put("newToday", ja);
ja = g.getJSONArray("revToday");
ja.put(1, ja.getInt(1) - rev);
g.put("revToday", ja);
mCol.getDecks().save(g);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private int _walkingCount() {
return _walkingCount(null, null, null);
}
private int _walkingCount(LinkedList<Long> dids) {
return _walkingCount(dids, null, null);
}
private int _walkingCount(Method limFn, Method cntFn) {
return _walkingCount(null, limFn, cntFn);
}
private int _walkingCount(LinkedList<Long> dids, Method limFn, Method cntFn) {
if (dids == null) {
dids = mCol.getDecks().active();
}
int tot = 0;
HashMap<Long, Integer> pcounts = new HashMap<Long, Integer>();
// for each of the active decks
try {
for (long did : dids) {
// get the individual deck's limit
int lim = 0;
// if (limFn != null) {
lim = (Integer) limFn.invoke(Sched.this, mCol.getDecks().get(did));
// }
if (lim == 0) {
continue;
}
// check the parents
ArrayList<JSONObject> parents = mCol.getDecks().parents(did);
for (JSONObject p : parents) {
// add if missing
long id = p.getLong("id");
if (!pcounts.containsKey(id)) {
pcounts.put(id, (Integer) limFn.invoke(Sched.this, p));
}
// take minimum of child and parent
lim = Math.min(pcounts.get(id), lim);
}
// see how many cards we actually have
int cnt = 0;
// if (cntFn != null) {
cnt = (Integer) cntFn.invoke(Sched.this, did, lim);
// }
// if non-zero, decrement from parents counts
for (JSONObject p : parents) {
long id = p.getLong("id");
pcounts.put(id, pcounts.get(id) - cnt);
}
// we may also be a parent
pcounts.put(did, lim - cnt);
// and add to running total
tot += cnt;
}
} catch (JSONException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return tot;
}
/**
* Deck list **************************************************************** *******************************
*/
/** LIBANKI: not in libanki */
public Object[] deckCounts() {
TreeSet<Object[]> decks = deckDueTree(0);
int[] counts = new int[] { 0, 0, 0 };
for (Object[] deck : decks) {
if (((String[]) deck[0]).length == 1) {
counts[0] += (Integer) deck[2];
counts[1] += (Integer) deck[3];
counts[2] += (Integer) deck[4];
}
}
TreeSet<Object[]> decksNet = new TreeSet<Object[]>(new DeckNameCompare());
for (Object[] d : decks) {
try {
boolean show = true;
for (JSONObject o : mCol.getDecks().parents((Long) d[1])) {
if (o.getBoolean("collapsed")) {
show = false;
break;
}
}
if (show) {
JSONObject deck = mCol.getDecks().get((Long) d[1]);
if (deck.getBoolean("collapsed")) {
String[] name = (String[]) d[0];
name[name.length - 1] = name[name.length - 1] + " (+)";
d[0] = name;
}
decksNet.add(new Object[]{d[0], d[1], d[2], d[3], d[4], deck.getInt("dyn") != 0});
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return new Object[] { decksNet, eta(counts), mCol.cardCount() };
}
public boolean getSpreadRev() {
return mSpreadRev;
}
public void setSpreadRev(boolean mSpreadRev) {
this.mSpreadRev = mSpreadRev;
}
public class DeckDueListComparator implements Comparator<JSONObject> {
public int compare(JSONObject o1, JSONObject o2) {
try {
return o1.getString("name").compareTo(o2.getString("name"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
/**
* Returns [deckname, did, rev, lrn, new]
*/
public ArrayList<Object[]> deckDueList(int counts) {
_checkDay();
mCol.getDecks().recoverOrphans();
unburyCards();
ArrayList<JSONObject> decks = mCol.getDecks().all();
Collections.sort(decks, new DeckDueListComparator());
HashMap<String, Integer[]> lims = new HashMap<String, Integer[]>();
ArrayList<Object[]> data = new ArrayList<Object[]>();
try {
for (JSONObject deck : decks) {
// if we've already seen the exact same deck name, remove the
// invalid duplicate and reload
if (lims.containsKey(deck.getString("name"))) {
mCol.getDecks().rem(deck.getLong("id"), false, true);
return deckDueList(counts);
}
String p;
String[] parts = deck.getString("name").split("::");
if (parts.length < 2) {
p = "";
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length - 1; i++) {
sb.append(parts[i]);
if (i < parts.length - 2) {
sb.append("::");
}
}
p = sb.toString();
}
// new
int nlim = _deckNewLimitSingle(deck);
if (p.length() > 0) {
if (!lims.containsKey(p)) {
// if parent was missing, this deck is invalid, and we need to reload the deck list
mCol.getDecks().rem(deck.getLong("id"), false, true);
return deckDueList(counts);
}
nlim = Math.min(nlim, lims.get(p)[0]);
}
int newC = _newForDeck(deck.getLong("id"), nlim);
// learning
int lrn = _lrnForDeck(deck.getLong("id"));
// reviews
int rlim = _deckRevLimitSingle(deck);
if (p.length() > 0) {
rlim = Math.min(rlim, lims.get(p)[1]);
}
int rev = _revForDeck(deck.getLong("id"), rlim);
// save to list
// LIBANKI: order differs from libanki (here: new, lrn, rev)
data.add(new Object[]{deck.getString("name"), deck.getLong("id"), newC, lrn, rev});
// add deck as a parent
lims.put(deck.getString("name"), new Integer[]{nlim, rlim});
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return data;
}
public TreeSet<Object[]> deckDueTree(int counts) {
return _groupChildren(deckDueList(counts));
}
private TreeSet<Object[]> _groupChildren(ArrayList<Object[]> grps) {
TreeSet<Object[]> set = new TreeSet<Object[]>(new DeckNameCompare());
// first, split the group names into components
for (Object[] g : grps) {
set.add(new Object[] { ((String) g[0]).split("::"), g[1], g[2], g[3], g[4] });
}
return _groupChildrenMain(set);
}
private TreeSet<Object[]> _groupChildrenMain(TreeSet<Object[]> grps) {
return _groupChildrenMain(grps, 0);
}
private TreeSet<Object[]> _groupChildrenMain(TreeSet<Object[]> grps, int depth) {
TreeSet<Object[]> tree = new TreeSet<Object[]>(new DeckNameCompare());
// group and recurse
Iterator<Object[]> it = grps.iterator();
Object[] tmp = null;
while (tmp != null || it.hasNext()) {
Object[] head;
if (tmp != null) {
head = tmp;
tmp = null;
} else {
head = it.next();
}
String[] title = (String[]) head[0];
long did = (Long) head[1];
int newCount = (Integer) head[2];
int lrnCount = (Integer) head[3];
int revCount = (Integer) head[4];
TreeSet<Object[]> children = new TreeSet<Object[]>(new DeckNameCompare());
while (it.hasNext()) {
Object[] o = it.next();
if (((String[])o[0])[depth].equals(title[depth])) {
// add to children
children.add(o);
} else {
// proceed with this as head
tmp = o;
break;
}
}
children = _groupChildrenMain(children, depth + 1);
// tally up children counts, but skip deeper sub-decks
for (Object[] ch : children) {
if (((String[])ch[0]).length == ((String[])head[0]).length+1) {
newCount += (Integer)ch[2];
lrnCount += (Integer)ch[3];
revCount += (Integer)ch[4];
}
}
// limit the counts to the deck's limits
JSONObject conf = mCol.getDecks().confForDid(did);
JSONObject deck = mCol.getDecks().get(did);
try {
if (conf.getInt("dyn") == 0) {
revCount = Math.max(0, Math.min(revCount, conf.getJSONObject("rev").getInt("perDay") - deck.getJSONArray("revToday").getInt(1)));
newCount = Math.max(0, Math.min(newCount, conf.getJSONObject("new").getInt("perDay") - deck.getJSONArray("newToday").getInt(1)));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
tree.add(new Object[] {title, did, newCount, lrnCount, revCount,
children});
}
TreeSet<Object[]> result = new TreeSet<Object[]>(new DeckNameCompare());
for (Object[] t : tree) {
result.add(new Object[]{t[0], t[1], t[2], t[3], t[4]});
result.addAll((TreeSet<Object[]>) t[5]);
}
return result;
}
/**
* Getting the next card ****************************************************
* *******************************************
*/
/**
* Return the next due card, or None.
*/
private Card _getCard() {
// learning card due?
Card c = _getLrnCard();
if (c != null) {
return c;
}
// new first, or time for one?
if (_timeForNewCard()) {
return _getNewCard();
}
// Card due for review?
c = _getRevCard();
if (c != null) {
return c;
}
// day learning card due?
c = _getLrnDayCard();
if (c != null) {
return c;
}
// New cards left?
c = _getNewCard();
if (c != null) {
return c;
}
// collapse or finish
return _getLrnCard(true);
}
//
// /** LIBANKI: not in libanki */
// public boolean removeCardFromQueues(Card card) {
// long id = card.getId();
// Iterator<long[]> i = mNewQueue.iterator();
// while (i.hasNext()) {
// long cid = i.next()[0];
// if (cid == id) {
// i.remove();
// mNewCount -= 1;
// return true;
// }
// }
// i = mLrnQueue.iterator();
// while (i.hasNext()) {
// long cid = i.next()[1];
// if (cid == id) {
// i.remove();
// mLrnCount -= card.getLeft();
// return true;
// }
// }
// i = mLrnDayQueue.iterator();
// while (i.hasNext()) {
// long cid = i.next()[1];
// if (cid == id) {
// i.remove();
// mLrnCount -= card.getLeft();
// return true;
// }
// }
// i = mRevQueue.iterator();
// while (i.hasNext()) {
// long cid = i.next()[0];
// if (cid == id) {
// i.remove();
// mRevCount -= 1;
// return true;
// }
// }
// return false;
// }
/**
* New cards **************************************************************** *******************************
*/
private void _resetNewCount() {
try {
mNewCount = _walkingCount(Sched.class.getDeclaredMethod("_deckNewLimitSingle", JSONObject.class),
Sched.class.getDeclaredMethod("_cntFnNew", long.class, int.class));
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private int _cntFnNew(long did, int lim) {
return mCol.getDb().queryScalar(
"SELECT count() FROM (SELECT 1 FROM cards WHERE did = " + did + " AND queue = 0 LIMIT " + lim + ")");
}
private void _resetNew() {
_resetNewCount();
mNewDids = new LinkedList<Long>(mCol.getDecks().active());
mNewQueue.clear();
_updateNewCardRatio();
}
private boolean _fillNew() {
if (mNewQueue.size() > 0) {
return true;
}
if (mNewCount == 0) {
return false;
}
while (!mNewDids.isEmpty()) {
long did = mNewDids.getFirst();
int lim = Math.min(mQueueLimit, _deckNewLimit(did));
mNewQueue.clear();
Cursor cur = null;
if (lim != 0) {
try {
cur = mCol
.getDb()
.getDatabase()
.rawQuery("SELECT id, due FROM cards WHERE did = " + did + " AND queue = 0 LIMIT " + lim,
null);
while (cur.moveToNext()) {
mNewQueue.add(new long[] { cur.getLong(0), cur.getLong(1) });
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
if (!mNewQueue.isEmpty()) {
return true;
}
}
// nothing left in the deck; move to next
mNewDids.remove();
}
return false;
}
private Card _getNewCard() {
if (!_fillNew()) {
return null;
}
long[] item = mNewQueue.remove();
// move any siblings to the end?
try {
JSONObject conf = mCol.getDecks().confForDid(mNewDids.getFirst());
if (conf.getInt("dyn") != 0 || conf.getJSONObject("new").getBoolean("separate")) {
int n = mNewQueue.size();
while (!mNewQueue.isEmpty() && mNewQueue.getFirst()[1] == item[1]) {
mNewQueue.add(mNewQueue.remove());
n -= 1;
if (n == 0) {
// we only have one fact in the queue; stop rotating
break;
}
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
mNewCount -= 1;
return mCol.getCard(item[0]);
}
private void _updateNewCardRatio() {
try {
if (mCol.getConf().getInt("newSpread") == NEW_CARDS_DISTRIBUTE) {
if (mNewCount != 0) {
mNewCardModulus = (mNewCount + mRevCount) / mNewCount;
// if there are cards to review, ensure modulo >= 2
if (mRevCount != 0) {
mNewCardModulus = Math.max(2, mNewCardModulus);
}
return;
}
}
mNewCardModulus = 0;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* @return True if it's time to display a new card when distributing.
*/
private boolean _timeForNewCard() {
if (mNewCount == 0) {
return false;
}
int spread;
try {
spread = mCol.getConf().getInt("newSpread");
} catch (JSONException e) {
throw new RuntimeException(e);
}
if (spread == NEW_CARDS_LAST) {
return false;
} else if (spread == NEW_CARDS_FIRST) {
return true;
} else if (mNewCardModulus != 0) {
return (mReps != 0 && (mReps % mNewCardModulus == 0));
} else {
return false;
}
}
private int _deckNewLimit(long did) {
return _deckNewLimit(did, null);
}
private int _deckNewLimit(long did, Method fn) {
try {
if (fn == null) {
fn = Sched.class.getDeclaredMethod("_deckNewLimitSingle", JSONObject.class);
}
ArrayList<JSONObject> decks = mCol.getDecks().parents(did);
decks.add(mCol.getDecks().get(did));
int lim = -1;
// for the deck and each of its parents
int rem = 0;
for (JSONObject g : decks) {
rem = (Integer) fn.invoke(Sched.this, g);
if (lim == -1) {
lim = rem;
} else {
lim = Math.min(rem, lim);
}
}
return lim;
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
/* New count for a single deck. */
public int _newForDeck(long did, int lim) {
if (lim == 0) {
return 0;
}
lim = Math.min(lim, mReportLimit);
return mCol.getDb().queryScalar("SELECT count() FROM (SELECT 1 FROM cards WHERE did = " + did + " AND queue = 0 LIMIT " + lim + ")", false);
}
/* Limit for deck without parent limits. */
public int _deckNewLimitSingle(JSONObject g) {
try {
if (g.getInt("dyn") != 0) {
return mReportLimit;
}
JSONObject c = mCol.getDecks().confForDid(g.getLong("id"));
return Math.max(0, c.getJSONObject("new").getInt("perDay") - g.getJSONArray("newToday").getInt(1));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public int totalNewForCurrentDeck() {
return mCol.getDb().queryScalar("SELECT count() FROM cards WHERE id IN (SELECT id FROM cards WHERE did IN " + Utils.ids2str(mCol.getDecks().active()) + " AND queue = 0 LIMIT " + mReportLimit + ")", false);
}
/**
* Learning queues *********************************************************** ************************************
*/
private void _resetLrnCount() {
mLrnCount = _cntFnLrn(_deckLimit());
// day
mLrnCount += (int) mCol.getDb().queryScalar(
"SELECT count() FROM cards WHERE did IN " + _deckLimit() + " AND queue = 3 AND due <= " + mToday
+ " LIMIT " + mReportLimit, false);
}
private int _cntFnLrn(String dids) {
return (int) mCol.getDb().queryScalar(
"SELECT sum(left / 1000) FROM (SELECT left FROM cards WHERE did IN " + dids
+ " AND queue = 1 AND due < " + mDayCutoff + " LIMIT " + mReportLimit + ")", false);
}
private void _resetLrn() {
_resetLrnCount();
mLrnQueue.clear();
mLrnDayQueue.clear();
mLrnDids = mCol.getDecks().active();
}
// sub-day learning
private boolean _fillLrn() {
if (mLrnCount == 0) {
return false;
}
if (!mLrnQueue.isEmpty()) {
return true;
}
Cursor cur = null;
mLrnQueue.clear();
try {