forked from nicolas-raoul/Anki-Android
/
Reviewer.java
3285 lines (2855 loc) · 123 KB
/
Reviewer.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 Kostas Spyropoulos <inigo.aldana@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public 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 Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
// TODO: implement own menu? http://www.codeproject.com/Articles/173121/Android-Menus-My-Way
package com.ichi2.anki;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.ClipboardManager;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ichi2.anim.ActivityTransitionAnimation;
import com.ichi2.anim.Animation3D;
import com.ichi2.anim.ViewAnimation;
import com.ichi2.anki.receiver.SdCardReceiver;
import com.ichi2.async.DeckTask;
import com.ichi2.libanki.Card;
import com.ichi2.libanki.Collection;
import com.ichi2.libanki.Models;
import com.ichi2.libanki.Note;
import com.ichi2.libanki.Sched;
import com.ichi2.libanki.Sound;
import com.ichi2.libanki.Utils;
import com.ichi2.themes.HtmlColors;
import com.ichi2.themes.StyledDialog;
import com.ichi2.themes.StyledOpenCollectionDialog;
import com.ichi2.themes.StyledProgressDialog;
import com.ichi2.themes.Themes;
import com.ichi2.utils.DiffEngine;
import com.ichi2.widget.WidgetStatus;
import org.amr.arabic.ArabicUtilities;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Reviewer extends AnkiActivity {
/**
* Result codes that are returned when this activity finishes.
*/
public static final int RESULT_DEFAULT = 50;
public static final int RESULT_SESSION_COMPLETED = 51;
public static final int RESULT_NO_MORE_CARDS = 52;
public static final int RESULT_EDIT_CARD_RESET = 53;
public static final int RESULT_DECK_CLOSED = 55;
/**
* Available options performed by other activities.
*/
public static final int EDIT_CURRENT_CARD = 0;
/** Constant for class attribute signaling answer */
public static final String ANSWER_CLASS = "answer";
/** Constant for class attribute signaling question */
public static final String QUESTION_CLASS = "question";
/** Max size of the font for dynamic calculation of font size */
private static final int DYNAMIC_FONT_MAX_SIZE = 14;
/** Min size of the font for dynamic calculation of font size */
private static final int DYNAMIC_FONT_MIN_SIZE = 3;
private static final int DYNAMIC_FONT_FACTOR = 5;
/**
* Menus
*/
private static final int MENU_WHITEBOARD = 0;
private static final int MENU_CLEAR_WHITEBOARD = 1;
private static final int MENU_EDIT = 2;
private static final int MENU_REMOVE = 3;
private static final int MENU_REMOVE_BURY = 31;
private static final int MENU_REMOVE_SUSPEND_CARD = 32;
private static final int MENU_REMOVE_SUSPEND_NOTE = 33;
private static final int MENU_REMOVE_DELETE = 34;
private static final int MENU_SEARCH = 4;
private static final int MENU_MARK = 5;
private static final int MENU_UNDO = 6;
public static final int EASE_FAILED = 1;
public static final int EASE_HARD = 2;
public static final int EASE_MID = 3;
public static final int EASE_EASY = 4;
/** Regex pattern used in removing tags from text before diff */
private static final Pattern sSpanPattern = Pattern.compile("</?span[^>]*>");
private static final Pattern sBrPattern = Pattern.compile("<br\\s?/?>");
// Type answer pattern
private static final Pattern sTypeAnsPat = Pattern.compile("\\[\\[type:(.+?)\\]\\]");
/** to be sento to and from the card editor */
private static Card sEditorCard;
private static boolean sDisplayAnswer = false;
/** The percentage of the absolute font size specified in the deck. */
private int mDisplayFontSize = 100;
/** Pattern for font-size style declarations */
private static final Pattern fFontSizePattern = Pattern.compile(
"font-size\\s*:\\s*([0-9.]+)\\s*((?:px|pt|in|cm|mm|pc|%|em))\\s*;?", Pattern.CASE_INSENSITIVE);
/** Pattern for opening/closing span/div tags */
private static final Pattern fSpanDivPattern = Pattern.compile(
"<(/?)(span|div)", Pattern.CASE_INSENSITIVE);
/** The relative CSS measurement units for pattern search */
private static final Set<String> fRelativeCssUnits = new HashSet<String>(
Arrays.asList(new String[]{ "%", "em" }));
/**
* Broadcast that informs us when the sd card is about to be unmounted
*/
private BroadcastReceiver mUnmountReceiver = null;
private boolean mInBackground = false;
/**
* Variables to hold preferences
*/
private boolean mPrefOvertime;
private boolean mPrefHideDueCount;
private boolean mPrefTimer;
private boolean mPrefWhiteboard;
private boolean mPrefWriteAnswers;
private boolean mPrefTextSelection;
private boolean mInputWorkaround;
private boolean mLongClickWorkaround;
private boolean mPrefFullscreenReview;
private boolean mshowNextReviewTime;
private boolean mZoomEnabled;
private String mCollectionFilename;
private int mRelativeButtonSize;
private boolean mDoubleScrolling;
private boolean mScrollingButtons;
private boolean mGesturesEnabled;
private boolean mShakeEnabled = false;
private int mShakeIntensity;
private boolean mShakeActionStarted = false;
private boolean mPrefFixArabic;
// Android WebView
private boolean mSpeakText;
private boolean mPlaySoundsAtStart;
private boolean mInvertedColors = false;
private int mCurrentBackgroundColor;
private boolean mBlackWhiteboard = true;
private boolean mNightMode = false;
private boolean mShowProgressBars;
private boolean mPrefFadeScrollbars;
private boolean mPrefUseTimer;
private boolean mShowAnimations = false;
private boolean mSimpleInterface = false;
private boolean mCurrentSimpleInterface = false;
private ArrayList<String> mSimpleInterfaceExcludeTags;
private int mAvailableInCardWidth;
// Answer card & cloze deletion variables
/** The correct answer in the compare to field if answer should be given by learner.
* Null if no answer is expected. */
private String mTypeCorrect;
/** The font name attribute of the type answer field for formatting */
private String mTypeFont;
/** The font size attribute of the type answer field for formatting */
private int mTypeSize;
private String mTypeWarning;
private boolean mIsSelecting = false;
private boolean mTouchStarted = false;
private boolean mInAnswer = false;
private String mCardTemplate;
/**
* Variables to hold layout objects that we need to update or handle events for
*/
private View mMainLayout;
private View mLookUpIcon;
private FrameLayout mCardContainer;
private WebView mCard;
private TextView mSimpleCard;
private WebView mNextCard;
private FrameLayout mCardFrame;
private FrameLayout mTouchLayer;
private TextView mTextBarRed;
private TextView mTextBarBlack;
private TextView mTextBarBlue;
private TextView mChosenAnswer;
private LinearLayout mProgressBars;
private View mSessionProgressTotalBar;
private View mSessionProgressBar;
private TextView mNext1;
private TextView mNext2;
private TextView mNext3;
private TextView mNext4;
private Button mFlipCard;
private EditText mAnswerField;
private Button mEase1;
private Button mEase2;
private Button mEase3;
private Button mEase4;
private LinearLayout mFlipCardLayout;
private LinearLayout mEase1Layout;
private LinearLayout mEase2Layout;
private LinearLayout mEase3Layout;
private LinearLayout mEase4Layout;
private Chronometer mCardTimer;
private Whiteboard mWhiteboard;
private ClipboardManager mClipboard;
private StyledProgressDialog mProgressDialog;
private StyledOpenCollectionDialog mOpenCollectionDialog;
private Bundle mSavedInstanceState;
private Menu mOptionsMenu;
private ProgressBar mProgressBar;
private Card mCurrentCard;
private int mCurrentEase;
private long mSessionTimeLimit;
private int mSessionCurrReps;
private boolean mShowWhiteboard = false;
private int mNextTimeTextColor;
private int mNextTimeTextRecomColor;
private int mForegroundColor;
private boolean mChangeBorderStyle;
private int mButtonHeight = 0;
private boolean mConfigurationChanged = false;
private int mShowChosenAnswerLength = 2000;
private int mStatisticBarsMax;
private int mStatisticBarsHeight;
private long mSavedTimer = 0;
private boolean mRefreshWebview = false;
private Map<String, AnkiFont> mCustomFonts;
private String mCustomDefaultFontCss;
private String mCustomFontStyle;
/**
* Shake Detection
*/
private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity
/**
* Swipe Detection
*/
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
private boolean mIsXScrolling = false;
private boolean mIsYScrolling = false;
/**
* Gesture Allocation
*/
private int mGestureSwipeUp;
private int mGestureSwipeDown;
private int mGestureSwipeLeft;
private int mGestureSwipeRight;
private int mGestureShake;
private int mGestureDoubleTap;
private int mGestureTapLeft;
private int mGestureTapRight;
private int mGestureTapTop;
private int mGestureTapBottom;
private int mGestureLongclick;
private static final int GESTURE_NOTHING = 0;
private static final int GESTURE_SHOW_ANSWER = 1;
private static final int GESTURE_ANSWER_EASE1 = 2;
private static final int GESTURE_ANSWER_EASE2 = 3;
private static final int GESTURE_ANSWER_EASE3 = 4;
private static final int GESTURE_ANSWER_EASE4 = 5;
private static final int GESTURE_ANSWER_RECOMMENDED = 6;
private static final int GESTURE_ANSWER_BETTER_THAN_RECOMMENDED = 7;
private static final int GESTURE_UNDO = 8;
private static final int GESTURE_EDIT = 9;
private static final int GESTURE_MARK = 10;
private static final int GESTURE_LOOKUP = 11;
private static final int GESTURE_BURY = 12;
private static final int GESTURE_SUSPEND = 13;
private static final int GESTURE_DELETE = 14;
private static final int GESTURE_CLEAR_WHITEBOARD = 15;
private static final int GESTURE_PLAY_MEDIA = 16;
private static final int GESTURE_EXIT = 17;
private Spanned mCardContent;
private String mBaseUrl;
private static final int ANIMATION_NO_ANIMATION = 0;
private static final int ANIMATION_TURN = 1;
private static final int ANIMATION_NEXT_CARD_FROM_RIGHT = 2;
private static final int ANIMATION_NEXT_CARD_FROM_LEFT = 3;
private static final int ANIMATION_SLIDE_OUT_TO_LEFT = 4;
private static final int ANIMATION_SLIDE_OUT_TO_RIGHT = 5;
private static final int ANIMATION_SLIDE_IN_FROM_RIGHT = 6;
private static final int ANIMATION_SLIDE_IN_FROM_LEFT = 7;
private int mNextAnimation = 0;
private int mAnimationDurationTurn = 500;
private int mAnimationDurationMove = 500;
private int mFadeDuration = 300;
private Method mSetTextIsSelectable = null;
private Sched mSched;
// private int zEase;
// ----------------------------------------------------------------------------
// LISTENERS
// ----------------------------------------------------------------------------
/**
* From http://stackoverflow.com/questions/2317428/android-i-want-to-shake-it Thilo Koehler
*/
private final SensorEventListener mSensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2] / 2;
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (!mShakeActionStarted && mAccel >= (mShakeIntensity / 10)) {
mShakeActionStarted = true;
executeCommand(mGestureShake);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Sound.stopSounds();
Sound.playSound((String) msg.obj, null);
}
};
private final Handler longClickHandler = new Handler();
private final Runnable longClickTestRunnable = new Runnable() {
public void run() {
Log.i(AnkiDroidApp.TAG, "onEmulatedLongClick");
Vibrator vibratorManager = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibratorManager.vibrate(50);
longClickHandler.postDelayed(startLongClickAction, 300);
}
};
private final Runnable startLongClickAction = new Runnable() {
public void run() {
executeCommand(mGestureLongclick);
}
};
private View.OnClickListener mCardStatisticsListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i(AnkiDroidApp.TAG, "Show card statistics");
stopTimer();
// Themes.htmlOkDialog(Reviewer.this, getResources().getString(R.string.card_browser_card_details),
// mCurrentCard.getCardDetails(Reviewer.this, false), new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// restartTimer();
// }
// }, new OnCancelListener() {
// @Override
// public void onCancel(DialogInterface arg0) {
// restartTimer();
// }
// }).show();
}
};
// Handler for the "show answer" button
private View.OnClickListener mFlipCardListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i(AnkiDroidApp.TAG, "Flip card changed:");
mTimeoutHandler.removeCallbacks(mShowAnswerTask);
displayCardAnswer();
}
};
private View.OnClickListener mSelectEaseHandler = new View.OnClickListener() {
@Override
public void onClick(View view) {
mTimeoutHandler.removeCallbacks(mShowQuestionTask);
switch (view.getId()) {
case R.id.flashcard_layout_ease1:
answerCard(EASE_FAILED);
break;
case R.id.flashcard_layout_ease2:
answerCard(EASE_HARD);
break;
case R.id.flashcard_layout_ease3:
answerCard(EASE_MID);
break;
case R.id.flashcard_layout_ease4:
answerCard(EASE_EASY);
break;
default:
mCurrentEase = 0;
return;
}
}
};
private View.OnTouchListener mGestureListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
if (mPrefTextSelection && !mLongClickWorkaround) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTouchStarted = true;
longClickHandler.postDelayed(longClickTestRunnable, 800);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
if (mTouchStarted) {
longClickHandler.removeCallbacks(longClickTestRunnable);
mTouchStarted = false;
}
break;
}
}
try {
if (event != null) {
if (mCurrentSimpleInterface) {
mSimpleCard.dispatchTouchEvent(event);
} else {
mCard.dispatchTouchEvent(event);
}
}
} catch (NullPointerException e) {
Log.e(AnkiDroidApp.TAG, "Error on dispatching touch event: " + e);
if (mInputWorkaround) {
Log.e(AnkiDroidApp.TAG, "Error on using InputWorkaround: " + e + " --> disabled");
AnkiDroidApp.getSharedPrefs(getBaseContext()).edit().putBoolean("inputWorkaround", false).commit();
Reviewer.this.finishWithoutAnimation();
}
}
return false;
}
};
private View.OnLongClickListener mLongClickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mIsSelecting) {
return false;
}
Log.i(AnkiDroidApp.TAG, "onLongClick");
Vibrator vibratorManager = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibratorManager.vibrate(50);
longClickHandler.postDelayed(startLongClickAction, 300);
return true;
}
};
private DeckTask.TaskListener mMarkCardHandler = new DeckTask.TaskListener() {
@Override
public void onPreExecute() {
Resources res = getResources();
mProgressDialog = StyledProgressDialog
.show(Reviewer.this, "", res.getString(R.string.saving_changes), true);
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
updateMenuItems();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (!result.getBoolean()) {
// RuntimeException occured on marking cards
closeReviewer(DeckPicker.RESULT_DB_ERROR, true);
}
}
};
private DeckTask.TaskListener mDismissCardHandler = new DeckTask.TaskListener() {
@Override
public void onPreExecute() {
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
mAnswerCardHandler.onProgressUpdate(values);
}
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (!result.getBoolean()) {
closeReviewer(DeckPicker.RESULT_DB_ERROR, false);
}
mAnswerCardHandler.onPostExecute(result);
}
};
private DeckTask.TaskListener mUpdateCardHandler = new DeckTask.TaskListener() {
private boolean mNoMoreCards;
@Override
public void onPreExecute() {
Resources res = getResources();
try {
mProgressDialog = StyledProgressDialog.show(Reviewer.this, "", res.getString(R.string.saving_changes),
true);
} catch (IllegalArgumentException e) {
Log.e(AnkiDroidApp.TAG, "Reviewer: Error on showing progress dialog: " + e);
}
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
mCurrentCard = values[0].getCard();
if (mCurrentCard == null) {
// If the card is null means that there are no more cards scheduled for review.
mNoMoreCards = true;
mProgressDialog = StyledProgressDialog.show(Reviewer.this, "",
getResources().getString(R.string.saving_changes), true);
setOutAnimation(false);
return;
}
if (mPrefWhiteboard) {
mWhiteboard.clear();
}
if (mPrefTimer) {
mCardTimer.setBase(SystemClock.elapsedRealtime());
mCardTimer.start();
}
if (sDisplayAnswer) {
displayCardAnswer();
} else {
displayCardQuestion();
}
try {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
} catch (IllegalArgumentException e) {
Log.e(AnkiDroidApp.TAG, "Reviewer: Error on dismissing progress dialog: " + e);
mProgressDialog = null;
}
}
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (!result.getBoolean()) {
// RuntimeException occured on update cards
closeReviewer(DeckPicker.RESULT_DB_ERROR, false);
return;
}
if (mNoMoreCards) {
closeReviewer(RESULT_NO_MORE_CARDS, true);
}
mShakeActionStarted = false;
}
};
private DeckTask.TaskListener mAnswerCardHandler = new DeckTask.TaskListener() {
private boolean mSessionComplete;
private boolean mNoMoreCards;
@Override
public void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
if (mPrefTimer) {
mCardTimer.stop();
}
blockControls();
}
@Override
public void onProgressUpdate(DeckTask.TaskData... values) {
Resources res = getResources();
// if in background, actualise widget
// if (mInBackground) {
// updateBigWidget(false);
// }
if (mSched == null) {
// TODO: proper testing for restored activity
finish();
return;
}
int leech = values[0].getInt();
// 0: normal; 1: leech; 2: leech & suspended
if (leech > 0) {
String leechMessage;
if (leech == 2) {
leechMessage = res.getString(R.string.leech_suspend_notification);
} else {
leechMessage = res.getString(R.string.leech_notification);
}
Themes.showThemedToast(Reviewer.this, leechMessage, true);
}
// // TODO: sessionLimithandling
// long sessionRepLimit = 100;//deck.getSessionRepLimit();
// long sessionTime = 1000;//deck.getSessionTimeLimit();
String sessionMessage = null;
// if ((sessionRepLimit > 0) && (mSessionCurrReps >= sessionRepLimit)) {
// sessionComplete = true;
// sessionMessage = res.getString(R.string.session_question_limit_reached);
// } else if ((sessionTime > 0) && (System.currentTimeMillis() >= mSessionTimeLimit)) {
// // session time limit reached, flag for halt once async task has completed.
// sessionComplete = true;
// sessionMessage = res.getString(R.string.session_time_limit_reached);
// } else if (mIsLastCard) {
// noMoreCards = true;
// mProgressDialog = StyledProgressDialog.show(Reviewer.this, "", getResources()
// .getString(R.string.saving_changes), true);
// setOutAnimation(true);
// } else {
// session limits not reached, show next card
mCurrentCard = values[0].getCard();
boolean timebox_reached = AnkiDroidApp.getCol().timeboxReached() != null ? true : false;
if (timebox_reached && mPrefOvertime && !AnkiDroidApp.getCol().getOvertime()) {
AnkiDroidApp.getCol().setOvertime(true);
}
//String timebox_message = "Timebox finished!";
if (mCurrentCard == null) {
// If the card is null means that there are no more cards scheduled for review.
mNoMoreCards = true;
mProgressDialog = StyledProgressDialog.show(Reviewer.this, "",
getResources().getString(R.string.saving_changes), true);
setOutAnimation(false);
} else if (timebox_reached && !mPrefOvertime) {
//SharedPreferences preferences = PrefSettings.getSharedPrefs(getActivity().getBaseContext()); //getActivity().getBaseContext()
//boolean overtime = preferences.getBoolean("overtime", true);
mSessionComplete = true;
mProgressDialog = StyledProgressDialog.show(Reviewer.this, "",
getResources().getString(R.string.saving_changes), true);
setOutAnimation(false);
sessionMessage = getResources().getString(R.string.timebox_reached);
} else {
if (timebox_reached) {
sessionMessage = getResources().getString(R.string.timebox_reached);
}
// Start reviewing next card
if (mPrefWriteAnswers) {
// only bother query deck if needed
updateTypeAnswerInfo();
} else {
mTypeCorrect = null;
}
mProgressBar.setVisibility(View.INVISIBLE);
Reviewer.this.unblockControls();
Reviewer.this.displayCardQuestion();
}
// if (mChosenAnswer.getText().equals("")) {
// setDueMessage();
// }
// Show a message to user if a session limit has been reached.
if (sessionMessage != null) {
Themes.showThemedToast(Reviewer.this, sessionMessage, true);
}
}
@Override
public void onPostExecute(DeckTask.TaskData result) {
if (!result.getBoolean()) {
// RuntimeException occured on answering cards
closeReviewer(DeckPicker.RESULT_DB_ERROR, false);
return;
}
// Check for no more cards before session complete. If they are both true, no more cards will take
// precedence when returning to study options.
if (mNoMoreCards) {
closeReviewer(RESULT_NO_MORE_CARDS, true);
} else if (mSessionComplete) {
closeReviewer(RESULT_SESSION_COMPLETED, true);
}
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
};
/**
* Extract type answer/cloze text and font/size
*/
private void updateTypeAnswerInfo() {
mTypeCorrect = null;
String q = mCurrentCard.getQuestion(false);
Matcher m = sTypeAnsPat.matcher(q);
int clozeIdx = 0;
if (!m.find()) {
return;
}
String fld = m.group(1);
// if it's a cloze, extract data
if (fld.startsWith("cloze:", 0)) {
// get field and cloze position
clozeIdx = mCurrentCard.getOrd() + 1;
fld = fld.split(":")[1];
}
// loop through fields for a match
try {
JSONArray ja = mCurrentCard.model().getJSONArray("flds");
for (int i = 0; i < ja.length(); i++) {
String name = (String) (ja.getJSONObject(i).get("name"));
if (name.equals(fld)) {
mTypeCorrect = mCurrentCard.note().getitem(name);
if (clozeIdx != 0) {
// narrow to cloze
mTypeCorrect = contentForCloze(mTypeCorrect, clozeIdx);
}
mTypeFont = (String) (ja.getJSONObject(i).get("font"));
mTypeSize = (Integer) (ja.getJSONObject(i).get("size"));
break;
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
if (mTypeCorrect == null) {
if (clozeIdx != 0) {
mTypeWarning = "Please run Tools>Maintenance>Empty Cards";
} else {
mTypeWarning = "Type answer: unknown field " + fld;
}
} else if (mTypeCorrect.equals("")) {
mTypeCorrect = null;
} else {
mTypeWarning = null;
}
}
/**
* Format question field when it contains typeAnswer or clozes.
* If there was an error during type text extraction, a warning is displayed
* @param buf The question text
* @return The formatted question text
*/
private String typeAnsQuestionFilter(String buf) {
Matcher m = sTypeAnsPat.matcher(buf);
if (mTypeWarning != null) {
return m.replaceFirst(mTypeWarning);
}
return m.replaceFirst("");
}
/**
* Format answer field when it contains typeAnswer or clozes
* @param buf The answer text
* @return The formatted answer text
*/
private String typeAnsAnswerFilter(String buf) {
Matcher m = sTypeAnsPat.matcher(buf);
return m.replaceFirst("");
}
private String contentForCloze(String txt, int idx) {
Pattern re = Pattern.compile("\\{\\{c" + idx + "::(.+?)\\}\\}");
Matcher m = re.matcher(txt);
if (!m.find()) {
return null;
}
String result = m.group(1);
while (m.find()) {
result += ", " + m.group(1);
}
return result;
}
private Handler mTimerHandler = new Handler();
private Runnable removeChosenAnswerText = new Runnable() {
public void run() {
mChosenAnswer.setText("");
setDueMessage();
}
};
private int mWaitAnswerSecond;
private int mWaitQuestionSecond;
// ----------------------------------------------------------------------------
// ANDROID METHODS
// ----------------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
Themes.applyTheme(this);
super.onCreate(savedInstanceState);
Log.i(AnkiDroidApp.TAG, "Reviewer - onCreate");
mChangeBorderStyle = Themes.getTheme() == Themes.THEME_ANDROID_LIGHT
|| Themes.getTheme() == Themes.THEME_ANDROID_DARK;
// The hardware buttons should control the music volume while reviewing.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
Collection col = AnkiDroidApp.getCol();
if (col == null) {
reloadCollection(savedInstanceState);
return;
} else {
mSched = col.getSched();
mCollectionFilename = col.getPath();
mBaseUrl = Utils.getBaseUrl(col.getMedia().getDir());
restorePreferences();
try {
String[] title = mSched.getCol().getDecks().current().getString("name").split("::");
setTitle(title[title.length - 1]);
} catch (JSONException e) {
throw new RuntimeException(e);
}
UIUtils.setActionBarSubtitle(this, "");
// Remove the status bar and title bar
if (mPrefFullscreenReview) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Do not hide the title bar in Honeycomb, since it contains the action bar.
if (AnkiDroidApp.SDK_VERSION <= 11) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
registerExternalStorageListener();
if (mNightMode) {
mCurrentBackgroundColor = Themes.getNightModeCardBackground(this);
} else {
mCurrentBackgroundColor = Color.WHITE;
}
mRefreshWebview = getRefreshWebviewAndInitializeWebviewVariables();
initLayout(R.layout.flashcard);
if (mPrefTextSelection) {
clipboardSetText("");
Lookup.initialize(this, mCollectionFilename);
}
// Load the template for the card
try {
mCardTemplate = Utils.convertStreamToString(getAssets().open("card_template.html"));
} catch (IOException e) {
e.printStackTrace();
}
// Initialize session limits
// long timelimit = deck.getSessionTimeLimit() * 1000;
// Log.i(AnkiDroidApp.TAG, "SessionTimeLimit: " + timelimit + " ms.");
// mSessionTimeLimit = System.currentTimeMillis() + timelimit;
mSessionCurrReps = 0;
// Initialize text-to-speech. This is an asynchronous operation.
if (mSpeakText) {
ReadText.initializeTts(this, mCollectionFilename);
}
// Get last whiteboard state
if (mPrefWhiteboard && MetaDB.getWhiteboardState(this, mCollectionFilename) == 1) {
mShowWhiteboard = true;
mWhiteboard.setVisibility(View.VISIBLE);
}
// Load the first card and start reviewing. Uses the answer card
// task to load a card, but since we send null
// as the card to answer, no card will be answered.
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ANSWER_CARD, mAnswerCardHandler, new DeckTask.TaskData(mSched,
null, 0));
}
}