-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
AbstractFlashcardViewer.kt
2661 lines (2431 loc) · 107 KB
/
AbstractFlashcardViewer.kt
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> *
* Copyright (c) 2014 Bruno Romero de Azevedo <brunodea@inf.ufsm.br> *
* Copyright (c) 2014–15 Roland Sieker <ospalh@gmail.com> *
* Copyright (c) 2015 Timothy Rae <perceptualchaos2@gmail.com> *
* Copyright (c) 2016 Mark Carter <mark@marcardar.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.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.*
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.media.MediaPlayer
import android.net.Uri
import android.os.*
import android.text.TextUtils
import android.view.*
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.View.OnTouchListener
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.webkit.*
import android.webkit.WebView.HitTestResult
import android.widget.*
import androidx.annotation.CheckResult
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.core.view.isVisible
import androidx.webkit.WebViewAssetLoader
import anki.collection.OpChanges
import com.afollestad.materialdialogs.MaterialDialog
import com.drakeet.drawer.FullDraggableContainer
import com.google.android.material.snackbar.Snackbar
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anim.ActivityTransitionAnimation.getInverseTransition
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.UIUtils.showThemedToast
import com.ichi2.anki.cardviewer.*
import com.ichi2.anki.cardviewer.CardHtml.Companion.legacyGetTtsTags
import com.ichi2.anki.cardviewer.HtmlGenerator.Companion.createInstance
import com.ichi2.anki.cardviewer.SoundPlayer.CardSoundConfig
import com.ichi2.anki.cardviewer.SoundPlayer.CardSoundConfig.Companion.create
import com.ichi2.anki.cardviewer.TypeAnswer.Companion.createInstance
import com.ichi2.anki.dialogs.tags.TagsDialog
import com.ichi2.anki.dialogs.tags.TagsDialogFactory
import com.ichi2.anki.dialogs.tags.TagsDialogListener
import com.ichi2.anki.receiver.SdCardReceiver
import com.ichi2.anki.reviewer.*
import com.ichi2.anki.reviewer.AutomaticAnswer.AutomaticallyAnswered
import com.ichi2.anki.reviewer.FullScreenMode.Companion.DEFAULT
import com.ichi2.anki.reviewer.FullScreenMode.Companion.fromPreference
import com.ichi2.anki.reviewer.ReviewerUi.ControlBlock
import com.ichi2.anki.servicelayer.AnkiMethod
import com.ichi2.anki.servicelayer.LanguageHintService.applyLanguageHint
import com.ichi2.anki.servicelayer.NoteService.isMarked
import com.ichi2.anki.servicelayer.SchedulerService.*
import com.ichi2.anki.servicelayer.TaskListenerBuilder
import com.ichi2.anki.servicelayer.UndoService.Undo
import com.ichi2.anki.snackbar.SnackbarBuilder
import com.ichi2.anki.snackbar.showSnackbar
import com.ichi2.annotations.NeedsTest
import com.ichi2.async.TaskListener
import com.ichi2.async.updateCard
import com.ichi2.compat.CompatHelper.Companion.compat
import com.ichi2.libanki.*
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Consts.BUTTON_TYPE
import com.ichi2.libanki.Sound.SoundSide
import com.ichi2.libanki.sched.AbstractSched
import com.ichi2.libanki.sched.SchedV2
import com.ichi2.themes.Themes
import com.ichi2.themes.Themes.getResFromAttr
import com.ichi2.ui.FixedEditText
import com.ichi2.utils.AdaptionUtil.hasWebBrowser
import com.ichi2.utils.AndroidUiUtils.isRunningOnTv
import com.ichi2.utils.AssetHelper.guessMimeType
import com.ichi2.utils.BlocksSchemaUpgrade
import com.ichi2.utils.ClipboardUtil.getText
import com.ichi2.utils.Computation
import com.ichi2.utils.HandlerUtils.executeFunctionWithDelay
import com.ichi2.utils.HandlerUtils.newHandler
import com.ichi2.utils.HashUtil.HashSetInit
import com.ichi2.utils.KotlinCleanup
import com.ichi2.utils.WebViewDebugging.initializeDebugging
import com.ichi2.utils.iconAttr
import kotlinx.coroutines.Job
import net.ankiweb.rsdroid.BackendFactory
import net.ankiweb.rsdroid.RustCleanup
import timber.log.Timber
import java.io.*
import java.lang.ref.WeakReference
import java.net.URLDecoder
import java.util.*
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.function.Consumer
import java.util.function.Function
import java.util.function.Supplier
import kotlin.math.abs
@KotlinCleanup("lots to deal with")
abstract class AbstractFlashcardViewer :
NavigationDrawerActivity(),
ReviewerUi,
ViewerCommand.CommandProcessor,
TagsDialogListener,
WhiteboardMultiTouchMethods,
AutomaticallyAnswered,
OnPageFinishedCallback,
ChangeManager.Subscriber {
private var mTtsInitialized = false
private var mReplayOnTtsInit = false
private var mAnkiDroidJsAPI: AnkiDroidJsAPI? = null
/**
* Broadcast that informs us when the sd card is about to be unmounted
*/
private var mUnmountReceiver: BroadcastReceiver? = null
private var mTagsDialogFactory: TagsDialogFactory? = null
/**
* Variables to hold preferences
*/
@KotlinCleanup("internal for AnkiDroidJsApi")
internal var prefShowTopbar = false
protected var fullscreenMode = DEFAULT
private set
private var mRelativeButtonSize = 0
private var mDoubleScrolling = false
private var mScrollingButtons = false
private var mGesturesEnabled = false
private var mLargeAnswerButtons = false
private var mAnswerButtonsPosition: String? = "bottom"
private var mDoubleTapTimeInterval = DEFAULT_DOUBLE_TAP_TIME_INTERVAL
// Android WebView
var automaticAnswer = AutomaticAnswer.defaultInstance(this)
protected var typeAnswer: TypeAnswer? = null
/** Generates HTML content */
private var mHtmlGenerator: HtmlGenerator? = null
// Default short animation duration, provided by Android framework
private var shortAnimDuration = 0
private var mBackButtonPressedToReturn = false
// Preferences from the collection
private var mShowNextReviewTime = false
private var mIsSelecting = false
private var mTouchStarted = false
private var mInAnswer = false
private var mAnswerSoundsAdded = false
/**
* Variables to hold layout objects that we need to update or handle events for
*/
var webView: WebView? = null
private set
private var mCardFrame: FrameLayout? = null
private var mTouchLayer: FrameLayout? = null
protected var answerField: FixedEditText? = null
protected var flipCardLayout: LinearLayout? = null
protected var easeButtonsLayout: LinearLayout? = null
@KotlinCleanup("internal for AnkiDroidJsApi")
internal var easeButton1: EaseButton? = null
@KotlinCleanup("internal for AnkiDroidJsApi")
internal var easeButton2: EaseButton? = null
@KotlinCleanup("internal for AnkiDroidJsApi")
internal var easeButton3: EaseButton? = null
@KotlinCleanup("internal for AnkiDroidJsApi")
internal var easeButton4: EaseButton? = null
protected var topBarLayout: RelativeLayout? = null
private val mClipboard: ClipboardManager? = null
private var mPreviousAnswerIndicator: PreviousAnswerIndicator? = null
/** set when [currentCard] is */
private var mCardSoundConfig: CardSoundConfig? = null
private var mCurrentEase = 0
private var mInitialFlipCardHeight = 0
private var mButtonHeightSet = false
/**
* A record of the last time the "show answer" or ease buttons were pressed. We keep track
* of this time to ignore accidental button presses.
*/
@VisibleForTesting
protected var lastClickTime: Long = 0
/**
* Swipe Detection
*/
var gestureDetector: GestureDetector? = null
private set
private lateinit var mGestureDetectorImpl: MyGestureDetector
private var mIsXScrolling = false
private var mIsYScrolling = false
/**
* Gesture Allocation
*/
protected val mGestureProcessor = GestureProcessor(this)
@get:VisibleForTesting
var cardContent: String? = null
private set
private var mBaseUrl: String? = null
private var mViewerUrl: String? = null
private var mAssetLoader: WebViewAssetLoader? = null
private val mFadeDuration = 300
@KotlinCleanup("made internal for tests")
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal var sched: AbstractSched? = null
protected val mSoundPlayer = Sound()
/**
* Time taken to play all medias in mSoundPlayer
* This is 0 if we have "Read card" enabled, as we can't calculate the duration.
*/
private var mUseTimerDynamicMS: Long = 0
/** Reference to the parent of the cardFrame to allow regeneration of the cardFrame in case of crash */
private var mCardFrameParent: ViewGroup? = null
/** Lock to allow thread-safe regeneration of mCard */
private val mCardLock: ReadWriteLock = ReentrantReadWriteLock()
/** whether controls are currently blocked, and how long we expect them to be */
override var controlBlocked = ControlBlock.SLOW
/** Preference: Whether the user wants press back twice to return to the main screen" */
private var mExitViaDoubleTapBack = false
@VisibleForTesting
val mOnRenderProcessGoneDelegate = OnRenderProcessGoneDelegate(this)
protected val mTTS = TTS()
// ----------------------------------------------------------------------------
// LISTENERS
// ----------------------------------------------------------------------------
private val mLongClickHandler = newHandler()
private val mLongClickTestRunnable = Runnable {
Timber.i("AbstractFlashcardViewer:: onEmulatedLongClick")
compat.vibrate(AnkiDroidApp.instance.applicationContext, 50)
mLongClickHandler.postDelayed(mStartLongClickAction, 300)
}
private val mStartLongClickAction = Runnable { mGestureProcessor.onLongTap() }
// Handler for the "show answer" button
private val mFlipCardListener = View.OnClickListener {
Timber.i("AbstractFlashcardViewer:: Show answer button pressed")
// Ignore what is most likely an accidental double-tap.
if (elapsedRealTime - lastClickTime < mDoubleTapTimeInterval) {
return@OnClickListener
}
lastClickTime = elapsedRealTime
automaticAnswer.onShowAnswer()
displayCardAnswer()
}
init {
ChangeManager.subscribe(this)
}
// Event handler for eases (answer buttons)
inner class SelectEaseHandler : View.OnClickListener, OnTouchListener {
private var mPrevCard: Card? = null
private var mHasBeenTouched = false
private var mTouchX = 0f
private var mTouchY = 0f
override fun onTouch(view: View, event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
// Save states when button pressed
mPrevCard = currentCard
mHasBeenTouched = true
// We will need to check if a touch is followed by a click
// Since onTouch always come before onClick, we should check if
// the touch is going to be a click by storing the start coordinates
// and comparing with the end coordinates of the touch
mTouchX = event.rawX
mTouchY = event.rawY
} else if (event.action == MotionEvent.ACTION_UP) {
val diffX = abs(event.rawX - mTouchX)
val diffY = abs(event.rawY - mTouchY)
// If a click is not coming then we reset the touch
if (diffX > Companion.CLICK_ACTION_THRESHOLD || diffY > Companion.CLICK_ACTION_THRESHOLD) {
mHasBeenTouched = false
}
}
return false
}
override fun onClick(view: View) {
// Try to perform intended action only if the button has been pressed for current card,
// or if the button was not touched,
if (mPrevCard === currentCard || !mHasBeenTouched) {
// Only perform if the click was not an accidental double-tap
if (elapsedRealTime - lastClickTime >= mDoubleTapTimeInterval) {
// For whatever reason, performClick does not return a visual feedback anymore
if (!mHasBeenTouched) {
view.isPressed = true
}
lastClickTime = elapsedRealTime
automaticAnswer.onSelectEase()
when (view.id) {
R.id.flashcard_layout_ease1 -> {
Timber.i("AbstractFlashcardViewer:: EASE_1 pressed")
answerCard(Consts.BUTTON_ONE)
}
R.id.flashcard_layout_ease2 -> {
Timber.i("AbstractFlashcardViewer:: EASE_2 pressed")
answerCard(Consts.BUTTON_TWO)
}
R.id.flashcard_layout_ease3 -> {
Timber.i("AbstractFlashcardViewer:: EASE_3 pressed")
answerCard(Consts.BUTTON_THREE)
}
R.id.flashcard_layout_ease4 -> {
Timber.i("AbstractFlashcardViewer:: EASE_4 pressed")
answerCard(Consts.BUTTON_FOUR)
}
else -> mCurrentEase = 0
}
if (!mHasBeenTouched) {
view.isPressed = false
}
}
}
// We will have to reset the touch after every onClick event
// Do not return early without considering this
mHasBeenTouched = false
}
}
private val mEaseHandler = SelectEaseHandler()
@get:VisibleForTesting
protected open val elapsedRealTime: Long
get() = SystemClock.elapsedRealtime()
private val mGestureListener = OnTouchListener { _, event ->
if (gestureDetector!!.onTouchEvent(event)) {
return@OnTouchListener true
}
if (!mGestureDetectorImpl.eventCanBeSentToWebView(event)) {
return@OnTouchListener false
}
// Gesture listener is added before mCard is set
processCardAction { cardWebView: WebView? ->
if (cardWebView == null) return@processCardAction
cardWebView.dispatchTouchEvent(event)
}
false
}
// This is intentionally package-private as it removes the need for synthetic accessors
@SuppressLint("CheckResult")
fun processCardAction(cardConsumer: Consumer<WebView?>) {
processCardFunction { cardWebView: WebView? ->
cardConsumer.accept(cardWebView)
true
}
}
@CheckResult
private fun <T> processCardFunction(cardFunction: Function<WebView?, T>): T {
val readLock = mCardLock.readLock()
return try {
readLock.lock()
cardFunction.apply(webView)
} finally {
readLock.unlock()
}
}
suspend fun saveEditedCard() {
val updatedCard: Card = withProgress {
withCol {
updateCard(this, editorCard!!, true, canAccessScheduler())
}
}
onCardUpdated(updatedCard)
}
private fun onCardUpdated(result: Card) {
if (currentCard !== result) {
/*
* Before updating currentCard, we check whether it is changing or not. If the current card changes,
* then we need to display it as a new card, without showing the answer.
*/
displayAnswer = false
}
currentCard = result
launchCatchingTask {
withCol {
sched.counts() // Ensure counts are recomputed if necessary, to know queue to look for
sched.preloadNextCard()
}
}
if (currentCard == null) {
// If the card is null means that there are no more cards scheduled for review.
showProgressBar()
closeReviewer(RESULT_NO_MORE_CARDS, true)
}
onCardEdited(currentCard)
if (displayAnswer) {
mSoundPlayer.resetSounds() // load sounds from scratch, to expose any edit changes
mAnswerSoundsAdded = false // causes answer sounds to be reloaded
generateQuestionSoundList() // questions must be intentionally regenerated
displayCardAnswer()
} else {
displayCardQuestion()
}
hideProgressBar()
}
@KotlinCleanup("nullability")
/** Operation after a card has been updated due to being edited. Called before display[Question/Answer] */
protected open fun onCardEdited(card: Card?) {
// intentionally blank
}
/** Invoked by [CardViewerWebClient.onPageFinished] */
override fun onPageFinished() {
// intentionally blank
}
internal inner class NextCardHandler<Result : Computation<NextCard<*>>?> :
TaskListener<Unit, Result>() {
override fun onPreExecute() {
dealWithTimeBox()
}
@KotlinCleanup("remove _ variables")
private fun dealWithTimeBox() {
val res = resources
val elapsed = col.timeboxReached()
if (elapsed != null) {
val nCards = elapsed.second
val nMins = elapsed.first / 60
val mins = res.getQuantityString(R.plurals.in_minutes, nMins, nMins)
val timeboxMessage = res.getQuantityString(R.plurals.timebox_reached, nCards, nCards, mins)
MaterialDialog(this@AbstractFlashcardViewer).show {
title(R.string.timebox_reached_title)
message(text = timeboxMessage)
positiveButton(R.string.dialog_continue) {
col.startTimebox()
}
negativeButton(R.string.close) {
finishWithAnimation(ActivityTransitionAnimation.Direction.END)
}
cancelable(true)
setOnCancelListener { col.startTimebox() }
}
}
}
override fun onPostExecute(result: Result) {
if (sched == null) {
// TODO: proper testing for restored activity
finishWithoutAnimation()
return
}
val displaySuccess = result!!.succeeded()
if (!displaySuccess) {
// RuntimeException occurred on answering cards
closeReviewer(DeckPicker.RESULT_DB_ERROR, false)
return
}
val nextCardAndResult = result.value
if (nextCardAndResult.hasNoMoreCards()) {
closeReviewer(RESULT_NO_MORE_CARDS, true)
// When launched with a shortcut, we want to display a message when finishing
if (intent.getBooleanExtra(EXTRA_STARTED_WITH_SHORTCUT, false)) {
showThemedToast(baseContext, R.string.studyoptions_congrats_finished, false)
}
return
}
currentCard = nextCardAndResult.nextScheduledCard()
// Start reviewing next card
hideProgressBar()
unblockControls()
this@AbstractFlashcardViewer.displayCardQuestion()
// set the correct mark/unmark icon on action bar
refreshActionBar()
focusDefaultLayout()
}
}
private fun focusDefaultLayout() {
if (!isRunningOnTv(this)) {
findViewById<View>(R.id.root_layout).requestFocus()
} else {
val flip = findViewById<View>(R.id.answer_options_layout) ?: return
Timber.d("Requesting focus for flip button")
flip.requestFocus()
}
}
protected fun answerCardHandler(quick: Boolean): TaskListenerBuilder<Unit, Computation<NextCard<*>>?> {
return nextCardHandler<Computation<NextCard<*>>?>()
.alsoExecuteBefore { blockControls(quick) }
}
open val answerButtonCount: Int
get() = col.sched.answerButtons(currentCard!!)
// ----------------------------------------------------------------------------
// ANDROID METHODS
// ----------------------------------------------------------------------------
override fun onCreate(savedInstanceState: Bundle?) {
Timber.d("onCreate()")
restorePreferences()
mTagsDialogFactory = TagsDialogFactory(this).attachToActivity<TagsDialogFactory>(this)
super.onCreate(savedInstanceState)
setContentView(getContentViewAttr(fullscreenMode))
// Make ACTION_PROCESS_TEXT for in-app searching possible on > Android 4.0
delegate.isHandleNativeActionModesEnabled = true
val mainView = findViewById<View>(android.R.id.content)
initNavigationDrawer(mainView)
mPreviousAnswerIndicator = PreviousAnswerIndicator(findViewById(R.id.chosen_answer))
shortAnimDuration = resources.getInteger(android.R.integer.config_shortAnimTime)
mGestureDetectorImpl = LinkDetectingGestureDetector()
}
@KotlinCleanup("non-null")
protected open fun getContentViewAttr(fullscreenMode: FullScreenMode?): Int {
return R.layout.reviewer
}
@get:VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
val isFullscreen: Boolean
get() = !supportActionBar!!.isShowing
override fun onConfigurationChanged(newConfig: Configuration) {
// called when screen rotated, etc, since recreating the Webview is too expensive
super.onConfigurationChanged(newConfig)
refreshActionBar()
}
protected abstract fun setTitle()
// Finish initializing the activity after the collection has been correctly loaded
public override fun onCollectionLoaded(col: Collection) {
super.onCollectionLoaded(col)
sched = col.sched
val mediaDir = col.media.dir()
mBaseUrl = Utils.getBaseUrl(mediaDir)
mViewerUrl = mBaseUrl + "__viewer__.html"
mAssetLoader = WebViewAssetLoader.Builder()
.addPathHandler("/") { path: String ->
try {
val file = File(mediaDir, path)
val inputStream = FileInputStream(file)
val mimeType = guessMimeType(path)
val headers = HashMap<String, String>()
headers["Access-Control-Allow-Origin"] = "*"
val response = WebResourceResponse(mimeType, null, inputStream)
response.responseHeaders = headers
return@addPathHandler response
} catch (e: Exception) {
Timber.w(e, "Error trying to open path in asset loader")
}
null
}
.build()
registerExternalStorageListener()
restoreCollectionPreferences(col)
initLayout()
setTitle()
mHtmlGenerator = createInstance(this, typeAnswer!!, mBaseUrl!!)
// Initialize text-to-speech. This is an asynchronous operation.
mTTS.initialize(this, ReadTextListener())
updateActionBar()
invalidateOptionsMenu()
}
// Saves deck each time Reviewer activity loses focus
override fun onPause() {
super.onPause()
Timber.d("onPause()")
automaticAnswer.disable()
mLongClickHandler.removeCallbacks(mLongClickTestRunnable)
mLongClickHandler.removeCallbacks(mStartLongClickAction)
mSoundPlayer.stopSounds()
// Prevent loss of data in Cookies
CookieManager.getInstance().flush()
}
override fun onResume() {
super.onResume()
// Set the context for the Sound manager
mSoundPlayer.setContext(WeakReference(this))
automaticAnswer.enable()
// Reset the activity title
setTitle()
updateActionBar()
selectNavigationItem(-1)
}
override fun onDestroy() {
super.onDestroy()
// Tells the scheduler there is no more current cards. 0 is
// not a valid id.
if (sched != null && sched is SchedV2) {
(sched!! as SchedV2).discardCurrentCard()
}
Timber.d("onDestroy()")
mTTS.releaseTts(this)
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver)
}
// WebView.destroy() should be called after the end of use
// http://developer.android.com/reference/android/webkit/WebView.html#destroy()
if (mCardFrame != null) {
mCardFrame!!.removeAllViews()
}
destroyWebView(webView) // OK to do without a lock
}
override fun onBackPressed() {
if (isDrawerOpen) {
super.onBackPressed()
} else {
Timber.i("Back key pressed")
if (!mExitViaDoubleTapBack || mBackButtonPressedToReturn) {
closeReviewer(RESULT_DEFAULT, false)
} else {
showSnackbar(R.string.back_pressed_once_reviewer, Snackbar.LENGTH_SHORT)
}
mBackButtonPressedToReturn = true
executeFunctionWithDelay(Consts.SHORT_TOAST_DURATION) { mBackButtonPressedToReturn = false }
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return if (processCardFunction { cardWebView: WebView? -> processHardwareButtonScroll(keyCode, cardWebView) }) {
true
} else super.onKeyDown(keyCode, event)
}
@KotlinCleanup("Use ?:")
public override val currentCardId: CardId?
get() = if (currentCard == null) {
null
} else currentCard!!.id
private fun processHardwareButtonScroll(keyCode: Int, card: WebView?): Boolean {
if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
card!!.pageUp(false)
if (mDoubleScrolling) {
card.pageUp(false)
}
return true
}
if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
card!!.pageDown(false)
if (mDoubleScrolling) {
card.pageDown(false)
}
return true
}
if (mScrollingButtons && keyCode == KeyEvent.KEYCODE_PICTSYMBOLS) {
card!!.pageUp(false)
if (mDoubleScrolling) {
card.pageUp(false)
}
return true
}
if (mScrollingButtons && keyCode == KeyEvent.KEYCODE_SWITCH_CHARSET) {
card!!.pageDown(false)
if (mDoubleScrolling) {
card.pageDown(false)
}
return true
}
return false
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (answerFieldIsFocused()) {
return super.onKeyUp(keyCode, event)
}
if (!displayAnswer) {
if (keyCode == KeyEvent.KEYCODE_SPACE || keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) {
displayCardAnswer()
return true
}
}
return super.onKeyUp(keyCode, event)
}
protected open fun answerFieldIsFocused(): Boolean {
return answerField != null && answerField!!.isFocused
}
protected fun clipboardHasText(): Boolean {
return !TextUtils.isEmpty(getText(mClipboard))
}
/**
* Returns the text stored in the clipboard or the empty string if the clipboard is empty or contains something that
* cannot be converted to text.
*
* @return the text in clipboard or the empty string.
*/
private fun clipboardGetText(): CharSequence {
val text = getText(mClipboard)
return text ?: ""
}
@Suppress("deprecation") // super.onActivityResult
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == DeckPicker.RESULT_DB_ERROR) {
closeReviewer(DeckPicker.RESULT_DB_ERROR, false)
}
if (resultCode == DeckPicker.RESULT_MEDIA_EJECTED) {
finishNoStorageAvailable()
}
/* Reset the schedule and reload the latest card off the top of the stack if required.
The card could have been rescheduled, the deck could have changed, or a change of
note type could have lead to the card being deleted */
val reloadRequired = data?.getBooleanExtra("reloadRequired", false) == true
if (reloadRequired) {
performReload()
}
if (requestCode == EDIT_CURRENT_CARD) {
if (resultCode == RESULT_OK) {
// content of note was changed so update the note and current card
Timber.i("AbstractFlashcardViewer:: Saving card...")
launchCatchingTask { saveEditedCard() }
onEditedNoteChanged()
} else if (resultCode == RESULT_CANCELED && !reloadRequired) {
// nothing was changed by the note editor so just redraw the card
redrawCard()
}
} else if (requestCode == DECK_OPTIONS && resultCode == RESULT_OK) {
performReload()
}
}
/**
* Whether the class should use collection.getSched() when performing tasks.
* The aim of this method is to completely distinguish FlashcardViewer from Reviewer
*
* This is partially implemented, the end goal is that the FlashcardViewer will not have any coupling to getSched
*
* Currently, this is used for note edits - in a reviewing context, this should show the next card.
* In a previewing context, the card should not change.
*/
open fun canAccessScheduler(): Boolean {
return false
}
protected open fun onEditedNoteChanged() {}
/** An action which may invalidate the current list of cards has been performed */
protected abstract fun performReload()
// ----------------------------------------------------------------------------
// CUSTOM METHODS
// ----------------------------------------------------------------------------
// Get the did of the parent deck (ignoring any subdecks)
protected val parentDid: DeckId
get() = col.decks.selected()
private fun redrawCard() {
// #3654 We can call this from ActivityResult, which could mean that the card content hasn't yet been set
// if the activity was destroyed. In this case, just wait until onCollectionLoaded callback succeeds.
if (hasLoadedCardContent()) {
fillFlashcard()
} else {
Timber.i("Skipping card redraw - card still initialising.")
}
}
/** Whether the callback to onCollectionLoaded has loaded card content */
private fun hasLoadedCardContent(): Boolean {
return cardContent != null
}
/**
* Show/dismiss dialog when sd card is ejected/remounted (collection is saved by SdCardReceiver)
*/
private fun registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == SdCardReceiver.MEDIA_EJECT) {
finishWithoutAnimation()
}
}
}
val iFilter = IntentFilter()
iFilter.addAction(SdCardReceiver.MEDIA_EJECT)
registerReceiver(mUnmountReceiver, iFilter)
}
}
open fun undo(): Job? {
if (isUndoAvailable) {
val undoneAction = col.undoName(resources)
val message = getString(R.string.undo_succeeded, undoneAction)
fun legacyUndo() {
Undo().runWithHandler(
answerCardHandler(false)
.alsoExecuteAfter { showSnackbarAboveAnswerButtons(message, Snackbar.LENGTH_SHORT) }
)
}
if (BackendFactory.defaultLegacySchema) {
legacyUndo()
} else {
return launchCatchingTask {
if (!backendUndoAndShowPopup(findViewById(R.id.flip_card))) {
legacyUndo()
}
}
}
}
return null
}
private fun finishNoStorageAvailable() {
this@AbstractFlashcardViewer.setResult(DeckPicker.RESULT_MEDIA_EJECTED)
finishWithoutAnimation()
}
@NeedsTest("Starting animation from swipe is inverse to the finishing one")
protected open fun editCard(fromGesture: Gesture? = null) {
if (currentCard == null) {
// This should never occurs. It means the review button was pressed while there is no more card in the reviewer.
return
}
val editCard = Intent(this@AbstractFlashcardViewer, NoteEditor::class.java)
val animation = getAnimationTransitionFromGesture(fromGesture)
editCard.putExtra(NoteEditor.EXTRA_CALLER, NoteEditor.CALLER_REVIEWER_EDIT)
editCard.putExtra(FINISH_ANIMATION_EXTRA, getInverseTransition(animation) as Parcelable)
editorCard = currentCard
startActivityForResultWithAnimation(editCard, EDIT_CURRENT_CARD, animation)
}
fun generateQuestionSoundList() {
val tags = Sound.extractTagsFromLegacyContent(currentCard!!.qSimple())
mSoundPlayer.addSounds(mBaseUrl!!, tags, SoundSide.QUESTION)
}
@KotlinCleanup("remove _ variables")
protected fun showDeleteNoteDialog() {
val res = resources
MaterialDialog(this).show {
title(R.string.delete_card_title)
iconAttr(R.attr.dialogErrorIcon)
message(
text = res.getString(
R.string.delete_note_message,
Utils.stripHTML(currentCard!!.q(true))
)
)
positiveButton(R.string.dialog_positive_delete) {
Timber.i(
"AbstractFlashcardViewer:: OK button pressed to delete note %d",
currentCard!!.nid
)
mSoundPlayer.stopSounds()
deleteNoteWithoutConfirmation()
}
negativeButton(R.string.dialog_cancel)
}
}
/** Consumers should use [.showDeleteNoteDialog] */
private fun deleteNoteWithoutConfirmation() {
dismiss(DeleteNote(currentCard!!)) {
showSnackbarWithUndoButton(R.string.deleted_note)
}
}
private fun showSnackbarWithUndoButton(
@StringRes textResource: Int,
duration: Int = Snackbar.LENGTH_SHORT
) {
showSnackbarAboveAnswerButtons(textResource, duration) {
setAction(R.string.undo) { undo() }
}
}
private fun getRecommendedEase(easy: Boolean): Int {
return try {
when (answerButtonCount) {
2 -> EASE_2
3 -> if (easy) EASE_3 else EASE_2
4 -> if (easy) EASE_4 else EASE_3
else -> 0
}
} catch (e: RuntimeException) {
CrashReportService.sendExceptionReport(e, "AbstractReviewer-getRecommendedEase")
closeReviewer(DeckPicker.RESULT_DB_ERROR, true)
0
}
}
open fun answerCard(@BUTTON_TYPE ease: Int) {
launchCatchingTask {
if (mInAnswer) {
return@launchCatchingTask
}
mIsSelecting = false
val buttonNumber = col.sched.answerButtons(currentCard!!)
// Detect invalid ease for current card (e.g. by using keyboard shortcut or gesture).
if (buttonNumber < ease) {
return@launchCatchingTask
}
// Temporarily sets the answer indicator dots appearing below the toolbar
mPreviousAnswerIndicator!!.displayAnswerIndicator(ease, buttonNumber)
mSoundPlayer.stopSounds()
mCurrentEase = ease
val oldCard = currentCard!!
val newCard = withCol {
Timber.i("Answering card %d", oldCard.id)
col.sched.answerCard(oldCard, ease)
Timber.i("Obtaining next card")
sched.card?.apply { render_output(reload = true) }
}
// TODO: this handling code is unnecessarily complex, and would be easier to follow
// if written imperatively
val handler = answerCardHandler(true)
handler.before?.run()
handler.after?.accept(Computation.ok(NextCard.withNoResult(newCard)))
}
}
// Set the content view to the one provided and initialize accessors.
@KotlinCleanup("Move a lot of these to onCreate()")
protected open fun initLayout() {
topBarLayout = findViewById(R.id.top_bar)
mCardFrame = findViewById(R.id.flashcard)
mCardFrameParent = mCardFrame!!.parent as ViewGroup
mTouchLayer = findViewById(R.id.touch_layer)
mTouchLayer!!.setOnTouchListener(mGestureListener)
mCardFrame!!.removeAllViews()
// Initialize swipe
gestureDetector = GestureDetector(this, mGestureDetectorImpl)
easeButtonsLayout = findViewById(R.id.ease_buttons)
easeButton1 = EaseButton(EASE_1, findViewById(R.id.flashcard_layout_ease1), findViewById(R.id.ease1), findViewById(R.id.nextTime1))
easeButton1!!.setListeners(mEaseHandler)
easeButton2 = EaseButton(EASE_2, findViewById(R.id.flashcard_layout_ease2), findViewById(R.id.ease2), findViewById(R.id.nextTime2))
easeButton2!!.setListeners(mEaseHandler)
easeButton3 = EaseButton(EASE_3, findViewById(R.id.flashcard_layout_ease3), findViewById(R.id.ease3), findViewById(R.id.nextTime3))
easeButton3!!.setListeners(mEaseHandler)
easeButton4 = EaseButton(EASE_4, findViewById(R.id.flashcard_layout_ease4), findViewById(R.id.ease4), findViewById(R.id.nextTime4))
easeButton4!!.setListeners(mEaseHandler)
if (!mShowNextReviewTime) {
easeButton1!!.hideNextReviewTime()
easeButton2!!.hideNextReviewTime()
easeButton3!!.hideNextReviewTime()
easeButton4!!.hideNextReviewTime()
}
val flipCard = findViewById<Button>(R.id.flip_card)
flipCardLayout = findViewById(R.id.flashcard_layout_flip)
flipCardLayout!!.setOnClickListener(mFlipCardListener)
if (animationEnabled()) {
flipCard.setBackgroundResource(getResFromAttr(this, R.attr.hardButtonRippleRef))
}
if (!mButtonHeightSet && mRelativeButtonSize != 100) {
val params = flipCardLayout!!.layoutParams
params.height = params.height * mRelativeButtonSize / 100
easeButton1!!.setButtonScale(mRelativeButtonSize)
easeButton2!!.setButtonScale(mRelativeButtonSize)
easeButton3!!.setButtonScale(mRelativeButtonSize)
easeButton4!!.setButtonScale(mRelativeButtonSize)
mButtonHeightSet = true
}
mInitialFlipCardHeight = flipCardLayout!!.layoutParams.height
if (mLargeAnswerButtons) {
val params = flipCardLayout!!.layoutParams