-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathAnkiDroidApp.kt
More file actions
666 lines (590 loc) · 25.9 KB
/
Copy pathAnkiDroidApp.kt
File metadata and controls
666 lines (590 loc) · 25.9 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
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright (c) 2009 Edu Zamora <edu.zasu@gmail.com>
// SPDX-FileCopyrightText: Copyright (c) 2009 Casey Link <unnamedrambler@gmail.com>
// SPDX-FileCopyrightText: Copyright (c) 2014 Timothy Rae <perceptualchaos2@gmail.com>
package com.ichi2.anki
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Resources
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.system.Os
import android.webkit.CookieManager
import androidx.annotation.VisibleForTesting
import androidx.core.net.toUri
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ProcessLifecycleOwner
import anki.collection.OpChanges
import com.ichi2.anki.AnkiDroidApp.Companion.sharedPreferencesTestingOverride
import com.ichi2.anki.analytics.UsageAnalytics
import com.ichi2.anki.browser.SharedPreferencesLastDeckIdRepository
import com.ichi2.anki.common.android.AdaptionUtil
import com.ichi2.anki.common.android.Animations
import com.ichi2.anki.common.android.ApplicationContextInitializer
import com.ichi2.anki.common.android.getCurrentLocaleTag
import com.ichi2.anki.common.android.withAppLocale
import com.ichi2.anki.common.annotations.LegacyNotifications
import com.ichi2.anki.common.annotations.NeedsTest
import com.ichi2.anki.common.coroutines.applicationScope
import com.ichi2.anki.common.crashreporting.CrashReportService.sendExceptionReport
import com.ichi2.anki.common.permissions.hasLegacyStorageAccessPermission
import com.ichi2.anki.common.preferences.sharedPrefs
import com.ichi2.anki.common.storage.CollectionHelper
import com.ichi2.anki.common.utils.android.SdCard
import com.ichi2.anki.common.utils.android.showThemedToast
import com.ichi2.anki.common.utils.annotation.KotlinCleanup
import com.ichi2.anki.compat.CompatHelper
import com.ichi2.anki.contextmenu.AnkiCardContextMenu
import com.ichi2.anki.contextmenu.CardBrowserContextMenu
import com.ichi2.anki.exception.StorageAccessException
import com.ichi2.anki.exception.SystemStorageException
import com.ichi2.anki.logging.FragmentLifecycleLogger
import com.ichi2.anki.logging.LogType
import com.ichi2.anki.logging.ProductionCrashReportingTree
import com.ichi2.anki.logging.RobolectricDebugTree
import com.ichi2.anki.navigation.initializeNavigator
import com.ichi2.anki.observability.ChangeManager
import com.ichi2.anki.preferences.SharedPreferencesProvider
import com.ichi2.anki.servicelayer.DebugInfoService
import com.ichi2.anki.servicelayer.ThrowableFilterService
import com.ichi2.anki.services.AlarmManagerService
import com.ichi2.anki.services.NotificationService
import com.ichi2.anki.settings.Prefs
import com.ichi2.anki.settings.PrefsRepository
import com.ichi2.anki.startup.ensureCollectionPathSet
import com.ichi2.anki.startup.getDefaultAnkiDroidDirectory
import com.ichi2.anki.ui.dialogs.ActivityAgnosticDialogs
import com.ichi2.utils.ExceptionUtil
import com.ichi2.utils.LanguageUtil
import com.ichi2.utils.measureTime
import com.ichi2.utils.setWebContentsDebuggingEnabled
import com.ichi2.widget.DayRolloverAlarm
import com.ichi2.widget.cardanalysis.CardAnalysisWidget
import com.ichi2.widget.deckpicker.DeckPickerWidget
import com.ichi2.widget.restoreRecurringAlarms
import kotlinx.coroutines.launch
import timber.log.Timber
import timber.log.Timber.DebugTree
import java.util.Locale
/**
* Application class.
*/
@KotlinCleanup("IDE Lint")
open class AnkiDroidApp :
Application(),
ChangeManager.Subscriber {
/** An exception if AnkiDroidApp fails to load */
private var fatalInitializationError: FatalInitializationError? = null
@LegacyNotifications("The widget triggers notifications by posting null to this, but we plan to stop relying on the widget")
private val notifications = MutableLiveData<Void?>()
lateinit var activityAgnosticDialogs: ActivityAgnosticDialogs
val sharedPrefsLastDeckIdRepository = SharedPreferencesLastDeckIdRepository()
/** Used to avoid showing extra progress dialogs when one already shown. */
var progressDialogShown = false
/**
* Executes a setup method: [block], logging execution time.
* Exceptions are logged and rethrown.
*
* @param methodName Method name, used for logging.
* @param block The method to execute and return
*/
// 'inline fun' so logs use the correct context
inline fun <T> setup(
methodName: String,
crossinline block: () -> T,
): T {
// TODO: #20168 warn users of non-fatal component errors rather than rethrowing
try {
return measureTime(methodName = methodName) { block() }
} catch (e: Exception) {
// NOTE: this can be called before Timber is initialized
Timber.w(e, "failed to execute $methodName")
throw e
}
}
/**
* On application creation, i.e. when the application process starts.
* This is called before any activities, services, or receivers are created.
*/
@KotlinCleanup("analytics can be moved to attachBaseContext()")
override fun onCreate() {
initAnkiBackend(debugTraceSqlCalls = false)
super.onCreate()
if (!setupAnkiDroidApp()) {
return
}
ApplicationContextInitializer.setInstance(this)
initializeAcraCrashReporter()
initializeNavigator()
Animations.setPreferencesProvider { context -> PrefsRepository(context) }
val logType = LogType.value
when (logType) {
LogType.DEBUG -> Timber.plant(DebugTree())
LogType.ROBOLECTRIC -> Timber.plant(RobolectricDebugTree())
LogType.PRODUCTION -> Timber.plant(ProductionCrashReportingTree())
}
if (BuildConfig.ENABLE_LEAK_CANARY) {
LeakCanaryConfiguration.setInitialConfigFor(this)
} else {
LeakCanaryConfiguration.disable()
}
Timber.tag(TAG)
Timber.d("Startup - Application Start")
Timber.i("Timber config: $logType")
// analytics after ACRA, they both install UncaughtExceptionHandlers but Analytics chains while ACRA does not
UsageAnalytics.initialize(this)
if (BuildConfig.DEBUG) {
UsageAnalytics.setDryRun(true)
}
// Last in the UncaughtExceptionHandlers chain is our filter service
ThrowableFilterService.initialize()
applicationScope.launch {
Timber.i("AnkiDroidApp: listing debug info")
Timber.i(DebugInfoService.getDebugInfo(this@AnkiDroidApp))
}
// Stop after analytics and logging are initialised.
if (isAcraSenderProcess()) {
Timber.d("Skipping AnkiDroidApp.onCreate from ACRA sender process")
return
}
if (AdaptionUtil.isUserATestClient) {
showThemedToast(this.applicationContext, getString(R.string.user_is_a_robot), false)
}
setWebContentsDebuggingEnabled(Prefs.isWebDebugEnabled)
setupContextMenus()
setup("makeBackendUsable") { makeBackendUsable(this) }
setupNotifications()
setupAppLifecycleObserver()
setupBackendChangeManager()
// Probe WebView availability before any other init touches it (#5794).
if (!checkWebViewAvailable()) {
return
}
// Forget the last deck that was used in the CardBrowser
CardBrowser.clearLastDeckId()
val anki = AnkiContext.apply { setupAnkiBackend() }
with(anki) { initializeAnkiDroidDirectory() }
with(anki) { setupDayRollover() }
restoreRecurringAlarms(this)
setupLifecycleLogging()
activityAgnosticDialogs = ActivityAgnosticDialogs.register(this)
setupTextToSpeech()
}
/**
* @param debugTraceSqlCalls Log all SQL statements executed by the backend.
* **Warning** The log may be delayed by 100ms, so you should not assume than a given SQL
* statement has run after a Timber.* line just because the SQL statement appeared later.
*/
private fun initAnkiBackend(
@Suppress("SameParameterValue") debugTraceSqlCalls: Boolean = false,
) {
runCatching {
setup(methodName = "initAnkiBackend") {
// Note: This method runs before logs are enabled.
Os.setenv("PLATFORM", syncPlatform(), false)
// enable debug logging of sync actions
if (BuildConfig.DEBUG) {
Os.setenv("RUST_LOG", "info,anki::sync=debug,anki::media=debug,fsrs=error", false)
}
if (debugTraceSqlCalls) {
Os.setenv("TRACESQL", "1", false)
}
}
}
}
/**
* Sets [isInitialized] to `true` ([instance] != null)
*
* [onCreate] can be called multiple times due to ACRA using a separate sender process
*
* @return false if `instance.resources` is unusable
*/
private fun setupAnkiDroidApp(): Boolean {
return setup("setupAnkiDroidApp") {
if (isInitialized) {
Timber.i("onCreate() called multiple times")
// 5887 - fix crash.
if (instance.resources == null) {
Timber.w("Skipping re-initialisation - no resources. Maybe uninstalling app?")
return@setup false
}
}
instance = this
true
}
}
/**
* Manually initializes the collection directory and `.nomedia` if
* [hasLegacyStorageAccessPermission] is set
*
* On failure, sets [fatalInitializationError] to [storageError][FatalInitializationError.StorageError]
*
* In most cases the Anki Backend now creates the collection and [initializeAnkiDroidDirectory]
* is called on startup of the activity.
*/
context(_: AnkiContext)
private fun initializeAnkiDroidDirectory() =
setup("initializeAnkiDroidDirectory") {
// #13207: `getCurrentAnkiDroidDirectory` failing is an unconditional be a fatal error
// TODO: For now, a null getExternalFilesDir, but a valid AnkiDroid Directory in prefs
// is not considered to be a fatal error, unless the directory itself is not writable.
val ankiDroidDir =
try {
ensureCollectionPathSet(this)
CollectionHelper.getCurrentAnkiDroidDirectory(this)
} catch (e: SystemStorageException) {
fatalInitializationError = FatalInitializationError.StorageError(e)
return@setup
}
// TODO: This line is questionable, as it doesn't work on most post-scoped-storage
// builds/Android versions, but we call initializeAnkiDroidDirectory later on startup
if (!hasLegacyStorageAccessPermission(this)) return@setup
try {
CollectionHelper.initializeAnkiDroidDirectory(ankiDroidDir)
return@setup
} catch (e: StorageAccessException) {
Timber.e(e, "Could not initialize AnkiDroid directory")
try {
val defaultDir = getDefaultAnkiDroidDirectory(this)
if (SdCard.isMounted && CollectionHelper.getCurrentAnkiDroidDirectory(this) == defaultDir) {
// Don't send report if the user is using a custom directory as SD cards trip up here a lot
sendExceptionReport(e, "AnkiDroidApp.onCreate")
}
} catch (e: SystemStorageException) {
// The user can't write to the AnkiDroid directory (=> cant write to the collection)
// AND getExternalFilesDir is null - file permissions are likely corrupted (Android 16 bug)
// => show the 'fatal storage error' screen
fatalInitializationError = FatalInitializationError.StorageError(e)
}
}
}
/**
* Sets up display of the context menus which appear when long pressing text on external apps,
* allowing it to be shared to this app.
*
* Example: 'Anki Card'
*
* @see Intent.ACTION_PROCESS_TEXT
*/
private fun setupContextMenus() =
setup("setupContextMenus") {
val preferences = this.sharedPrefs()
// setup 'Card Browser'
CardBrowserContextMenu.ensureConsistentStateWithPreferenceStatus(
this,
preferences.getBoolean(
getString(R.string.card_browser_external_context_menu_key),
false,
),
)
// Setup 'Anki Card'
AnkiCardContextMenu.ensureConsistentStateWithPreferenceStatus(
this,
preferences.getBoolean(getString(R.string.anki_card_external_context_menu_key), true),
)
}
private fun setupNotifications() =
setup("setupNotifications") {
setupNotificationChannels(applicationContext)
val context = this.withAppLocale()
if (Prefs.newReviewRemindersEnabled) {
Timber.i("Setting review reminder notifications if they have not already been set")
applicationScope.launch {
AlarmManagerService.scheduleAllNotifications(context)
}
} else {
// Register for notifications
Timber.i("AnkiDroidApp: Starting Services")
notifications.observeForever { NotificationService.triggerNotificationFor(context) }
}
}
private fun setupAppLifecycleObserver() =
setup("setupAppLifecycleObserver") {
val appLifecycleObserver = AppLifecycleObserver(applicationContext)
ProcessLifecycleOwner
.get()
.lifecycle
.addObserver(appLifecycleObserver)
}
/**
* Ensures any changes in the backend are propagated to:
*
* - widgets
*
* @see opExecuted
* @see ChangeManager
*/
private fun setupBackendChangeManager() =
setup("setupBackendChangeManager") {
ChangeManager.subscribe(this)
}
private fun setupAnkiBackend() =
setup("setupAnkiBackend") {
LanguageUtil.setDefaultBackendLanguages()
}
/** Listen for day rollover: time + timezone changes and refresh on the day cutoff. */
context(_: AnkiContext)
private fun setupDayRollover() =
setup("setupDayRollover") {
DayRolloverHandler.listenForRolloverEvents(this)
DayRolloverAlarm.scheduleNext(this)
}
private fun setupLifecycleLogging() =
setup("setupLifecycleLogging") {
registerActivityLifecycleCallbacks(
object : ActivityLifecycleCallbacks {
override fun onActivityCreated(
activity: Activity,
savedInstanceState: Bundle?,
) {
Timber.i(
"${activity::class.simpleName}::onCreate, savedInstanceState: %s",
savedInstanceState?.let { "${it.keySet().size} keys" },
)
(activity as? FragmentActivity)
?.supportFragmentManager
?.registerFragmentLifecycleCallbacks(
FragmentLifecycleLogger(activity),
true,
)
}
override fun onActivityStarted(activity: Activity) {
Timber.i("${activity::class.simpleName}::onStart")
}
override fun onActivityResumed(activity: Activity) {
Timber.i("${activity::class.simpleName}::onResume")
}
override fun onActivityPaused(activity: Activity) {
Timber.i("${activity::class.simpleName}::onPause")
}
override fun onActivityStopped(activity: Activity) {
Timber.i("${activity::class.simpleName}::onStop")
}
override fun onActivitySaveInstanceState(
activity: Activity,
outState: Bundle,
) {
Timber.i("${activity::class.simpleName}::onSaveInstanceState")
}
override fun onActivityDestroyed(activity: Activity) {
Timber.i("${activity::class.simpleName}::onDestroy")
}
},
)
}
private fun setupTextToSpeech() {
setup("setupTextToSpeech") {
TtsVoices.launchBuildLocalesJob()
// enable {{tts-voices:}} field filter
TtsVoicesFieldFilter.ensureApplied()
}
}
/**
* @return the app version, OS version and device model, provided when syncing.
*/
private fun syncPlatform(): String {
// AnkiWeb reads this string and uses , and : as delimiters, so we remove them.
val model = Build.MODEL.replace(',', ' ').replace(':', ' ')
return String.format(
Locale.US,
"android:%s:%s:%s",
BuildConfig.VERSION_NAME,
Build.VERSION.RELEASE,
model,
)
}
@LegacyNotifications("Only used by the widget to trigger notifications, we plan to stop relying on the widget")
fun scheduleNotification() {
notifications.postValue(null)
}
/**
* Checks that [android.webkit.WebView] is usable.
*/
protected fun checkWebViewAvailable(): Boolean =
try {
CookieManager.getInstance()
true
} catch (e: Throwable) {
// 5794: Errors occur if the WebView fails to load
// android.webkit.WebViewFactory.MissingWebViewPackageException.MissingWebViewPackageException
// Error may be excessive, but I expect a UnsatisfiedLinkError to be possible here.
fatalInitializationError = FatalInitializationError.WebViewError(e)
sendExceptionReport(e, "checkWebViewAvailable")
Timber.e(e, "checkWebViewAvailable")
false
}
/**
* Callback method invoked when operations that affect the app state are executed.
* If relevant changes related to the study queues are detected, the Deck Picker Widgets
* are updated accordingly.
*
* @param changes The set of changes that occurred.
* @param handler An optional handler that can be used for custom processing (unused here).
*/
override fun opExecuted(
changes: OpChanges,
handler: Any?,
) {
Timber.d("ChangeSubscriber - opExecuted called with changes: %s", changes)
if (changes.studyQueues) {
DeckPickerWidget.updateDeckPickerWidgets(this)
CardAnalysisWidget.updateCardAnalysisWidgets(this)
} else {
Timber.d("No relevant changes to update the widget")
}
}
/**
* Initialization for the Anki Backend has completed:
* - [initAnkiBackend] - platform environment variables/logging
* - [makeBackendUsable] - load rsdroid.so
* - [setupBackendChangeManager] - change manager is subscribed
* - [setupAnkiBackend] - i18n is set up
*/
object AnkiContext
companion object {
/**
* A [SharedPreferencesProvider] which does not require [onCreate] when run from tests
*
* @see sharedPreferencesTestingOverride
*/
val sharedPreferencesProvider get() = SharedPreferencesProvider { sharedPrefs() }
const val ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android"
// Tag for logging messages.
const val TAG = "AnkiDroid"
/** Singleton instance of this class.
* Note: this may not be initialized if AnkiDroid is run via BackupManager
*/
lateinit var instance: AnkiDroidApp
private set
/**
* An override for Shared Preferences to use for unit tests
*
* This does not depend on an instance of AnkiDroidApp and therefore has no Android
* implementations
*/
@VisibleForTesting
var sharedPreferencesTestingOverride: SharedPreferences? = null
/**
* A test-friendly accessor to Shared Preferences.
*
* In tests, this can avoid an instance of `AnkiDroidApp`, which is slow
* This was added to avoid code churn
*/
fun sharedPrefs() = sharedPreferencesTestingOverride ?: instance.sharedPrefs()
/**
* [sharedPrefs], or `null` if unavailable: [instance] is not initialized when running
* under a test-only [Application] (e.g. `EmptyApplication`) or in pure JVM tests
*/
fun sharedPrefsOrNull(): SharedPreferences? =
sharedPreferencesTestingOverride ?: if (isInitialized) instance.sharedPrefs() else null
/** HACK: Whether an exception report has been thrown - TODO: Rewrite an ACRA Listener to do this */
@VisibleForTesting
var sentExceptionReportHack = false
@get:JvmName("isInitialized")
val isInitialized: Boolean
get() = this::instance.isInitialized
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun simulateRestoreFromBackup() {
val field = AnkiDroidApp::class.java.getDeclaredField("instance")
with(field) {
isAccessible = true
set(field, null)
}
// Mirror reality: when AnkiDroidApp.onCreate doesn't run (the bmgr-restore
// scenario), appContext is also uninitialized.
ApplicationContextInitializer.clearForTesting()
}
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun internalSetInstanceValue(value: AnkiDroidApp) {
val field = AnkiDroidApp::class.java.getDeclaredField("instance")
with(field) {
isAccessible = true
set(field, value)
}
// Production code (AnkiDroidApp.onCreate) sets appContext
// right after AnkiDroidApp.instance. Mirror that in tests so callers using the
// common-side accessor see the same mock.
ApplicationContextInitializer.setInstance(value)
}
/** Load the libraries to allow access to Anki-Android-Backend */
@NeedsTest("Not calling this in the ContentProvider should have failed a test")
fun makeBackendUsable(context: Context) {
// Robolectric uses RustBackendLoader.ensureSetup()
if (Build.FINGERPRINT == "robolectric") return
// Prevent sqlite throwing error 6410 due to the lack of /tmp on Android
Os.setenv("TMPDIR", context.cacheDir.path, false)
// Load backend library
System.loadLibrary("rsdroid")
}
val appResources: Resources
get() = instance.resources
fun getMarketIntent(context: Context): Intent {
val uri =
context.getString(if (CompatHelper.isKindle) R.string.link_market_kindle else R.string.link_market)
val parsed = uri.toUri()
return Intent(Intent.ACTION_VIEW, parsed)
} // TODO actually this can be done by translating "link_help" string for each language when the App is
@VisibleForTesting
fun clearFatalError() {
this.instance.fatalInitializationError = null
}
/**
* Get the url for the properly translated feedback page
* @return
*/
val feedbackUrl: String
get() = // TODO actually this can be done by translating "link_help" string for each language when the App is
// properly translated
when (getCurrentLocaleTag()) {
"ja" -> appResources.getString(R.string.link_help_ja)
"zh" -> appResources.getString(R.string.link_help_zh)
"ar" -> appResources.getString(R.string.link_help_ar)
else -> appResources.getString(R.string.link_help)
} // TODO actually this can be done by translating "link_manual" string for each language when the App is
/**
* Get the url for the properly translated manual
* @return
*/
val manualUrl: String
get() = // TODO actually this can be done by translating "link_manual" string for each language when the App is
// properly translated
when (getCurrentLocaleTag()) {
"ja" -> appResources.getString(R.string.link_manual_ja)
"zh" -> appResources.getString(R.string.link_manual_zh)
"ar" -> appResources.getString(R.string.link_manual_ar)
else -> appResources.getString(R.string.link_manual)
}
/** (optional) set if an unrecoverable error occurs during Application startup */
val fatalError: FatalInitializationError?
get() = instance.fatalInitializationError
}
}
/**
* Types of unrecoverable errors which we want to inform the user of
*/
sealed class FatalInitializationError {
data class WebViewError(
val error: Throwable,
) : FatalInitializationError()
data class StorageError(
val error: SystemStorageException,
) : FatalInitializationError()
/** Advanced/developer-facing string representing the error */
val errorDetail: String
get() =
when (this) {
is WebViewError -> ExceptionUtil.getExceptionMessage(error)
is StorageError -> error.message
}
val infoLink: Uri?
get() =
when (this) {
is WebViewError -> null
is StorageError -> error.infoUri?.toUri()
}
}