-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathDeckPicker.kt
2783 lines (2567 loc) · 119 KB
/
DeckPicker.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) 2009 Andrew Dubya <[email protected]> *
* Copyright (c) 2009 Nicolas Raoul <[email protected]> *
* Copyright (c) 2009 Edu Zamora <[email protected]> *
* Copyright (c) 2009 Daniel Svard <[email protected]> *
* Copyright (c) 2010 Norbert Nagold <[email protected]> *
* Copyright (c) 2014 Timothy Rae <[email protected]>
* *
* 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/>. *
****************************************************************************************/
// usage of 'this' in constructors when class is non-final - weak warning
// should be OK as this is only non-final for tests
@file:Suppress("LeakingThis")
package com.ichi2.anki
import android.Manifest
import android.content.*
import android.content.pm.PackageManager
import android.database.SQLException
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.text.TextUtils
import android.util.Pair
import android.util.TypedValue
import android.view.*
import android.view.View.OnLongClickListener
import android.view.WindowManager.BadTokenException
import android.widget.*
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.fragment.app.commit
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import anki.collection.OpChanges
import com.afollestad.materialdialogs.MaterialDialog
import com.google.android.material.snackbar.Snackbar
import com.ichi2.anim.ActivityTransitionAnimation.Direction.*
import com.ichi2.anki.CollectionHelper.CollectionIntegrityStorageCheck
import com.ichi2.anki.CollectionManager.TR
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.CollectionManager.withOpenColOrNull
import com.ichi2.anki.InitialActivity.StartupFailure
import com.ichi2.anki.InitialActivity.StartupFailure.*
import com.ichi2.anki.StudyOptionsFragment.DeckStudyData
import com.ichi2.anki.StudyOptionsFragment.StudyOptionsListener
import com.ichi2.anki.UIUtils.showThemedToast
import com.ichi2.anki.analytics.UsageAnalytics
import com.ichi2.anki.dialogs.*
import com.ichi2.anki.dialogs.DeckPickerNoSpaceToDowngradeDialog.FileSizeFormatter
import com.ichi2.anki.dialogs.ImportDialog.ImportDialogListener
import com.ichi2.anki.dialogs.MediaCheckDialog.MediaCheckDialogListener
import com.ichi2.anki.dialogs.SyncErrorDialog.Companion.newInstance
import com.ichi2.anki.dialogs.SyncErrorDialog.SyncErrorDialogListener
import com.ichi2.anki.dialogs.customstudy.CustomStudyDialog
import com.ichi2.anki.dialogs.customstudy.CustomStudyDialog.CustomStudyListener
import com.ichi2.anki.dialogs.customstudy.CustomStudyDialogFactory
import com.ichi2.anki.exception.ConfirmModSchemaException
import com.ichi2.anki.export.ActivityExportingDelegate
import com.ichi2.anki.pages.CsvImporter
import com.ichi2.anki.preferences.AdvancedSettingsFragment
import com.ichi2.anki.receiver.SdCardReceiver
import com.ichi2.anki.servicelayer.DeckService
import com.ichi2.anki.servicelayer.SchedulerService.NextCard
import com.ichi2.anki.servicelayer.UndoService.Undo
import com.ichi2.anki.snackbar.showSnackbar
import com.ichi2.anki.stats.AnkiStatsTaskHandler
import com.ichi2.anki.web.CustomSyncServer
import com.ichi2.anki.web.HostNumFactory
import com.ichi2.anki.widgets.DeckAdapter
import com.ichi2.annotations.NeedsTest
import com.ichi2.async.*
import com.ichi2.async.CollectionTask.*
import com.ichi2.async.Connection.CancellableTaskListener
import com.ichi2.async.Connection.ConflictResolution
import com.ichi2.compat.CompatHelper.Companion.sdkVersion
import com.ichi2.libanki.*
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Collection.CheckDatabaseResult
import com.ichi2.libanki.importer.AnkiPackageImporter
import com.ichi2.libanki.sched.AbstractDeckTreeNode
import com.ichi2.libanki.sched.DeckDueTreeNode
import com.ichi2.libanki.sched.TreeNode
import com.ichi2.libanki.sched.findInDeckTree
import com.ichi2.libanki.sync.CustomSyncServerUrlException
import com.ichi2.libanki.sync.Syncer.ConnectionResultType
import com.ichi2.libanki.utils.TimeManager
import com.ichi2.themes.StyledProgressDialog
import com.ichi2.ui.BadgeDrawableBuilder
import com.ichi2.utils.*
import com.ichi2.utils.NetworkUtils.isActiveNetworkMetered
import com.ichi2.utils.Permissions.hasStorageAccessPermission
import com.ichi2.widget.WidgetStatus
import kotlinx.coroutines.Job
import net.ankiweb.rsdroid.BackendFactory
import net.ankiweb.rsdroid.RustCleanup
import timber.log.Timber
import java.io.File
import kotlin.math.abs
import kotlin.math.roundToLong
/**
* The current entry point for AnkiDroid. Displays decks, allowing users to study. Many other functions.
*
* On a tablet, this is a fragmented view, with [StudyOptionsFragment] to the right: [loadStudyOptionsFragment]
*
* Often used as navigation to: [Reviewer], [NoteEditor] (adding notes), [StudyOptionsFragment] [SharedDecksDownloadFragment]
*
* Responsibilities:
* * Setup/upgrades of the application: [handleStartup]
* * Error handling [handleDbError] [handleDbLocked]
* * Displaying a tree of decks, some of which may be collapsible: [mDeckListAdapter]
* * Allows users to study the decks
* * Displays deck progress
* * A long press opens a menu allowing modification of the deck
* * Filtering decks (if more than 10) [mToolbarSearchView]
* * Controlling syncs
* * A user may [pull down][mPullToSyncWrapper] on the 'tree view' to sync
* * A [button][displaySyncBadge] which relies on [SyncStatus] to display whether a sync is needed
* * Blocks the UI and displays sync progress when syncing
* * Displaying 'General' AnkiDroid options: backups, import, 'check media' etc...
* * General handler for error/global dialogs (search for 'as DeckPicker')
* * Such as import: [ImportDialogListener]
* * A Floating Action Button [mFloatingActionMenu] allowing the user to quickly add notes/cards.
* * A custom image as a background can be added: [applyDeckPickerBackground]
*/
@KotlinCleanup("lots to do")
@NeedsTest("On a new startup, the App Intro is displayed")
@NeedsTest("If the collection has been created, the app intro is not displayed")
@NeedsTest("If the user selects 'Sync Profile' in the app intro, a sync starts immediately")
open class DeckPicker :
NavigationDrawerActivity(),
StudyOptionsListener,
SyncErrorDialogListener,
ImportDialogListener,
MediaCheckDialogListener,
OnRequestPermissionsResultCallback,
CustomStudyListener,
ChangeManager.Subscriber {
// Short animation duration from system
private var mShortAnimDuration = 0
private var mBackButtonPressedToExit = false
private lateinit var mDeckPickerContent: RelativeLayout
@Suppress("Deprecation") // TODO: Encapsulate ProgressDialog within a class to limit the use of deprecated functionality
private var mProgressDialog: android.app.ProgressDialog? = null
private var mStudyoptionsFrame: View? = null // not lateInit - can be null
private lateinit var mRecyclerView: RecyclerView
private lateinit var mRecyclerViewLayoutManager: LinearLayoutManager
private lateinit var mDeckListAdapter: DeckAdapter
private val mSnackbarShowHideCallback = Snackbar.Callback()
private lateinit var mExportingDelegate: ActivityExportingDelegate
private lateinit var mNoDecksPlaceholder: LinearLayout
private lateinit var mPullToSyncWrapper: SwipeRefreshLayout
private lateinit var mReviewSummaryTextView: TextView
@KotlinCleanup("make lateinit, but needs more changes")
private var mUnmountReceiver: BroadcastReceiver? = null
private lateinit var mFloatingActionMenu: DeckPickerFloatingActionMenu
// flag asking user to do a full sync which is used in upgrade path
private var mRecommendFullSync = false
// flag keeping track of when the app has been paused
private var mActivityPaused = false
// Flag to keep track of startup error
private var mStartupError = false
private var mEmptyCardTask: Cancellable? = null
/** See [OptionsMenuState]. */
@VisibleForTesting
var optionsMenuState: OptionsMenuState? = null
@VisibleForTesting
var dueTree: List<TreeNode<AbstractDeckTreeNode>>? = null
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
var searchDecksIcon: MenuItem? = null
/**
* Flag to indicate whether the activity will perform a sync in its onResume.
* Since syncing closes the database, this flag allows us to avoid doing any
* work in onResume that might use the database and go straight to syncing.
*/
private var mSyncOnResume = false
/**
* Keep track of which deck was last given focus in the deck list. If we find that this value
* has changed between deck list refreshes, we need to recenter the deck list to the new current
* deck.
*/
private var mFocusedDeck: Long = 0
private var mToolbarSearchView: SearchView? = null
private lateinit var mCustomStudyDialogFactory: CustomStudyDialogFactory
private lateinit var mContextMenuFactory: DeckPickerContextMenu.Factory
// stored for testing purposes
@VisibleForTesting
var createMenuJob: Job? = null
init {
ChangeManager.subscribe(this)
}
// ----------------------------------------------------------------------------
// LISTENERS
// ----------------------------------------------------------------------------
private val mDeckExpanderClickListener = View.OnClickListener { view: View ->
toggleDeckExpand(view.tag as Long)
}
private val mDeckClickListener = View.OnClickListener { v: View -> onDeckClick(v, DeckSelectionType.DEFAULT) }
private val mCountsClickListener = View.OnClickListener { v: View -> onDeckClick(v, DeckSelectionType.SHOW_STUDY_OPTIONS) }
private fun onDeckClick(v: View, selectionType: DeckSelectionType) {
val deckId = v.tag as Long
Timber.i("DeckPicker:: Selected deck with id %d", deckId)
var collectionIsOpen = false
try {
collectionIsOpen = colIsOpen()
handleDeckSelection(deckId, selectionType)
if (fragmented) {
// Calling notifyDataSetChanged() will update the color of the selected deck.
// This interferes with the ripple effect, so we don't do it if lollipop and not tablet view
mDeckListAdapter.notifyDataSetChanged()
}
} catch (e: Exception) {
// Maybe later don't report if collectionIsOpen is false?
Timber.w(e)
val info = "$deckId colOpen:$collectionIsOpen"
CrashReportService.sendExceptionReport(e, "deckPicker::onDeckClick", info)
displayFailedToOpenDeck(deckId)
}
}
private fun displayFailedToOpenDeck(deckId: DeckId) {
// #6208 - if the click is accepted before the sync completes, we get a failure.
// We use the Deck ID as the deck likely doesn't exist any more.
val message = getString(R.string.deck_picker_failed_deck_load, deckId.toString())
showThemedToast(this, message, false)
Timber.w(message)
}
private val mDeckLongClickListener = OnLongClickListener { v ->
val deckId = v.tag as Long
Timber.i("DeckPicker:: Long tapped on deck with id %d", deckId)
showDialogFragment(mContextMenuFactory.newDeckPickerContextMenu(deckId))
true
}
@KotlinCleanup("remove ?")
open val backupManager: BackupManager?
get() = BackupManager()
private val mImportAddListener = ImportAddListener(this)
@KotlinCleanup("Migrate from Triple to Kotlin class")
private class ImportAddListener(deckPicker: DeckPicker?) : TaskListenerWithContext<DeckPicker, String, Triple<List<AnkiPackageImporter>?, Boolean, String?>?>(deckPicker) {
override fun actualOnPostExecute(context: DeckPicker, result: Triple<List<AnkiPackageImporter>?, Boolean, String?>?) {
if (context.mProgressDialog != null && context.mProgressDialog!!.isShowing) {
context.mProgressDialog!!.dismiss()
}
// If result.second and result are both set, we are signalling
// some files were imported successfully & some errors occurred.
// If result.first is null & result.second & result.third is set
// we are signalling all the files which were selected threw error
if (result!!.first == null && result.second && result.third != null) {
Timber.w("Import: Add Failed: %s", result.third)
context.showSimpleMessageDialog(result.third)
} else {
Timber.i("Import: Add succeeded")
var fileCount = 0
var totalCardCount = 0
var errorMsg = ""
for (data in result.first!!) {
// Check if mLog is not null or empty
// If mLog is not null or empty that indicates an error has occurred.
if (data.log.isNullOrEmpty()) {
fileCount += 1
totalCardCount += data.cardCount
} else { errorMsg += data.fileName + "\n" + data.log[0] + "\n" }
}
var dialogMsg = context.resources.getQuantityString(R.plurals.import_complete_message, fileCount, fileCount, totalCardCount)
if (result.third != null) {
errorMsg += result.third
}
if (errorMsg.isNotEmpty()) {
dialogMsg += "\n\n" + context.resources.getString(R.string.import_stats_error, errorMsg)
}
context.showSimpleMessageDialog(dialogMsg)
context.updateDeckList()
}
}
override fun actualOnPreExecute(context: DeckPicker) {
if (context.mProgressDialog == null || !context.mProgressDialog!!.isShowing) {
context.mProgressDialog = StyledProgressDialog.show(
context,
context.resources.getString(R.string.import_title), null, false
)
}
}
override fun actualOnProgressUpdate(context: DeckPicker, value: String) {
@Suppress("Deprecation")
context.mProgressDialog!!.setMessage(value)
}
}
private fun importReplaceListener(): ImportReplaceListener {
return ImportReplaceListener(this)
}
private class ImportReplaceListener(deckPicker: DeckPicker?) : TaskListenerWithContext<DeckPicker, String, Computation<*>?>(deckPicker) {
override fun actualOnPostExecute(context: DeckPicker, result: Computation<*>?) {
Timber.i("Import: Replace Task Completed")
if (context.mProgressDialog != null && context.mProgressDialog!!.isShowing) {
context.mProgressDialog!!.dismiss()
}
val res = context.resources
if (result!!.succeeded()) {
context.updateDeckList()
} else {
context.showSimpleMessageDialog(res.getString(R.string.import_log_no_apkg), reload = true)
}
}
override fun actualOnPreExecute(context: DeckPicker) {
if (context.mProgressDialog == null || !context.mProgressDialog!!.isShowing) {
context.mProgressDialog = StyledProgressDialog.show(
context,
context.resources.getString(R.string.import_title),
context.resources.getString(R.string.import_replacing), false
)
}
}
/**
* @param value A message
*/
override fun actualOnProgressUpdate(context: DeckPicker, value: String) {
@Suppress("Deprecation")
context.mProgressDialog!!.setMessage(value)
}
}
// ----------------------------------------------------------------------------
// ANDROID ACTIVITY METHODS
// ----------------------------------------------------------------------------
/** Called when the activity is first created. */
@Throws(SQLException::class)
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
Timber.d("onCreate()")
mExportingDelegate = ActivityExportingDelegate(this) { col }
mCustomStudyDialogFactory = CustomStudyDialogFactory({ col }, this).attachToActivity(this)
mContextMenuFactory = DeckPickerContextMenu.Factory { col }.attachToActivity(this)
// Then set theme and content view
super.onCreate(savedInstanceState)
// handle the first load: display the app introduction
if (!hasShownAppIntro()) {
val appIntro = Intent(this, IntroductionActivity::class.java)
appIntro.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivityWithoutAnimation(appIntro)
finish() // calls onDestroy() immediately
return
}
if (intent.hasExtra(INTENT_SYNC_FROM_LOGIN)) {
mSyncOnResume = true
}
setContentView(R.layout.homescreen)
handleStartup()
val mainView = findViewById<View>(android.R.id.content)
// check, if tablet layout
mStudyoptionsFrame = findViewById(R.id.studyoptions_fragment)
// set protected variable from NavigationDrawerActivity
fragmented = mStudyoptionsFrame != null && mStudyoptionsFrame!!.visibility == View.VISIBLE
// Open StudyOptionsFragment if in fragmented mode
if (fragmented && !mStartupError) {
loadStudyOptionsFragment(false)
}
registerExternalStorageListener()
// create inherited navigation drawer layout here so that it can be used by parent class
initNavigationDrawer(mainView)
title = resources.getString(R.string.app_name)
mDeckPickerContent = findViewById(R.id.deck_picker_content)
mRecyclerView = findViewById(R.id.files)
mNoDecksPlaceholder = findViewById(R.id.no_decks_placeholder)
mDeckPickerContent.visibility = View.GONE
mNoDecksPlaceholder.visibility = View.GONE
// specify a LinearLayoutManager and set up item dividers for the RecyclerView
mRecyclerViewLayoutManager = LinearLayoutManager(this)
mRecyclerView.layoutManager = mRecyclerViewLayoutManager
val ta = this.obtainStyledAttributes(intArrayOf(R.attr.deckDivider))
val divider = ta.getDrawable(0)
ta.recycle()
val dividerDecorator = DividerItemDecoration(this, mRecyclerViewLayoutManager.orientation)
dividerDecorator.setDrawable(divider!!)
mRecyclerView.addItemDecoration(dividerDecorator)
// Add background to Deckpicker activity
val view = if (fragmented) findViewById(R.id.deckpicker_xl_view) else findViewById<View>(R.id.root_layout)
var hasDeckPickerBackground = false
try {
hasDeckPickerBackground = applyDeckPickerBackground(view)
} catch (e: OutOfMemoryError) { // 6608 - OOM should be catchable here.
Timber.w(e, "Failed to apply background - OOM")
showThemedToast(this, getString(R.string.background_image_too_large), false)
} catch (e: Exception) {
Timber.w(e, "Failed to apply background")
showThemedToast(this, getString(R.string.failed_to_apply_background_image, e.localizedMessage), false)
}
// create and set an adapter for the RecyclerView
mDeckListAdapter = DeckAdapter(layoutInflater, this).apply {
setDeckClickListener(mDeckClickListener)
setCountsClickListener(mCountsClickListener)
setDeckExpanderClickListener(mDeckExpanderClickListener)
setDeckLongClickListener(mDeckLongClickListener)
enablePartialTransparencyForBackground(hasDeckPickerBackground)
}
mRecyclerView.adapter = mDeckListAdapter
mPullToSyncWrapper = findViewById<SwipeRefreshLayout?>(R.id.pull_to_sync_wrapper).apply {
setDistanceToTriggerSync(SWIPE_TO_SYNC_TRIGGER_DISTANCE)
setOnRefreshListener {
Timber.i("Pull to Sync: Syncing")
mPullToSyncWrapper.isRefreshing = false
sync()
}
viewTreeObserver.addOnScrollChangedListener {
mPullToSyncWrapper.isEnabled = mRecyclerViewLayoutManager.findFirstCompletelyVisibleItemPosition() == 0
}
}
// Setup the FloatingActionButtons, should work everywhere with min API >= 15
mFloatingActionMenu = DeckPickerFloatingActionMenu(this, view, this)
mReviewSummaryTextView = findViewById(R.id.today_stats_text_view)
mShortAnimDuration = resources.getInteger(android.R.integer.config_shortAnimTime)
Onboarding.DeckPicker(this, mRecyclerViewLayoutManager).onCreate()
}
private fun hasShownAppIntro(): Boolean {
val prefs = AnkiDroidApp.getSharedPrefs(this)
// if moving from 2.15 to 2.16 then we do not want to show the intro
// remove this after ~2.17 and default to 'false' if the pref is not set
if (!prefs.contains(IntroductionActivity.INTRODUCTION_SLIDES_SHOWN)) {
return if (!InitialActivity.wasFreshInstall(prefs)) {
prefs.edit { putBoolean(IntroductionActivity.INTRODUCTION_SLIDES_SHOWN, true) }
true
} else {
false
}
}
return prefs.getBoolean(IntroductionActivity.INTRODUCTION_SLIDES_SHOWN, false)
}
/**
* The first call in showing dialogs for startup - error or success.
* Attempts startup if storage permission has been acquired, else, it requests the permission
*/
fun handleStartup() {
if (hasStorageAccessPermission(this)) {
val failure = InitialActivity.getStartupFailureType(this)
mStartupError = if (failure == null) {
// Show any necessary dialogs (e.g. changelog, special messages, etc)
val sharedPrefs = AnkiDroidApp.getSharedPrefs(this)
showStartupScreensAndDialogs(sharedPrefs, 0)
false
} else {
// Show error dialogs
handleStartupFailure(failure)
true
}
} else {
requestStoragePermission()
}
if (!BackendFactory.defaultLegacySchema) {
CustomSyncServer.setOrUnsetEnvironmentalVariablesForBackend(this)
}
}
@VisibleForTesting
fun handleStartupFailure(failure: StartupFailure?) {
when (failure) {
SD_CARD_NOT_MOUNTED -> {
Timber.i("SD card not mounted")
onSdCardNotMounted()
}
DIRECTORY_NOT_ACCESSIBLE -> {
Timber.i("AnkiDroid directory inaccessible")
val i = AdvancedSettingsFragment.getSubscreenIntent(this)
startActivityForResultWithoutAnimation(i, REQUEST_PATH_UPDATE)
showThemedToast(this, R.string.directory_inaccessible, false)
}
FUTURE_ANKIDROID_VERSION -> {
Timber.i("Displaying database versioning")
showDatabaseErrorDialog(DatabaseErrorDialog.INCOMPATIBLE_DB_VERSION)
}
DATABASE_LOCKED -> {
Timber.i("Displaying database locked error")
showDatabaseErrorDialog(DatabaseErrorDialog.DIALOG_DB_LOCKED)
}
WEBVIEW_FAILED -> MaterialDialog(this).show {
title(R.string.ankidroid_init_failed_webview_title)
message(
text = getString(
R.string.ankidroid_init_failed_webview,
AnkiDroidApp.webViewErrorMessage
)
)
positiveButton(R.string.close) {
exit()
}
cancelable(false)
}
DB_ERROR -> displayDatabaseFailure()
else -> displayDatabaseFailure()
}
}
fun displayDatabaseFailure() {
Timber.i("Displaying database error")
showDatabaseErrorDialog(DatabaseErrorDialog.DIALOG_LOAD_FAILED)
}
// throws doesn't seem to be checked by the compiler - consider it to be documentation
@Throws(OutOfMemoryError::class)
private fun applyDeckPickerBackground(view: View): Boolean {
// Allow the user to clear data and get back to a good state if they provide an invalid background.
if (!AnkiDroidApp.getSharedPrefs(this).getBoolean("deckPickerBackground", false)) {
Timber.d("No DeckPicker background preference")
view.setBackgroundResource(0)
return false
}
val currentAnkiDroidDirectory = CollectionHelper.getCurrentAnkiDroidDirectory(this)
val imgFile = File(currentAnkiDroidDirectory, "DeckPickerBackground.png")
return if (!imgFile.exists()) {
Timber.d("No DeckPicker background image")
view.setBackgroundResource(0)
false
} else {
Timber.i("Applying background")
val drawable = Drawable.createFromPath(imgFile.absolutePath)
view.background = drawable
true
}
}
fun requestStoragePermission() {
fun showStoragePermissionDialog() {
val storagePermissions = arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
ActivityCompat.requestPermissions(this, storagePermissions, REQUEST_STORAGE_PERMISSION)
}
val sharedPrefs = AnkiDroidApp.getSharedPrefs(this)
val welcomeDialogDismissed = sharedPrefs.getBoolean("welcomeDialogDismissed", false)
if (welcomeDialogDismissed) {
// DEFECT #5847: This fails if the activity is killed.
// Even if the dialog is showing, we want to show it again.
showStoragePermissionDialog()
return
}
Timber.i("Displaying initial permission request dialog")
// Request storage permission if we don't have it (e.g. on Android 6.0+)
MaterialDialog(this).show {
title(R.string.collection_load_welcome_request_permissions_title)
message(R.string.collection_load_welcome_request_permissions_details)
positiveButton(R.string.dialog_ok) {
sharedPrefs.edit { putBoolean("welcomeDialogDismissed", true) }
showStoragePermissionDialog()
}
cancelable(false)
cancelOnTouchOutside(false)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
Timber.d("onCreateOptionsMenu()")
mFloatingActionMenu.closeFloatingActionMenu()
menuInflater.inflate(R.menu.deck_picker, menu)
setupSearchIcon(menu.findItem(R.id.deck_picker_action_filter))
// redraw menu synchronously to avoid flicker
updateMenuFromState(menu)
// ...then launch a task to possibly update the visible icons.
// Store the job so that tests can easily await it. In the future
// this may be better done by injecting a custom test scheduler
// into CollectionManager, and awaiting that.
createMenuJob = launchCatchingTask {
updateMenuState()
updateMenuFromState(menu)
}
return super.onCreateOptionsMenu(menu)
}
private fun setupSearchIcon(menuItem: MenuItem) {
menuItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
// When SearchItem is expanded
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
Timber.i("DeckPicker:: SearchItem opened")
// Hide the floating action button if it is visible
mFloatingActionMenu.hideFloatingActionButton()
return true
}
// When SearchItem is collapsed
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
Timber.i("DeckPicker:: SearchItem closed")
// Show the floating action button if it is hidden
mFloatingActionMenu.showFloatingActionButton()
return true
}
})
(menuItem.actionView as SearchView).run {
queryHint = getString(R.string.search_decks)
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
clearFocus()
return true
}
override fun onQueryTextChange(newText: String): Boolean {
val adapter = mRecyclerView.adapter as Filterable?
adapter!!.filter.filter(newText)
return true
}
})
}
searchDecksIcon = menuItem
}
private fun updateMenuFromState(menu: Menu) {
menu.setGroupVisible(R.id.allItems, optionsMenuState != null)
optionsMenuState?.run {
menu.findItem(R.id.deck_picker_action_filter).isVisible = searchIcon
updateUndoIconFromState(menu.findItem(R.id.action_undo), undoIcon)
updateSyncIconFromState(menu.findItem(R.id.action_sync), syncIcon)
}
}
private fun updateUndoIconFromState(menuItem: MenuItem, undoTitle: String?) {
menuItem.run {
if (undoTitle != null) {
isVisible = true
title = resources.getString(R.string.studyoptions_congrats_undo, undoTitle)
} else {
isVisible = false
}
}
}
private fun updateSyncIconFromState(menuItem: MenuItem, syncIcon: SyncIconState) {
when (syncIcon) {
SyncIconState.Normal -> {
BadgeDrawableBuilder.removeBadge(menuItem)
menuItem.setTitle(R.string.button_sync)
}
SyncIconState.PendingChanges -> {
BadgeDrawableBuilder(resources)
.withColor(ContextCompat.getColor(this@DeckPicker, R.color.badge_warning))
.replaceBadge(menuItem)
menuItem.setTitle(R.string.button_sync)
}
SyncIconState.FullSync, SyncIconState.NotLoggedIn -> {
BadgeDrawableBuilder(resources)
.withText('!')
.withColor(ContextCompat.getColor(this@DeckPicker, R.color.badge_error))
.replaceBadge(menuItem)
if (syncIcon == SyncIconState.FullSync) {
menuItem.setTitle(R.string.sync_menu_title_full_sync)
} else {
menuItem.setTitle(R.string.sync_menu_title_no_account)
}
}
}
}
@VisibleForTesting
suspend fun updateMenuState() {
optionsMenuState = withOpenColOrNull {
val searchIcon = decks.count() >= 10
val undoIcon = undoName(resources).let {
if (it.isEmpty()) {
null
} else {
it
}
}
val syncIcon = fetchSyncStatus(col)
OptionsMenuState(searchIcon, undoIcon, syncIcon)
}
}
private fun fetchSyncStatus(col: Collection): SyncIconState {
val auth = syncAuth()
val syncStatus = SyncStatus.getSyncStatus(col, auth)
return when (syncStatus) {
SyncStatus.BADGE_DISABLED, SyncStatus.NO_CHANGES, SyncStatus.INCONCLUSIVE -> {
SyncIconState.Normal
}
SyncStatus.HAS_CHANGES -> {
SyncIconState.PendingChanges
}
SyncStatus.NO_ACCOUNT -> SyncIconState.NotLoggedIn
SyncStatus.FULL_SYNC -> SyncIconState.FullSync
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
mFloatingActionMenu.closeFloatingActionMenu()
if (drawerToggle.onOptionsItemSelected(item)) {
return true
}
when (item.itemId) {
R.id.action_undo -> {
Timber.i("DeckPicker:: Undo button pressed")
undo()
return true
}
R.id.deck_picker_action_filter -> {
Timber.i("DeckPicker:: Search button pressed")
return true
}
R.id.action_sync -> {
Timber.i("DeckPicker:: Sync button pressed")
sync()
return true
}
R.id.action_import -> {
Timber.i("DeckPicker:: Import button pressed")
showDialogFragment(ImportFileSelectionFragment.createInstance(this))
return true
}
R.id.action_new_filtered_deck -> {
val createFilteredDeckDialog = CreateDeckDialog(this@DeckPicker, R.string.new_deck, CreateDeckDialog.DeckDialogType.FILTERED_DECK, null)
createFilteredDeckDialog.setOnNewDeckCreated {
// a filtered deck was created
openStudyOptions(true)
}
createFilteredDeckDialog.showFilteredDeckDialog()
return true
}
R.id.action_check_database -> {
Timber.i("DeckPicker:: Check database button pressed")
showDatabaseErrorDialog(DatabaseErrorDialog.DIALOG_CONFIRM_DATABASE_CHECK)
return true
}
R.id.action_check_media -> {
Timber.i("DeckPicker:: Check media button pressed")
showMediaCheckDialog(MediaCheckDialog.DIALOG_CONFIRM_MEDIA_CHECK)
return true
}
R.id.action_empty_cards -> {
Timber.i("DeckPicker:: Empty cards button pressed")
handleEmptyCards()
return true
}
R.id.action_model_browser_open -> {
Timber.i("DeckPicker:: Model browser button pressed")
val noteTypeBrowser = Intent(this, ModelBrowser::class.java)
startActivityForResultWithAnimation(noteTypeBrowser, 0, START)
return true
}
R.id.action_restore_backup -> {
Timber.i("DeckPicker:: Restore from backup button pressed")
showDatabaseErrorDialog(DatabaseErrorDialog.DIALOG_CONFIRM_RESTORE_BACKUP)
return true
}
R.id.action_export -> {
Timber.i("DeckPicker:: Export collection button pressed")
val msg = resources.getString(R.string.confirm_apkg_export)
mExportingDelegate.showExportDialog(msg)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
@Deprecated("Deprecated in Java")
@Suppress("deprecation") // onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_MEDIA_EJECTED) {
onSdCardNotMounted()
return
} else if (resultCode == RESULT_DB_ERROR) {
handleDbError()
return
}
if (requestCode == SHOW_INFO_NEW_VERSION) {
showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(baseContext), 3)
} else if (requestCode == LOG_IN_FOR_SYNC && resultCode == RESULT_OK) {
mSyncOnResume = true
} else if (requestCode == REQUEST_REVIEW || requestCode == SHOW_STUDYOPTIONS) {
if (resultCode == AbstractFlashcardViewer.RESULT_NO_MORE_CARDS) {
// Show a message when reviewing has finished
if (col.sched.count() == 0) {
showSnackbar(R.string.studyoptions_congrats_finished)
} else {
showSnackbar(R.string.studyoptions_no_cards_due)
}
} else if (resultCode == AbstractFlashcardViewer.RESULT_ABORT_AND_SYNC) {
Timber.i("Obtained Abort and Sync result")
TaskManager.waitForAllToFinish(4)
sync()
}
} else if (requestCode == REQUEST_PATH_UPDATE) {
// The collection path was inaccessible on startup so just close the activity and let user restart
finishWithoutAnimation()
} else if (requestCode == PICK_APKG_FILE && resultCode == RESULT_OK) {
val importResult = ImportUtils.handleFileImport(this, data!!)
if (!importResult.isSuccess) {
ImportUtils.showImportUnsuccessfulDialog(this, importResult.humanReadableMessage, false)
}
} else if (requestCode == PICK_CSV_FILE && resultCode == RESULT_OK) {
val path = ImportUtils.getFileCachedCopy(this, data!!) ?: return
startActivity(CsvImporter.getIntent(this, path))
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_STORAGE_PERMISSION && permissions.isNotEmpty()) {
if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
invalidateOptionsMenu()
handleStartup()
} else {
// User denied access to file storage so show error toast and display "App Info"
showThemedToast(this, R.string.startup_no_storage_permission, false)
finishWithoutAnimation()
// Open the Android settings page for our app so that the user can grant the missing permission
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivityWithoutAnimation(intent)
}
}
}
override fun onResume() {
Timber.d("onResume()")
super.onResume()
refreshState()
}
fun refreshState() {
mActivityPaused = false
// Due to the App Introduction, this may be called before permission has been granted.
if (mSyncOnResume && hasStorageAccessPermission(this)) {
Timber.i("Performing Sync on Resume")
sync()
mSyncOnResume = false
} else if (colIsOpen()) {
selectNavigationItem(R.id.nav_decks)
if (dueTree == null) {
updateDeckList(true)
}
updateDeckList()
title = resources.getString(R.string.app_name)
}
/* Complete task and enqueue fetching nonessential data for
startup. */
if (colIsOpen()) {
launchCatchingTask { withCol { CollectionHelper.loadCollectionComplete(col) } }
}
// Update sync status (if we've come back from a screen)
invalidateOptionsMenu()
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putBoolean("mIsFABOpen", mFloatingActionMenu.isFABOpen)
}
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
mFloatingActionMenu.isFABOpen = savedInstanceState.getBoolean("mIsFABOpen")
}
override fun onPause() {
Timber.d("onPause()")
mActivityPaused = true
// The deck count will be computed on resume. No need to compute it now
TaskManager.cancelAllTasks(LoadDeckCounts::class.java)
super.onPause()
}
override fun onStop() {
Timber.d("onStop()")
super.onStop()
if (colIsOpen()) {
WidgetStatus.update(this)
// Ignore the modification - a change in deck shouldn't trigger the icon for "pending changes".
saveCollectionInBackground(true)
}
}
override fun onDestroy() {
super.onDestroy()
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver)
}
if (mProgressDialog != null && mProgressDialog!!.isShowing) {
mProgressDialog!!.dismiss()
}
Timber.d("onDestroy()")
}
private fun automaticSync() {
val preferences = AnkiDroidApp.getSharedPrefs(baseContext)
// Check whether the option is selected, the user is signed in, last sync was AUTOMATIC_SYNC_TIME ago
// (currently 10 minutes), and is not under a metered connection (if not allowed by preference)
val isLoggedIn = preferences.getString("hkey", "")!!.isNotEmpty()
val lastSyncTime = preferences.getLong("lastSyncTime", 0)
val autoSyncIsEnabled = preferences.getBoolean("automaticSyncMode", false)
val syncIntervalPassed = TimeManager.time.intTimeMS() - lastSyncTime > AUTOMATIC_SYNC_MIN_INTERVAL
val isNotBlockedByMeteredConnection = preferences.getBoolean(getString(R.string.metered_sync_key), false) || !isActiveNetworkMetered()
if (isLoggedIn && autoSyncIsEnabled && NetworkUtils.isOnline && syncIntervalPassed && isNotBlockedByMeteredConnection) {
Timber.i("Triggering Automatic Sync")
sync()
}
}
override fun onBackPressed() {
val preferences = AnkiDroidApp.getSharedPrefs(baseContext)
if (isDrawerOpen) {
super.onBackPressed()
} else {
Timber.i("Back key pressed")
if (mFloatingActionMenu.isFABOpen) {
mFloatingActionMenu.closeFloatingActionMenu()
} else {
if (!preferences.getBoolean("exitViaDoubleTapBack", false) || mBackButtonPressedToExit) {
automaticSync()
finishWithAnimation()
} else {
showSnackbar(R.string.back_pressed_once, Snackbar.LENGTH_SHORT)
}
mBackButtonPressedToExit = true
HandlerUtils.executeFunctionWithDelay(Consts.SHORT_TOAST_DURATION) { mBackButtonPressedToExit = false }
}
}
}
private fun finishWithAnimation() {
super.finishWithAnimation(DEFAULT)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (mToolbarSearchView != null && mToolbarSearchView!!.hasFocus()) {