forked from ankidroid/Anki-Android
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReviewer.kt
More file actions
1675 lines (1546 loc) · 62.7 KB
/
Reviewer.kt
File metadata and controls
1675 lines (1546 loc) · 62.7 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>
*
* 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/>.
*/
package com.ichi2.anki
import android.Manifest
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.Parcelable
import android.text.SpannableString
import android.text.style.UnderlineSpan
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.webkit.WebView
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.CheckResult
import androidx.annotation.DrawableRes
import androidx.annotation.IntDef
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.menu.MenuBuilder
import androidx.appcompat.widget.ThemeUtils
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import androidx.lifecycle.lifecycleScope
import anki.frontend.SetSchedulingStatesRequest
import com.google.android.material.color.MaterialColors
import com.google.android.material.snackbar.Snackbar
import com.ichi2.anim.ActivityTransitionAnimation.getInverseTransition
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.Whiteboard.Companion.createInstance
import com.ichi2.anki.Whiteboard.OnPaintColorChangeListener
import com.ichi2.anki.cardviewer.Gesture
import com.ichi2.anki.cardviewer.ViewerCommand
import com.ichi2.anki.common.time.TimeManager
import com.ichi2.anki.multimedia.audio.AudioRecordingController
import com.ichi2.anki.multimedia.audio.AudioRecordingController.Companion.generateTempAudioFile
import com.ichi2.anki.multimedia.audio.AudioRecordingController.Companion.isAudioRecordingSaved
import com.ichi2.anki.multimedia.audio.AudioRecordingController.Companion.isRecording
import com.ichi2.anki.multimedia.audio.AudioRecordingController.Companion.setEditorStatus
import com.ichi2.anki.multimedia.audio.AudioRecordingController.Companion.tempAudioPath
import com.ichi2.anki.multimedia.audio.AudioRecordingController.RecordingState
import com.ichi2.anki.noteeditor.NoteEditorLauncher
import com.ichi2.anki.pages.AnkiServer.Companion.ANKIDROID_JS_PREFIX
import com.ichi2.anki.pages.AnkiServer.Companion.ANKI_PREFIX
import com.ichi2.anki.pages.CardInfoDestination
import com.ichi2.anki.preferences.sharedPrefs
import com.ichi2.anki.reviewer.ActionButtons
import com.ichi2.anki.reviewer.AnswerButtons.Companion.getBackgroundColors
import com.ichi2.anki.reviewer.AnswerButtons.Companion.getTextColors
import com.ichi2.anki.reviewer.AnswerTimer
import com.ichi2.anki.reviewer.AutomaticAnswerAction
import com.ichi2.anki.reviewer.Binding
import com.ichi2.anki.reviewer.BindingMap
import com.ichi2.anki.reviewer.BindingProcessor
import com.ichi2.anki.reviewer.CardMarker
import com.ichi2.anki.reviewer.CardSide
import com.ichi2.anki.reviewer.FullScreenMode
import com.ichi2.anki.reviewer.FullScreenMode.Companion.fromPreference
import com.ichi2.anki.reviewer.FullScreenMode.Companion.isFullScreenReview
import com.ichi2.anki.reviewer.ReviewerBinding
import com.ichi2.anki.reviewer.ReviewerUi
import com.ichi2.anki.scheduling.ForgetCardsDialog
import com.ichi2.anki.scheduling.SetDueDateDialog
import com.ichi2.anki.scheduling.registerOnForgetHandler
import com.ichi2.anki.servicelayer.NoteService.isMarked
import com.ichi2.anki.servicelayer.NoteService.toggleMark
import com.ichi2.anki.snackbar.showSnackbar
import com.ichi2.anki.ui.internationalization.toSentenceCase
import com.ichi2.anki.ui.windows.reviewer.ReviewerFragment
import com.ichi2.anki.utils.ext.flag
import com.ichi2.anki.utils.ext.setUserFlagForCards
import com.ichi2.anki.utils.ext.showDialogFragment
import com.ichi2.anki.utils.navBarNeedsScrim
import com.ichi2.anki.utils.remainingTime
import com.ichi2.annotations.NeedsTest
import com.ichi2.libanki.Card
import com.ichi2.libanki.CardId
import com.ichi2.libanki.Collection
import com.ichi2.libanki.QueueType
import com.ichi2.libanki.sched.Counts
import com.ichi2.libanki.sched.CurrentQueueState
import com.ichi2.libanki.undoableOp
import com.ichi2.themes.Themes
import com.ichi2.themes.Themes.currentTheme
import com.ichi2.utils.HandlerUtils.executeFunctionWithDelay
import com.ichi2.utils.HandlerUtils.getDefaultLooper
import com.ichi2.utils.Permissions.canRecordAudio
import com.ichi2.utils.ViewGroupUtils.setRenderWorkaround
import com.ichi2.utils.cancelable
import com.ichi2.utils.iconAlpha
import com.ichi2.utils.increaseHorizontalPaddingOfOverflowMenuIcons
import com.ichi2.utils.message
import com.ichi2.utils.negativeButton
import com.ichi2.utils.positiveButton
import com.ichi2.utils.show
import com.ichi2.utils.tintOverflowMenuIcons
import com.ichi2.utils.title
import com.ichi2.widget.WidgetStatus.updateInBackground
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import timber.log.Timber
import kotlin.coroutines.resume
@Suppress("LeakingThis")
@NeedsTest("#14709: Timebox shouldn't appear instantly when the Reviewer is opened")
open class Reviewer :
AbstractFlashcardViewer(),
ReviewerUi,
BindingProcessor<ReviewerBinding, ViewerCommand> {
private var queueState: CurrentQueueState? = null
private val customSchedulingKey = TimeManager.time.intTimeMS().toString()
private var hasDrawerSwipeConflicts = false
private var showWhiteboard = true
private var prefFullscreenReview = false
private lateinit var colorPalette: LinearLayout
private var toggleStylus = false
// A flag that determines if the SchedulingStates in CurrentQueueState are
// safe to persist in the database when answering a card. This is used to
// ensure that the custom JS scheduler has persisted its SchedulingStates
// back to the Reviewer before we save it to the database. If the custom
// scheduler has not been configured, then it is safe to immediately set
// this to true
//
// This flag should be set to false when we show the front of the card
// and only set to true once we know the custom scheduler has finished its
// execution, or set to true immediately if the custom scheduler has not
// been configured
private var statesMutated = false
// TODO: Consider extracting to ViewModel
// Card counts
private var newCount: SpannableString? = null
private var lrnCount: SpannableString? = null
private var revCount: SpannableString? = null
private lateinit var textBarNew: TextView
private lateinit var textBarLearn: TextView
private lateinit var textBarReview: TextView
private lateinit var answerTimer: AnswerTimer
private var prefHideDueCount = false
// Whiteboard
var prefWhiteboard = false
@get:CheckResult
@get:VisibleForTesting(otherwise = VisibleForTesting.NONE)
var whiteboard: Whiteboard? = null
protected set
// Record Audio
private var isMicToolBarVisible = false
/** Controller for 'Voice Playback' feature */
private var audioRecordingController: AudioRecordingController? = null
private var isAudioUIInitialized = false
private lateinit var micToolBarLayer: LinearLayout
// ETA
private var eta = 0
private var prefShowETA = false
/** Handle Mark/Flag state of cards */
@VisibleForTesting
internal var cardMarker: CardMarker? = null
// Preferences from the collection
private var showRemainingCardCount = false
private var stopTimerOnAnswer = false
private val actionButtons = ActionButtons()
private lateinit var toolbar: Toolbar
@VisibleForTesting
protected open lateinit var processor: BindingMap<ReviewerBinding, ViewerCommand>
private val addNoteLauncher =
registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
FlashCardViewerResultCallback(),
)
private val flagItemIds = mutableSetOf<Int>()
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
super.onCreate(savedInstanceState)
if (!ensureStoragePermissions()) {
return
}
colorPalette = findViewById(R.id.whiteboard_editor)
answerTimer = AnswerTimer(findViewById(R.id.card_time))
textBarNew = findViewById(R.id.new_number)
textBarLearn = findViewById(R.id.learn_number)
textBarReview = findViewById(R.id.review_number)
toolbar = findViewById(R.id.toolbar)
micToolBarLayer = findViewById(R.id.mic_tool_bar_layer)
processor = BindingMap(sharedPrefs(), ViewerCommand.entries, this)
if (sharedPrefs().getString("answerButtonPosition", "bottom") == "bottom" && !navBarNeedsScrim) {
setNavigationBarColor(R.attr.showAnswerColor)
}
if (!sharedPrefs().getBoolean("showDeckTitle", false)) {
// avoid showing "AnkiDroid"
supportActionBar?.title = ""
}
startLoadingCollection()
registerOnForgetHandler { listOf(currentCardId!!) }
}
override fun onPause() {
answerTimer.pause()
super.onPause()
}
override fun onResume() {
when {
stopTimerOnAnswer && isDisplayingAnswer -> {}
else -> launchCatchingTask { answerTimer.resume() }
}
super.onResume()
if (typeAnswer?.autoFocusEditText() == true) {
answerField?.focusWithKeyboard()
}
}
protected val flagToDisplay: Flag
get() {
return FlagToDisplay(
currentCard!!.flag,
actionButtons.findMenuItem(ActionButtons.RES_FLAG)?.isActionButton ?: true,
prefFullscreenReview,
).get()
}
override fun recreateWebView() {
super.recreateWebView()
setRenderWorkaround(this)
}
@NeedsTest("is hidden if marked is on app bar")
@NeedsTest("is not hidden if marked is not on app bar")
@NeedsTest("is not hidden if marked is on app bar and fullscreen is enabled")
override fun shouldDisplayMark(): Boolean {
val markValue = super.shouldDisplayMark()
if (!markValue) {
return false
}
// If we don't know: assume it's not shown
val shownAsToolbarButton = actionButtons.findMenuItem(ActionButtons.RES_MARK)?.isActionButton == true
return !shownAsToolbarButton || prefFullscreenReview
}
protected open fun onMark(card: Card?) {
if (card == null) {
return
}
launchCatchingTask {
toggleMark(card.note(getColUnsafe), handler = this@Reviewer)
refreshActionBar()
onMarkChanged()
}
}
private fun onMarkChanged() {
if (currentCard == null) {
return
}
cardMarker!!.displayMark(shouldDisplayMark())
}
protected open fun onFlag(
card: Card?,
flag: Flag,
) {
if (card == null) {
return
}
launchCatchingTask {
card.setUserFlag(flag.code)
undoableOp(this@Reviewer) {
setUserFlagForCards(listOf(card.id), flag)
}
refreshActionBar()
onFlagChanged()
}
}
private fun onFlagChanged() {
if (currentCard == null) {
return
}
cardMarker!!.displayFlag(flagToDisplay)
}
private fun selectDeckFromExtra() {
val extras = intent.extras
if (extras == null || !extras.containsKey(EXTRA_DECK_ID)) {
// deckId is not set, load default
return
}
val did = extras.getLong(EXTRA_DECK_ID, Long.MIN_VALUE)
Timber.d("selectDeckFromExtra() with deckId = %d", did)
// deckId does not exist, load default
if (getColUnsafe.decks.get(did) == null) {
Timber.w("selectDeckFromExtra() deckId '%d' doesn't exist", did)
return
}
// Select the deck
getColUnsafe.decks.select(did)
}
override fun getContentViewAttr(fullscreenMode: FullScreenMode): Int =
when (fullscreenMode) {
FullScreenMode.BUTTONS_ONLY -> R.layout.reviewer_fullscreen
FullScreenMode.FULLSCREEN_ALL_GONE -> R.layout.reviewer_fullscreen_noanswers
FullScreenMode.BUTTONS_AND_MENU -> R.layout.reviewer
}
public override fun fitsSystemWindows(): Boolean = !fullscreenMode.isFullScreenReview()
override fun onCollectionLoaded(col: Collection) {
super.onCollectionLoaded(col)
if (Intent.ACTION_VIEW == intent.action) {
Timber.d("onCreate() :: received Intent with action = %s", intent.action)
selectDeckFromExtra()
}
// 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.
prefWhiteboard = MetaDB.getWhiteboardState(this, parentDid)
if (prefWhiteboard) {
// DEFECT: Slight inefficiency here, as we set the database using these methods
val whiteboardVisibility = MetaDB.getWhiteboardVisibility(this, parentDid)
setWhiteboardEnabledState(true)
setWhiteboardVisibility(whiteboardVisibility)
toggleStylus = MetaDB.getWhiteboardStylusState(this, parentDid)
whiteboard!!.toggleStylus = toggleStylus
}
val isMicToolbarEnabled = MetaDB.getMicToolbarState(this, parentDid)
if (isMicToolbarEnabled) {
openMicToolbar()
}
launchCatchingTask {
withCol { startTimebox() }
updateCardAndRedraw()
}
disableDrawerSwipeOnConflicts()
// Set full screen/immersive mode if needed
if (prefFullscreenReview) {
setFullScreen(this)
}
setRenderWorkaround(this)
}
fun redo() {
launchCatchingTask { redoAndShowSnackbar(ACTION_SNACKBAR_TIME) }
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// 100ms was not enough on my device (Honor 9 Lite - Android Pie)
delayedHide(1000)
if (drawerToggle.onOptionsItemSelected(item)) {
return true
}
Flag.entries.find { it.id == item.itemId }?.let { flag ->
Timber.i("Reviewer:: onOptionItemSelected Flag - ${flag.name} clicked")
onFlag(currentCard, flag)
return true
}
when (item.itemId) {
android.R.id.home -> {
Timber.i("Reviewer:: Home button pressed")
closeReviewer(RESULT_OK)
}
R.id.action_undo -> {
Timber.i("Reviewer:: Undo button pressed")
if (showWhiteboard && whiteboard != null && !whiteboard!!.undoEmpty()) {
whiteboard!!.undo()
} else {
undo()
}
}
R.id.action_redo -> {
Timber.i("Reviewer:: Redo button pressed")
redo()
}
R.id.action_reset_card_progress -> {
Timber.i("Reviewer:: Reset progress button pressed")
showResetCardDialog()
}
R.id.action_mark_card -> {
Timber.i("Reviewer:: Mark button pressed")
onMark(currentCard)
}
R.id.action_replay -> {
Timber.i("Reviewer:: Replay media button pressed (from menu)")
playMedia(doMediaReplay = true)
}
R.id.action_toggle_mic_tool_bar -> {
Timber.i("Reviewer:: Voice playback visibility set to %b", !isMicToolBarVisible)
// Check permission to record and request if not granted
openOrToggleMicToolbar()
}
R.id.action_tag -> {
Timber.i("Reviewer:: Tag button pressed")
showTagsDialog()
}
R.id.action_edit -> {
Timber.i("Reviewer:: Edit note button pressed")
editCard()
}
R.id.action_bury_card -> buryCard()
R.id.action_bury_note -> buryNote()
R.id.action_suspend_card -> suspendCard()
R.id.action_suspend_note -> suspendNote()
R.id.action_reschedule_card -> showDueDateDialog()
R.id.action_reset_card_progress -> showResetCardDialog()
R.id.action_delete -> {
Timber.i("Reviewer:: Delete note button pressed")
showDeleteNoteDialog()
}
R.id.action_change_whiteboard_pen_color -> {
Timber.i("Reviewer:: Pen Color button pressed")
changeWhiteboardPenColor()
}
R.id.action_save_whiteboard -> {
Timber.i("Reviewer:: Save whiteboard button pressed")
if (whiteboard != null) {
try {
val savedWhiteboardFileName = whiteboard!!.saveWhiteboard(TimeManager.time).path
showSnackbar(getString(R.string.white_board_image_saved, savedWhiteboardFileName), Snackbar.LENGTH_SHORT)
} catch (e: Exception) {
Timber.w(e)
showSnackbar(getString(R.string.white_board_image_save_failed, e.localizedMessage), Snackbar.LENGTH_SHORT)
}
}
}
R.id.action_clear_whiteboard -> {
Timber.i("Reviewer:: Clear whiteboard button pressed")
clearWhiteboard()
}
R.id.action_hide_whiteboard -> { // toggle whiteboard visibility
Timber.i("Reviewer:: Whiteboard visibility set to %b", !showWhiteboard)
setWhiteboardVisibility(!showWhiteboard)
refreshActionBar()
}
R.id.action_toggle_stylus -> { // toggle stylus mode
Timber.i("Reviewer:: Stylus set to %b", !toggleStylus)
toggleStylus = !toggleStylus
whiteboard!!.toggleStylus = toggleStylus
MetaDB.storeWhiteboardStylusState(this, parentDid, toggleStylus)
refreshActionBar()
}
R.id.action_toggle_whiteboard -> {
toggleWhiteboard()
}
R.id.action_open_deck_options -> {
val i =
com.ichi2.anki.pages.DeckOptions
.getIntent(this, getColUnsafe.decks.current().id)
deckOptionsLauncher.launch(i)
}
R.id.action_select_tts -> {
Timber.i("Reviewer:: Select TTS button pressed")
showSelectTtsDialogue()
}
R.id.action_add_note_reviewer -> {
Timber.i("Reviewer:: Add note button pressed")
addNote()
}
R.id.action_card_info -> {
Timber.i("Card Viewer:: Card Info")
openCardInfo()
}
R.id.user_action_1 -> userAction(1)
R.id.user_action_2 -> userAction(2)
R.id.user_action_3 -> userAction(3)
R.id.user_action_4 -> userAction(4)
R.id.user_action_5 -> userAction(5)
R.id.user_action_6 -> userAction(6)
R.id.user_action_7 -> userAction(7)
R.id.user_action_8 -> userAction(8)
R.id.user_action_9 -> userAction(9)
else -> {
return super.onOptionsItemSelected(item)
}
}
return true
}
public override fun toggleWhiteboard() {
prefWhiteboard = !prefWhiteboard
Timber.i("Reviewer:: Whiteboard enabled state set to %b", prefWhiteboard)
// Even though the visibility is now stored in its own setting, we want it to be dependent
// on the enabled status
setWhiteboardEnabledState(prefWhiteboard)
setWhiteboardVisibility(prefWhiteboard)
if (!prefWhiteboard) {
colorPalette.visibility = View.GONE
}
refreshActionBar()
}
public override fun clearWhiteboard() {
if (whiteboard != null) {
whiteboard!!.clear()
}
}
public override fun changeWhiteboardPenColor() {
if (colorPalette.isGone) {
colorPalette.visibility = View.VISIBLE
} else {
colorPalette.visibility = View.GONE
}
updateWhiteboardEditorPosition()
}
override fun replayVoice() {
if (!openMicToolbar()) {
return
}
if (isAudioRecordingSaved) {
audioRecordingController?.playPausePlayer()
} else {
return
}
}
override fun recordVoice() {
if (!openMicToolbar()) {
return
}
audioRecordingController?.toggleToRecorder()
}
override fun saveRecording() {
if (!openMicToolbar()) {
return
}
if (isRecording) {
audioRecordingController?.toggleSave()
} else {
return
}
}
override fun updateForNewCard() {
super.updateForNewCard()
if (prefWhiteboard && whiteboard != null) {
whiteboard!!.clear()
}
audioRecordingController?.updateUIForNewCard()
}
override fun unblockControls() {
if (prefWhiteboard && whiteboard != null) {
whiteboard!!.isEnabled = true
}
super.unblockControls()
}
override fun closeReviewer(result: Int) {
// Stop the mic recording if still pending
if (isRecording) audioRecordingController?.stopAndSaveRecording()
// Remove the temporary audio file
tempAudioPath?.let { tempAudioPathToDelete ->
if (tempAudioPathToDelete.exists()) {
tempAudioPathToDelete.delete()
}
}
super.closeReviewer(result)
}
/**
*
* @return Whether the mic toolbar is usable
*/
@VisibleForTesting
fun openMicToolbar(): Boolean {
if (micToolBarLayer.visibility != View.VISIBLE || audioRecordingController == null) {
openOrToggleMicToolbar()
}
return audioRecordingController != null
}
private fun openOrToggleMicToolbar() {
if (!canRecordAudio(this)) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.RECORD_AUDIO),
REQUEST_AUDIO_PERMISSION,
)
} else {
toggleMicToolBar()
}
}
private fun toggleMicToolBar() {
tempAudioPath = generateTempAudioFile(this)
if (isMicToolBarVisible) {
micToolBarLayer.visibility = View.GONE
} else {
setEditorStatus(false)
if (!isAudioUIInitialized) {
try {
audioRecordingController = AudioRecordingController(context = this)
audioRecordingController?.createUI(
this,
micToolBarLayer,
initialState = RecordingState.ImmediatePlayback.CLEARED,
R.layout.activity_audio_recording_reviewer,
)
} catch (e: Exception) {
Timber.w(e, "unable to add the audio recorder to toolbar")
CrashReportService.sendExceptionReport(e, "Unable to create recorder tool bar")
showThemedToast(
this,
this.getText(R.string.multimedia_editor_audio_view_create_failed).toString(),
true,
)
}
isAudioUIInitialized = true
}
micToolBarLayer.visibility = View.VISIBLE
}
isMicToolBarVisible = !isMicToolBarVisible
MetaDB.storeMicToolbarState(this, parentDid, isMicToolBarVisible)
refreshActionBar()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray,
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_AUDIO_PERMISSION &&
permissions.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
// Get get audio record permission, so we can create the record tool bar
toggleMicToolBar()
}
}
private fun showDueDateDialog() =
launchCatchingTask {
val dialog = SetDueDateDialog.newInstance(listOf(currentCardId!!))
showDialogFragment(dialog)
}
private fun showResetCardDialog() {
Timber.i("showResetCardDialog() Reset progress button pressed")
showDialogFragment(ForgetCardsDialog())
}
fun addNote(fromGesture: Gesture? = null) {
val animation = getAnimationTransitionFromGesture(fromGesture)
val inverseAnimation = getInverseTransition(animation)
val intent = NoteEditorLauncher.AddNoteFromReviewer(inverseAnimation).toIntent(this)
addNoteLauncher.launch(intent)
}
@NeedsTest("Starting animation from swipe is inverse to the finishing one")
protected fun openCardInfo(fromGesture: Gesture? = null) {
if (currentCard == null) {
showSnackbar(getString(R.string.multimedia_editor_something_wrong), Snackbar.LENGTH_SHORT)
return
}
val intent = CardInfoDestination(currentCard!!.id).toIntent(this)
val animation = getAnimationTransitionFromGesture(fromGesture)
intent.putExtra(FINISH_ANIMATION_EXTRA, getInverseTransition(animation) as Parcelable)
startActivityWithAnimation(intent, animation)
}
// Related to https://github.com/ankidroid/Anki-Android/pull/11061#issuecomment-1107868455
@NeedsTest("Order of operations needs Testing around Menu (Overflow) Icons and their colors.")
override fun onCreateOptionsMenu(menu: Menu): Boolean {
Timber.d("onCreateOptionsMenu()")
// NOTE: This is called every time a new question is shown via invalidate options menu
menuInflater.inflate(R.menu.reviewer, menu)
menu.findItem(R.id.action_flag).subMenu?.let { subMenu -> setupFlags(subMenu) }
displayIcons(menu)
actionButtons.setCustomButtonsStatus(menu)
val alpha = Themes.ALPHA_ICON_ENABLED_LIGHT
val markCardIcon = menu.findItem(R.id.action_mark_card)
if (currentCard != null && isMarked(getColUnsafe, currentCard!!.note(getColUnsafe))) {
markCardIcon.setTitle(R.string.menu_unmark_note).setIcon(R.drawable.ic_star_white)
} else {
markCardIcon.setTitle(R.string.menu_mark_note).setIcon(R.drawable.ic_star_border_white)
}
markCardIcon.iconAlpha = alpha
val flagIcon = menu.findItem(R.id.action_flag)
if (flagIcon != null) {
if (currentCard != null) {
val flag = currentCard!!.flag
flagIcon.setIcon(flag.drawableRes)
if (flag == Flag.NONE && actionButtons.status.flagsIsOverflown()) {
val flagColor = ThemeUtils.getThemeAttrColor(this, android.R.attr.colorControlNormal)
flagIcon.icon?.mutate()?.setTint(flagColor)
}
}
}
// Anki Desktop Translations
menu.findItem(R.id.action_reschedule_card).title =
CollectionManager.TR.actionsSetDueDate().toSentenceCase(this, R.string.sentence_set_due_date)
// Undo button
@DrawableRes val undoIconId: Int
val undoEnabled: Boolean
val whiteboardIsShownAndHasStrokes = showWhiteboard && whiteboard?.undoEmpty() == false
if (whiteboardIsShownAndHasStrokes) {
undoIconId = R.drawable.eraser
undoEnabled = true
} else {
undoIconId = R.drawable.ic_undo_white
undoEnabled = colIsOpenUnsafe() && getColUnsafe.undoAvailable()
}
val alphaUndo = Themes.ALPHA_ICON_ENABLED_LIGHT
val undoIcon = menu.findItem(R.id.action_undo)
undoIcon.setIcon(undoIconId)
undoIcon.setEnabled(undoEnabled).iconAlpha = alphaUndo
undoIcon.actionView!!.isEnabled = undoEnabled
if (colIsOpenUnsafe()) { // Required mostly because there are tests where `col` is null
if (whiteboardIsShownAndHasStrokes) {
undoIcon.title = resources.getString(R.string.undo_action_whiteboard_last_stroke)
} else if (getColUnsafe.undoAvailable()) {
undoIcon.title = getColUnsafe.undoLabel()
// e.g. Undo Bury, Undo Change Deck, Undo Update Note
} else {
// In this case, there is no object word for the verb, "Undo",
// so in some languages such as Japanese, which have pre/post-positional particle with the object,
// we need to use the string for just "Undo" instead of the string for "Undo %s".
undoIcon.title = resources.getString(R.string.undo)
undoIcon.iconAlpha = Themes.ALPHA_ICON_DISABLED_LIGHT
}
menu.findItem(R.id.action_redo)?.apply {
if (getColUnsafe.redoAvailable()) {
title = getColUnsafe.redoLabel()
iconAlpha = Themes.ALPHA_ICON_ENABLED_LIGHT
isEnabled = true
} else {
setTitle(R.string.redo)
iconAlpha = Themes.ALPHA_ICON_DISABLED_LIGHT
isEnabled = false
}
}
}
val toggleWhiteboardIcon = menu.findItem(R.id.action_toggle_whiteboard)
val toggleStylusIcon = menu.findItem(R.id.action_toggle_stylus)
val hideWhiteboardIcon = menu.findItem(R.id.action_hide_whiteboard)
val changePenColorIcon = menu.findItem(R.id.action_change_whiteboard_pen_color)
// White board button
if (prefWhiteboard) {
// Configure the whiteboard related items in the action bar
toggleWhiteboardIcon.setTitle(R.string.disable_whiteboard)
// Always allow "Disable Whiteboard", even if "Enable Whiteboard" is disabled
toggleWhiteboardIcon.isVisible = true
if (!actionButtons.status.toggleStylusIsDisabled()) {
toggleStylusIcon.isVisible = true
}
if (!actionButtons.status.hideWhiteboardIsDisabled()) {
hideWhiteboardIcon.isVisible = true
}
if (!actionButtons.status.clearWhiteboardIsDisabled()) {
menu.findItem(R.id.action_clear_whiteboard).isVisible = true
}
if (!actionButtons.status.saveWhiteboardIsDisabled()) {
menu.findItem(R.id.action_save_whiteboard).isVisible = true
}
if (!actionButtons.status.whiteboardPenColorIsDisabled()) {
changePenColorIcon.isVisible = true
}
val whiteboardIcon = ContextCompat.getDrawable(applicationContext, R.drawable.ic_gesture_white)!!.mutate()
val stylusIcon = ContextCompat.getDrawable(this, R.drawable.ic_gesture_stylus)!!.mutate()
val whiteboardColorPaletteIcon = ContextCompat.getDrawable(applicationContext, R.drawable.ic_color_lens_white_24dp)!!.mutate()
if (showWhiteboard) {
whiteboardIcon.alpha = Themes.ALPHA_ICON_ENABLED_LIGHT
hideWhiteboardIcon.icon = whiteboardIcon
hideWhiteboardIcon.setTitle(R.string.hide_whiteboard)
whiteboardColorPaletteIcon.alpha = Themes.ALPHA_ICON_ENABLED_LIGHT
changePenColorIcon.icon = whiteboardColorPaletteIcon
if (toggleStylus) {
toggleStylusIcon.setTitle(R.string.disable_stylus)
stylusIcon.alpha = Themes.ALPHA_ICON_ENABLED_LIGHT
} else {
toggleStylusIcon.setTitle(R.string.enable_stylus)
stylusIcon.alpha = Themes.ALPHA_ICON_DISABLED_LIGHT
}
toggleStylusIcon.icon = stylusIcon
} else {
whiteboardIcon.alpha = Themes.ALPHA_ICON_DISABLED_LIGHT
hideWhiteboardIcon.icon = whiteboardIcon
hideWhiteboardIcon.setTitle(R.string.show_whiteboard)
whiteboardColorPaletteIcon.alpha = Themes.ALPHA_ICON_DISABLED_LIGHT
stylusIcon.alpha = Themes.ALPHA_ICON_DISABLED_LIGHT
toggleStylusIcon.isEnabled = false
toggleStylusIcon.icon = stylusIcon
changePenColorIcon.isEnabled = false
changePenColorIcon.icon = whiteboardColorPaletteIcon
colorPalette.visibility = View.GONE
}
} else {
toggleWhiteboardIcon.setTitle(R.string.enable_whiteboard)
}
if (colIsOpenUnsafe() && getColUnsafe.decks.isFiltered(parentDid)) {
menu.findItem(R.id.action_open_deck_options).isVisible = false
}
if (tts.enabled && !actionButtons.status.selectTtsIsDisabled()) {
menu.findItem(R.id.action_select_tts).isVisible = true
}
if (!suspendNoteAvailable() && !actionButtons.status.suspendIsDisabled()) {
menu.findItem(R.id.action_suspend).isVisible = false
menu.findItem(R.id.action_suspend_card).isVisible = true
}
if (!buryNoteAvailable() && !actionButtons.status.buryIsDisabled()) {
menu.findItem(R.id.action_bury).isVisible = false
menu.findItem(R.id.action_bury_card).isVisible = true
}
val voicePlaybackIcon = menu.findItem(R.id.action_toggle_mic_tool_bar)
if (isMicToolBarVisible) {
voicePlaybackIcon.setTitle(R.string.menu_disable_voice_playback)
// #18477: always show 'disable', even if 'enable' was invisible
voicePlaybackIcon.isVisible = true
} else {
voicePlaybackIcon.setTitle(R.string.menu_enable_voice_playback)
}
increaseHorizontalPaddingOfOverflowMenuIcons(menu)
tintOverflowMenuIcons(menu, skipIf = { isFlagItem(it) })
return super.onCreateOptionsMenu(menu)
}
private fun setupFlags(subMenu: SubMenu) {
lifecycleScope.launch {
for ((flag, displayName) in Flag.queryDisplayNames()) {
subMenu.findItem(flag.id).setTitle(displayName)
flagItemIds.add(flag.id)
}
}
}
@SuppressLint("RestrictedApi")
private fun displayIcons(menu: Menu) {
try {
if (menu is MenuBuilder) {
menu.setOptionalIconsVisible(true)
}
} catch (e: Exception) {
Timber.w(e, "Failed to display icons in Over flow menu")
} catch (e: Error) {
Timber.w(e, "Failed to display icons in Over flow menu")
}
}
private fun isFlagItem(menuItem: MenuItem): Boolean = flagItemIds.contains(menuItem.itemId)
override fun onKeyDown(
keyCode: Int,
event: KeyEvent,
): Boolean {
if (answerFieldIsFocused()) {
return super.onKeyDown(keyCode, event)
}
if (processor.onKeyDown(event) || super.onKeyDown(keyCode, event)) {
return true
}
return false
}
override fun onGenericMotionEvent(event: MotionEvent?): Boolean {
if (processor.onGenericMotionEvent(event)) {
return true
}
return super.onGenericMotionEvent(event)
}
override fun canAccessScheduler(): Boolean = true
override fun performReload() {
launchCatchingTask { updateCardAndRedraw() }
}
override fun displayAnswerBottomBar() {
super.displayAnswerBottomBar()
// Set correct label and background resource for each button
// Note that it's necessary to set the resource dynamically as the ease2 / ease3 buttons
// (which libanki expects ease to be 2 and 3) can either be hard, good, or easy - depending on num buttons shown
val background = getBackgroundColors(this)
val textColor = getTextColors(this)
easeButton1!!.setVisibility(View.VISIBLE)
easeButton1!!.setColor(background[0])
easeButton4!!.setColor(background[3])
// Ease 2 is "hard"
easeButton2!!.setup(background[1], textColor[1], R.string.ease_button_hard)
easeButton2!!.requestFocus()
// Ease 3 is good
easeButton3!!.setup(background[2], textColor[2], R.string.ease_button_good)
easeButton4!!.setVisibility(View.VISIBLE)
easeButton3!!.requestFocus()
// Show next review time
if (shouldShowNextReviewTime()) {
val state = queueState!!
launchCatchingTask {
val labels = withCol { sched.describeNextStates(state.states) }
easeButton1!!.nextTime = labels[0]
easeButton2!!.nextTime = labels[1]
easeButton3!!.nextTime = labels[2]
easeButton4!!.nextTime = labels[3]
}
}
}
override fun automaticShowQuestion(action: AutomaticAnswerAction) {
// explicitly do not call super
if (easeButton1!!.canPerformClick) {
action.execute(this)
}
}
override fun restorePreferences(): SharedPreferences {
val preferences = super.restorePreferences()
prefHideDueCount = preferences.getBoolean("hideDueCount", false)
prefShowETA = preferences.getBoolean("showETA", false)
prefFullscreenReview = isFullScreenReview(preferences)
actionButtons.setup(preferences)
return preferences
}
override fun updateActionBar() {
super.updateActionBar()
updateScreenCounts()
}
private fun updateWhiteboardEditorPosition() {
answerButtonsPosition =
this
.sharedPrefs()
.getString("answerButtonPosition", "bottom")
val layoutParams: RelativeLayout.LayoutParams
when (answerButtonsPosition) {
"none", "top" -> {
layoutParams = colorPalette.layoutParams as RelativeLayout.LayoutParams
layoutParams.removeRule(RelativeLayout.ABOVE)
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
colorPalette.layoutParams = layoutParams
}
"bottom" -> {
layoutParams = colorPalette.layoutParams as RelativeLayout.LayoutParams
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM)