forked from ankidroid/Anki-Android
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractFlashcardViewer.kt
More file actions
2719 lines (2448 loc) · 101 KB
/
AbstractFlashcardViewer.kt
File metadata and controls
2719 lines (2448 loc) · 101 KB
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.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Color
import android.hardware.SensorManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import android.view.ViewParent
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.webkit.CookieManager
import android.webkit.JsResult
import android.webkit.PermissionRequest
import android.webkit.RenderProcessGoneDetail
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebView.HitTestResult
import android.webkit.WebViewClient
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.CheckResult
import androidx.annotation.IdRes
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle.State.RESUMED
import anki.collection.OpChanges
import com.drakeet.drawer.FullDraggableContainer
import com.google.android.material.snackbar.Snackbar
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anki.AbstractFlashcardViewer.Signal.Companion.toSignal
import com.ichi2.anki.CollectionManager.TR
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.android.back.exitViaDoubleTapBackCallback
import com.ichi2.anki.cardviewer.AndroidCardRenderContext
import com.ichi2.anki.cardviewer.AndroidCardRenderContext.Companion.createInstance
import com.ichi2.anki.cardviewer.CardMediaPlayer
import com.ichi2.anki.cardviewer.Gesture
import com.ichi2.anki.cardviewer.GestureProcessor
import com.ichi2.anki.cardviewer.JavascriptEvaluator
import com.ichi2.anki.cardviewer.MediaErrorHandler
import com.ichi2.anki.cardviewer.OnRenderProcessGoneDelegate
import com.ichi2.anki.cardviewer.RenderedCard
import com.ichi2.anki.cardviewer.SingleCardSide
import com.ichi2.anki.cardviewer.TTS
import com.ichi2.anki.cardviewer.TypeAnswer
import com.ichi2.anki.cardviewer.TypeAnswer.Companion.createInstance
import com.ichi2.anki.cardviewer.ViewerCommand
import com.ichi2.anki.cardviewer.ViewerRefresh
import com.ichi2.anki.cardviewer.handledGamepadKeyDown
import com.ichi2.anki.cardviewer.handledGamepadKeyUp
import com.ichi2.anki.dialogs.TtsVoicesDialogFragment
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.model.CardStateFilter
import com.ichi2.anki.noteeditor.NoteEditorLauncher
import com.ichi2.anki.pages.AnkiServer
import com.ichi2.anki.pages.CongratsPage
import com.ichi2.anki.pages.PostRequestHandler
import com.ichi2.anki.preferences.sharedPrefs
import com.ichi2.anki.reviewer.AutomaticAnswer
import com.ichi2.anki.reviewer.AutomaticAnswer.AutomaticallyAnswered
import com.ichi2.anki.reviewer.AutomaticAnswerAction
import com.ichi2.anki.reviewer.CardSide
import com.ichi2.anki.reviewer.EaseButton
import com.ichi2.anki.reviewer.FullScreenMode
import com.ichi2.anki.reviewer.FullScreenMode.Companion.DEFAULT
import com.ichi2.anki.reviewer.FullScreenMode.Companion.fromPreference
import com.ichi2.anki.reviewer.PreviousAnswerIndicator
import com.ichi2.anki.servicelayer.LanguageHintService.applyLanguageHint
import com.ichi2.anki.servicelayer.NoteService.isMarked
import com.ichi2.anki.settings.Prefs
import com.ichi2.anki.snackbar.BaseSnackbarBuilderProvider
import com.ichi2.anki.snackbar.SnackbarBuilder
import com.ichi2.anki.snackbar.showSnackbar
import com.ichi2.anki.ui.windows.reviewer.ReviewerFragment
import com.ichi2.anki.utils.OnlyOnce.Method.ANSWER_CARD
import com.ichi2.anki.utils.OnlyOnce.preventSimultaneousExecutions
import com.ichi2.anki.utils.ext.showDialogFragment
import com.ichi2.annotations.NeedsTest
import com.ichi2.compat.CompatHelper.Companion.resolveActivityCompat
import com.ichi2.compat.ResolveInfoFlagsCompat
import com.ichi2.libanki.Card
import com.ichi2.libanki.CardId
import com.ichi2.libanki.ChangeManager
import com.ichi2.libanki.Collection
import com.ichi2.libanki.DeckId
import com.ichi2.libanki.Decks
import com.ichi2.libanki.Sound.getAvTag
import com.ichi2.libanki.SoundOrVideoTag
import com.ichi2.libanki.TTSTag
import com.ichi2.libanki.Utils
import com.ichi2.libanki.undoableOp
import com.ichi2.themes.Themes
import com.ichi2.themes.Themes.getResFromAttr
import com.ichi2.ui.FixedEditText
import com.ichi2.utils.HandlerUtils.newHandler
import com.ichi2.utils.HashUtil.hashSetInit
import com.ichi2.utils.Stopwatch
import com.ichi2.utils.WebViewDebugging.initializeDebugging
import com.ichi2.utils.message
import com.ichi2.utils.negativeButton
import com.ichi2.utils.positiveButton
import com.ichi2.utils.show
import com.ichi2.utils.title
import com.squareup.seismic.ShakeDetector
import kotlinx.coroutines.Job
import kotlinx.coroutines.runBlocking
import timber.log.Timber
import java.io.File
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
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 kotlin.math.abs
abstract class AbstractFlashcardViewer :
NavigationDrawerActivity(),
ViewerCommand.CommandProcessor,
TagsDialogListener,
WhiteboardMultiTouchMethods,
AutomaticallyAnswered,
OnPageFinishedCallback,
BaseSnackbarBuilderProvider,
ChangeManager.Subscriber,
PostRequestHandler {
private var ttsInitialized = false
private var replayOnTtsInit = false
@VisibleForTesting
val jsApi by lazy { AnkiDroidJsAPI(this) }
private var tagsDialogFactory: TagsDialogFactory? = null
/**
* Variables to hold preferences
*/
internal var prefShowTopbar = false
protected var fullscreenMode = DEFAULT
private set
private var relativeButtonSize = 0
private var minimalClickSpeed = 0
private var doubleScrolling = false
private var gesturesEnabled = false
private var largeAnswerButtons = false
protected var answerButtonsPosition: String? = "bottom"
private var doubleTapTimeInterval = DEFAULT_DOUBLE_TAP_TIME_INTERVAL
// Android WebView
var automaticAnswer = AutomaticAnswer.defaultInstance(this)
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal var typeAnswer: TypeAnswer? = null
/** Generates HTML content */
private var cardRenderContext: AndroidCardRenderContext? = null
// Default short animation duration, provided by Android framework
private var shortAnimDuration = 0
private var backButtonPressedToReturn = false
// Preferences from the collection
private var showNextReviewTime = false
private var isSelecting = false
private var inAnswer = false
/**
* Variables to hold layout objects that we need to update or handle events for
*/
var webView: WebView? = null
private set
/** Accessor for [WebView.getWebViewClient] before API 26 */
var webViewClient: CardViewerWebClient? = null
private var cardFrame: FrameLayout? = null
private var touchLayer: FrameLayout? = null
protected var answerField: FixedEditText? = null
protected var flipCardLayout: FrameLayout? = null
private var easeButtonsLayout: LinearLayout? = null
internal var easeButton1: EaseButton? = null
internal var easeButton2: EaseButton? = null
internal var easeButton3: EaseButton? = null
internal var easeButton4: EaseButton? = null
protected var topBarLayout: RelativeLayout? = null
private var previousAnswerIndicator: PreviousAnswerIndicator? = null
private var currentEase: Ease? = null
private var initialFlipCardHeight = 0
private var buttonHeightSet = 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 gestureDetectorImpl: MyGestureDetector
private var isXScrolling = false
private var isYScrolling = false
/**
* Gesture Allocation
*/
protected val gestureProcessor = GestureProcessor(this)
// needs to be lateinit due to a reliance on Context
lateinit var server: AnkiServer
@get:VisibleForTesting
var cardContent: String? = null
private set
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal lateinit var cardMediaPlayer: CardMediaPlayer
/** Reference to the parent of the cardFrame to allow regeneration of the cardFrame in case of crash */
private var cardFrameParent: ViewGroup? = null
/** Lock to allow thread-safe regeneration of mCard */
private val cardLock: ReadWriteLock = ReentrantReadWriteLock()
@VisibleForTesting
val onRenderProcessGoneDelegate = OnRenderProcessGoneDelegate(this)
protected val tts = TTS()
// ----------------------------------------------------------------------------
// LISTENERS
// ----------------------------------------------------------------------------
// Handler for the "show answer" button
private val flipCardListener =
View.OnClickListener {
Timber.i("AbstractFlashcardViewer:: Show answer button pressed")
// Ignore what is most likely an accidental double-tap.
if (elapsedRealTime - lastClickTime < doubleTapTimeInterval) {
return@OnClickListener
}
lastClickTime = elapsedRealTime
automaticAnswer.onShowAnswer()
displayCardAnswer()
}
/**
* Changes which were received when the viewer was in the background
* which should be executed once the viewer is visible again
* @see opExecuted
* @see refreshIfRequired
*/
@VisibleForTesting
internal var refreshRequired: ViewerRefresh? = null
private val editCurrentCardLauncher =
registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
FlashCardViewerResultCallback { result, reloadRequired ->
if (result.resultCode == RESULT_OK) {
Timber.i("AbstractFlashcardViewer:: card edited...")
onEditedNoteChanged()
} else if (result.resultCode == RESULT_CANCELED && !reloadRequired) {
// nothing was changed by the note editor so just redraw the card
redrawCard()
}
},
)
private val defaultOnBackCallback =
object : OnBackPressedCallback(enabled = true) {
override fun handleOnBackPressed() {
// TODO: This should be improved now we're using callbacks
closeReviewer(RESULT_DEFAULT)
}
}
protected inner class FlashCardViewerResultCallback(
private val callback: (result: ActivityResult, reloadRequired: Boolean) -> Unit = { _, _ -> },
) : ActivityResultCallback<ActivityResult> {
override fun onActivityResult(result: ActivityResult) {
if (result.resultCode == DeckPicker.RESULT_DB_ERROR) {
closeReviewer(DeckPicker.RESULT_DB_ERROR)
}
if (result.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 =
result.data?.getBooleanExtra(NoteEditor.RELOAD_REQUIRED_EXTRA_KEY, false) == true
if (reloadRequired) {
performReload()
}
callback(result, reloadRequired)
}
}
init {
ChangeManager.subscribe(this)
}
// Event handler for eases (answer buttons)
inner class SelectEaseHandler :
View.OnClickListener,
OnTouchListener {
private var prevCard: Card? = null
private var hasBeenTouched = false
private var touchX = 0f
private var touchY = 0f
override fun onTouch(
view: View,
event: MotionEvent,
): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
// Save states when button pressed
prevCard = currentCard
hasBeenTouched = 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
touchX = event.rawX
touchY = event.rawY
} else if (event.action == MotionEvent.ACTION_UP) {
val diffX = abs(event.rawX - touchX)
val diffY = abs(event.rawY - touchY)
// If a click is not coming then we reset the touch
if (diffX > CLICK_ACTION_THRESHOLD || diffY > CLICK_ACTION_THRESHOLD) {
hasBeenTouched = 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 (prevCard === currentCard || !hasBeenTouched) {
// Only perform if the click was not an accidental double-tap
if (elapsedRealTime - lastClickTime >= doubleTapTimeInterval) {
// For whatever reason, performClick does not return a visual feedback anymore
if (!hasBeenTouched) {
view.isPressed = true
}
lastClickTime = elapsedRealTime
automaticAnswer.onSelectEase()
when (view.id) {
R.id.flashcard_layout_ease1 -> {
Timber.i("AbstractFlashcardViewer:: Ease_1 pressed")
answerCard(Ease.AGAIN)
}
R.id.flashcard_layout_ease2 -> {
Timber.i("AbstractFlashcardViewer:: Ease_2 pressed")
answerCard(Ease.HARD)
}
R.id.flashcard_layout_ease3 -> {
Timber.i("AbstractFlashcardViewer:: Ease_3 pressed")
answerCard(Ease.GOOD)
}
R.id.flashcard_layout_ease4 -> {
Timber.i("AbstractFlashcardViewer:: Ease_4 pressed")
answerCard(Ease.EASY)
}
else -> currentEase = null
}
if (!hasBeenTouched) {
view.isPressed = false
}
}
}
// We will have to reset the touch after every onClick event
// Do not return early without considering this
hasBeenTouched = false
}
}
private val easeHandler = SelectEaseHandler()
@get:VisibleForTesting
protected open val elapsedRealTime: Long
get() = SystemClock.elapsedRealtime()
private val gestureListener =
OnTouchListener { _, event ->
if (gestureDetector!!.onTouchEvent(event)) {
return@OnTouchListener true
}
if (!gestureDetectorImpl.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 = cardLock.readLock()
return try {
readLock.lock()
cardFunction.apply(webView)
} finally {
readLock.unlock()
}
}
/** 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(view: WebView) {
// intentionally blank
}
/** Called after an undo or undoable operation takes place. * Should set currentCard to the current card to display. */
open suspend fun updateCurrentCard() {
// Legacy tests assume the current card will be grabbed from the collection,
// despite that making no sense outside of Reviewer.kt
currentCard =
withCol {
sched.card?.apply {
renderOutput(this@withCol, reload = false, browser = false)
}
}
}
internal suspend fun updateCardAndRedraw() {
Timber.d("updateCardAndRedraw")
refreshRequired = null // this method is called on refresh
updateCurrentCard()
if (currentCard == null) {
closeReviewer(RESULT_NO_MORE_CARDS)
// When launched with a shortcut, we want to display a message when finishing
if (intent.getBooleanExtra(EXTRA_STARTED_WITH_SHORTCUT, false)) {
CongratsPage.display(this)
}
return
}
// Start reviewing next card
hideProgressBar()
unblockControls()
displayCardQuestion()
// set the correct mark/unmark icon on action bar
refreshActionBar()
focusDefaultLayout()
}
private fun focusDefaultLayout() {
findViewById<View>(R.id.root_layout).requestFocus()
}
// ----------------------------------------------------------------------------
// ANDROID METHODS
// ----------------------------------------------------------------------------
override fun onCreate(savedInstanceState: Bundle?) {
restorePreferences()
tagsDialogFactory = TagsDialogFactory(this).attachToActivity<TagsDialogFactory>(this)
super.onCreate(savedInstanceState)
// Issue 14142: The reviewer had a focus highlight after answering using a keyboard.
// This theme removes the highlight, but there is likely a better way.
this.setTheme(R.style.ThemeOverlay_DisableKeyboardHighlight)
setContentView(getContentViewAttr(fullscreenMode))
val port = ReviewerFragment.getServerPort()
server = AnkiServer(this, port).also { it.start() }
// 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)
previousAnswerIndicator = PreviousAnswerIndicator(findViewById(R.id.chosen_answer))
shortAnimDuration = resources.getInteger(android.R.integer.config_shortAnimTime)
gestureDetectorImpl = LinkDetectingGestureDetector()
TtsVoicesFieldFilter.ensureApplied()
}
override fun setupBackPressedCallbacks() {
onBackPressedDispatcher.addCallback(this, defaultOnBackCallback)
onBackPressedDispatcher.addCallback(this, exitViaDoubleTapBackCallback())
super.setupBackPressedCallbacks()
}
protected open fun getContentViewAttr(fullscreenMode: FullScreenMode): Int = 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()
}
// Finish initializing the activity after the collection has been correctly loaded
public override fun onCollectionLoaded(col: Collection) {
super.onCollectionLoaded(col)
val mediaDir = col.media.dir
cardMediaPlayer = CardMediaPlayer.newInstance(this, getMediaBaseUrl(mediaDir))
registerReceiver()
restoreCollectionPreferences(col)
initLayout()
cardRenderContext = createInstance(this, col, typeAnswer!!)
// Initialize text-to-speech. This is an asynchronous operation.
tts.initialize(this, ReadTextListener())
updateActionBar()
invalidateOptionsMenu()
}
// Saves deck each time Reviewer activity loses focus
override fun onPause() {
super.onPause()
automaticAnswer.disable()
gestureDetectorImpl.stopShakeDetector()
if (this::cardMediaPlayer.isInitialized) {
cardMediaPlayer.isEnabled = false
}
// Prevent loss of data in Cookies
CookieManager.getInstance().flush()
}
override fun onResume() {
super.onResume()
automaticAnswer.enable()
gestureDetectorImpl.startShakeDetector()
if (this::cardMediaPlayer.isInitialized) {
cardMediaPlayer.isEnabled = true
}
// Reset the activity title
updateActionBar()
selectNavigationItem(-1)
refreshIfRequired(isResuming = true)
}
/**
* If the activity is [RESUMED], or is called from [onResume] then execute the pending
* operations in [refreshRequired].
*
* If the activity is NOT [RESUMED], wait until [onResume]
*/
@VisibleForTesting
internal fun refreshIfRequired(isResuming: Boolean = false) {
// Defer the execution of `opExecuted` until the user is looking at the screen.
// This ensures that audio/timers are not accidentally started
if (isResuming || lifecycle.currentState.isAtLeast(RESUMED)) {
refreshRequired?.let {
Timber.d("refreshIfRequired: redraw")
// if changing code, re-evaluate `refreshRequired = null` in `updateCardAndRedraw`
launchCatchingTask { updateCardAndRedraw() }
refreshRequired = null
}
} else if (refreshRequired != null) {
// onResume() will execute this method
Timber.d("deferred refresh as activity was not STARTED")
}
}
override fun onDestroy() {
super.onDestroy()
if (this::server.isInitialized) {
server.stop()
}
tts.releaseTts(this)
// WebView.destroy() should be called after the end of use
// http://developer.android.com/reference/android/webkit/WebView.html#destroy()
if (cardFrame != null) {
cardFrame!!.removeAllViews()
}
destroyWebView(webView) // OK to do without a lock
if (this::cardMediaPlayer.isInitialized) {
cardMediaPlayer.close()
}
}
override fun onKeyDown(
keyCode: Int,
event: KeyEvent,
): Boolean {
if (processCardFunction { cardWebView: WebView? ->
processHardwareButtonScroll(
keyCode,
cardWebView,
)
}
) {
return true
}
// Subclasses other than 'Reviewer' have not been setup with Gestures/KeyPresses
// so hardcode this functionality for now.
// This is in onKeyDown to match the gesture processor in the Reviewer
if (!displayAnswer && !answerFieldIsFocused()) {
if (keyCode == KeyEvent.KEYCODE_SPACE || keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) {
displayCardAnswer()
return true
}
}
if (webView.handledGamepadKeyDown(keyCode, event)) {
return true
}
return super.onKeyDown(keyCode, event)
}
override fun onKeyUp(
keyCode: Int,
event: KeyEvent,
): Boolean {
if (webView.handledGamepadKeyUp(keyCode, event)) {
return true
}
return super.onKeyUp(keyCode, event)
}
public override val currentCardId: CardId? get() = currentCard?.id
private fun processHardwareButtonScroll(
keyCode: Int,
card: WebView?,
): Boolean {
if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
card!!.pageUp(false)
if (doubleScrolling) {
card.pageUp(false)
}
return true
}
if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
card!!.pageDown(false)
if (doubleScrolling) {
card.pageDown(false)
}
return true
}
return false
}
protected open fun answerFieldIsFocused(): Boolean = answerField != null && answerField!!.isFocused
val deckOptionsLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { _ ->
Timber.i("Returned from deck options -> Restarting activity")
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 = 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() = getColUnsafe.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 = cardContent != null
open fun undo(): Job =
launchCatchingTask {
undoAndShowSnackbar(duration = Reviewer.ACTION_SNACKBAR_TIME)
}
private fun finishNoStorageAvailable() {
this@AbstractFlashcardViewer.setResult(DeckPicker.RESULT_MEDIA_EJECTED)
finish()
}
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 animation = fromGesture.toAnimationTransition().invert()
val editCardIntent = NoteEditorLauncher.EditCard(currentCard!!.id, animation).toIntent(this)
editCurrentCardLauncher.launch(editCardIntent)
}
protected fun showDeleteNoteDialog() {
AlertDialog.Builder(this).show {
title(R.string.delete_card_title)
setIcon(R.drawable.ic_warning)
message(
text =
resources.getString(
R.string.delete_note_message,
Utils.stripHTMLAndSpecialFields(currentCard!!.question(getColUnsafe, true)).trim(),
),
)
positiveButton(R.string.dialog_positive_delete) {
Timber.i(
"AbstractFlashcardViewer:: OK button pressed to delete note %d",
currentCard!!.nid,
)
launchCatchingTask { cardMediaPlayer.stop() }
deleteNoteWithoutConfirmation()
}
negativeButton(R.string.dialog_cancel)
}
}
/** Consumers should use [.showDeleteNoteDialog] */
private fun deleteNoteWithoutConfirmation() {
val cardId = currentCard!!.id
launchCatchingTask {
val noteCount =
withProgress {
undoableOp {
removeNotes(cids = listOf(cardId))
}.count
}
val deletedMessage =
resources.getQuantityString(
R.plurals.card_browser_cards_deleted,
noteCount,
noteCount,
)
showSnackbar(deletedMessage, Snackbar.LENGTH_LONG) {
setAction(R.string.undo) { launchCatchingTask { undoAndShowSnackbar() } }
}
}
}
open fun answerCard(ease: Ease) =
preventSimultaneousExecutions(ANSWER_CARD) {
launchCatchingTask {
if (inAnswer) {
return@launchCatchingTask
}
isSelecting = false
if (previousAnswerIndicator == null) {
// workaround for a broken ReviewerKeyboardInputTest
return@launchCatchingTask
}
// Temporarily sets the answer indicator dots appearing below the toolbar
previousAnswerIndicator?.displayAnswerIndicator(ease)
cardMediaPlayer.stop()
currentEase = ease
answerCardInner(ease)
updateCardAndRedraw()
}
}
open suspend fun answerCardInner(ease: Ease) {
// Legacy tests assume they can call answerCard() even outside of Reviewer
withCol {
sched.answerCard(currentCard!!, ease)
}
}
// Set the content view to the one provided and initialize accessors.
protected open fun initLayout() {
topBarLayout = findViewById(R.id.top_bar)
cardFrame = findViewById(R.id.flashcard)
cardFrameParent = cardFrame!!.parent as ViewGroup
touchLayer =
findViewById<FrameLayout>(R.id.touch_layer).apply { setOnTouchListener(gestureListener) }
cardFrame!!.removeAllViews()
// Initialize swipe
gestureDetector = GestureDetector(this, gestureDetectorImpl)
easeButtonsLayout = findViewById(R.id.ease_buttons)
easeButton1 =
EaseButton(
Ease.AGAIN,
findViewById(R.id.flashcard_layout_ease1),
findViewById(R.id.ease1),
findViewById(R.id.nextTime1),
).apply { setListeners(easeHandler) }
easeButton2 =
EaseButton(
Ease.HARD,
findViewById(R.id.flashcard_layout_ease2),
findViewById(R.id.ease2),
findViewById(R.id.nextTime2),
).apply { setListeners(easeHandler) }
easeButton3 =
EaseButton(
Ease.GOOD,
findViewById(R.id.flashcard_layout_ease3),
findViewById(R.id.ease3),
findViewById(R.id.nextTime3),
).apply { setListeners(easeHandler) }
easeButton4 =
EaseButton(
Ease.EASY,
findViewById(R.id.flashcard_layout_ease4),
findViewById(R.id.ease4),
findViewById(R.id.nextTime4),
).apply { setListeners(easeHandler) }
if (!showNextReviewTime) {
easeButton1!!.hideNextReviewTime()
easeButton2!!.hideNextReviewTime()
easeButton3!!.hideNextReviewTime()
easeButton4!!.hideNextReviewTime()
}
flipCardLayout = findViewById(R.id.flashcard_layout_flip)
flipCardLayout?.let { layout ->
if (minimalClickSpeed == 0) {
layout.setOnClickListener(flipCardListener)
} else {
val handler = Handler(Looper.getMainLooper())
layout.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
handler.postDelayed({
flipCardListener.onClick(layout)
}, minimalClickSpeed.toLong())
false
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_HOVER_ENTER -> {
handler.removeCallbacksAndMessages(null)
false
}
else -> false
}
}
}
}
if (animationEnabled()) {
flipCardLayout?.setBackgroundResource(getResFromAttr(this, R.attr.hardButtonRippleRef))
}
if (!buttonHeightSet && relativeButtonSize != 100) {
val params = flipCardLayout!!.layoutParams
params.height = params.height * relativeButtonSize / 100
easeButton1!!.setButtonScale(relativeButtonSize)
easeButton2!!.setButtonScale(relativeButtonSize)
easeButton3!!.setButtonScale(relativeButtonSize)
easeButton4!!.setButtonScale(relativeButtonSize)
buttonHeightSet = true
}
initialFlipCardHeight = flipCardLayout!!.layoutParams.height
if (largeAnswerButtons) {
val params = flipCardLayout!!.layoutParams
params.height = initialFlipCardHeight * 2
}
answerField = findViewById(R.id.answer_field)
initControls()
// Position answer buttons
val answerButtonsPosition =
this.sharedPrefs().getString(
getString(R.string.answer_buttons_position_preference),
"bottom",
)
this.answerButtonsPosition = answerButtonsPosition
val answerArea = findViewById<LinearLayout>(R.id.bottom_area_layout)
val answerAreaParams = answerArea.layoutParams as RelativeLayout.LayoutParams
val whiteboardContainer = findViewById<FrameLayout>(R.id.whiteboard)
val whiteboardContainerParams =
whiteboardContainer.layoutParams as RelativeLayout.LayoutParams
val flashcardContainerParams = cardFrame!!.layoutParams as RelativeLayout.LayoutParams
val touchLayerContainerParams = touchLayer!!.layoutParams as RelativeLayout.LayoutParams
when (answerButtonsPosition) {
"top" -> {
whiteboardContainerParams.addRule(RelativeLayout.BELOW, R.id.bottom_area_layout)
flashcardContainerParams.addRule(RelativeLayout.BELOW, R.id.bottom_area_layout)
touchLayerContainerParams.addRule(RelativeLayout.BELOW, R.id.bottom_area_layout)
answerAreaParams.addRule(RelativeLayout.BELOW, R.id.mic_tool_bar_layer)
answerArea.removeView(answerField)
answerArea.addView(answerField, 1)
}
"bottom",
"none",
-> {
whiteboardContainerParams.addRule(RelativeLayout.ABOVE, R.id.bottom_area_layout)
whiteboardContainerParams.addRule(RelativeLayout.BELOW, R.id.mic_tool_bar_layer)
flashcardContainerParams.addRule(RelativeLayout.ABOVE, R.id.bottom_area_layout)
flashcardContainerParams.addRule(RelativeLayout.BELOW, R.id.mic_tool_bar_layer)
touchLayerContainerParams.addRule(RelativeLayout.ABOVE, R.id.bottom_area_layout)
touchLayerContainerParams.addRule(RelativeLayout.BELOW, R.id.mic_tool_bar_layer)
answerAreaParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
}
else -> Timber.w("Unknown answerButtonsPosition: %s", answerButtonsPosition)
}
answerArea.visibility = if (answerButtonsPosition == "none") View.GONE else View.VISIBLE
// workaround for #14419, iterate over the bottom area children and manually enable the
// answer field while still hiding the other children
if (answerButtonsPosition == "none") {
answerArea.visibility = View.VISIBLE
answerArea.children.forEach {
it.visibility = if (it.id == R.id.answer_field) View.VISIBLE else View.GONE
}
}