diff --git a/app/main/AndroidManifest.xml b/app/main/AndroidManifest.xml
new file mode 100644
index 000000000000..f3a8a19f64df
--- /dev/null
+++ b/app/main/AndroidManifest.xml
@@ -0,0 +1,209 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/main/assets/definition.json b/app/main/assets/definition.json
new file mode 100644
index 000000000000..c522cfd4b85d
--- /dev/null
+++ b/app/main/assets/definition.json
@@ -0,0 +1,14 @@
+{
+ "Latest versions": "",
+ "30": "3.3.2.0",
+ "31": "3.3.2.0",
+ "32": "3.3.2.0",
+ "33": "3.3.2.0",
+ "34": "3.3.2.0",
+ "35": "3.3.2.0",
+ "36": "3.3.2.0",
+ "37": "3.3.2.0",
+ "38": "3.3.2.0",
+ "Expire dates": "",
+ "3.3.0.0": "2025-05-30"
+}
\ No newline at end of file
diff --git a/app/main/assets/logback.xml b/app/main/assets/logback.xml
new file mode 100644
index 000000000000..6726cdd2f100
--- /dev/null
+++ b/app/main/assets/logback.xml
@@ -0,0 +1,38 @@
+
+
+
+
+ ${EXT_FILES_DIR}/AndroidAPS.log
+
+
+ ${EXT_FILES_DIR}/AndroidAPS._%d{yyyy-MM-dd}_%d{HH-mm-ss, aux}_.%i.zip
+
+
+
+ 5MB
+
+
+ 120
+
+
+ %d{HH:mm:ss.SSS} [%thread] %.-1level/%logger: %msg%n
+
+
+
+
+
+ %logger{0}
+
+
+ [%thread]: %msg%n
+
+
+
+
+
+
+
+
+
diff --git a/app/main/assets/revoked_certs.txt b/app/main/assets/revoked_certs.txt
new file mode 100644
index 000000000000..e9ae7e4d7a45
--- /dev/null
+++ b/app/main/assets/revoked_certs.txt
@@ -0,0 +1,14 @@
+#Demo certificate
+51:6D:12:67:4C:27:F4:9B:9F:E5:42:9B:01:B3:98:E4:66:2B:85:B7:A8:DD:70:32:B7:6A:D7:97:9A:0D:97:10
+#Leaked
+55:5D:70:C9:BE:10:41:7E:4B:01:A9:C4:C6:44:4A:F8:69:71:35:25:ED:95:23:16:C7:15:E8:EB:C6:08:FC:B1
+# àqΣnΖ`ZϼγwÛ/τàΒϳ9Φ'$ΑϵžλUΛ`ÆÌΣЃA
+E0:71:A3:6E:96:60:5A:FC:B3:77:DB:2F:C4:E0:92:F3:39:A6:27:24:91:F5:7E:BB:55:9B:60:C6:CC:A3:03:41
+# 2ΙšÄΠΒϨÒÇeЄtЄЗž-*Ж*ZcHijЊÄœ<|x"Ε
+32:99:61:C4:A0:92:E8:D2:C7:65:04:74:04:17:7E:2D:2A:16:2A:5A:63:48:69:6A:0A:C4:53:3C:7C:78:22:95
+# mςRr¡ЇζΛLφK&ĐΨ5CnЎϴPDñЍŒkϼ{ΨδwВb
+6D:C2:52:72:A1:07:B6:9B:4C:C6:4B:26:10:A8:35:43:6E:0E:F4:50:44:F1:0D:52:6B:FC:7B:A8:B4:77:12:62
+# èΩQ\kné8EΔËZKòΓϳ^ΙÈμXÄ~ÉìϰηmôЉЋ
+E8:A9:51:5C:6B:6E:E9:38:45:94:CB:5A:4B:F2:93:F3:5E:99:C8:BC:58:C4:7E:C9:EC:F0:B7:6D:F4:A2:09:0B
+# gsЂ?ν°ćЅϯk0ϸÇ$rЁ3ΥЕϹϿΘt4βΛmÄ|I´І
+67:73:02:3F:BD:B0:07:05:EF:6B:30:F8:C7:24:72:01:33:A5:15:F9:FF:98:74:34:B2:9B:6D:C4:7C:49:B4:06
diff --git a/app/main/kotlin/app/aaps/AppLanguage.kt b/app/main/kotlin/app/aaps/AppLanguage.kt
new file mode 100644
index 000000000000..64a43786d5c0
--- /dev/null
+++ b/app/main/kotlin/app/aaps/AppLanguage.kt
@@ -0,0 +1,12 @@
+package app.aaps
+
+import app.aaps.core.interfaces.resources.LanguageTag
+
+/**
+ * The language Android should show AAPS in, as a BCP 47 tag, or null for the phone's language.
+ *
+ * [stored] is the AAPS language setting (`StringKey.GeneralLanguage`), with its old values fixed up by
+ * [LanguageTag]. Simple mode always follows the phone.
+ */
+internal fun appLanguageTag(stored: String, simpleMode: Boolean): String? =
+ if (simpleMode) null else LanguageTag.of(stored)
diff --git a/app/main/kotlin/app/aaps/ComposeMainActivity.kt b/app/main/kotlin/app/aaps/ComposeMainActivity.kt
new file mode 100644
index 000000000000..35e923aedc46
--- /dev/null
+++ b/app/main/kotlin/app/aaps/ComposeMainActivity.kt
@@ -0,0 +1,745 @@
+package app.aaps
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.content.ActivityNotFoundException
+import android.content.Intent
+import android.net.Uri
+import android.os.Bundle
+import android.provider.Settings
+import android.view.WindowManager
+import androidx.activity.compose.LocalActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.activity.result.ActivityResultLauncher
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.activity.viewModels
+import androidx.browser.customtabs.CustomTabsIntent
+import androidx.compose.foundation.Image
+import androidx.compose.material3.SnackbarHostState
+import androidx.compose.material3.SnackbarResult
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.res.stringResource
+import androidx.core.app.ActivityCompat
+import androidx.core.net.toUri
+import androidx.fragment.app.FragmentActivity
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import androidx.navigation.NavController
+import androidx.navigation.NavHostController
+import androidx.navigation.compose.NavHost
+import app.aaps.appshell.AapsAppRoot
+import app.aaps.appshell.navigation.AppRoute
+import app.aaps.appshell.navigation.ElementNavigator
+import app.aaps.appshell.navigation.appNavGraph
+import app.aaps.appshell.navigation.handleNotificationAction
+import app.aaps.appshell.navigation.handleQuickLaunchAction
+import app.aaps.appshell.navigation.handleSearchResultClick
+import app.aaps.core.interfaces.bgQualityCheck.BgQualityCheck
+import app.aaps.core.interfaces.clientcontrol.ClientControlActionDispatcher
+import app.aaps.core.interfaces.configuration.Config
+import app.aaps.core.interfaces.configuration.ConfigBuilder
+import app.aaps.core.interfaces.constraints.Objectives
+import app.aaps.core.interfaces.db.PersistenceLayer
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.maintenance.FileListProvider
+import app.aaps.core.interfaces.navigation.ElementType
+import app.aaps.core.interfaces.notifications.AlarmSound
+import app.aaps.core.interfaces.notifications.NotificationId
+import app.aaps.core.interfaces.notifications.NotificationLevel
+import app.aaps.core.interfaces.notifications.NotificationManager
+import app.aaps.core.interfaces.overview.graph.OverviewDataCache
+import app.aaps.core.interfaces.plugin.ActivePlugin
+import app.aaps.core.interfaces.plugin.PluginPermissions
+import app.aaps.core.interfaces.profile.ProfileUtil
+import app.aaps.core.interfaces.protection.ExportPasswordDataStore
+import app.aaps.core.interfaces.protection.PasswordCheck
+import app.aaps.core.interfaces.protection.ProtectionCheck
+import app.aaps.core.interfaces.protection.ProtectionResult
+import app.aaps.core.interfaces.pump.BolusProgressData
+import app.aaps.core.interfaces.queue.CommandQueue
+import app.aaps.core.interfaces.resources.ResourceHelper
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.rx.events.EventShowDialog
+import app.aaps.core.interfaces.source.DexcomBoyda
+import app.aaps.core.interfaces.sync.NsClient
+import app.aaps.core.interfaces.ui.IconsProvider
+import app.aaps.core.interfaces.ui.SnackbarHostPresence
+import app.aaps.core.interfaces.ui.UiInteraction
+import app.aaps.core.interfaces.ui.UiRestart
+import app.aaps.core.interfaces.utils.DateUtil
+import app.aaps.core.interfaces.utils.DecimalFormatter
+import app.aaps.core.interfaces.utils.fabric.FabricPrivacy
+import app.aaps.core.keys.BooleanKey
+import app.aaps.core.keys.StringKey
+import app.aaps.core.keys.interfaces.Preferences
+import app.aaps.core.keys.interfaces.VisibilityContext
+import app.aaps.core.objects.crypto.CryptoUtil
+import app.aaps.core.ui.compose.FallbackViewModelFactory
+import app.aaps.core.ui.compose.MetroAppCompatActivity
+import app.aaps.core.ui.compose.MetroViewModelFactoryOwner
+import app.aaps.core.ui.compose.navigation.NavigationRequest
+import app.aaps.core.ui.compose.pump.PumpCommunicationStatus
+import app.aaps.core.utils.isRunningRealPumpTest
+import app.aaps.implementation.androidNotification.AlarmNotificationManager
+import app.aaps.implementation.plugin.PluginPermissionsImpl
+import app.aaps.implementation.protection.BiometricCheck
+import app.aaps.plugins.automation.AutomationRuntime
+import app.aaps.plugins.configuration.setupwizard.SWDefinition
+import app.aaps.plugins.source.DexcomPlugin
+import app.aaps.plugins.source.activities.RequestDexcomPermissionActivity
+import app.aaps.settingsstore.AndroidStorage
+import app.aaps.settingsstore.SettingsUnreadableActivity
+import app.aaps.ui.compose.configuration.ConfigurationViewModel
+import app.aaps.ui.compose.insulinManagement.InsulinManagementViewModel
+import app.aaps.ui.compose.loopSheet.LoopActionViewModel
+import app.aaps.ui.compose.main.MainViewModel
+import app.aaps.ui.compose.main.OverviewScreen
+import app.aaps.ui.compose.maintenance.ImportViewModel
+import app.aaps.ui.compose.maintenance.MaintenanceViewModel
+import app.aaps.ui.compose.manageSheet.ManageViewModel
+import app.aaps.ui.compose.overview.chips.ChipsViewModel
+import app.aaps.ui.compose.overview.graphs.GraphViewModel
+import app.aaps.ui.compose.overview.statusLights.StatusViewModel
+import app.aaps.ui.compose.permissionsSheet.PermissionsSheet
+import app.aaps.ui.compose.permissionsSheet.PermissionsSideEffect
+import app.aaps.ui.compose.permissionsSheet.PermissionsViewModel
+import app.aaps.ui.compose.profileManagement.viewmodels.ProfileEditorViewModel
+import app.aaps.ui.compose.profileManagement.viewmodels.ProfileHelperViewModel
+import app.aaps.ui.compose.profileManagement.viewmodels.ProfileManagementViewModel
+import app.aaps.ui.compose.quickLaunch.QuickLaunchAction
+import app.aaps.ui.compose.quickWizard.viewmodels.QuickWizardManagementViewModel
+import app.aaps.ui.compose.runningMode.RunningModeManagementViewModel
+import app.aaps.ui.compose.scenesSheet.ScenesViewModel
+import app.aaps.ui.compose.siteRotationDialog.viewModels.SiteRotationManagementViewModel
+import app.aaps.ui.compose.stats.viewmodels.StatsViewModel
+import app.aaps.ui.compose.tempTarget.TempTargetManagementViewModel
+import app.aaps.ui.compose.treatments.viewmodels.TreatmentsViewModel
+import app.aaps.ui.compose.treatmentsSheet.TreatmentViewModel
+import app.aaps.ui.search.BuiltInSearchables
+import app.aaps.ui.search.SearchIndexEntry
+import app.aaps.ui.search.SearchViewModel
+import com.google.firebase.crashlytics.FirebaseCrashlytics
+import dev.zacsweers.metro.Inject
+import io.reactivex.rxjava3.disposables.CompositeDisposable
+import kotlinx.coroutines.flow.drop
+import kotlinx.coroutines.launch
+import app.aaps.core.ui.R as CoreUiR
+
+class ComposeMainActivity : MetroAppCompatActivity() {
+
+ @Inject lateinit var rxBus: RxBus
+ @Inject lateinit var snackbarHostPresence: SnackbarHostPresence
+ @Inject lateinit var rh: ResourceHelper
+ @Inject lateinit var aapsLogger: AAPSLogger
+ @Inject lateinit var preferences: Preferences
+ @Inject lateinit var uiRestart: UiRestart
+ @Inject lateinit var decimalFormatter: DecimalFormatter
+ @Inject lateinit var iconsProvider: IconsProvider
+ @Inject lateinit var uiInteraction: UiInteraction
+ @Inject lateinit var fabricPrivacy: FabricPrivacy
+ @Inject lateinit var protectionCheck: ProtectionCheck
+ @Inject lateinit var passwordCheck: PasswordCheck
+ @Inject lateinit var cryptoUtil: CryptoUtil
+ @Inject lateinit var exportPasswordDataStore: ExportPasswordDataStore
+ @Inject lateinit var activePlugin: ActivePlugin
+ @Inject lateinit var pluginPermissions: PluginPermissions
+ @Inject lateinit var nsClient: NsClient
+ @Inject lateinit var clientControlActionDispatcher: ClientControlActionDispatcher
+ @Inject lateinit var automationRuntime: AutomationRuntime
+ @Inject lateinit var configBuilder: ConfigBuilder
+ @Inject lateinit var swDefinition: SWDefinition
+ @Inject lateinit var config: Config
+ @Inject lateinit var profileUtil: ProfileUtil
+ @Inject lateinit var visibilityContext: VisibilityContext
+ @Inject lateinit var dexcomBoyda: DexcomBoyda
+ @Inject lateinit var persistenceLayer: PersistenceLayer
+ @Inject lateinit var prefFileList: FileListProvider
+ @Inject lateinit var notificationManager: NotificationManager
+ @Inject lateinit var alarmNotificationManager: AlarmNotificationManager
+ @Inject lateinit var dateUtil: DateUtil
+ @Inject lateinit var builtInSearchables: BuiltInSearchables
+ @Inject lateinit var bolusProgressData: BolusProgressData
+ @Inject lateinit var commandQueue: CommandQueue
+ @Inject lateinit var bgQualityCheck: BgQualityCheck
+ @Inject lateinit var objectives: Objectives
+ @Inject lateinit var graphViewModelFactory: GraphViewModel.Factory
+ @Inject lateinit var chipsViewModelFactory: ChipsViewModel.Factory
+ @Inject lateinit var overviewDataCache: OverviewDataCache
+
+ private var accessTree: ActivityResultLauncher? = null
+ private var requestMultiplePermissions: ActivityResultLauncher>? = null
+ private var onPermissionResultDenied: ((List) -> Unit)? = null
+
+ /** Set when this activity is recreated because of a `UiRestart` request, so its view models go too. */
+ private var rebuildingForRestart = false
+
+ /**
+ * The factory `by viewModels()` uses.
+ */
+ override val defaultViewModelProviderFactory: ViewModelProvider.Factory
+ get() = FallbackViewModelFactory(
+ primary = (applicationContext as MetroViewModelFactoryOwner).metroViewModelFactory,
+ // Anything the graph does not contribute still has to be buildable. AndroidX creates its
+ // own view models through this activity - BiometricPrompt makes a BiometricViewModel -
+ // and handing out the Metro factory alone made that throw, taking the biometric prompt
+ // down and with it the Configuration screen and profile editing.
+ fallback = super.defaultViewModelProviderFactory
+ )
+
+ // View models, built by Metro - each carries @ContributesIntoMap and @ViewModelKey.
+ private val mainViewModel: MainViewModel by viewModels()
+ private val manageViewModel: ManageViewModel by viewModels()
+ private val maintenanceViewModel: MaintenanceViewModel by viewModels()
+ private val statusViewModel: StatusViewModel by viewModels()
+ private val treatmentViewModel: TreatmentViewModel by viewModels()
+ private val scenesViewModel: ScenesViewModel by viewModels()
+ private val loopActionViewModel: LoopActionViewModel by viewModels()
+ private val graphViewModel: GraphViewModel by viewModels {
+ viewModelFactory { initializer { graphViewModelFactory.create(overviewDataCache, fullWindow = false) } }
+ }
+ private val chipsViewModel: ChipsViewModel by viewModels {
+ viewModelFactory { initializer { chipsViewModelFactory.create(overviewDataCache) } }
+ }
+ private val treatmentsViewModel: TreatmentsViewModel by viewModels()
+ private val insulinManagementViewModel: InsulinManagementViewModel by viewModels()
+ private val tempTargetManagementViewModel: TempTargetManagementViewModel by viewModels()
+ private val quickWizardManagementViewModel: QuickWizardManagementViewModel by viewModels()
+ private val statsViewModel: StatsViewModel by viewModels()
+ private val profileHelperViewModel: ProfileHelperViewModel by viewModels()
+ private val profileEditorViewModel: ProfileEditorViewModel by viewModels()
+ private val profileManagementViewModel: ProfileManagementViewModel by viewModels()
+ private val runningModeManagementViewModel: RunningModeManagementViewModel by viewModels()
+ private val importViewModel: ImportViewModel by viewModels()
+ private val searchViewModel: SearchViewModel by viewModels()
+ private val permissionsViewModel: PermissionsViewModel by viewModels()
+ private val configurationViewModel: ConfigurationViewModel by viewModels()
+ private val siteRotationManagementViewModel: SiteRotationManagementViewModel by viewModels()
+
+ private val pumpCommunicationStatus by lazy {
+ PumpCommunicationStatus(rxBus, commandQueue, rh, lifecycleScope)
+ }
+ private var navController: NavHostController? = null
+ private val _autoShowNotifications = mutableStateOf(false)
+ private val disposable = CompositeDisposable()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ if (AndroidStorage.failure != null) {
+ // The settings cannot be opened, and AAPS is not started. This activity is not injected then (see
+ // MainApp.injectMembers): it only hands over. finish() here skips onStart and onResume.
+ super.onCreate(savedInstanceState)
+ startActivity(Intent(this, SettingsUnreadableActivity::class.java))
+ finish()
+ return
+ }
+ // Recreated in another language: the one picked in AAPS (Android 13 and newer), or the phone's while AAPS
+ // follows it. Android recreates this screen itself then, and keeps the view models, with the text they built in
+ // the old language. So they go. Before super.onCreate, so that none is made from the old store first.
+ if (savedInstanceState != null && savedInstanceState.getString(STATE_LANGUAGE) != resources.configuration.locales.toLanguageTags())
+ viewModelStore.clear()
+ // Bar icon color is kept in sync with the AAPS-effective theme reactively
+ // from inside AapsTheme via a SideEffect on WindowInsetsControllerCompat,
+ // so a plain enableEdgeToEdge() here is enough.
+ enableEdgeToEdge()
+ super.onCreate(savedInstanceState)
+ // Other apps may not draw over AAPS: an overlay could hide what a tap really does, for example on a bolus
+ // confirmation. It also covers the dialogs, because this window stays visible under them. System and
+ // accessibility overlays still show. Needs HIDE_OVERLAY_WINDOWS.
+ window.setHideOverlayWindows(true)
+
+ // Activity result launchers (from base class)
+ accessTree = registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
+ uri?.let {
+ val lastPathSegment = uri.lastPathSegment ?: ""
+ val pathAfterColon = if (lastPathSegment.contains(":")) lastPathSegment.substringAfterLast(":") else lastPathSegment
+ val directoryName = pathAfterColon.substringAfterLast("/", pathAfterColon)
+ val managedSubdirectories = listOf("preferences", "extra", "exports", "temp")
+ if (managedSubdirectories.any { it.equals(directoryName, ignoreCase = true) }) {
+ rxBus.send(
+ EventShowDialog.Error(
+ title = rh.gs(app.aaps.plugins.configuration.R.string.warning_wrong_directory_selected),
+ message = rh.gs(app.aaps.plugins.configuration.R.string.warning_wrong_directory_message, directoryName)
+ )
+ )
+ return@registerForActivityResult
+ }
+ contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
+ preferences.put(StringKey.AapsDirectoryUri, uri.toString())
+ }
+ }
+ requestMultiplePermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
+ val denied = mutableListOf()
+ permissions.entries.forEach {
+ aapsLogger.info(LTag.CORE, "Permission ${it.key} ${it.value}")
+ if (!it.value) denied.add(it.key)
+ }
+ if (denied.isNotEmpty()) onPermissionResultDenied?.invoke(denied)
+ updateButtons()
+ }
+
+ onPermissionResultDenied = { denied ->
+ permissionsViewModel.onPermissionsDenied(
+ deniedPermissions = denied,
+ canShowRationale = { ActivityCompat.shouldShowRequestPermissionRationale(this, it) }
+ )
+ }
+
+ observePreferences()
+
+ setContent {
+ MainContent()
+ }
+ }
+
+ @Composable
+ private fun MainContent() {
+ // LocalActivity, not a cast of LocalContext: that context is usually a ContextWrapper, where
+ // `as? FragmentActivity` is null - and then the biometric prompt cannot be shown at all.
+ // Read here so the prompt lambdas below can capture it; the shared host no longer takes one.
+ val activity = LocalActivity.current as? FragmentActivity
+ AapsAppRoot(
+ config = config,
+ preferences = preferences,
+ dateUtil = dateUtil,
+ decimalFormatter = decimalFormatter,
+ profileUtil = profileUtil,
+ passwordHasher = cryptoUtil,
+ passwordCheck = passwordCheck,
+ protectionCheck = protectionCheck,
+ // The biometric prompt is the only platform-specific part of protection. The host used
+ // to be handed the activity; it captures it here instead, which is what let the host
+ // itself move to commonMain.
+ showBiometric = { title, onGranted, onCancelled, onDenied ->
+ if (activity != null) BiometricCheck.biometricPrompt(activity, title, rxBus, onGranted, onCancelled, onDenied, passwordCheck)
+ else onCancelled()
+ },
+ showBiometricSimple = { title, onSuccess, onFallback, onCancel ->
+ if (activity != null) BiometricCheck.biometricPromptSimple(activity, title, rxBus, onSuccess, onFallback, onCancel)
+ else onFallback()
+ },
+ exportPasswordDataStore = exportPasswordDataStore,
+ visibilityContext = visibilityContext,
+ nsClient = nsClient,
+ rxBus = rxBus,
+ snackbarHostPresence = snackbarHostPresence,
+ clientControlActionDispatcher = clientControlActionDispatcher,
+ bolusProgressData = bolusProgressData,
+ commandQueue = commandQueue,
+ pumpCommunicationStatus = pumpCommunicationStatus,
+ // The two per-build bitmaps the shared root cannot paint itself.
+ appIcon = { modifier -> Image(painterResource(iconsProvider.getIcon()), null, modifier) },
+ splashLogo = { modifier -> Image(painterResource(CoreUiR.drawable.splash_logo), null, modifier) },
+ // The Activity keeps a reference so an incoming intent can route without the composition.
+ onNavControllerReady = { navController = it },
+ onClose = { finish() },
+ // An instrumented pump test starts with an empty preference store, so without this every
+ // one of them would open the wizard instead of the screen it means to drive. The check is
+ // androidMain only, which is why the shared root takes it as a parameter.
+ suppressSetupWizard = isRunningRealPumpTest(),
+ content = { navController -> AppContent(navController) }
+ )
+ }
+
+ @SuppressLint("BatteryLife")
+ @Composable
+ private fun AppContent(navController: NavHostController) {
+ // Trigger initial refresh when app content first appears (after init completes)
+ LaunchedEffect(Unit) { refreshOnResume() }
+
+ // Track last navigated route as a Crashlytics custom key for crash reports
+ DisposableEffect(navController) {
+ val listener = NavController.OnDestinationChangedListener { _, dest, _ ->
+ FirebaseCrashlytics.getInstance().setCustomKey("last_route", dest.route ?: "unknown")
+ }
+ navController.addOnDestinationChangedListener(listener)
+ onDispose { navController.removeOnDestinationChangedListener(listener) }
+ }
+
+ // The first-run setup wizard used to be opened here, which is why only Android ever offered
+ // it. It is in `AapsAppRoot` now, so desktop and iOS get it too; this shell only says when to
+ // keep it shut - see `suppressSetupWizard` where AapsAppRoot is called below.
+
+ // Permissions bottom sheet
+ val permState by permissionsViewModel.uiState.collectAsStateWithLifecycle()
+
+ // Sheet-scoped snackbar state (separate from the root host so messages
+ // triggered from the permissions flow render inside the modal sheet,
+ // and never duplicate on the activity's root host).
+ val permissionsSnackbarHostState = remember { SnackbarHostState() }
+
+ LaunchedEffect(Unit) {
+ permissionsViewModel.sideEffect.collect { effect ->
+ when (effect) {
+ is PermissionsSideEffect.RequestPermissions ->
+ requestMultiplePermissions?.launch(effect.permissions.toTypedArray())
+
+ is PermissionsSideEffect.LaunchSpecialPermission ->
+ when {
+ effect.group.permissions.contains(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) ->
+ try {
+ startActivity(
+ Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
+ data = "package:$packageName".toUri()
+ }
+ )
+ } catch (_: ActivityNotFoundException) {
+ permissionsSnackbarHostState.showSnackbar(getString(app.aaps.plugins.configuration.R.string.alert_dialog_permission_battery_optimization_failed))
+ }
+
+ effect.group.permissions.contains(PluginPermissionsImpl.PERMISSION_SELECT_DIRECTORY) ->
+ try {
+ accessTree?.launch(null)
+ } catch (_: Exception) {
+ permissionsSnackbarHostState.showSnackbar(getString(app.aaps.ui.R.string.permission_directory_picker_error))
+ }
+
+ effect.group.permissions.contains(DexcomPlugin.PERMISSION) ->
+ startActivity(Intent(this@ComposeMainActivity, RequestDexcomPermissionActivity::class.java))
+
+ effect.group.permissions.contains(Manifest.permission.POST_NOTIFICATIONS) ->
+ startActivity(
+ Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
+ putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
+ }
+ )
+
+ effect.group.permissions.contains(Manifest.permission.SCHEDULE_EXACT_ALARM) ->
+ // Every user can get here now, not only EOPatch users. If a ROM has no screen
+ // for this intent, open the app's own settings page instead of crashing.
+ try {
+ startActivity(
+ Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM).apply {
+ data = "package:$packageName".toUri()
+ }
+ )
+ } catch (_: ActivityNotFoundException) {
+ runCatching {
+ startActivity(
+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
+ data = "package:$packageName".toUri()
+ }
+ )
+ }
+ }
+
+ effect.group.permissions.contains(PluginPermissionsImpl.PERMISSION_NOTIFICATION_LISTENER) ->
+ startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS))
+ }
+
+ is PermissionsSideEffect.ShowError ->
+ permissionsSnackbarHostState.showSnackbar(effect.message)
+
+ is PermissionsSideEffect.PermanentlyDenied -> {
+ val result = permissionsSnackbarHostState.showSnackbar(
+ message = getString(app.aaps.ui.R.string.permission_denied_go_to_settings),
+ actionLabel = getString(app.aaps.ui.R.string.permission_open_settings),
+ )
+ if (result == SnackbarResult.ActionPerformed) {
+ startActivity(
+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
+ data = "package:$packageName".toUri()
+ }
+ )
+ }
+ }
+ }
+ }
+ }
+
+ if (permState.showSheet) {
+ PermissionsSheet(
+ items = permState.items,
+ snackbarHostState = permissionsSnackbarHostState,
+ onRequestPermission = { permissionsViewModel.requestPermission(it) },
+ onDismiss = { permissionsViewModel.dismissSheet() }
+ )
+ }
+
+ val state by mainViewModel.uiState.collectAsStateWithLifecycle()
+
+ NavHost(
+ navController = navController,
+ startDestination = AppRoute.Main.route
+ ) {
+ appNavGraph(
+ navController = navController,
+ insulinManagementViewModel = insulinManagementViewModel,
+ profileManagementViewModel = profileManagementViewModel,
+ profileEditorViewModel = profileEditorViewModel,
+ profileHelperViewModel = profileHelperViewModel,
+ tempTargetManagementViewModel = tempTargetManagementViewModel,
+ quickWizardManagementViewModel = quickWizardManagementViewModel,
+ runningModeManagementViewModel = runningModeManagementViewModel,
+ importViewModel = importViewModel,
+ configurationViewModel = configurationViewModel,
+ treatmentsViewModel = treatmentsViewModel,
+ statsViewModel = statsViewModel,
+ siteRotationManagementViewModel = siteRotationManagementViewModel,
+ graphViewModel = graphViewModel,
+ chipsViewModel = chipsViewModel,
+ swDefinition = swDefinition,
+ rxBus = rxBus,
+ activePlugin = activePlugin,
+ pluginPermissions = pluginPermissions,
+ automationRuntime = automationRuntime,
+ preferences = preferences,
+ rh = rh,
+ builtInSearchables = builtInSearchables,
+ configBuilder = configBuilder,
+ prefFileList = prefFileList,
+ persistenceLayer = persistenceLayer,
+ visibilityContext = visibilityContext,
+ onNavigationRequest = { request, nc -> handleNavigationRequest(request, nc) },
+ onShowDeliveryError = { comment, title ->
+ uiInteraction.runAlarm(comment, rh.gs(title), AlarmSound.BOLUS_ERROR)
+ },
+ withProtection = { protection, action -> navigator(navController).guarded(protection, action) },
+ requestEditModeAuthorization = { onGranted ->
+ protectionCheck.requestAuthorization(ProtectionCheck.Protection.PREFERENCES) { result ->
+ if (result.grantedLevel != null) onGranted()
+ }
+ },
+ onRefreshPermissions = { permissionsViewModel.refresh() },
+ onExecuteQuickWizard = { guid -> mainViewModel.executeQuickWizard(guid) },
+ onRequestDirectoryAccess = {
+ try {
+ accessTree?.launch(null)
+ } catch (_: Exception) {
+ }
+ },
+ onRequestPermission = { group -> permissionsViewModel.requestPermission(group) },
+ overview = {
+ OverviewScreen(
+ mainViewModel = mainViewModel,
+ manageViewModel = manageViewModel,
+ maintenanceViewModel = maintenanceViewModel,
+ statusViewModel = statusViewModel,
+ treatmentViewModel = treatmentViewModel,
+ scenesViewModel = scenesViewModel,
+ loopActionViewModel = loopActionViewModel,
+ searchViewModel = searchViewModel,
+ permissionsViewModel = permissionsViewModel,
+ graphViewModel = graphViewModel,
+ chipsViewModel = chipsViewModel,
+ activePlugin = activePlugin,
+ config = config,
+ objectives = objectives,
+ bgQualityCheck = bgQualityCheck,
+ notificationManager = notificationManager,
+ uiInteraction = uiInteraction,
+ builtInSearchables = builtInSearchables,
+ bolusProgressData = bolusProgressData,
+ clientControlActionDispatcher = clientControlActionDispatcher,
+ commandQueue = commandQueue,
+ pumpCommunicationStatus = pumpCommunicationStatus,
+ appName = stringResource(R.string.app_name),
+ authorizationFailedMessage = stringResource(R.string.authorizationfailed),
+ onNavigate = { request -> handleNavigationRequest(request, navController) },
+ onSearchResultClick = { entry -> handleSearchResultClick(entry, navController) },
+ onNotificationActionClick = { notification -> handleNotificationAction(notification.id, navController) },
+ onQuickLaunchActionClick = { action -> handleQuickLaunchAction(action, navController) },
+ onImportSettingsNavigate = { source -> navController.navigate(AppRoute.ImportSettings.createRoute(source.name)) },
+ onDirectoryClick = {
+ try {
+ accessTree?.launch(null)
+ } catch (_: Exception) {
+ maintenanceViewModel.emitError("Unable to launch activity. This is an Android issue")
+ }
+ },
+ onLaunchBrowser = { url ->
+ try {
+ val customTabsIntent = CustomTabsIntent.Builder()
+ .setShowTitle(true)
+ .build()
+ customTabsIntent.launchUrl(this@ComposeMainActivity, url.toUri())
+ } catch (_: Exception) {
+ maintenanceViewModel.emitError("Unable to open browser")
+ }
+ },
+ onBringToForeground = {
+ val intent = Intent(this@ComposeMainActivity, ComposeMainActivity::class.java)
+ .addFlags(
+ Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
+ or Intent.FLAG_ACTIVITY_SINGLE_TOP
+ or Intent.FLAG_ACTIVITY_CLEAR_TOP
+ or Intent.FLAG_ACTIVITY_NO_ANIMATION
+ )
+ startActivity(intent)
+ },
+ onRecreateActivity = { recreate() },
+ onAuthorizationFailed = { finish() },
+ autoShowNotificationSheet = _autoShowNotifications.value,
+ onAutoShowConsumed = { _autoShowNotifications.value = false }
+ )
+ },
+ )
+ }
+ }
+
+
+ private var isProtectionCheckActive = false
+
+ private fun refreshOnResume() {
+ manageViewModel.refreshState()
+ permissionsViewModel.refresh()
+ if (notificationManager.notifications.value.any { it.level.priority <= NotificationLevel.IMPORTANT.priority }) {
+ _autoShowNotifications.value = true
+ }
+ if (!isProtectionCheckActive) {
+ isProtectionCheckActive = true
+ protectionCheck.requestProtection(ProtectionCheck.Protection.APPLICATION) { result ->
+ isProtectionCheckActive = false
+ if (result != ProtectionResult.GRANTED) {
+ mainViewModel.setShowAuthFailedDialog(true)
+ }
+ }
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ // A background alarm the user has not answered: nothing in this screen can stop it, so show
+ // its alarm screen again (#5338). In onStart and not in onResume: the alarm screen is
+ // translucent, so leaving it with Back resumes this activity without starting it, and the
+ // alarm screen does not come straight back.
+ alarmNotificationManager.unansweredAlarmIntent()?.let { startActivity(it) }
+ }
+
+ override fun onResume() {
+ super.onResume()
+ if (!config.appInitialized) return
+ refreshOnResume()
+ }
+
+ private fun updateButtons() {
+ permissionsViewModel.refresh()
+ }
+
+ override fun onSaveInstanceState(outState: Bundle) {
+ super.onSaveInstanceState(outState)
+ outState.putString(STATE_LANGUAGE, resources.configuration.locales.toLanguageTags())
+ }
+
+ private companion object {
+
+ /** The language this screen was shown in, to notice a recreate in another one (see onCreate). */
+ const val STATE_LANGUAGE = "appLanguage"
+ }
+
+ override fun onDestroy() {
+ // A recreate keeps the view models, so after a language change they still showed the texts
+ // they had built in the old language ("Buclă închisă" on a Czech screen), and after an import
+ // the values from before it. A restart rebuilds them too, as iOS and the desktop do. Cleared
+ // here, while Android hands this store to the next activity, so that one starts with none.
+ if (rebuildingForRestart) viewModelStore.clear()
+ disposable.clear()
+ accessTree = null
+ requestMultiplePermissions = null
+ onPermissionResultDenied = null
+ super.onDestroy()
+ }
+
+ private fun observePreferences() {
+ // Wake lock: initial value applies on startup, subsequent changes update the flag
+ lifecycleScope.launch {
+ preferences.observe(BooleanKey.OverviewKeepScreenOn).collect { setupWakeLock() }
+ }
+ // A rebuild asked for by code that cannot reach this activity: `MainApp` once Android has applied a
+ // new language, an import applying its settings. Android answers it by recreating; the view models
+ // go too, see onDestroy.
+ lifecycleScope.launch {
+ uiRestart.signal.drop(1).collect {
+ rebuildingForRestart = true
+ recreate()
+ }
+ }
+ }
+
+ private fun setupWakeLock() {
+ val keepScreenOn = preferences.get(BooleanKey.OverviewKeepScreenOn)
+ if (keepScreenOn) {
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ } else {
+ window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+ }
+
+ /**
+ * The shared navigator, built with the four actions only Android can perform.
+ *
+ * The mapping from an element, a search result, a notification or a quick launch tile to a
+ * route lives in `:appshell` so every platform behaves the same; what differs is opening a CGM
+ * app, opening a browser, launching the directory picker and finishing the activity.
+ */
+ private fun navigator(navController: NavController) = ElementNavigator(
+ navController = navController,
+ mainViewModel = mainViewModel,
+ activePlugin = activePlugin,
+ protectionCheck = protectionCheck,
+ configBuilder = configBuilder,
+ dexcomBoyda = dexcomBoyda,
+ onOpenCgmApp = { packageName -> openCgmApp(packageName) },
+ onExit = { finish() },
+ onRequestDirectoryAccess = {
+ try {
+ accessTree?.launch(null)
+ } catch (_: Exception) {
+ }
+ },
+ onOpenUrl = { url -> startActivity(Intent(Intent.ACTION_VIEW, url.toUri())) }
+ )
+
+ private fun handleNavigationRequest(request: NavigationRequest, navController: NavController) {
+ navigator(navController).handleNavigationRequest(request)
+ }
+
+ private fun handleQuickLaunchAction(action: QuickLaunchAction, navController: NavController) {
+ navigator(navController).handleQuickLaunchAction(action)
+ }
+
+ private fun handleNotificationAction(notificationId: NotificationId, navController: NavController) {
+ navigator(navController).handleNotificationAction(notificationId)
+ }
+
+ private fun handleSearchResultClick(entry: SearchIndexEntry, navController: NavController) {
+ navigator(navController).handleSearchResultClick(entry)
+ }
+
+ private fun openCgmApp(packageName: String) {
+ try {
+ val intent = packageManager.getLaunchIntentForPackage(packageName) ?: throw ActivityNotFoundException()
+ intent.addCategory(Intent.CATEGORY_LAUNCHER)
+ startActivity(intent)
+ } catch (_: ActivityNotFoundException) {
+ aapsLogger.debug("Error opening CGM app: $packageName")
+ }
+ }
+
+ /**
+ * Navigate to [elementType] using hierarchical authorization.
+ * For management screens, the granted level determines the screen mode
+ * (PLAY for BOLUS, EDIT for PREFERENCES or higher).
+ */
+
+ /**
+ * Execute [action] after verifying protection level.
+ * Protection level is defined once in [ElementType] — no manual lookup needed at call sites.
+ */
+
+ /**
+ * Navigate to an [ElementType] destination. Protection is handled by the caller.
+ * No `else` — compiler catches missing enum values.
+ */
+
+}
+
diff --git a/app/main/kotlin/app/aaps/LegacyPreferenceValue.kt b/app/main/kotlin/app/aaps/LegacyPreferenceValue.kt
new file mode 100644
index 000000000000..5d5857b611ae
--- /dev/null
+++ b/app/main/kotlin/app/aaps/LegacyPreferenceValue.kt
@@ -0,0 +1,40 @@
+package app.aaps
+
+import app.aaps.LegacyPreferenceValue.asString
+
+/**
+ * Reads a value out of the raw preference store as the type a migration expects, or reports that it
+ * cannot.
+ *
+ * The raw store holds whatever any AAPS version, any import file or any third party ever wrote, so
+ * a key whose name says "total" does not have to hold a `Long`. The start-up migrations in `MainApp`
+ * used to cast (`value as Long`), and a cast that fails there is caught as "Fatal initialization
+ * error" - the app does not start at all until the user clears its data.
+ *
+ * Every function here returns null instead of throwing, and null means SKIP: leave the old key
+ * alone, log it, let the next start try again. None of them guesses a replacement value. That is the
+ * whole point, and it is the thing to preserve if this is ever edited:
+ *
+ * - `toBooleanStrictOrNull`, never `toBoolean`. `toBoolean` maps anything that is not "true" to
+ * false, so a broken value would migrate as a real `false` and turn a plugin off.
+ * - [asString] rejects non-text instead of calling `toString()`. These values are the profile's ISF,
+ * IC, basal and target arrays; a number rendered as text would be taken downstream as a profile.
+ */
+internal object LegacyPreferenceValue {
+
+ /** `Int` is included because that is what the store returns for a value written as an int. */
+ fun asLong(value: Any?): Long? = when (value) {
+ is Long -> value
+ is Int -> value.toLong()
+ is String -> value.toLongOrNull()
+ else -> null
+ }
+
+ fun asBoolean(value: Any?): Boolean? = when (value) {
+ is Boolean -> value
+ is String -> value.toBooleanStrictOrNull()
+ else -> null
+ }
+
+ fun asString(value: Any?): String? = value as? String
+}
diff --git a/app/main/kotlin/app/aaps/MainApp.kt b/app/main/kotlin/app/aaps/MainApp.kt
new file mode 100644
index 000000000000..2c101fa0e75d
--- /dev/null
+++ b/app/main/kotlin/app/aaps/MainApp.kt
@@ -0,0 +1,947 @@
+package app.aaps
+
+import android.app.Application
+import android.app.LocaleManager
+import android.bluetooth.BluetoothDevice
+import android.content.Intent
+import android.content.IntentFilter
+import android.net.ConnectivityManager
+import android.net.wifi.WifiManager
+import android.os.Build
+import android.os.Handler
+import android.os.HandlerThread
+import android.os.LocaleList
+import androidx.lifecycle.ProcessLifecycleOwner
+import androidx.work.Configuration
+import app.aaps.core.data.configuration.Constants
+import app.aaps.core.data.model.GlucoseUnit
+import app.aaps.core.data.model.TE
+import app.aaps.core.data.model.TT
+import app.aaps.core.data.model.TTPreset
+import app.aaps.core.data.time.T
+import app.aaps.core.data.ue.Action
+import app.aaps.core.data.ue.Sources
+import app.aaps.core.interfaces.configuration.ExternalOptions
+import app.aaps.core.interfaces.db.VacuumResult
+import app.aaps.core.interfaces.di.MetroMemberInjector
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.notifications.NotificationAction
+import app.aaps.core.interfaces.notifications.NotificationId
+import app.aaps.core.interfaces.notifications.NotificationLevel
+import app.aaps.core.interfaces.rx.events.EventAppInitialized
+import app.aaps.core.interfaces.tempTargets.toJson
+import app.aaps.core.keys.BooleanKey
+import app.aaps.core.keys.BooleanNonKey
+import app.aaps.core.keys.LongNonKey
+import app.aaps.core.keys.StringKey
+import app.aaps.core.keys.StringNonKey
+import app.aaps.core.keys.interfaces.TextRef
+import app.aaps.core.ui.compose.MetroViewModelFactoryOwner
+import app.aaps.database.di.DatabaseConfig
+import app.aaps.di.ExternalOptionsOverride
+import app.aaps.di.GeneratedStringOwners
+import app.aaps.di.metro.MetroGraphs
+import app.aaps.di.metro.MetroWorkerFactory
+import app.aaps.implementation.maintenance.migration.InsulinMigration
+import app.aaps.implementation.maintenance.migration.InsulinMigrationPlan
+import app.aaps.implementation.maintenance.migration.LegacyInsulin
+import app.aaps.implementation.maintenance.migration.PreferenceMigrations
+import app.aaps.implementation.maintenance.migration.ProfileDiaHarvest
+import app.aaps.implementation.receivers.BTReceiver
+import app.aaps.implementation.receivers.ChargingStateReceiver
+import app.aaps.implementation.receivers.KeepAliveWorker
+import app.aaps.implementation.receivers.NetworkChangeReceiver
+import app.aaps.implementation.receivers.TimeDateOrTZChangeReceiver
+import app.aaps.settingsstore.AndroidStorage
+import app.aaps.settingsstore.IdleWorkerFactory
+import app.aaps.settingsstore.SettingsUnreadableNotification
+import app.aaps.utils.configureLeakCanary
+import com.google.firebase.Firebase
+import com.google.firebase.FirebaseApp
+import com.google.firebase.crashlytics.FirebaseCrashlytics
+import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings
+import com.google.firebase.remoteconfig.remoteConfig
+import dev.zacsweers.metrox.viewmodel.MetroViewModelFactory
+import io.reactivex.rxjava3.exceptions.UndeliverableException
+import io.reactivex.rxjava3.plugins.RxJavaPlugins
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.drop
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.merge
+import kotlinx.coroutines.joinAll
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeoutOrNull
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonObject
+import rxdogtag2.RxDogTag
+import java.io.IOException
+import java.util.Locale
+import kotlin.reflect.KMutableProperty
+import kotlin.reflect.full.declaredMemberProperties
+import kotlin.time.Duration.Companion.milliseconds
+import kotlin.time.Duration.Companion.seconds
+import android.content.res.Configuration as ResourcesConfiguration
+import app.aaps.core.interfaces.R as InterfacesR
+import app.aaps.core.ui.R as CoreUiR
+
+class MainApp : Application(), MetroMemberInjector, MetroViewModelFactoryOwner, Configuration.Provider {
+
+ companion object {
+
+ /**
+ * How long start up waits for the plugins to finish starting before carrying on regardless.
+ * Matches `ConfigBuilderImpl.PLUGIN_SETTLE_WAIT`, which bounds the same wait on the import path -
+ * the two start paths should behave the same, which is the whole point of waiting here at all.
+ */
+ private val PLUGIN_START_WAIT = 30.seconds
+ }
+
+ // When the settings cannot be opened, ComposeMainActivity only hands over to SettingsUnreadableActivity and
+ // finishes. Filling its fields would build some 40 objects - plugins, the command queue - for nothing,
+ // and on settings that are not the user's.
+ override fun injectMembers(target: Any): Boolean =
+ if (AndroidStorage.failure != null && target is ComposeMainActivity) true
+ else metroGraphs.injectMembers(target)
+
+ override val metroViewModelFactory: MetroViewModelFactory get() = metroGraphs.viewModelFactory
+
+ /**
+ * `by lazy` so nothing is resolved before `onCreate` runs - the graph reaches Android services, and
+ * an Application field initialiser runs before the framework is ready for that.
+ * The last two arguments are the only things an instrumented test does differently; see
+ * `AppRootGraph.Factory`. Production wants the real database and no forced options.
+ */
+ private val metroGraphs by lazy {
+ MetroGraphs(
+ context = this,
+ memberInjector = this,
+ databaseConfig = DatabaseConfig.PRODUCTION,
+ externalOptionsOverride = ExternalOptionsOverride.NONE
+ )
+ }
+ // WorkManager on-demand initialization. `MetroWorkerFactory` builds every worker in the app; what
+ // it does not know returns null and falls back to WorkManager's default reflective factory, which
+ // is what builds WorkManager's own internal workers. The default androidx.startup
+ // WorkManagerInitializer is removed in AndroidManifest.xml so this config wins.
+ // While the settings cannot be opened, the app's jobs do nothing (see IdleWorkerFactory).
+ override val workManagerConfiguration: Configuration
+ get() = Configuration.Builder()
+ .setWorkerFactory(
+ if (AndroidStorage.failure == null) MetroWorkerFactory(metroGraphs)
+ else IdleWorkerFactory { metroGraphs.workerCreators().keys }
+ )
+ .build()
+
+ private val pluginStore get() = metroGraphs.pluginStore
+ private val aapsLogger get() = metroGraphs.aapsLogger
+ private val versionCheckersUtils get() = metroGraphs.versionCheckerUtils
+ private val sp get() = metroGraphs.keyValueStore
+ private val preferences get() = metroGraphs.preferences
+ private val config get() = metroGraphs.config
+ private val configBuilder get() = metroGraphs.configBuilder
+ private val plugins get() = metroGraphs.allPlugins(aapsLogger)
+ private val persistenceLayer get() = metroGraphs.persistenceLayer
+ private val dateUtil get() = metroGraphs.dateUtil
+ private val uiInteraction get() = metroGraphs.uiInteraction
+ private val processLifecycleListener get() = metroGraphs.processLifecycleListener
+ private val localAlertUtils get() = metroGraphs.localAlertUtils
+ private val notificationManager get() = metroGraphs.notificationManager
+ private val rh get() = metroGraphs.resourceHelper
+ private val loop get() = metroGraphs.loop
+ private val profileFunction get() = metroGraphs.profileFunction
+ private val profileUtil get() = metroGraphs.profileUtil
+ private val fabricPrivacy get() = metroGraphs.fabricPrivacy
+ // The concrete types, only so their start() can be called below. Both are @Singleton, so these are
+ // the same objects the interface bindings hand out. `rh` is a Provider already - kept that way here
+ // rather than risking the cycle that shape exists to avoid.
+ private val resourceHelperImpl get() = metroGraphs.resourceHelperImpl
+ private val fabricPrivacyImpl get() = metroGraphs.fabricPrivacyImpl
+ private val rxBus get() = metroGraphs.rxBus
+ private val repository get() = metroGraphs.appRepository
+ private val hardLimits get() = metroGraphs.hardLimits
+ private val activePlugin get() = metroGraphs.activePlugin
+ private val profileRepository get() = metroGraphs.profileRepository
+ private val localInsulinManager get() = metroGraphs.insulinManager
+ private val constraintChecker get() = metroGraphs.constraintsChecker
+ private val signatureVerifierPlugin get() = metroGraphs.signatureVerifier
+ private val fileListProvider get() = metroGraphs.fileListProvider
+ private val cryptoUtil get() = metroGraphs.cryptoUtil
+ private val exportPasswordDataStore get() = metroGraphs.exportPasswordDataStore
+ private val widgetUpdater get() = metroGraphs.widgetUpdater
+ private val runningModeReconciler get() = metroGraphs.runningModeReconciler
+ private val runningModeExpiryScheduler get() = metroGraphs.runningModeExpiryScheduler
+ private val profileSwitchScheduler get() = metroGraphs.profileSwitchScheduler
+ private val automationRuntime get() = metroGraphs.automationRuntime
+ private val snackbarNotificationFallback get() = metroGraphs.snackbarNotificationFallback
+ private val eatReminder get() = metroGraphs.eatReminder
+ private val appScope get() = metroGraphs.applicationScope
+ private val uiRestart get() = metroGraphs.uiRestart
+
+ /** The rules; the two fields below are what this app's start-up sequence carries between its steps. */
+ private val insulinMigration get() = InsulinMigration(aapsLogger, hardLimits, rh)
+
+ /**
+ * The v3 insulin plugin selection, read before the migrations delete its keys. Null when there was none.
+ */
+ private var legacyInsulin: LegacyInsulin? = null
+
+ /**
+ * The DIA each v3 profile was using, with the raw keys those values came from still in the old store.
+ *
+ * `doMigrations` used to remove those keys as it read them, which put the only copy of the DIA values
+ * in a field, in memory. `dataMigrations` is the only consumer and runs much later, after
+ * `vacuumDatabaseIfDue` (which documents that it can take the process down below the JVM, where no
+ * `catch` reaches) and after the plugins start. A death anywhere in that gap lost the DIA values for
+ * good: the next start finds no keys and stamps the old records with a guess instead. That is wrong IOB
+ * on historical records and it is one-way - the sentinel is consumed and those rows are never revisited.
+ *
+ * So they are removed only once the value they carry is safely in the insulin list.
+ */
+ private var profileDia: ProfileDiaHarvest = ProfileDiaHarvest(emptyMap(), emptyList())
+
+ private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
+ private lateinit var refreshWidget: Runnable
+ private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
+
+ override fun onCreate() {
+ super.onCreate()
+
+ // The settings first: everything below reads them. Opened here on purpose, not on first use, so a
+ // store that cannot be read is found at once and handled in one place.
+ val storage = AndroidStorage.open(this)
+ storage.failure?.let { failure ->
+ startWithoutSettings(failure, storage.notes)
+ return
+ }
+ GeneratedStringOwners.registerAll()
+ resourceHelperImpl.start()
+ // As early as possible, so the first screen is already in it
+ applyAppLanguage()
+ appLocales = resources.configuration.locales
+ // Applies the analytics opt-out. Must come before configureLeakCanary below, which reports
+ // through fabricPrivacy.
+ fabricPrivacyImpl.start()
+ // Build identity goes on the crash report here, not in setUserStats() near the end of doInit.
+ // A crash during plugin initialization happens seconds before that runs, so those reports carried
+ // no HEAD and no Committed - exactly the ones where the build has to be known to tell a stale
+ // local build from a live bug. Collection is already gated by the call above, so an opted-out
+ // user still uploads nothing.
+ setBuildIdentityKeys()
+
+ // Here should be everything injected
+ aapsLogger.debug("onCreate")
+ storage.notes.forEach { aapsLogger.info(LTag.CORE, it) }
+ AndroidStorage.onSaveFailure = { aapsLogger.error(LTag.CORE, "Settings could not be saved, the next change tries again: ${it.message}") }
+ // Left by an earlier start whose settings could not be opened.
+ SettingsUnreadableNotification.cancel(this)
+ ProcessLifecycleOwner.get().lifecycle.addObserver(processLifecycleListener)
+
+ // Background fallback for EventShowSnackbar: when no GlobalSnackbarHost is collecting,
+ // promote the snackbar to a system Notification so the message is not lost. Shared code -
+ // the iOS and desktop shells start the same class. Started here, before the migrations
+ // below, so messages sent during startup are covered too.
+ snackbarNotificationFallback.start()
+
+ // All initialization in background thread to avoid blocking main thread
+ // (ComposeMainActivity shows splash screen until initProgress.done)
+ scope.launch {
+ try {
+ // Configure LeakCanary with Firebase reporting. Memory leaks are uploaded to Firebase
+ // Crashlytics via FabricPrivacy.logException. Not on the main thread: reading the
+ // DISABLE_LEAK_CANARY marker lists the AAPS directory through SAF, and on slow phones
+ // that held up app start long enough for an ANR (4.0.0-rc1).
+ configureLeakCanary(
+ isEnabled = { !config.isEnabled(ExternalOptions.DISABLE_LEAK_CANARY) },
+ fabricPrivacy = fabricPrivacy
+ )
+
+ config.updateInitProgress(getString(R.string.migrating_preferences))
+ doMigrations()
+
+ // Re-read the profiles now that doMigrations() has converted the ancient raw
+ // SharedPreferences profile keys into the numbered ones. Without this the upgrade
+ // would only be picked up on the next start, and the profile-to-JSON conversion
+ // with it.
+ //
+ // This used to say the repository "already loaded during field injection". There is
+ // no field injection any more - it is a lazy `metroGraphs` accessor, so whether it
+ // was built before this line depends on what else happened to pull it in. Which is
+ // exactly why the call stays: it costs a re-read when nothing was loaded, and it is
+ // the difference between a right and a stale profile when something was.
+ profileRepository.reset()
+
+ // Defragment the DB while it is quiescent: plugins, loop, sync and UI all start
+ // later, so the (memory heavy) VACUUM has the DB to itself. Runs at most monthly.
+ vacuumDatabaseIfDue()
+
+ // Register and initialize plugins
+ config.updateInitProgress(getString(R.string.initializing_plugins))
+ pluginStore.plugins = plugins
+ // Wait for the plugins to actually start, not just to be marked enabled. initialize()
+ // only schedules onStart, and everything below reads plugin state - the reconciler asks
+ // for the active pump on the next line. Bounded for the same reason applyConfiguration
+ // bounds it: a driver whose onStart will not settle must not hold up start up for ever.
+ val started = configBuilder.initialize()
+ if (withTimeoutOrNull(PLUGIN_START_WAIT) { started.joinAll() } == null)
+ aapsLogger.warn(LTag.CORE, "Plugins did not finish starting within $PLUGIN_START_WAIT")
+
+ // Running-mode reconciler + expiry scheduler. Start after plugins are registered:
+ // the reconciler's startup-drift check reads the active pump, which requires
+ // pluginStore.plugins to be populated. Both internally gated by config.APS.
+ runningModeReconciler.start()
+ runningModeExpiryScheduler.start()
+ // Fires a profile change at the exact end of a temporary ProfileSwitch (master-only),
+ // removing the up-to-5-min KeepAlive latency. KeepAlive remains the backstop.
+ profileSwitchScheduler.start()
+
+ // Standalone automation runtime (no longer a plugin). Loads definitions on all
+ // flavors; the processing loop + location service are master-only (gated internally).
+ automationRuntime.start()
+ // A reboot or a force stop removes the alarm of a running "time to eat" timer; set it again.
+ // Master only (gated internally).
+ eatReminder.restore()
+
+ // Data migrations (DB I/O)
+ dataMigrations()
+
+ config.updateInitProgress(getString(R.string.initializing))
+ doInit()
+ } catch (e: Exception) {
+ aapsLogger.error(LTag.CORE, "Fatal initialization error", e)
+ config.initFailed(e.message ?: "Unknown error")
+ }
+ }
+ }
+
+ /**
+ * The settings could not be opened ([AndroidStorage] says why), so AAPS does not start: no plugins, so no
+ * loop, and nothing written to the database. The app runs on an empty store that lives in memory only,
+ * which keeps its parts from crashing without writing over the unreadable file. A notification that
+ * cannot be swiped away says so, and SettingsUnreadableActivity shows the way out.
+ */
+ private fun startWithoutSettings(failure: Exception, notes: List) {
+ GeneratedStringOwners.registerAll()
+ // The user's answer about analytics and crash reports is in the settings that cannot be read, so it
+ // is "no" now - in memory only, like everything else.
+ sp.putBoolean(BooleanKey.MaintenanceEnableFabric.key, false)
+ fabricPrivacyImpl.start()
+ notes.forEach { aapsLogger.info(LTag.CORE, it) }
+ aapsLogger.error(LTag.CORE, "The settings cannot be opened, so AAPS does not start", failure)
+ SettingsUnreadableNotification.show(this, metroGraphs.iconsProvider.getNotificationIcon())
+ }
+
+ // Perform a full VACUUM at most once a month. VACUUM defragments the DB file and reclaims
+ // space, restoring query performance that degrades after long use. It is heavy and memory
+ // intensive, so it runs only here at startup while nothing else touches the DB (this avoids
+ // the SQLITE_NOMEM crash seen when VACUUM overlapped live DB activity).
+ private suspend fun vacuumDatabaseIfDue() {
+ val lastRun = preferences.get(LongNonKey.LastVacuumRun)
+ if (lastRun >= dateUtil.now() - T.days(30).msecs()) return
+
+ // Crash-loop guard. VACUUM can die below the JVM (native SQLite abort / OOM) in a way no
+ // try/catch can intercept — the process just vanishes, leaving no log. If that happened last
+ // time, the committed flag below is still set (the finally never ran). Detect it, skip
+ // VACUUM so the app can boot, and back off a month instead of re-crashing on every launch.
+ if (preferences.get(BooleanNonKey.VacuumInProgress)) {
+ aapsLogger.error(LTag.CORE, "Previous startup VACUUM did not finish (likely native crash) — skipping for 30 days")
+ // Report to Firebase so we get a fleet-wide count of users hit by a crashing startup VACUUM.
+ fabricPrivacy.logCustom("db_vacuum_crash_recovered")
+ preferences.put(BooleanNonKey.VacuumInProgress, false)
+ preferences.put(LongNonKey.LastVacuumRun, dateUtil.now())
+ return
+ }
+
+ config.updateInitProgress(getString(R.string.optimizing_database))
+ try {
+ // Log size + per-table counts (total / older-than-retention backlog / tracked changes)
+ // before VACUUM, so a crash report tells us whether the DB is the problem. 6*31 mirrors
+ // KeepAliveWorker.databaseCleanup's retention so "deletable" reflects the real backlog.
+ val info = persistenceLayer.databaseMaintenanceInfo(retentionDays = 6L * 31)
+ aapsLogger.info(LTag.CORE, "Startup DB maintenance, pre-VACUUM diagnostics:\n${info.report}")
+ // Crashlytics breadcrumb: attaches the diagnostics to any exception logged below.
+ fabricPrivacy.logMessage("Pre-VACUUM: ${info.report}")
+ val dbMb = info.dbSizeBytes / 1_048_576
+ // VACUUM rebuilds the whole DB into a temporary copy, so it needs roughly the DB size
+ // again in free space. Skip (and retry next launch) if there isn't enough, to avoid a
+ // SQLITE_FULL failure mid-rebuild.
+ if (info.availableBytes in 0 until info.dbSizeBytes * 2) {
+ val freeMb = info.availableBytes / 1_048_576
+ aapsLogger.warn(LTag.CORE, "Skipping startup VACUUM: free $freeMb MB < 2x DB $dbMb MB")
+ fabricPrivacy.logCustom("db_vacuum_skip_space", mapOf("db_mb" to dbMb, "free_mb" to freeMb))
+ return
+ }
+ // Commit the marker synchronously BEFORE running: a plain put() uses apply() and may not
+ // reach disk before an early native abort (e.g. during the wal_checkpoint VACUUM starts with).
+ sp.edit(commit = true) { putBoolean(BooleanNonKey.VacuumInProgress.key, true) }
+ val result = persistenceLayer.vacuumDatabase()
+ // Advance the timestamp on every result here, and only here: a thrown failure (e.g. DB busy
+ // because a persisted worker is running) is retried on a future launch instead of suppressed
+ // for a month. OUT_OF_MEMORY is not one of those: the next launch would fail the same way, so
+ // it waits a month too.
+ preferences.put(LongNonKey.LastVacuumRun, dateUtil.now())
+ when (result) {
+ VacuumResult.DONE, VacuumResult.DONE_AFTER_TRIM -> {
+ aapsLogger.debug(LTag.CORE, "Startup VACUUM done: $result")
+ // Fleet overview of DB size / cleanup backlog / change-row volume across users.
+ fabricPrivacy.logCustom("db_vacuum_ok", mapOf("db_mb" to dbMb, "deletable" to info.deletableRows, "changes" to info.changeRows))
+ // How many databases only fit after the old APS results and device statuses were deleted.
+ if (result == VacuumResult.DONE_AFTER_TRIM) fabricPrivacy.logCustom("db_vacuum_trimmed", mapOf("db_mb" to dbMb))
+ }
+
+ VacuumResult.OUT_OF_MEMORY -> {
+ aapsLogger.error(LTag.CORE, "Startup VACUUM ran out of memory, even after trimming. Next try in 30 days.")
+ fabricPrivacy.logCustom("db_vacuum_out_of_memory", mapOf("db_mb" to dbMb))
+ }
+ }
+ } catch (e: Throwable) {
+ // Throwable, not just Exception: a JVM OutOfMemoryError here must not abort app init.
+ aapsLogger.error(LTag.CORE, "Startup VACUUM failed", e)
+ // Catchable failures (SQLiteException, OOM) → Crashlytics non-fatal for the overview.
+ fabricPrivacy.logException(e)
+ } finally {
+ preferences.put(BooleanNonKey.VacuumInProgress, false)
+ }
+ }
+
+ /**
+ * Gives Android the language picked in AAPS as this app's language (Android 13 and newer). Android then shows
+ * the whole app in it - every screen, the notifications, the widget - and keeps the default locale on it, so
+ * numbers and dates are formatted in it too.
+ *
+ * AAPS used to move the default locale itself. Android sets the default locale back from the app's resources
+ * on many configuration updates, often without calling [onConfigurationChanged], so a Czech AAPS on an English
+ * phone showed "4.5" instead of "4,5" after its alarm screen had been shown.
+ *
+ * Android 12 has no app languages: there AAPS follows the phone's language, and the setting is hidden. Simple
+ * mode follows the phone too. Nothing is sent when Android has this language already.
+ */
+ private fun applyAppLanguage() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
+ val tag = appLanguageTag(preferences.get(StringKey.GeneralLanguage), preferences.get(BooleanKey.GeneralSimpleMode))
+ val wanted = tag?.let { LocaleList.forLanguageTags(it) } ?: LocaleList.getEmptyLocaleList()
+ val localeManager = getSystemService(LocaleManager::class.java)
+ if (localeManager.applicationLocales == wanted) return
+ aapsLogger.debug(LTag.CORE, "App language: ${tag ?: "the phone's"}")
+ localeManager.applicationLocales = wanted
+ }
+
+ /** A change of the AAPS language or of Simple mode goes to Android. What follows is in [onConfigurationChanged]. */
+ private fun followLanguage() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
+ appScope.launch {
+ merge(preferences.observe(StringKey.GeneralLanguage), preferences.observe(BooleanKey.GeneralSimpleMode))
+ .map { appLanguageTag(preferences.get(StringKey.GeneralLanguage), preferences.get(BooleanKey.GeneralSimpleMode)) }
+ .distinctUntilChanged()
+ .drop(1)
+ .collect { applyAppLanguage() }
+ }
+ }
+
+ /** The app's language as Android applies it, to notice a change. Null until the app has started. */
+ private var appLocales: LocaleList? = null
+
+ /**
+ * The app's language changed: the one picked in AAPS ([applyAppLanguage]), or the phone's while AAPS follows it.
+ * Android recreates the screens itself, but text built before - in the overview cache and in the view models -
+ * is in the old language. So the screens are rebuilt through `UiRestart`, as iOS and the desktop do, and the home
+ * screen widget draws again; it would otherwise wait up to a minute.
+ *
+ * Here and not where the language is picked: Android delivers the new language a moment later, and text read
+ * before that would still come out in the old one.
+ */
+ override fun onConfigurationChanged(newConfig: ResourcesConfiguration) {
+ super.onConfigurationChanged(newConfig)
+ val previous = appLocales ?: return
+ if (newConfig.locales == previous) return
+ appLocales = newConfig.locales
+ aapsLogger.debug(LTag.CORE, "App language changed to ${newConfig.locales.toLanguageTags()}")
+ uiRestart.request()
+ widgetUpdater.update("LanguageChanged")
+ }
+
+ private suspend fun doInit() {
+ aapsLogger.debug("doInit")
+ RxDogTag.install()
+ setRxErrorHandler()
+ followLanguage()
+
+ var gitRemote: String? = config.REMOTE
+ var commitHash: String? = BuildConfig.HEAD
+ if (gitRemote?.contains("NoGitSystemAvailable") == true) {
+ gitRemote = null
+ commitHash = null
+ }
+ aapsLogger.debug("Version: " + config.VERSION_NAME)
+ aapsLogger.debug("BuildVersion: " + config.BUILD_VERSION)
+ aapsLogger.debug("Remote: " + config.REMOTE)
+ aapsLogger.debug("Phone: " + Build.MANUFACTURER + " " + Build.MODEL)
+ registerLocalBroadcastReceiver()
+ setupRemoteConfig()
+
+ // trigger here to see the new version on app start after an update
+ handler.postDelayed({ versionCheckersUtils.triggerCheckVersion() }, 30000)
+
+ // delayed actions to make rh context updated for translations
+ handler.postDelayed(
+ {
+ // log version
+ appScope.launch {
+ persistenceLayer.insertVersionChangeIfChanged(config.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)
+ }
+ // log app start
+ if (preferences.get(BooleanKey.NsClientLogAppStart))
+ appScope.launch {
+ persistenceLayer.insertPumpTherapyEventIfNewByTimestamp(
+ therapyEvent = TE(
+ timestamp = dateUtil.now(),
+ type = TE.Type.NOTE,
+ note = rh.gs(InterfacesR.string.values_with_dash, rh.gs(CoreUiR.string.androidaps_start), "${Build.MANUFACTURER} ${Build.MODEL}"),
+ glucoseUnit = GlucoseUnit.MGDL
+ ),
+ action = Action.START_AAPS,
+ source = Sources.Aaps, note = "", listValues = listOf()
+ )
+ }
+ }, 10000
+ )
+ postSetupNotifications()
+ KeepAliveWorker.schedule(this@MainApp)
+ localAlertUtils.shortenSnoozeInterval()
+ localAlertUtils.preSnoozeAlarms()
+
+ // schedule widget update
+ refreshWidget = Runnable {
+ handler.postDelayed(refreshWidget, 60000)
+ widgetUpdater.update("ScheduleEveryMin")
+ }
+ handler.postDelayed(refreshWidget, 5000)
+ setUserStats()
+ passwordResetCheck()
+ exportPasswordResetCheck()
+ config.initCompleted()
+ rxBus.send(EventAppInitialized())
+ aapsLogger.debug("doInit end")
+ }
+
+ /** The build this is, in short form - "github:owner/repo". */
+ private val gitRemoteShort: String
+ get() = config.REMOTE.lowercase(Locale.getDefault())
+ .replace("https://", "")
+ .replace("http://", "")
+ .replace(".git", "")
+ .replace(".com/", ":")
+ .replace(".org/", ":")
+ .replace(".net/", ":")
+
+ /**
+ * Which build is running. All of it is known from BuildConfig before anything starts, so it is set as
+ * early as collection is allowed - see the call in [onCreate].
+ */
+ private fun setBuildIdentityKeys() {
+ FirebaseCrashlytics.getInstance().apply {
+ setCustomKey("HEAD", BuildConfig.HEAD)
+ setCustomKey("Version", config.VERSION_NAME)
+ setCustomKey("BuildType", config.BUILD_TYPE)
+ setCustomKey("BuildFlavor", config.FLAVOR)
+ setCustomKey("Remote", gitRemoteShort)
+ setCustomKey("Committed", config.COMMITTED)
+ }
+ }
+
+ private suspend fun setUserStats() {
+ if (!fabricPrivacy.fabricEnabled()) return
+ val closedLoopEnabled = if (constraintChecker.isClosedLoopAllowed().value()) "CLOSED_LOOP_ENABLED" else "CLOSED_LOOP_DISABLED"
+ fabricPrivacy.setUserProperty("Mode", config.APPLICATION_ID + "-" + closedLoopEnabled)
+ fabricPrivacy.setUserProperty("Language", preferences.getIfExists(StringKey.GeneralLanguage) ?: Locale.getDefault().language)
+ fabricPrivacy.setUserProperty("Version", config.VERSION_NAME)
+ fabricPrivacy.setUserProperty("HEAD", BuildConfig.BUILDVERSION)
+ fabricPrivacy.setUserProperty("Remote", gitRemoteShort)
+ val hashes: List = signatureVerifierPlugin.shortHashes()
+ if (hashes.isNotEmpty()) fabricPrivacy.setUserProperty("Hash", hashes[0])
+ activePlugin.activePumpInternal.let { fabricPrivacy.setUserProperty("Pump", it::class.java.simpleName) }
+ if (!config.AAPSCLIENT && !config.PUMPCONTROL)
+ activePlugin.activeAPS?.let { fabricPrivacy.setUserProperty("Aps", it::class.java.simpleName) }
+ activePlugin.activeBgSource.let { fabricPrivacy.setUserProperty("BgSource", it::class.java.simpleName) }
+ activePlugin.activeSensitivity.let { fabricPrivacy.setUserProperty("Sensitivity", it::class.java.simpleName) }
+ // HEAD/Version/BuildType/BuildFlavor/Remote/Committed are set in setBuildIdentityKeys() during
+ // onCreate. These two are not known that early.
+ if (hashes.isNotEmpty()) FirebaseCrashlytics.getInstance().setCustomKey("Hash", hashes[0])
+ FirebaseCrashlytics.getInstance().setCustomKey("Email", preferences.get(StringKey.MaintenanceIdentification))
+ }
+
+ private suspend fun passwordResetCheck() {
+ val fh = fileListProvider.ensureExtraDirExists()?.findFile("PasswordReset")
+ if (fh?.exists() == true) {
+ config.updateInitProgress(getString(CoreUiR.string.waiting_for_pump))
+ val serialNumber = withTimeoutOrNull(30_000.milliseconds) {
+ while (activePlugin.activePump.serialNumber().isEmpty()) {
+ delay(100.milliseconds)
+ }
+ activePlugin.activePump.serialNumber()
+ }
+ if (serialNumber != null) {
+ preferences.put(StringKey.ProtectionMasterPassword, cryptoUtil.hashPassword(serialNumber))
+ fh.delete()
+ exportPasswordDataStore.clearPasswordDataStore()
+ config.showInitSnackbar(getString(app.aaps.core.ui.R.string.password_set))
+ } else {
+ aapsLogger.warn(LTag.CORE, "Password reset timed out waiting for pump serial number")
+ }
+ }
+ }
+
+ private fun exportPasswordResetCheck() {
+ val fh = fileListProvider.ensureExtraDirExists()?.findFile("ExportPasswordReset")
+ if (fh?.exists() == true) {
+ exportPasswordDataStore.clearPasswordDataStore()
+ fh.delete()
+ config.showInitSnackbar(getString(app.aaps.core.ui.R.string.datastore_password_cleared))
+ }
+ }
+
+ private fun postSetupNotifications() {
+ // Identification not set (dev builds only)
+ if (config.isDev() && preferences.get(StringKey.MaintenanceIdentification).isBlank())
+ notificationManager.post(
+ id = NotificationId.IDENTIFICATION_NOT_SET,
+ TextRef.AndroidRes(R.string.identification_not_set),
+ level = NotificationLevel.INFO,
+ actions = listOf(NotificationAction(TextRef.AndroidRes(R.string.set)) {}),
+ validityCheck = { config.isDev() && preferences.get(StringKey.MaintenanceIdentification).isBlank() }
+ )
+ // Master password not set
+ if (preferences.get(StringKey.ProtectionMasterPassword) == "")
+ notificationManager.post(
+ id = NotificationId.MASTER_PASSWORD_NOT_SET,
+ TextRef.AndroidRes(app.aaps.core.ui.R.string.master_password_not_set),
+ level = NotificationLevel.NORMAL,
+ actions = listOf(NotificationAction(TextRef.AndroidRes(R.string.set)) {}),
+ validityCheck = { preferences.get(StringKey.ProtectionMasterPassword) == "" }
+ )
+ // AAPS directory not selected
+ if (preferences.getIfExists(StringKey.AapsDirectoryUri).isNullOrEmpty())
+ notificationManager.post(
+ id = NotificationId.AAPS_DIR_NOT_SELECTED,
+ TextRef.AndroidRes(app.aaps.core.ui.R.string.aaps_directory_not_selected),
+ level = NotificationLevel.LOW,
+ actions = listOf(NotificationAction(TextRef.AndroidRes(R.string.select)) {}),
+ validityCheck = { preferences.getIfExists(StringKey.AapsDirectoryUri).isNullOrEmpty() }
+ )
+ // AAPS directory selected, but the permission behind it is gone.
+ //
+ // The check above only ever looked at whether the URI string is there, so this case was
+ // completely silent: the directory is still "selected", the folder and the old exports are
+ // still on the phone, and the Local export button simply goes grey. Android drops a persisted
+ // SAF grant on reinstall and on "clear storage", so it happens to people who did nothing
+ // wrong. Found on a real phone where the last local backup was four months old and nobody
+ // knew - and a user with no cloud set up has, at that point, no backup at all.
+ else if (!fileListProvider.isDirectoryAccessGranted())
+ notificationManager.post(
+ id = NotificationId.AAPS_DIR_ACCESS_LOST,
+ TextRef.AndroidRes(app.aaps.core.ui.R.string.aaps_directory_access_lost),
+ actions = listOf(NotificationAction(TextRef.AndroidRes(R.string.select)) {}),
+ validityCheck = { !fileListProvider.isDirectoryAccessGranted() }
+ )
+ }
+
+ private fun setRxErrorHandler() {
+ RxJavaPlugins.setErrorHandler { t: Throwable ->
+ var e = t
+ if (e is UndeliverableException) {
+ e = e.cause!!
+ }
+ if (e is IOException) {
+ // fine, irrelevant network problem or API that throws on cancellation
+ return@setErrorHandler
+ }
+ if (e is InterruptedException) {
+ // fine, some blocking code was interrupted by a dispose call
+ return@setErrorHandler
+ }
+ if (e is NullPointerException || e is IllegalArgumentException) {
+ // that's likely a bug in the application
+ Thread.currentThread().uncaughtExceptionHandler?.uncaughtException(Thread.currentThread(), e)
+ return@setErrorHandler
+ }
+ if (e is IllegalStateException) {
+ // that's a bug in RxJava or in a custom operator
+ Thread.currentThread().uncaughtExceptionHandler?.uncaughtException(Thread.currentThread(), e)
+ return@setErrorHandler
+ }
+ aapsLogger.warn(LTag.CORE, "Undeliverable exception received, not sure what to do", e.localizedMessage)
+ }
+ }
+
+ private suspend fun doMigrations() {
+ // Which insulin curve the old records were delivered with, for the database migration in
+ // dataMigrations(). Read BEFORE the migrations, because the migration that deletes these dead
+ // ConfigBuilder rows is one of them now. InsulinMigrationTest pins that order.
+ legacyInsulin = insulinMigration.readLegacyInsulin(sp)
+
+ // The preference migrations, in order, against this device's store.
+ //
+ // They live in :implementation and take the store to work on, because the settings IMPORT runs
+ // exactly the same functions over the imported file. An old backup's names never reach this
+ // store any more - PreferenceImportApplier drops what it cannot resolve - so a start-up only
+ // pass can no longer see them, and the user loses their profiles, plugin selection, objectives
+ // and loop mode. See PreferenceMigrations for what is in the list and what is deliberately not.
+ PreferenceMigrations(aapsLogger, config, persistenceLayer, dateUtil, profileUtil).migrate(sp)
+ // Those writes go below Preferences, so the cached flows have not seen them.
+ preferences.reloadFromStore()
+
+ // Seeds simple mode for an install that predates the key.
+ //
+ // NOT a migration and deliberately not in the list above: it invents a value rather than moving
+ // one, and `simple_mode` feeds PreferencesImpl.calculatedDefaultValue, so a wrong guess changes
+ // the effective value of a whole family of settings. Skipped on a client, which adopts the
+ // value from the master via sync - a local put here would trigger a client→master round-trip
+ // (modal) at startup. The master seeds and publishes; the client follows.
+ if (!config.AAPSCLIENT && preferences.getIfExists(BooleanKey.GeneralSimpleMode) == null)
+ preferences.put(BooleanKey.GeneralSimpleMode, !preferences.get(BooleanNonKey.GeneralSetupWizardProcessed))
+
+ // Harvest the DIA each old profile was using, for the database migration in dataMigrations().
+ //
+ // NOT a key migration and deliberately not in PreferenceMigrations: it fills a field this class
+ // reads much later. The migration writes the new `_name` key but leaves the raw one, exactly so
+ // this can still pair a profile with its DIA - see profileDia, whose keys are dropped in
+ // dataMigrations(), once the values they carry are safely in the insulin list.
+ profileDia = insulinMigration.harvestProfileDia(sp)
+
+ // Rebuilding them from the old keys is a migration and has already run above. This only fills
+ // in the three factory presets for an install that has none.
+ seedTempTargetPresets()
+ }
+
+ /**
+ * Creates the three factory temp target presets for an install that has none.
+ *
+ * New-install bootstrap only. Rebuilding the presets from an older AAPS's keys is a migration and
+ * lives in `PreferenceMigrations`; this half cannot, because it INVENTS values, and over an
+ * imported file it would write factory presets on top of the ones the user actually has.
+ *
+ * Skipped on a client, which adopts the presets from the master over the sync channel - a local
+ * put here would trigger a client-to-master round trip at startup.
+ */
+ private fun seedTempTargetPresets() {
+ if (config.AAPSCLIENT) return
+ val existing = preferences.get(StringNonKey.TempTargetPresets)
+ if (existing != "[]" && existing.isNotEmpty()) return
+ // Only when there is nothing to migrate from. PreferenceMigrations has already run and would
+ // have written the document if the old keys were there.
+ if (sp.contains("eatingsoon_target")) return
+
+ val presets = listOf(
+ TTPreset(
+ id = "eatingsoon", reason = TT.Reason.EATING_SOON,
+ targetValue = Constants.DEFAULT_TT_EATING_SOON_TARGET,
+ duration = Constants.DEFAULT_TT_EATING_SOON_DURATION * 60L * 1000L, isDeletable = false
+ ),
+ TTPreset(
+ id = "activity", reason = TT.Reason.ACTIVITY,
+ targetValue = Constants.DEFAULT_TT_ACTIVITY_TARGET,
+ duration = Constants.DEFAULT_TT_ACTIVITY_DURATION * 60L * 1000L, isDeletable = false
+ ),
+ TTPreset(
+ id = "hypo", reason = TT.Reason.HYPOGLYCEMIA,
+ targetValue = Constants.DEFAULT_TT_HYPO_TARGET,
+ duration = Constants.DEFAULT_TT_HYPO_DURATION * 60L * 1000L, isDeletable = false
+ )
+ )
+ preferences.put(StringNonKey.TempTargetPresets, presets.toJson())
+ aapsLogger.debug(LTag.CORE, "Seeded default temp target presets")
+ }
+
+ private suspend fun dataMigrations() {
+ // Migrate to database 33 (ICfg)
+ //
+ // Goal: legacy rows predate ICfg, so they carry the `insulinEndTime = -1` sentinel and their IOB
+ // is computed from the clamped math floors in ICfg.iobCalcForTreatment — which under-counts IOB.
+ // Stamping them makes the insulin curve a property of the record, as v33 intends.
+ //
+ // The value must be the insulin those records were actually delivered with, and InsulinMigration
+ // owns that decision - see its KDoc for the order it asks in and why. The record's own insulin wins:
+ // migration32to33 carries the v3 columns across, so for a profile switch the row already knows. The
+ // legacy preferences answer the rows that have nothing, boluses above all - v3 never stamped one.
+ //
+ // The record, not profileFunction.getProfile(): this runs before app init completes, and no profile
+ // is handed out until then. getRunningOrRequestedICfg() rejects an unusable iCfg, so a running row
+ // that still carries the sentinel falls through instead of writing the sentinel back over itself.
+ val plan = insulinMigration.plan(
+ recordICfg = profileFunction.getRunningOrRequestedICfg(),
+ legacy = legacyInsulin,
+ harvest = profileDia,
+ activeProfileName = persistenceLayer.getEffectiveProfileSwitchActiveAt(dateUtil.now())?.originalProfileName
+ )
+ // Puts it in the catalogue and gives back the stored copy, whose label the records are stamped with.
+ // On a v3 install this REPLACES the default the first load invented, so the user does not come out
+ // of the upgrade with an insulin they never had sitting in front of their own.
+ //
+ // NO_LEGACY_DATA is the exception, and a fresh install is why: nothing from v3, no profile yet and
+ // no records to stamp all look the same from here. So that plan is used for the stamping below -
+ // which then changes nothing - and the catalogue is left alone, because the default already in it
+ // is just as good and a second invented insulin beside the first is not.
+ val runningICfg =
+ if (plan.source == InsulinMigrationPlan.Source.NO_LEGACY_DATA) plan.iCfg
+ else localInsulinManager.seedFromMigration(plan.iCfg)
+
+ // The DIA these keys carry is now in the insulin list, so the old copies can go. This is the
+ // first point where losing them costs nothing - see profileDia for why they were not dropped
+ // when they were read.
+ profileDia.keysToRemove.forEach { sp.remove(it) }
+ profileDia = ProfileDiaHarvest(emptyMap(), emptyList())
+
+ val label = runningICfg.insulinLabel
+ val end = runningICfg.insulinEndTime
+ val peak = runningICfg.insulinPeakTime
+ val conc = runningICfg.concentration
+
+ config.updateInitProgress(rh.gs(R.string.migrating_profile_switches))
+ val migratedPs = repository.bulkMigrateProfileSwitchInsulinConfig(label, end, peak, conc)
+
+ config.updateInitProgress(rh.gs(R.string.migrating_effective_profile_switches))
+ val migratedEps = repository.bulkMigrateEffectiveProfileSwitchInsulinConfig(label, end, peak, conc)
+
+ config.updateInitProgress(rh.gs(R.string.migrating_boluses))
+ val migratedBoluses = repository.bulkMigrateBolusInsulinConfig(label, end, peak, conc)
+
+ val totalMigrated = migratedPs + migratedEps + migratedBoluses
+ if (totalMigrated > 0) {
+ // Part of the value was invented, and records really were stamped with it, so say so. The count
+ // is what makes this quiet on an install with nothing to migrate - a fresh one above all, which
+ // used to be told its "older records" had no insulin configuration. It is one-way: the sentinel
+ // is consumed, so these records are not revisited, which is why the notification says that too.
+ if (plan.isGuess) reportGuessedInsulinMigration(plan)
+ profileFunction.invalidateCache()
+ aapsLogger.debug(LTag.CORE, "Migration to DB 33 complete: $totalMigrated records updated")
+ persistenceLayer.insertPumpTherapyEventIfNewByTimestamp(
+ therapyEvent = TE(
+ timestamp = dateUtil.now(),
+ type = TE.Type.NOTE,
+ note = "Database migration to v33: $totalMigrated records updated (insulin configuration)",
+ glucoseUnit = GlucoseUnit.MGDL
+ ),
+ action = Action.START_AAPS,
+ source = Sources.Aaps,
+ note = "",
+ listValues = listOf()
+ )
+ }
+ }
+
+ /**
+ * Tells the user that part of the insulin stamped onto their old records was invented.
+ *
+ * Both cases are permanent: the stamp consumes the v33 sentinel, so these records are never revisited
+ * and the value is not corrected later. That is why this is a notification and not only a log line.
+ *
+ * [InsulinMigrationPlan.Source.GUESSED_DIA] is the one that used to be silent. The insulin itself is
+ * right - the v3 plugin selection said so - but no DIA could be found for it, so the hard-limit maximum
+ * stands in, which is 9 h for an adult. On an install with one local profile, or several that agree,
+ * `ProfileDiaHarvest.diaFor` now answers and this does not fire at all.
+ */
+ private fun reportGuessedInsulinMigration(plan: InsulinMigrationPlan) {
+ val label = plan.iCfg.insulinLabel.ifBlank { plan.iCfg.insulinNickname }
+ aapsLogger.warn(LTag.CORE, "Migration to DB 33: ${plan.source}, stamping $label with ${plan.iCfg.dia} h DIA")
+ val text =
+ if (plan.source == InsulinMigrationPlan.Source.GUESSED_DIA) rh.gs(R.string.insulin_migration_default_dia_used, plan.iCfg.dia, label)
+ else rh.gs(R.string.insulin_migration_default_used, label)
+ notificationManager.post(
+ id = NotificationId.INSULIN_MIGRATION_DEFAULT_USED,
+ text,
+ level = NotificationLevel.IMPORTANT
+ )
+ }
+
+ private val timeDateReceiver = TimeDateOrTZChangeReceiver()
+ private val networkReceiver = NetworkChangeReceiver()
+ private val chargingReceiver = ChargingStateReceiver()
+ private val btReceiver = BTReceiver()
+
+ private fun registerLocalBroadcastReceiver() {
+ var filter = IntentFilter()
+ filter.addAction(Intent.ACTION_TIME_CHANGED)
+ filter.addAction(Intent.ACTION_TIMEZONE_CHANGED)
+ registerReceiver(timeDateReceiver, filter)
+ filter = IntentFilter()
+ @Suppress("DEPRECATION")
+ filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
+ filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
+ filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
+ registerReceiver(networkReceiver, filter)
+ filter = IntentFilter()
+ filter.addAction(Intent.ACTION_POWER_CONNECTED)
+ filter.addAction(Intent.ACTION_POWER_DISCONNECTED)
+ filter.addAction(Intent.ACTION_BATTERY_CHANGED)
+ registerReceiver(chargingReceiver, filter)
+ filter = IntentFilter()
+ filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
+ filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
+ registerReceiver(btReceiver, filter)
+ }
+
+ private fun unregisterReceivers() {
+ super.onTerminate()
+ unregisterReceiver(timeDateReceiver)
+ unregisterReceiver(networkReceiver)
+ unregisterReceiver(chargingReceiver)
+ unregisterReceiver(btReceiver)
+ }
+
+ private fun setupRemoteConfig() {
+ FirebaseApp.initializeApp(this)
+ Firebase.remoteConfig.also { firebaseRemoteConfig ->
+
+ firebaseRemoteConfig.setConfigSettingsAsync(
+ FirebaseRemoteConfigSettings
+ .Builder()
+ .setMinimumFetchIntervalInSeconds(3600)
+ .build()
+ )
+ firebaseRemoteConfig
+ .fetchAndActivate()
+ .addOnCompleteListener { task ->
+ if (task.isSuccessful) {
+ aapsLogger.debug("RemoteConfig received successfully")
+ @Suppress("UNCHECKED_CAST")
+ (versionCheckersUtils::class.declaredMemberProperties.find { it.name == "definition" } as KMutableProperty?)
+ ?.let {
+ // `definition` is read through reflection, so the cast below is unchecked and the
+ // compiler cannot see it. It said JSONObject long after the property became a
+ // kotlinx JsonObject, and the app crashed on start as soon as a remote config
+ // fetch actually succeeded - which needs network and Play Services, so no test or
+ // CI build ever reached it. Keep the two types here in step by hand.
+ val current = it.getter.call(versionCheckersUtils) as JsonObject
+ val remote = Json.parseToJsonElement(firebaseRemoteConfig.getString("defs")).jsonObject
+ // Plus on the maps is a shallow merge with the remote keys winning.
+ it.setter.call(versionCheckersUtils, JsonObject(current + remote))
+ }
+ } else aapsLogger.error("RemoteConfig fetch failed")
+ }
+ }
+ }
+
+ override fun onTerminate() {
+ aapsLogger.debug(LTag.CORE, "onTerminate")
+ handler.removeCallbacksAndMessages(null)
+ handler.looper.quitSafely()
+ unregisterReceivers()
+ uiInteraction.stopAlarm("onTerminate")
+ super.onTerminate()
+ }
+
+ /**
+ * Teaches the resolvers which module owns which string names.
+ * A `TextRef.Named` carries an owner and a name, and both the Compose and the ResourceHelper
+ * paths need a way to turn that into an `R.string` id. `:core:keys`, `:core:interfaces` and
+ * `:core:ui` are resolved directly because `:core:ui` sits above them, but a plugin or pump
+ * module sits ABOVE `:core:ui`, so it can only be reached from here - `:app` is the one place
+ * that depends on all of them.
+ * Without this the lookup answers null and the raw name is drawn: `virtualpump_settings`
+ * instead of "Virtual pump settings".
+ */
+}
diff --git a/app/main/kotlin/app/aaps/di/ExternalOptionsOverride.kt b/app/main/kotlin/app/aaps/di/ExternalOptionsOverride.kt
new file mode 100644
index 000000000000..a31300462e4c
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/ExternalOptionsOverride.kt
@@ -0,0 +1,27 @@
+package app.aaps.di
+
+import app.aaps.core.interfaces.configuration.ExternalOptions
+import app.aaps.di.ExternalOptionsOverride.Companion.NONE
+
+/**
+ * Extra [ExternalOptions] to report as enabled, on top of what the production file lookup finds.
+ * Production passes [NONE]. The instrumented tests pass a live one so they can drive the in-tree pump
+ * emulators, which are selected purely on `config.isEnabled(EMULATE_*)`.
+ * ## Why this is a graph input rather than a replaced binding
+ * So the only channel into the one graph is its factory, which is what this travels through. It is the
+ * same shape `DatabaseConfig.IN_MEMORY` already uses, and keeping **one** graph matters more than
+ * keeping the seam out of production: a second graph declared in androidTest could drift from the real
+ * one silently, which is the exact class of bug this migration has kept producing.
+ * A function, not a value: the tests set their options **per test**, long after the application has
+ * built the graph, so this has to be read on each call rather than captured at construction.
+ */
+fun interface ExternalOptionsOverride {
+
+ fun enabled(): Set
+
+ companion object {
+
+ /** Production: the file lookup decides everything. */
+ val NONE = ExternalOptionsOverride { emptySet() }
+ }
+}
diff --git a/app/main/kotlin/app/aaps/di/PluginListMerge.kt b/app/main/kotlin/app/aaps/di/PluginListMerge.kt
new file mode 100644
index 000000000000..ec48a6626d8e
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/PluginListMerge.kt
@@ -0,0 +1,60 @@
+package app.aaps.di
+
+import app.aaps.core.interfaces.plugin.PluginBase
+
+/**
+ * One source of plugins, so a problem can name where it came from.
+ * @param name shown in the error message, for example "Metro @APS" or "Metro".
+ * @param plugins the plugins that source contributes, keyed by their display order.
+ */
+data class PluginSource(val name: String, val plugins: Map)
+
+/**
+ * Merges the plugin maps and reports anything wrong with the result.
+ * Global `@IntKey` ordering - one contiguous block per feature module, step 10 within a block:
+ * ```
+ * 0-10 general (persistent notification, iob) :plugins:main
+ * 100-120 sensitivity :plugins:sensitivity
+ * 200-240 aps (loop, openAPS engines, autotune) :plugins:aps
+ * 300-370 sync (sms, nsclient, upload, wear, …) :plugins:sync
+ * 400-550 bg sources :plugins:source
+ * 600-630 smoothing :plugins:smoothing
+ * 700-710 calibration :plugins:calibration
+ * 800-860 constraints (safety, objectives, …) :plugins:constraints
+ * 1000 VirtualPump (all configs) :pump:virtual
+ * 1010+ real pump drivers (@PumpDriver, step 10) :pump:* modules
+ * ```
+ * Two mistakes are possible across the buckets, and **both are silent**:
+ * A bucket cannot see the other buckets' contributions, so the framework cannot detect either case
+ * on its own. Hence this.
+ * @return the merged plugins in display order, plus a list of problems. An empty problem list means
+ * the merge is healthy.
+ */
+fun mergePlugins(sources: List): Pair, List> {
+ val problems = mutableListOf()
+ val merged = LinkedHashMap()
+ val keyOwner = mutableMapOf()
+
+ for (source in sources) {
+ for ((key, plugin) in source.plugins) {
+ val previousOwner = keyOwner[key]
+ if (previousOwner != null) {
+ val previous = merged.getValue(key)
+ problems += "order key $key used by both ${previousOwner} (${previous.javaClass.simpleName})" +
+ " and ${source.name} (${plugin.javaClass.simpleName}) - one of them is dropped"
+ }
+ merged[key] = plugin
+ keyOwner[key] = source.name
+ }
+ }
+
+ val ordered = merged.toList().sortedBy { it.first }.map { it.second }
+ ordered.groupBy { it.javaClass }
+ .filterValues { it.size > 1 }
+ .forEach { (type, copies) ->
+ problems += "plugin ${type.simpleName} is in the list ${copies.size} times" +
+ " - it is probably contributed by two buckets at once"
+ }
+
+ return ordered to problems
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/AapsViewModelFactory.kt b/app/main/kotlin/app/aaps/di/metro/AapsViewModelFactory.kt
new file mode 100644
index 000000000000..cc6e532bbfc7
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/AapsViewModelFactory.kt
@@ -0,0 +1,31 @@
+package app.aaps.di.metro
+
+import androidx.lifecycle.ViewModel
+import app.aaps.plugins.sync.di.OpenHumansMetroBridge
+import dev.zacsweers.metrox.viewmodel.ManualViewModelAssistedFactory
+import dev.zacsweers.metrox.viewmodel.MetroViewModelFactory
+import dev.zacsweers.metrox.viewmodel.ViewModelAssistedFactory
+import kotlin.reflect.KClass
+
+/**
+ * Each view model carries its own registration - `@ContributesIntoMap` plus `@ViewModelKey` on the
+ * class - so adding one touches no graph and no factory. This class only merges the maps.
+ * Two maps, because there are two graphs. Open Humans is still a root of its own rather than an
+ * extension (its view models are `internal`, see `OpenHumansMetroGraph`), so its contributions land in
+ * a separate map. The keys are view model classes, so the two cannot collide.
+ */
+class AapsViewModelFactory(
+ root: AppRootGraph,
+ openHumans: OpenHumansMetroBridge
+) : MetroViewModelFactory() {
+
+ override val viewModelProviders: Map, () -> ViewModel> =
+ root.viewModelProviders + openHumans.viewModelProviders
+
+ override val assistedFactoryProviders: Map, () -> ViewModelAssistedFactory> =
+ root.assistedFactoryProviders + openHumans.assistedFactoryProviders
+
+ override val manualAssistedFactoryProviders:
+ Map, () -> ManualViewModelAssistedFactory> =
+ root.manualAssistedFactoryProviders + openHumans.manualAssistedFactoryProviders
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/AppAndroidBindings.kt b/app/main/kotlin/app/aaps/di/metro/AppAndroidBindings.kt
new file mode 100644
index 000000000000..a6491897350d
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/AppAndroidBindings.kt
@@ -0,0 +1,59 @@
+package app.aaps.di.metro
+
+import android.content.Context
+import android.telephony.SmsManager
+import app.aaps.core.interfaces.resources.ResourceHelper
+import app.aaps.core.interfaces.resources.TextResolver
+import app.aaps.core.utils.receivers.DataInbox
+import app.aaps.history.HistoryBrowserData
+import app.aaps.ui.compose.history.HistoryScope
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.BindingContainer
+import dev.zacsweers.metro.ContributesTo
+import dev.zacsweers.metro.Provides
+import dev.zacsweers.metro.SingleIn
+
+/**
+ * These have no interface and no implementation class to annotate, so they cannot be contributed with
+ * `@ContributesBinding` - they need a container with a `@Provides`. `:app` is Android only, so this can
+ * live here; a module that is multiplatform would need the same thing in its **androidMain**, the way
+ * `CoreObjectsJvmContainer` does for `CryptoUtil`.
+ */
+@ContributesTo(AppScope::class)
+@BindingContainer
+object AppAndroidBindings {
+
+ /**
+ * Metro would construct this by itself - it has an `@Inject` constructor - but only the scope makes
+ * it a singleton, and it must be one: it is the inbox the broadcast receivers hand data to. It is
+ * declared here rather than annotated in place because `:core:utils` does not run Metro.
+ */
+ @Provides
+ @SingleIn(AppScope::class)
+ fun dataInbox(context: Context): DataInbox = DataInbox(context)
+
+ /**
+ * The SMS service, which is null on a device without telephony.
+ */
+ @Suppress("DEPRECATION")
+ @Provides
+ fun smsManager(context: Context): SmsManager? = context.getSystemService(SmsManager::class.java)
+
+ /**
+ * `ResourceHelper` is the Android implementation of the multiplatform [TextResolver].
+ */
+ @Provides
+ fun textResolver(rh: ResourceHelper): TextResolver = rh
+
+ /**
+ * The History Browser's own calculation objects.
+ * Scoped here rather than on the class: the window must be created **once**, because the whole
+ * point of `HistoryBrowserData` is that browsing history does not share - and so cannot rewrite -
+ * the state the running loop calculates on. An unscoped provider would hand out a fresh window per
+ * injection point and quietly undo that.
+ */
+ @Provides
+ @SingleIn(AppScope::class)
+ fun historyScope(historyWindowFactory: HistoryWindowGraph.Factory): HistoryScope =
+ HistoryBrowserData(historyWindowFactory.create())
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/AppCoroutineBindings.kt b/app/main/kotlin/app/aaps/di/metro/AppCoroutineBindings.kt
new file mode 100644
index 000000000000..017d71c54b92
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/AppCoroutineBindings.kt
@@ -0,0 +1,33 @@
+package app.aaps.di.metro
+
+import app.aaps.core.interfaces.di.ApplicationScope
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.BindingContainer
+import dev.zacsweers.metro.ContributesTo
+import dev.zacsweers.metro.Provides
+import kotlinx.coroutines.CoroutineScope
+
+/**
+ * The application scope, owned by Metro.
+ * There must be exactly one. A second scope would not fail anything loudly: it would simply never be
+ * cancelled with the first, so work started on it would outlive what was supposed to stop it.
+ */
+@ContributesTo(AppScope::class)
+@BindingContainer
+object AppCoroutineBindings {
+
+ /**
+ * The same scope again, unqualified, for the classes that take a plain `CoroutineScope`.
+ *
+ * Not because the qualifier is unavailable to them: `ApplicationScope` is a Metro `@Qualifier`
+ * and lives in `core/interfaces` **commonMain**, so shared code can and does ask for it -
+ * `ClientGraphBindings` does exactly that. The comment here used to say it was a javax qualifier
+ * that could not appear in commonMain, which was wrong on both counts.
+ *
+ * The alias exists so that a class which only ever wants "the app scope" can say so without
+ * naming a qualifier. The client graphs derive the qualified one from the plain one instead -
+ * opposite order, same single object, and each graph owns whichever end it declares.
+ */
+ @Provides
+ fun unqualifiedAppScope(@ApplicationScope scope: CoroutineScope): CoroutineScope = scope
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/AppMemberInjectors.kt b/app/main/kotlin/app/aaps/di/metro/AppMemberInjectors.kt
new file mode 100644
index 000000000000..24be5f31a965
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/AppMemberInjectors.kt
@@ -0,0 +1,32 @@
+package app.aaps.di.metro
+
+import app.aaps.ComposeMainActivity
+import app.aaps.core.interfaces.di.FeatureMemberInjectors
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.BindingContainer
+import dev.zacsweers.metro.ClassKey
+import dev.zacsweers.metro.ContributesTo
+import dev.zacsweers.metro.IntoMap
+import dev.zacsweers.metro.MembersInjector
+import dev.zacsweers.metro.Provides
+
+/**
+ * Member injectors for the activities this module owns.
+ *
+ * Same shape as `UiMemberInjectors` in `:ui`: Android builds the activity, so it cannot take its
+ * dependencies in a constructor and fills its own fields once it exists. `MetroAppCompatActivity`
+ * reads this map in `onCreate`.
+ *
+ * An activity missing from here fails on launch with its own name in the message, rather than later
+ * at the first use of a field that was never set.
+ */
+@ContributesTo(AppScope::class)
+@BindingContainer
+object AppMemberInjectors {
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(ComposeMainActivity::class)
+ fun bindComposeMainActivity(injector: MembersInjector): MembersInjector<*> = injector
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/AppReceiversBindings.kt b/app/main/kotlin/app/aaps/di/metro/AppReceiversBindings.kt
new file mode 100644
index 000000000000..5ff9588d8c01
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/AppReceiversBindings.kt
@@ -0,0 +1,109 @@
+package app.aaps.di.metro
+
+import app.aaps.core.interfaces.di.FeatureMemberInjectors
+import app.aaps.implementation.alerts.EatReminderReceiver
+import app.aaps.implementation.androidNotification.AlarmMuteReceiver
+import app.aaps.implementation.receivers.BTReceiver
+import app.aaps.implementation.receivers.ChargingStateReceiver
+import app.aaps.implementation.receivers.NetworkChangeReceiver
+import app.aaps.implementation.receivers.TimeDateOrTZChangeReceiver
+import app.aaps.persistentNotification.DummyService
+import app.aaps.receivers.AutoStartReceiver
+import app.aaps.receivers.CarbSuggestionReceiver
+import app.aaps.receivers.DataReceiver
+import app.aaps.receivers.SmsReceiver
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.BindingContainer
+import dev.zacsweers.metro.ClassKey
+import dev.zacsweers.metro.ContributesTo
+import dev.zacsweers.metro.IntoMap
+import dev.zacsweers.metro.MembersInjector
+import dev.zacsweers.metro.Provides
+
+/**
+ * Metro wiring for Android classes that inject their own fields - the `@ContributesAndroidInjector`
+ * replacement, and the biggest of the four categories at 294 sites.
+ * Contributed into the root's one `@FeatureMemberInjectors` map, the same way every pump module does
+ * it - see `DanaRSMemberInjectors`. It used to be a graph extension with a map of its own, which meant
+ * `MetroGraphs` had to name it and then search four maps in turn to find an injector. One map is one
+ * lookup, and a module can add to it without anything in `:app` knowing.
+ * Cost per converted class is one `@Provides @IntoMap @ClassKey` line, the same order of work as the
+ * `@ContributesAndroidInjector` line it replaces.
+ */
+@ContributesTo(AppScope::class)
+@BindingContainer
+object AppReceiversBindings {
+
+ // Android builds this one from a notification action, so it must be in the map like the rest.
+ // It was converted to MetroBroadcastReceiver without an entry here, and tapping Mute or Dismiss
+ // on the background alarm notification then died with "No Metro binding for AlarmMuteReceiver"
+ // (issue #5124).
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(AlarmMuteReceiver::class)
+ fun bindAlarmMuteReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ // The "time to eat" alarm and its notification buttons - same story as AlarmMuteReceiver above.
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(EatReminderReceiver::class)
+ fun bindEatReminderReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(ChargingStateReceiver::class)
+ fun bindChargingStateReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(NetworkChangeReceiver::class)
+ fun bindNetworkChangeReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(BTReceiver::class)
+ fun bindBTReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(CarbSuggestionReceiver::class)
+ fun bindCarbSuggestionReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(DummyService::class)
+ fun bindDummyService(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(AutoStartReceiver::class)
+ fun bindAutoStartReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(DataReceiver::class)
+ fun bindDataReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(SmsReceiver::class)
+ fun bindSmsReceiver(injector: MembersInjector): MembersInjector<*> = injector
+
+ @Provides
+ @FeatureMemberInjectors
+ @IntoMap
+ @ClassKey(TimeDateOrTZChangeReceiver::class)
+ fun bindTimeDateOrTZChangeReceiver(
+ injector: MembersInjector
+ ): MembersInjector<*> = injector
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/AppRootGraph.kt b/app/main/kotlin/app/aaps/di/metro/AppRootGraph.kt
new file mode 100644
index 000000000000..676b596591ea
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/AppRootGraph.kt
@@ -0,0 +1,554 @@
+package app.aaps.di.metro
+
+import android.content.Context
+import androidx.work.WorkManager
+import app.aaps.core.interfaces.alerts.EatReminder
+import app.aaps.core.interfaces.alerts.LocalAlertUtils
+import app.aaps.core.interfaces.aps.APSResult
+import app.aaps.core.interfaces.aps.AutosensData
+import app.aaps.core.interfaces.aps.Loop
+import app.aaps.core.interfaces.automation.Automation
+import app.aaps.core.interfaces.autotune.Autotune
+import app.aaps.core.interfaces.bgQualityCheck.BgQualityCheck
+import app.aaps.core.interfaces.bolus.BatchExecutor
+import app.aaps.core.interfaces.bolus.MasterActionExecutor
+import app.aaps.core.interfaces.bolus.WizardExecutor
+import app.aaps.core.interfaces.clientcontrol.ClientControlActionDispatcher
+import app.aaps.core.interfaces.configuration.Config
+import app.aaps.core.interfaces.configuration.ConfigBuilder
+import app.aaps.core.interfaces.configuration.RunningConfigurationKeys
+import app.aaps.core.interfaces.constraints.ConstraintsChecker
+import app.aaps.core.interfaces.db.PersistenceLayer
+import app.aaps.core.interfaces.db.ProcessedTbrEbData
+import app.aaps.core.interfaces.di.APS
+import app.aaps.core.interfaces.di.ApplicationScope
+import app.aaps.core.interfaces.di.FeatureMemberInjectors
+import app.aaps.core.interfaces.di.MetroMemberInjector
+import app.aaps.core.interfaces.di.NotNSClient
+import app.aaps.core.interfaces.di.PumpDriver
+import app.aaps.core.interfaces.dst.DstHelper
+import app.aaps.core.interfaces.insulin.ConcentrationHelper
+import app.aaps.core.interfaces.insulin.InsulinManager
+import app.aaps.core.interfaces.iob.GlucoseStatusProvider
+import app.aaps.core.interfaces.iob.IobCobCalculator
+import app.aaps.core.interfaces.local.LocaleDependentSetting
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.L
+import app.aaps.core.interfaces.logging.LoggerUtils
+import app.aaps.core.interfaces.logging.UserEntryLogger
+import app.aaps.core.interfaces.maintenance.CloudDirectoryManager
+import app.aaps.core.interfaces.maintenance.CloudStorageProvider
+import app.aaps.core.interfaces.maintenance.FileListProvider
+import app.aaps.core.interfaces.maintenance.ImportExportPrefs
+import app.aaps.core.interfaces.maintenance.Maintenance
+import app.aaps.core.interfaces.notifications.AlarmSoundPlayer
+import app.aaps.core.interfaces.notifications.NotificationHolder
+import app.aaps.core.interfaces.notifications.NotificationManager
+import app.aaps.core.interfaces.nsclient.NSClientRepository
+import app.aaps.core.interfaces.nsclient.ProcessedDeviceStatusData
+import app.aaps.core.interfaces.nsclient.StoreDataForDb
+import app.aaps.core.interfaces.overview.LastBgData
+import app.aaps.core.interfaces.overview.OverviewData
+import app.aaps.core.interfaces.overview.graph.GraphConfigRepository
+import app.aaps.core.interfaces.overview.graph.OverviewDataCache
+import app.aaps.core.interfaces.plugin.ActivePlugin
+import app.aaps.core.interfaces.plugin.PermissionProvider
+import app.aaps.core.interfaces.plugin.PluginBase
+import app.aaps.core.interfaces.plugin.PluginPermissions
+import app.aaps.core.interfaces.profile.ProfileFunction
+import app.aaps.core.interfaces.profile.ProfileRepository
+import app.aaps.core.interfaces.profile.ProfileStore
+import app.aaps.core.interfaces.profile.ProfileUtil
+import app.aaps.core.interfaces.profiling.Profiler
+import app.aaps.core.interfaces.protection.ExportPasswordDataStore
+import app.aaps.core.interfaces.protection.PasswordCheck
+import app.aaps.core.interfaces.protection.ProtectionCheck
+import app.aaps.core.interfaces.protection.SecureEncrypt
+import app.aaps.core.interfaces.pump.BlePreCheck
+import app.aaps.core.interfaces.pump.BolusProgressData
+import app.aaps.core.interfaces.pump.DetailedBolusInfoStorage
+import app.aaps.core.interfaces.pump.PumpEnactResult
+import app.aaps.core.interfaces.pump.PumpStatusProvider
+import app.aaps.core.interfaces.pump.PumpSync
+import app.aaps.core.interfaces.pump.PumpWithConcentration
+import app.aaps.core.interfaces.pump.TemporaryBasalStorage
+import app.aaps.core.interfaces.queue.CommandQueue
+import app.aaps.core.interfaces.receivers.ReceiverStatusStore
+import app.aaps.core.interfaces.resources.ResourceHelper
+import app.aaps.core.interfaces.rx.AapsSchedulers
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.scenes.ActiveSceneSync
+import app.aaps.core.interfaces.scenes.SceneActions
+import app.aaps.core.interfaces.scenes.SceneAutomationApi
+import app.aaps.core.interfaces.scenes.SceneChainResolver
+import app.aaps.core.interfaces.scenes.SceneIconResolver
+import app.aaps.core.interfaces.scenes.SceneStore
+import app.aaps.core.interfaces.scenes.Scenes
+import app.aaps.core.interfaces.sharedPreferences.KeyValueStore
+import app.aaps.core.interfaces.source.NSClientSource
+import app.aaps.core.interfaces.stats.DexcomTirCalculator
+import app.aaps.core.interfaces.stats.TddCalculator
+import app.aaps.core.interfaces.stats.TirCalculator
+import app.aaps.core.interfaces.storage.Storage
+import app.aaps.core.interfaces.sync.DataSyncSelectorXdrip
+import app.aaps.core.interfaces.sync.NsClient
+import app.aaps.core.interfaces.sync.XDripBroadcast
+import app.aaps.core.interfaces.ui.CarbSuggestionActions
+import app.aaps.core.interfaces.ui.IconsProvider
+import app.aaps.core.interfaces.ui.UiInteraction
+import app.aaps.core.interfaces.ui.UiRestart
+import app.aaps.core.interfaces.userEntry.UserEntryPresentationHelper
+import app.aaps.core.interfaces.utils.DateUtil
+import app.aaps.core.interfaces.utils.DecimalFormatter
+import app.aaps.core.interfaces.utils.HardLimits
+import app.aaps.core.interfaces.utils.Translator
+import app.aaps.core.interfaces.utils.TrendCalculator
+import app.aaps.core.interfaces.utils.fabric.FabricPrivacy
+import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils
+import app.aaps.core.interfaces.widget.WidgetUpdater
+import app.aaps.core.interfaces.workflow.CalculationSignals
+import app.aaps.core.interfaces.workflow.CalculationSignalsEmitter
+import app.aaps.core.interfaces.workflow.CalculationWorkflow
+import app.aaps.core.keys.interfaces.Preferences
+import app.aaps.core.keys.interfaces.VisibilityContext
+import app.aaps.core.nssdk.interfaces.RunningConfiguration
+import app.aaps.core.objects.crypto.CryptoUtil
+import app.aaps.core.objects.di.CoreObjectsGraph
+import app.aaps.core.objects.runningMode.RunningModeGuard
+import app.aaps.core.objects.wizard.BolusWizard
+import app.aaps.core.objects.wizard.QuickWizard
+import app.aaps.core.utils.receivers.DataInbox
+import app.aaps.database.AppRepository
+import app.aaps.database.di.DatabaseConfig
+import app.aaps.di.ExternalOptionsOverride
+import app.aaps.implementation.lifecycle.ProcessLifecycleListener
+import app.aaps.implementation.maintenance.cloud.CloudStorageManager
+import app.aaps.implementation.notifications.SnackbarNotificationFallback
+import app.aaps.implementation.plugin.PluginStore
+import app.aaps.implementation.profile.ProfileSwitchScheduler
+import app.aaps.implementation.profile.ProfileSwitchSilentGate
+import app.aaps.implementation.resources.ResourceHelperImpl
+import app.aaps.implementation.scenes.ActiveSceneManager
+import app.aaps.implementation.scenes.SceneExecutor
+import app.aaps.implementation.utils.fabric.FabricPrivacyImpl
+import app.aaps.plugins.aps.loop.runningMode.RunningModeExpiryJob
+import app.aaps.plugins.aps.loop.runningMode.RunningModeReconciler
+import app.aaps.plugins.aps.openAPS.DeltaCalculator
+import app.aaps.plugins.aps.openAPSAMA.DetermineBasalAMA
+import app.aaps.plugins.aps.openAPSAutoISF.DetermineBasalAutoISF
+import app.aaps.plugins.aps.openAPSAutoISF.GlucoseStatusCalculatorAutoIsf
+import app.aaps.plugins.aps.openAPSSMB.DetermineBasalSMB
+import app.aaps.plugins.aps.openAPSSMB.GlucoseStatusCalculatorSMB
+import app.aaps.plugins.automation.AutomationRuntime
+import app.aaps.plugins.automation.services.LastLocationDataContainer
+import app.aaps.plugins.constraints.bgQualityCheck.BgQualityCheckPlugin
+import app.aaps.plugins.constraints.dstHelper.DstHelperPlugin
+import app.aaps.plugins.constraints.objectives.ObjectivesPlugin
+import app.aaps.plugins.constraints.objectives.objectives.Objective
+import app.aaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin
+import app.aaps.plugins.source.DexcomPlugin
+import app.aaps.plugins.source.NSClientSourcePlugin
+import app.aaps.plugins.source.XdripSourcePlugin
+import app.aaps.plugins.source.di.SourceMetroGraph
+import app.aaps.plugins.sync.di.OpenHumansMetroBridge
+import app.aaps.plugins.sync.nsclientV3.NSClientV3Plugin
+import app.aaps.plugins.sync.nsclientV3.NsIncomingDataProcessor
+import app.aaps.plugins.sync.nsclientV3.ReceiverDelegate
+import app.aaps.plugins.sync.nsclientV3.clientcontrol.AuthorizedClientsRepository
+import app.aaps.plugins.sync.nsclientV3.clientcontrol.ClientControlPublisher
+import app.aaps.plugins.sync.nsclientV3.clientcontrol.ClientPairingRepository
+import app.aaps.plugins.sync.nsclientV3.clientcontrol.PairingOfferFetcher
+import app.aaps.plugins.sync.nsclientV3.clientcontrol.PairingOfferPublisher
+import app.aaps.plugins.sync.smsCommunicator.SmsCommunicatorPlugin
+import app.aaps.plugins.sync.smsCommunicator.compose.SmsCommunicatorRepository
+import app.aaps.plugins.sync.tidepool.auth.AuthFlowOut
+import app.aaps.plugins.sync.tidepool.comm.TidepoolUploader
+import app.aaps.plugins.sync.tidepool.compose.TidepoolRepository
+import app.aaps.plugins.sync.tidepool.utils.RateLimit
+import app.aaps.plugins.sync.wear.WearPlugin
+import app.aaps.plugins.sync.xdrip.compose.XdripMvvmRepository
+import app.aaps.ui.search.BuiltInSearchables
+import app.aaps.workflow.WorkflowChainData
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.DependencyGraph
+import dev.zacsweers.metro.Includes
+import dev.zacsweers.metro.MembersInjector
+import dev.zacsweers.metro.Multibinds
+import dev.zacsweers.metro.Provides
+import dev.zacsweers.metrox.viewmodel.MetroViewModelMultibindings
+import kotlinx.coroutines.CoroutineScope
+import kotlin.reflect.KClass
+
+/**
+ * The one Metro root. Everything else hangs off it as a graph extension.
+ *
+ * **There is exactly one root, and that is the safety property.** Several root graphs would be unsafe
+ * by construction: two roots that both scope the same type get one instance each, silently.
+ * `MetroScopingTest` shows exactly that - two roots built from the same factory share nothing at all.
+ * A duplicated calculator or command queue is not a cosmetic problem in this app.
+ *
+ * With one root that cannot happen: a scoped binding lives here once and every extension sees the same
+ * instance. An extension that declares its own scope gets its own instances of what it scopes, which is
+ * what the history browser needs and what the same test verifies.
+ */
+/**
+ * Pump accessors are NOT a supertype here. They used to be: a `PumpAccessors` interface in
+ * `src/withPumps` named the Dana and Equil types so instrumented tests could reach the app's own
+ * instances at compile time, with an empty copy in `src/aapsclient` so this file still compiled for a
+ * follower. But `src/withPumps` is part of the `full` and `pumpcontrol` MAIN source sets, so that made
+ * those pump modules a compile-time dependency of the app itself - removing `:pump:equil` from
+ * `settings.gradle` failed `:app:compileFullDebugKotlin` and produced no APK at all.
+ *
+ * Each pump module now declares its own accessor interface and contributes it, so the accessors exist
+ * exactly when their module does and nothing here names a pump. See `DanaAccessors` in
+ * `:pump:dana:common` for what that costs - a test resolves them with a cast rather than at compile
+ * time, and their accessors become roots that every `AppScope` graph on the same classpath has to
+ * satisfy.
+ */
+@DependencyGraph(AppScope::class)
+interface AppRootGraph : MetroViewModelMultibindings {
+
+ // Both of the graphs below are extensions rather than roots of their own. A second
+ // `@DependencyGraph(AppScope::class)` is unsafe: two graphs both declaring `AppScope` get a
+ // separate copy of anything scoped there, and nothing reports it. As extensions they share this
+ // graph's bindings instead of restating them, so their factories take no arguments at all.
+
+ /** Workers, which WorkManager builds through `MetroWorkerFactory`. */
+ val workersGraph: AppWorkersGraph
+
+ /**
+ * Opens one history browsing window. A factory rather than an accessor, because each window is a
+ * separate scope with its own calculation objects - see [HistoryWindowGraph].
+ */
+ val historyWindowFactory: HistoryWindowGraph.Factory
+
+ /**
+ * The shared wizard and running-mode objects, from a binding container in `:core:objects`.
+ *
+ * A binding container, not a `@GraphExtension`: an extension can see its parent, but the parent
+ * cannot see the extension, so anything contributed here could not depend on a wizard. As a
+ * container its bindings are part of this graph, and it lives in commonMain where the Apple
+ * targets can include it too.
+ */
+ val runningModeGuard: RunningModeGuard
+ val quickWizard: QuickWizard
+ val bolusWizard: BolusWizard
+
+ /**
+ * Plugins that register themselves with @ContributesIntoMap rather than being listed in a graph.
+ *
+ * Smoothing, sensitivity and calibration are on this shape: their plugins carry the binding on the
+ * class, so those modules have no DI file at all. As other modules follow, their entries land here.
+ */
+ val contributedPlugins: Map
+
+ /**
+ * Contributed plugins that only belong in a build that runs the loop.
+ *
+ * The qualifier is the whole point: `:app` merges this bucket only when `config.APS`. Objectives,
+ * the signature verifier and the storage constraint have no meaning in a build that never makes a
+ * decision, and a plugin in the wrong bucket fails silently - a plugin list is just a list.
+ */
+ @APS
+ val contributedApsPlugins: Map
+
+ /** Contributed plugins that must NOT appear in a follower build. */
+ @NotNSClient
+ val contributedNotNsClientPlugins: Map
+
+ /**
+ * Pump drivers, which only a build with pump support merges.
+ *
+ * Safe to declare here even though this file is compiled for follower builds: the map is keyed on
+ * `Int` and holds [PluginBase], so no pump type is named. A follower has no pump module on its
+ * classpath, nothing contributes, and the map is empty - which is the correct answer for a follower.
+ *
+ * `@Multibinds(allowEmpty = true)` is what makes that legal. Without it Metro reports "no binding
+ * found" for the follower flavours, because a map with no contributions has no binding at all.
+ */
+ @Multibinds(allowEmpty = true)
+ @PumpDriver
+ val contributedPumpDriverPlugins: Map
+
+ /**
+ * Member injectors contributed by feature modules, for classes the app constructs by hand.
+ *
+ * The four extensions below the root each carry their own such map, but an extension has to be named
+ * by [MetroGraphs] to be read - and that file is compiled for follower builds, where no pump module
+ * exists. A map declared here instead can be filled from anywhere with `@ContributesTo`, and nothing
+ * pump-specific appears in its type, so a follower simply sees fewer entries.
+ *
+ * How the pump protocol classes are member-injected: a
+ * packet is built with `new`, then fills its own fields from this map.
+ */
+ @Multibinds(allowEmpty = true)
+ @FeatureMemberInjectors
+ val contributedMemberInjectors: Map, MembersInjector<*>>
+
+ /**
+ * The ten objectives, in order. `ObjectivesPlugin` takes this list and is built here, so the
+ * objectives are contributed to this graph too.
+ */
+ @Provides
+ fun objectivesList(objectives: Map): List =
+ objectives.toList().sortedBy { it.first }.map { it.second }
+
+ /**
+ * Constraint plugins that are also bound to an interface, or injected directly.
+ * to these instances rather than building their own.
+ */
+ /**
+ * Objects the graph exposes for code that resolves them by hand rather than by injection.
+ */
+ val trendCalculator: TrendCalculator
+ val resourceHelper: ResourceHelper
+ val fabricPrivacy: FabricPrivacy
+ val uiInteraction: UiInteraction
+ val carbSuggestionActions: CarbSuggestionActions
+ val temporaryBasalStorage: TemporaryBasalStorage
+ val detailedBolusInfoStorage: DetailedBolusInfoStorage
+ val blePreCheck: BlePreCheck
+ val visibilityContext: VisibilityContext
+ val cloudDirectoryManager: CloudDirectoryManager
+ val graphConfigRepository: GraphConfigRepository
+ val batchExecutor: BatchExecutor
+ val masterActionExecutor: MasterActionExecutor
+ val loggerUtils: LoggerUtils
+ val importExportPrefs: ImportExportPrefs
+ val preferences: Preferences
+ val pumpWithConcentration: PumpWithConcentration
+ val calculationWorkflow: CalculationWorkflow
+ val workflowChainData: WorkflowChainData
+ val aapsLogger: AAPSLogger
+ val rxBus: RxBus
+ val dateUtil: DateUtil
+ val l: L
+ val aapsSchedulers: AapsSchedulers
+ val keyValueStore: KeyValueStore
+ val widgetUpdater: WidgetUpdater
+ val sceneIconResolver: SceneIconResolver
+ val processedDeviceStatusData: ProcessedDeviceStatusData
+ val lastLocationDataContainer: LastLocationDataContainer
+ val storeDataForDb: StoreDataForDb
+ val sceneExecutor: SceneExecutor
+ val dataInbox: DataInbox
+ val autosensData: AutosensData
+ val commandQueue: CommandQueue
+ val localAlertUtils: LocalAlertUtils
+ val bolusProgressData: BolusProgressData
+ val persistenceLayer: PersistenceLayer
+ val cloudStorageManager: CloudStorageManager
+ val overviewDataCache: OverviewDataCache
+ val calculationSignals: CalculationSignals
+ val calculationSignalsEmitter: CalculationSignalsEmitter
+ val appRepository: AppRepository
+ val cloudStorageProviders: Set
+ val constraintsChecker: ConstraintsChecker
+ val nsClientRepository: NSClientRepository
+ val builtInSearchables: BuiltInSearchables
+
+ /** The one application scope. */
+ @ApplicationScope val appScope: CoroutineScope
+ val notificationManager: NotificationManager
+ val apsResult: APSResult
+ val pumpEnactResult: PumpEnactResult
+ val profileSwitchSilentGate: ProfileSwitchSilentGate
+ val profileSwitchScheduler: ProfileSwitchScheduler
+ val snackbarNotificationFallback: SnackbarNotificationFallback
+ val eatReminder: EatReminder
+ val uiRestart: UiRestart
+ val runningConfiguration: RunningConfiguration
+ val runningConfigurationKeys: RunningConfigurationKeys
+ val activePlugin: ActivePlugin
+ val pluginPermissions: PluginPermissions
+ val pluginStore: PluginStore
+ val xDripBroadcast: XDripBroadcast
+ val maintenance: Maintenance
+ val fileListProvider: FileListProvider
+ val lastBgData: LastBgData
+ val localeDependentSetting: LocaleDependentSetting
+ val pumpStatusProvider: PumpStatusProvider
+ val passwordCheck: PasswordCheck
+ val overviewData: OverviewData
+ val exportPasswordDataStore: ExportPasswordDataStore
+ val secureEncrypt: SecureEncrypt
+ val cryptoUtil: CryptoUtil
+ val concentrationHelper: ConcentrationHelper
+ val processedTbrEbData: ProcessedTbrEbData
+ val userEntryLogger: UserEntryLogger
+ val glucoseStatusProvider: GlucoseStatusProvider
+ val notificationHolder: NotificationHolder
+ val userEntryPresentationHelper: UserEntryPresentationHelper
+ val profiler: Profiler
+ val alarmSoundPlayer: AlarmSoundPlayer
+ val wizardExecutor: WizardExecutor
+ val configBuilder: ConfigBuilder
+
+ // Read by MainApp, which builds this graph and then starts these itself. The two `*Impl` types are
+ // here rather than their interfaces because only the concrete class has `start()`; both are
+ // `@SingleIn`, so it is the same object the interface binding hands out.
+ val config: Config
+ val resourceHelperImpl: ResourceHelperImpl
+ val fabricPrivacyImpl: FabricPrivacyImpl
+ val processLifecycleListener: ProcessLifecycleListener
+ val dataSyncSelectorXdrip: DataSyncSelectorXdrip
+ val activeSceneSync: ActiveSceneSync
+
+ /**
+ * The same object as [activeSceneSync], by class.
+ *
+ * `SceneExecutor`, `SceneAutomationApiImpl` and `SceneExpiryRunner` all ask for the concrete type and
+ * would otherwise get a copy of their own - and an unscoped one, since the
+ * class carries only Metro's `@SingleIn`. The scene then activated on an object no screen was reading.
+ */
+ val activeSceneManager: ActiveSceneManager
+ val sceneChainResolver: SceneChainResolver
+ val sceneStore: SceneStore
+ val scenes: Scenes
+ val sceneActions: SceneActions
+ val sceneAutomationApi: SceneAutomationApi
+ val decimalFormatter: DecimalFormatter
+ val profileUtil: ProfileUtil
+ val hardLimits: HardLimits
+ val nsIncomingDataProcessor: NsIncomingDataProcessor
+ val openHumansMetroBridge: OpenHumansMetroBridge
+ val xdripMvvmRepository: XdripMvvmRepository
+ val wearPlugin: WearPlugin
+ val rateLimit: RateLimit
+ val tidepoolRepository: TidepoolRepository
+ val tidepoolUploader: TidepoolUploader
+ val authFlowOut: AuthFlowOut
+ val smsCommunicatorRepository: SmsCommunicatorRepository
+ val smsCommunicatorPlugin: SmsCommunicatorPlugin
+ val pairingOfferPublisher: PairingOfferPublisher
+ val pairingOfferFetcher: PairingOfferFetcher
+ val clientPairingRepository: ClientPairingRepository
+ val clientControlPublisher: ClientControlPublisher
+ val authorizedClientsRepository: AuthorizedClientsRepository
+ val receiverDelegate: ReceiverDelegate
+ val nsClientV3Plugin: NSClientV3Plugin
+ val workManager: WorkManager
+ val clientControlActionDispatcher: ClientControlActionDispatcher
+ val nsClient: NsClient
+ val profileFunction: ProfileFunction
+ val versionCheckerUtils: VersionCheckerUtils
+ val storage: Storage
+ val receiverStatusStore: ReceiverStatusStore
+
+ val translator: Translator
+ val protectionCheck: ProtectionCheck
+ val tddCalculator: TddCalculator
+ val tirCalculator: TirCalculator
+ val dexcomTirCalculator: DexcomTirCalculator
+ val pumpSync: PumpSync
+ val iconsProvider: IconsProvider
+ val insulinManager: InsulinManager
+ val profileRepository: ProfileRepository
+ val profileStore: ProfileStore
+
+ val bgQualityCheckPlugin: BgQualityCheckPlugin
+ val dstHelperPlugin: DstHelperPlugin
+ val dstHelper: DstHelper
+ val objectivesPlugin: ObjectivesPlugin
+
+ /**
+ * Automation, and the permission providers it is the only contributor to.
+ *
+ * `AutomationRuntime` lives here.
+ * instead of the other way round.
+ */
+ val automation: Automation
+
+ /** Same object as [automation], by class: ComposeMainActivity and AppNavGraph inject the concrete type. */
+ val automationRuntime: AutomationRuntime
+ val permissionProviders: Set
+
+ /** The live loop's calculator. A history window has its own, at `HistoryWindowScope`. */
+ val iobCobCalculator: IobCobCalculator
+
+ /** The loop. */
+ val loop: Loop
+
+ /** Autotune, for the automation actions. */
+ val autotune: Autotune
+
+ /** Running-mode helpers, from commonMain. `MainApp` reads the reconciler. */
+ val runningModeReconciler: RunningModeReconciler
+ val runningModeExpiryJob: RunningModeExpiryJob
+
+ /**
+ * The openAPS pieces.
+ *
+ * Only the four the instrumented APS tests inject. `DeltaCalculator` and the AutoISF glucose status
+ * calculator are reached through these, so nothing outside Metro ever asks for them by name.
+ */
+ val glucoseStatusCalculatorSMB: GlucoseStatusCalculatorSMB
+ val determineBasalSMB: DetermineBasalSMB
+ val determineBasalAMA: DetermineBasalAMA
+ val determineBasalAutoISF: DetermineBasalAutoISF
+ val glucoseStatusCalculatorAutoIsf: GlucoseStatusCalculatorAutoIsf
+ val deltaCalculator: DeltaCalculator
+ val signatureVerifierPlugin: SignatureVerifierPlugin
+
+ /**
+ * Source plugins that are also bound to an interface for other callers.
+ *
+ * Built here, so nothing constructs a second copy.
+ */
+ val xdripSourcePlugin: XdripSourcePlugin
+ val nsClientSourcePlugin: NSClientSourcePlugin
+ val nsClientSource: NSClientSource
+ val dexcomPlugin: DexcomPlugin
+
+ val sourceGraph: SourceMetroGraph
+ /**
+ * Interfaces backed by a plugin this graph already builds. A `@Provides` rather than a delegate,
+ * because the instance is the plugin.
+ *
+ * This used to claim that binding it any other way "would make a second one". That is not true of
+ * Metro: `@ContributesBinding` on a `@SingleIn` class resolves to the same scoped instance, which is
+ * why `DexcomPlugin` and `XdripSourcePlugin` carry their second binding on the class now. Only
+ * `BgQualityCheckPlugin` still needs stating here - see below.
+ */
+ /** Metro already builds the plugin; the openAPS plugins ask for the interface. */
+ @Provides fun bgQualityCheck(plugin: BgQualityCheckPlugin): BgQualityCheck = plugin
+
+ @DependencyGraph.Factory
+ fun interface Factory {
+
+ /**
+ * The graph's inputs - what the **caller** genuinely decides.
+ *
+ * The last two are how an instrumented test differs from production, and they are parameters
+ * rather than replaced bindings for a reason worth keeping: contributions declared in
+ * `androidTest` never reach this graph, because it is compiled during
+ * `:app:compileFullDebugKotlin` and androidTest is a later, separate compilation. Metro's
+ * `replaces` is real, but it cannot help from there. The factory is the only way in.
+ */
+ fun create(
+ /**
+ * The application scope, passed in rather than built here so the caller decides its
+ * dispatcher: production uses `Dispatchers.Default`, the unit tests an Unconfined one, so
+ * that work started while the graph is being built runs on the calling thread.
+ */
+ @Provides @ApplicationScope appScope: CoroutineScope,
+
+ /** The application context. Android owns it, so it is passed in rather than bound. */
+ @Provides context: Context,
+
+ /**
+ * The Application, handed back to the graph as the injector for anything Android builds
+ * itself - a service or a receiver filling its own fields.
+ */
+ @Provides memberInjector: MetroMemberInjector,
+
+ /** Which database to open. `DatabaseConfig.IN_MEMORY` is what the instrumented tests pass. */
+ @Provides databaseConfig: DatabaseConfig,
+
+ /** Extra external options to report enabled. `ExternalOptionsOverride.NONE` in production. */
+ @Provides externalOptionsOverride: ExternalOptionsOverride,
+
+ @Includes coreObjects: CoreObjectsGraph
+ ): AppRootGraph
+ }
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/AppWorkersGraph.kt b/app/main/kotlin/app/aaps/di/metro/AppWorkersGraph.kt
new file mode 100644
index 000000000000..e7ab78199bea
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/AppWorkersGraph.kt
@@ -0,0 +1,124 @@
+package app.aaps.di.metro
+
+import androidx.work.ListenableWorker
+import app.aaps.core.objects.workflow.MetroWorkerCreator
+import app.aaps.core.objects.workflow.WorkerKey
+import app.aaps.implementation.maintenance.ImportExportPrefsImpl
+import app.aaps.implementation.receivers.KeepAliveWorker
+import app.aaps.implementation.scenes.SceneExpiryWorker
+import app.aaps.plugins.aps.loop.runningMode.RunningModeExpiryScheduler
+import app.aaps.plugins.aps.loop.runningMode.RunningModeExpiryWorker
+import app.aaps.plugins.sync.nsclientV3.workers.DataSyncWorker
+import app.aaps.plugins.sync.nsclientV3.workers.LoadBgWorker
+import app.aaps.plugins.sync.nsclientV3.workers.LoadDeviceStatusWorker
+import app.aaps.plugins.sync.nsclientV3.workers.LoadFoodsWorker
+import app.aaps.plugins.sync.nsclientV3.workers.LoadLastModificationWorker
+import app.aaps.plugins.sync.nsclientV3.workers.LoadProfileStoreWorker
+import app.aaps.plugins.sync.nsclientV3.workers.LoadSettingsWorker
+import app.aaps.plugins.sync.nsclientV3.workers.LoadStatusWorker
+import app.aaps.plugins.sync.nsclientV3.workers.LoadTreatmentsWorker
+import app.aaps.plugins.sync.smsCommunicator.SmsCommunicatorPlugin
+import app.aaps.plugins.sync.xdrip.workers.XdripDataSyncWorker
+import dev.zacsweers.metro.GraphExtension
+import dev.zacsweers.metro.IntoMap
+import dev.zacsweers.metro.Provides
+import kotlin.reflect.KClass
+
+/**
+ * This graph exists to answer one question: can Metro build an Android entry point that the framework
+ * constructs for us? A worker is the hardest of the four, because WorkManager holds the constructor
+ * call and only hands over a class name at runtime. The answer is the map below - a real compile-time
+ * `@IntoMap` multibinding keyed by worker class, which [MetroWorkerFactory] looks up.
+ * This is a graph extension of [AppRootGraph], so it declares only what it adds: the app-wide
+ * dependencies live once in the root and are inherited, and its factory takes no arguments.
+ */
+@GraphExtension
+interface AppWorkersGraph {
+
+ val runningModeExpiryScheduler: RunningModeExpiryScheduler
+
+ /** Every Metro-wired worker, keyed by its class. [MetroWorkerFactory] matches on the class name. */
+ val workerCreators: Map, MetroWorkerCreator>
+
+ @Provides
+ @IntoMap
+ @WorkerKey(RunningModeExpiryWorker::class)
+ fun bindRunningModeExpiryWorker(factory: RunningModeExpiryWorker.Factory): MetroWorkerCreator = factory
+
+ @Provides
+ @IntoMap
+ @WorkerKey(KeepAliveWorker::class)
+ fun bindKeepAliveWorker(factory: KeepAliveWorker.Factory): MetroWorkerCreator = factory
+
+ @Provides
+ @IntoMap
+ @WorkerKey(SceneExpiryWorker::class)
+ fun bindSceneExpiryWorker(factory: SceneExpiryWorker.Factory): MetroWorkerCreator = factory
+
+ @Provides
+ @IntoMap
+ @WorkerKey(ImportExportPrefsImpl.CsvExportWorker::class)
+ fun bindCsvExportWorker(f: ImportExportPrefsImpl.CsvExportWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(ImportExportPrefsImpl.ApsResultExportWorker::class)
+ fun bindApsResultExportWorker(
+ f: ImportExportPrefsImpl.ApsResultExportWorker.Factory
+ ): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(DataSyncWorker::class)
+ fun bindDataSyncWorker(f: DataSyncWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(LoadBgWorker::class)
+ fun bindLoadBgWorker(f: LoadBgWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(LoadDeviceStatusWorker::class)
+ fun bindLoadDeviceStatusWorker(f: LoadDeviceStatusWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(LoadFoodsWorker::class)
+ fun bindLoadFoodsWorker(f: LoadFoodsWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(LoadLastModificationWorker::class)
+ fun bindLoadLastModificationWorker(f: LoadLastModificationWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(LoadProfileStoreWorker::class)
+ fun bindLoadProfileStoreWorker(f: LoadProfileStoreWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(LoadSettingsWorker::class)
+ fun bindLoadSettingsWorker(f: LoadSettingsWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(LoadStatusWorker::class)
+ fun bindLoadStatusWorker(f: LoadStatusWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(LoadTreatmentsWorker::class)
+ fun bindLoadTreatmentsWorker(f: LoadTreatmentsWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(XdripDataSyncWorker::class)
+ fun bindXdripDataSyncWorker(f: XdripDataSyncWorker.Factory): MetroWorkerCreator = f
+
+ @Provides
+ @IntoMap
+ @WorkerKey(SmsCommunicatorPlugin.SmsCommunicatorWorker::class)
+ fun bindSmsCommunicatorWorker(f: SmsCommunicatorPlugin.SmsCommunicatorWorker.Factory): MetroWorkerCreator = f
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/HistoryWindowGraph.kt b/app/main/kotlin/app/aaps/di/metro/HistoryWindowGraph.kt
new file mode 100644
index 000000000000..1cffc30930cb
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/HistoryWindowGraph.kt
@@ -0,0 +1,110 @@
+package app.aaps.di.metro
+
+import app.aaps.core.interfaces.db.PersistenceLayer
+import app.aaps.core.interfaces.db.ProcessedTbrEbData
+import app.aaps.core.interfaces.iob.IobCobCalculator
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.notifications.NotificationManager
+import app.aaps.core.interfaces.overview.OverviewData
+import app.aaps.core.interfaces.overview.graph.OverviewDataCache
+import app.aaps.core.interfaces.plugin.ActivePlugin
+import app.aaps.core.interfaces.profile.ProfileFunction
+import app.aaps.core.interfaces.resources.TextResolver
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.utils.DateUtil
+import app.aaps.core.interfaces.utils.DecimalFormatter
+import app.aaps.core.interfaces.workflow.CalculationSignalsEmitter
+import app.aaps.core.interfaces.workflow.CalculationWorkflow
+import app.aaps.core.keys.interfaces.Preferences
+import app.aaps.core.objects.workflow.CalculationSignalsImpl
+import app.aaps.implementation.overview.OverviewDataImpl
+import app.aaps.plugins.main.iob.iobCobCalculator.IobCobCalculatorPlugin
+import app.aaps.ui.compose.overview.OverviewDataCacheFactory
+import dev.zacsweers.metro.GraphExtension
+import dev.zacsweers.metro.Provides
+import dev.zacsweers.metro.SingleIn
+
+/**
+ * Marks objects that belong to one history browsing window rather than to the running app.
+ *
+ * A separate scope, because that is the whole point: the History Browser recalculates over a different
+ * time range and must not touch the loop's own calculation state while doing it.
+ */
+abstract class HistoryWindowScope private constructor()
+
+/**
+ * One history browsing window's calculation objects.
+ *
+ * This is the case that makes graph extensions worth having. It is an extension of [AppRootGraph] with
+ * **its own scope**, so it inherits the app-wide objects - logger, database, preferences - while every
+ * `@SingleIn(HistoryWindowScope::class)` binding below is its own. Ask the root for two windows and
+ * they share the database and own separate calculators. `MetroScopingTest` checks exactly that
+ * behaviour rather than trusting it.
+ *
+ * The bug this whole class exists to prevent is handing the window the app's own `OverviewData`:
+ * history browsing would then write into the state the loop is running on.
+ */
+@GraphExtension(HistoryWindowScope::class)
+interface HistoryWindowGraph {
+
+ val overviewData: OverviewData
+ val signals: CalculationSignalsEmitter
+ val cache: OverviewDataCache
+ val iobCobCalculator: IobCobCalculator
+
+ /** Held by the root, so a caller can open a window whenever the user picks a day. */
+ @GraphExtension.Factory
+ fun interface Factory {
+
+ fun create(): HistoryWindowGraph
+ }
+
+ @SingleIn(HistoryWindowScope::class)
+ @Provides
+ fun provideOverviewData(): OverviewData = OverviewDataImpl()
+
+ @SingleIn(HistoryWindowScope::class)
+ @Provides
+ fun provideSignals(): CalculationSignalsEmitter = CalculationSignalsImpl()
+
+ /**
+ * The cache and the calculator need each other. A function type is a deferred lookup, so the
+ * graph accepts it where a direct reference would be a cycle error.
+ */
+ @SingleIn(HistoryWindowScope::class)
+ @Provides
+ fun provideCache(
+ factory: OverviewDataCacheFactory,
+ signals: CalculationSignalsEmitter,
+ iobCobCalculator: () -> IobCobCalculator
+ ): OverviewDataCache = factory.create(
+ iobCobCalculatorProvider = { iobCobCalculator() },
+ signals = signals,
+ // A history window reads a fixed range. Following live database changes is the live loop's job.
+ observeDatabase = false
+ )
+
+ @Suppress("LongParameterList")
+ @SingleIn(HistoryWindowScope::class)
+ @Provides
+ fun provideIobCobCalculator(
+ aapsLogger: AAPSLogger,
+ rxBus: RxBus,
+ preferences: Preferences,
+ rh: TextResolver,
+ profileFunction: ProfileFunction,
+ activePlugin: ActivePlugin,
+ dateUtil: DateUtil,
+ persistenceLayer: PersistenceLayer,
+ overviewData: OverviewData,
+ calculationWorkflow: CalculationWorkflow,
+ decimalFormatter: DecimalFormatter,
+ processedTbrEbData: ProcessedTbrEbData,
+ signals: CalculationSignalsEmitter,
+ notificationManager: NotificationManager,
+ cache: () -> OverviewDataCache
+ ): IobCobCalculator = IobCobCalculatorPlugin(
+ aapsLogger, rxBus, preferences, rh, profileFunction, activePlugin, dateUtil, persistenceLayer,
+ overviewData, calculationWorkflow, decimalFormatter, processedTbrEbData, signals, notificationManager
+ ) { cache() }
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/MainPluginsBindings.kt b/app/main/kotlin/app/aaps/di/metro/MainPluginsBindings.kt
new file mode 100644
index 000000000000..31e8340ac215
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/MainPluginsBindings.kt
@@ -0,0 +1,97 @@
+package app.aaps.di.metro
+
+import app.aaps.core.interfaces.constraints.Objectives
+import app.aaps.core.interfaces.db.PersistenceLayer
+import app.aaps.core.interfaces.db.ProcessedTbrEbData
+import app.aaps.core.interfaces.iob.IobCobCalculator
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.notifications.NotificationManager
+import app.aaps.core.interfaces.overview.OverviewData
+import app.aaps.core.interfaces.overview.graph.OverviewDataCache
+import app.aaps.core.interfaces.plugin.ActivePlugin
+import app.aaps.core.interfaces.plugin.PluginBase
+import app.aaps.core.interfaces.profile.ProfileFunction
+import app.aaps.core.interfaces.resources.TextResolver
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.utils.DateUtil
+import app.aaps.core.interfaces.utils.DecimalFormatter
+import app.aaps.core.interfaces.workflow.CalculationSignalsEmitter
+import app.aaps.core.interfaces.workflow.CalculationWorkflow
+import app.aaps.core.keys.interfaces.Preferences
+import app.aaps.plugins.constraints.objectives.ObjectivesPlugin
+import app.aaps.plugins.main.iob.iobCobCalculator.IobCobCalculatorPlugin
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.BindingContainer
+import dev.zacsweers.metro.ContributesTo
+import dev.zacsweers.metro.IntKey
+import dev.zacsweers.metro.IntoMap
+import dev.zacsweers.metro.Provides
+import dev.zacsweers.metro.SingleIn
+
+/**
+ * The live loop's `IobCobCalculatorPlugin`, replacing the hand-construction in `MainPluginsModule`.
+ * ## Why the class is not simply annotated
+ * `VirtualPumpPlugin` took `@Inject` and `@ContributesIntoMap` directly, which is tidier. This one
+ * cannot: it is built **twice**, on purpose. `HistoryWindowGraph` builds a second one at
+ * `HistoryWindowScope` over a fixed time range, so the history browser can calculate without disturbing
+ * the live loop. A `@SingleIn(AppScope::class)` on the class would put a binding for the same type in
+ * the parent of that extension, and which one a window saw would stop being obvious. Each graph naming
+ * its own is what keeps the two apart - the shape `HistoryWindowGraph` already uses.
+ * ## The cycle
+ * The calculator and the cache need each other. [Provider] defers the lookup, so the graph accepts here
+ * what a direct reference would reject, and `runCalculation` only ever runs after construction. The
+ * plugin takes a plain lambda rather than a [Provider] because it is common code and Metro's own
+ * `Provider` would be fine there, but the class predates this and the lambda costs nothing to adapt.
+ */
+@ContributesTo(AppScope::class)
+@BindingContainer
+object MainPluginsBindings {
+
+ @Suppress("LongParameterList")
+ @Provides
+ @SingleIn(AppScope::class)
+ fun iobCobCalculatorPlugin(
+ aapsLogger: AAPSLogger,
+ rxBus: RxBus,
+ preferences: Preferences,
+ rh: TextResolver,
+ profileFunction: ProfileFunction,
+ activePlugin: ActivePlugin,
+ dateUtil: DateUtil,
+ persistenceLayer: PersistenceLayer,
+ overviewData: OverviewData,
+ calculationWorkflow: CalculationWorkflow,
+ decimalFormatter: DecimalFormatter,
+ processedTbrEbData: ProcessedTbrEbData,
+ signals: CalculationSignalsEmitter,
+ notificationManager: NotificationManager,
+ cache: () -> OverviewDataCache
+ ): IobCobCalculatorPlugin = IobCobCalculatorPlugin(
+ aapsLogger, rxBus, preferences, rh, profileFunction, activePlugin, dateUtil, persistenceLayer,
+ overviewData, calculationWorkflow, decimalFormatter, processedTbrEbData, signals, notificationManager
+ ) { cache() }
+
+ @Provides
+ fun iobCobCalculator(plugin: IobCobCalculatorPlugin): IobCobCalculator = plugin
+
+ @Provides
+ @IntoMap
+ @IntKey(10)
+ fun iobCobCalculatorEntry(plugin: IobCobCalculatorPlugin): PluginBase = plugin
+
+ /**
+ * The `Objectives` interface, unqualified.
+ *
+ * `ObjectivesPlugin` carries `@APS` on the class for the plugin-list multibinding, and a second
+ * `@ContributesBinding` there would inherit it - the interface would then only be readable as
+ * `@APS Objectives`, which is not what a reader asks for.
+ *
+ * Metro documents the way out: put the qualifier on the bound type instead, `binding<@APS
+ * PluginBase>()`. The version pinned here rejects that form outright -
+ * `Inapplicable candidate(s): constructor(scope: KClass<*>, binding: binding<*> = ...)` - which is
+ * the same wall `SyncPluginsBindings` hits for its qualified entry. So this stays stated, and
+ * hands out the same scoped instance either way. Retry both when Metro leaves the snapshot.
+ */
+ @Provides
+ fun objectives(plugin: ObjectivesPlugin): Objectives = plugin
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/MetroGraphs.kt b/app/main/kotlin/app/aaps/di/metro/MetroGraphs.kt
new file mode 100644
index 000000000000..3eb8a6a71c5d
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/MetroGraphs.kt
@@ -0,0 +1,313 @@
+package app.aaps.di.metro
+
+import android.content.Context
+import app.aaps.core.interfaces.alerts.EatReminder
+import app.aaps.core.interfaces.alerts.LocalAlertUtils
+import app.aaps.core.interfaces.aps.Loop
+import app.aaps.core.interfaces.automation.Automation
+import app.aaps.core.interfaces.autotune.Autotune
+import app.aaps.core.interfaces.bgQualityCheck.BgQualityCheck
+import app.aaps.core.interfaces.configuration.Config
+import app.aaps.core.interfaces.configuration.ConfigBuilder
+import app.aaps.core.interfaces.constraints.ConstraintsChecker
+import app.aaps.core.interfaces.constraints.Objectives
+import app.aaps.core.interfaces.db.PersistenceLayer
+import app.aaps.core.interfaces.db.ProcessedTbrEbData
+import app.aaps.core.interfaces.di.MetroMemberInjector
+import app.aaps.core.interfaces.insulin.ConcentrationHelper
+import app.aaps.core.interfaces.insulin.InsulinManager
+import app.aaps.core.interfaces.iob.IobCobCalculator
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.L
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.maintenance.FileListProvider
+import app.aaps.core.interfaces.maintenance.Maintenance
+import app.aaps.core.interfaces.notifications.NotificationManager
+import app.aaps.core.interfaces.plugin.ActivePlugin
+import app.aaps.core.interfaces.plugin.PluginBase
+import app.aaps.core.interfaces.profile.ProfileFunction
+import app.aaps.core.interfaces.profile.ProfileRepository
+import app.aaps.core.interfaces.profile.ProfileUtil
+import app.aaps.core.interfaces.protection.ExportPasswordDataStore
+import app.aaps.core.interfaces.pump.PumpSync
+import app.aaps.core.interfaces.queue.CommandQueue
+import app.aaps.core.interfaces.resources.ResourceHelper
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.scenes.Scenes
+import app.aaps.core.interfaces.sharedPreferences.KeyValueStore
+import app.aaps.core.interfaces.source.DexcomBoyda
+import app.aaps.core.interfaces.source.XDripSource
+import app.aaps.core.interfaces.storage.Storage
+import app.aaps.core.interfaces.ui.IconsProvider
+import app.aaps.core.interfaces.ui.UiInteraction
+import app.aaps.core.interfaces.ui.UiRestart
+import app.aaps.core.interfaces.utils.DateUtil
+import app.aaps.core.interfaces.utils.DecimalFormatter
+import app.aaps.core.interfaces.utils.HardLimits
+import app.aaps.core.interfaces.utils.fabric.FabricPrivacy
+import app.aaps.core.interfaces.versionChecker.VersionCheckerUtils
+import app.aaps.core.interfaces.widget.WidgetUpdater
+import app.aaps.core.keys.interfaces.Preferences
+import app.aaps.core.objects.crypto.CryptoUtil
+import app.aaps.core.objects.di.CoreObjectsGraph
+import app.aaps.core.objects.workflow.MetroWorkerCreator
+import app.aaps.database.AppRepository
+import app.aaps.database.di.DatabaseConfig
+import app.aaps.di.ExternalOptionsOverride
+import app.aaps.di.PluginSource
+import app.aaps.di.mergePlugins
+import app.aaps.implementation.lifecycle.ProcessLifecycleListener
+import app.aaps.implementation.notifications.SnackbarNotificationFallback
+import app.aaps.implementation.plugin.PluginStore
+import app.aaps.implementation.profile.ProfileSwitchScheduler
+import app.aaps.implementation.resources.ResourceHelperImpl
+import app.aaps.implementation.utils.fabric.FabricPrivacyImpl
+import app.aaps.plugins.aps.loop.runningMode.RunningModeExpiryScheduler
+import app.aaps.plugins.aps.loop.runningMode.RunningModeReconciler
+import app.aaps.plugins.aps.openAPSAMA.DetermineBasalAMA
+import app.aaps.plugins.aps.openAPSAutoISF.DetermineBasalAutoISF
+import app.aaps.plugins.aps.openAPSSMB.DetermineBasalSMB
+import app.aaps.plugins.automation.AutomationRuntime
+import app.aaps.plugins.constraints.objectives.ObjectivesPlugin
+import app.aaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin
+import app.aaps.plugins.source.di.SourceMetroGraph
+import app.aaps.plugins.sync.di.OpenHumansMetroBridge
+import app.aaps.plugins.sync.nsclientV3.NsIncomingDataProcessor
+import dev.zacsweers.metro.MembersInjector
+import dev.zacsweers.metro.createGraphFactory
+import dev.zacsweers.metrox.viewmodel.MetroViewModelFactory
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+
+/**
+ * The object graph, owned by the Application.
+ *
+ * A thin reader: it builds [AppRootGraph] once and hands out what the extensions below it contain. The
+ * only graph it creates separately is Open Humans, which stays a root for the reason written up in
+ * [OpenHumansMetroBridge].
+ *
+ * A single instance is guaranteed by there being one Application, rather than by a scope annotation.
+ */
+class MetroGraphs(
+
+ private val context: Context,
+ private val memberInjector: MetroMemberInjector,
+ private val databaseConfig: DatabaseConfig,
+ private val externalOptionsOverride: ExternalOptionsOverride
+) {
+
+
+ /**
+ * Workers Metro can build, keyed by class name because that is all WorkManager gives us.
+ *
+ * Resolved on each call rather than cached, so nothing here runs until a worker is really built -
+ * WorkManager can initialise during startup, so nothing here runs until a worker is really built.
+ */
+ /** Built in the module that owns the worker. */
+ val runningModeExpiryScheduler: RunningModeExpiryScheduler get() = workers.runningModeExpiryScheduler
+
+ fun workerCreators(): Map =
+ (workers.workerCreators + openHumans.workerCreators + source.workerCreators)
+ .mapKeys { (klass, _) -> klass.java.name }
+
+ /**
+ * The one application scope.
+ */
+ val applicationScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ /** The one Metro root. Sub-graphs are extensions of it rather than roots of their own. */
+ private val root: AppRootGraph by lazy {
+ createGraphFactory()
+ .create(applicationScope, context, memberInjector, databaseConfig, externalOptionsOverride, CoreObjectsGraph)
+ }
+
+ /**
+ * The root graph itself, for instrumented tests that need a pump's own objects.
+ *
+ * A pump module contributes an accessor interface (`DanaRAccessors`, `EquilAccessors`, ...), so the
+ * generated graph implements it and a test casts to the one it needs:
+ * `(testGraphs.rootGraph as EquilAccessors).equilManager`. That keeps `:app` free of pump types -
+ * the accessors exist exactly when their module is in the build.
+ *
+ * Not for production code: anything in the app that needs a binding should be injected, not fished
+ * out of the graph by hand.
+ */
+ val rootGraph: AppRootGraph get() = root
+
+ private val source: SourceMetroGraph get() = root.sourceGraph
+
+ private val workers: AppWorkersGraph get() = root.workersGraph
+
+ // The module owns its own bridge, because its DI qualifiers are internal to it.
+ // The bridge comes from the root graph.
+ private val openHumans: OpenHumansMetroBridge get() = root.openHumansMetroBridge
+ /**
+ * Builds one history browsing window, with its own calculation objects.
+ *
+ * A new graph each call, on purpose - the graph instance is what makes the window's objects its
+ * own. Everything the window shares with the app arrives deferred, because [ActivePlugin] leads
+ * back to the plugin list and so back into these graphs.
+ */
+ fun newHistoryWindow(): HistoryWindowGraph = root.historyWindowFactory.create()
+
+ /**
+ * Fills the `@Inject` fields of an Android class the graph knows about.
+ */
+ @Suppress("UNCHECKED_CAST")
+ fun injectMembers(target: Any): Boolean {
+ val injector = openHumans.memberInjectors[target::class]
+ ?: source.memberInjectors[target::class]
+ // Contributed straight into the root, which is how a pump module reaches this map without
+ // MetroGraphs naming it - see `contributedMemberInjectors`.
+ ?: root.contributedMemberInjectors[target::class]
+ ?: return false
+ (injector as MembersInjector).injectMembers(target)
+ return true
+ }
+
+ /**
+ * The one `ViewModelProvider.Factory`. Built once, from every module graph that contributes view
+ * models, so the whole app reads one map.
+ */
+ val viewModelFactory: MetroViewModelFactory by lazy { AapsViewModelFactory(root, openHumans) }
+
+ /**
+ * Plugins contributed by Metro graphs, keyed by order.
+ *
+ * A real `@IntoMap @IntKey(n)` multibinding built this map at compile time - the same annotation
+ * shape, built at compile time.
+ */
+ fun plugins(): Map =
+ root.contributedPlugins
+
+ /**
+ * The whole plugin list, in order - what `PluginStore.plugins` is set to.
+ *
+ * The qualified buckets are merged **only** under the condition that build should have them.
+ * Keeping them apart is what stops a plugin appearing in a build that never had it - a follower
+ * showing Objectives, say. `mergePlugins` names which bucket a clashing plugin came from, which is
+ * why the sources are listed rather than merged directly.
+ */
+ fun allPlugins(aapsLogger: AAPSLogger): List {
+ val sources = buildList {
+ add(PluginSource("Metro", plugins()))
+ if (config.APS) add(PluginSource("Metro @APS", apsPlugins()))
+ if (config.PUMPDRIVERS) add(PluginSource("Metro @PumpDriver", pumpDriverPlugins()))
+ if (!config.AAPSCLIENT) add(PluginSource("Metro @NotNSClient", notNsClientPlugins()))
+ }
+
+ val (plugins, problems) = mergePlugins(sources)
+ // Two buckets can still collide on one order key, which loses a plugin silently. Logged rather
+ // than thrown: a wrong plugin list must not stop the app from starting, and this is loud enough
+ // to find in a log.
+ problems.forEach { aapsLogger.error(LTag.CORE, "PLUGIN LIST: $it") }
+
+ return plugins
+ }
+
+ /**
+ * Plugins that must NOT appear in an AAPSCLIENT build.
+ *
+ * Kept apart from [plugins] because these carry a `@NotNSClient`
+ * qualifier, and [allPlugins] merges that bucket only when the build is not a
+ * follower. Merging it unconditionally would quietly add Open Humans to follower builds.
+ */
+ fun notNsClientPlugins(): Map =
+ openHumans.notNsClientPlugins + root.contributedNotNsClientPlugins
+
+ /**
+ * Plugins that only belong in a build that runs the loop.
+ *
+ * Same reasoning as [notNsClientPlugins], for the `@APS` qualifier. Objectives, the signature
+ * verifier and the storage constraint have no meaning in a build that never makes a decision.
+ */
+ fun apsPlugins(): Map = root.contributedApsPlugins
+
+ /**
+ * Pump drivers, merged only by a build that has them.
+ *
+ * Empty in a follower, because no pump module is on that classpath to contribute - so the caller can
+ * merge this only under `config.PUMPDRIVERS`.
+ */
+ fun pumpDriverPlugins(): Map = root.contributedPumpDriverPlugins
+
+ /**
+ * Constraint plugins that are also bound to an interface.
+ *
+ * wrong otherwise.
+ */
+ val xDripSource: XDripSource get() = root.xdripSourcePlugin
+ val dexcomBoyda: DexcomBoyda get() = root.dexcomPlugin
+ val bgQualityCheck: BgQualityCheck get() = root.bgQualityCheckPlugin
+ val objectives: Objectives get() = root.objectivesPlugin
+
+ val profileFunction: ProfileFunction get() = root.profileFunction
+ val versionCheckerUtils: VersionCheckerUtils get() = root.versionCheckerUtils
+ val nsIncomingDataProcessor: NsIncomingDataProcessor get() = root.nsIncomingDataProcessor
+ val automation: Automation get() = root.automation
+ val automationRuntime: AutomationRuntime get() = root.automationRuntime
+
+ /** Same plugin as [objectives], by class. The instrumented tests ask for the concrete type. */
+ val objectivesPlugin: ObjectivesPlugin get() = root.objectivesPlugin
+
+ /** The live loop's calculator - not the history browser's. */
+ val iobCobCalculator: IobCobCalculator get() = root.iobCobCalculator
+
+ /** The loop. */
+ val loop: Loop get() = root.loop
+ val autotune: Autotune get() = root.autotune
+ val runningModeReconciler: RunningModeReconciler get() = root.runningModeReconciler
+
+ /** The openAPS pieces the instrumented APS tests read. */
+ val determineBasalSMB: DetermineBasalSMB get() = root.determineBasalSMB
+ val determineBasalAMA: DetermineBasalAMA get() = root.determineBasalAMA
+ val determineBasalAutoISF: DetermineBasalAutoISF get() = root.determineBasalAutoISF
+ val signatureVerifier: SignatureVerifierPlugin get() = root.signatureVerifierPlugin
+ val resourceHelper: ResourceHelper get() = root.resourceHelper
+ val fabricPrivacy: FabricPrivacy get() = root.fabricPrivacy
+ val uiInteraction: UiInteraction get() = root.uiInteraction
+ val preferences: Preferences get() = root.preferences
+ val aapsLogger: AAPSLogger get() = root.aapsLogger
+ val rxBus: RxBus get() = root.rxBus
+ val dateUtil: DateUtil get() = root.dateUtil
+ val l: L get() = root.l
+ val keyValueStore: KeyValueStore get() = root.keyValueStore
+ val iconsProvider: IconsProvider get() = root.iconsProvider
+ val widgetUpdater: WidgetUpdater get() = root.widgetUpdater
+ val commandQueue: CommandQueue get() = root.commandQueue
+ val localAlertUtils: LocalAlertUtils get() = root.localAlertUtils
+ val persistenceLayer: PersistenceLayer get() = root.persistenceLayer
+ val appRepository: AppRepository get() = root.appRepository
+ val constraintsChecker: ConstraintsChecker get() = root.constraintsChecker
+ val notificationManager: NotificationManager get() = root.notificationManager
+ val profileSwitchScheduler: ProfileSwitchScheduler get() = root.profileSwitchScheduler
+ val snackbarNotificationFallback: SnackbarNotificationFallback get() = root.snackbarNotificationFallback
+ val eatReminder: EatReminder get() = root.eatReminder
+ val uiRestart: UiRestart get() = root.uiRestart
+ val activePlugin: ActivePlugin get() = root.activePlugin
+ val pluginStore: PluginStore get() = root.pluginStore
+ val maintenance: Maintenance get() = root.maintenance
+ val fileListProvider: FileListProvider get() = root.fileListProvider
+ val exportPasswordDataStore: ExportPasswordDataStore get() = root.exportPasswordDataStore
+ val cryptoUtil: CryptoUtil get() = root.cryptoUtil
+ val concentrationHelper: ConcentrationHelper get() = root.concentrationHelper
+ val processedTbrEbData: ProcessedTbrEbData get() = root.processedTbrEbData
+ val configBuilder: ConfigBuilder get() = root.configBuilder
+ val scenes: Scenes get() = root.scenes
+
+ /** The one scene state holder, for classes that ask for the concrete type. */
+ val decimalFormatter: DecimalFormatter get() = root.decimalFormatter
+ val profileUtil: ProfileUtil get() = root.profileUtil
+ val hardLimits: HardLimits get() = root.hardLimits
+ val storage: Storage get() = root.storage
+
+ val pumpSync: PumpSync get() = root.pumpSync
+ val insulinManager: InsulinManager get() = root.insulinManager
+
+ val config: Config get() = root.config
+ val resourceHelperImpl: ResourceHelperImpl get() = root.resourceHelperImpl
+ val fabricPrivacyImpl: FabricPrivacyImpl get() = root.fabricPrivacyImpl
+ val processLifecycleListener: ProcessLifecycleListener get() = root.processLifecycleListener
+ val profileRepository: ProfileRepository get() = root.profileRepository
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/MetroWorkerFactory.kt b/app/main/kotlin/app/aaps/di/metro/MetroWorkerFactory.kt
new file mode 100644
index 000000000000..70010bb2c218
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/MetroWorkerFactory.kt
@@ -0,0 +1,23 @@
+package app.aaps.di.metro
+
+import android.content.Context
+import androidx.work.ListenableWorker
+import androidx.work.WorkerFactory
+import androidx.work.WorkerParameters
+
+/**
+ * Builds every worker in the app.
+ * Returning null is WorkManager's documented "I do not handle this one" signal, and it still matters:
+ * WorkManager's own internal workers are not ours and are built reflectively, exactly as before.
+ */
+class MetroWorkerFactory(
+ private val metroGraphs: MetroGraphs
+) : WorkerFactory() {
+
+ override fun createWorker(
+ appContext: Context,
+ workerClassName: String,
+ workerParameters: WorkerParameters
+ ): ListenableWorker? =
+ metroGraphs.workerCreators()[workerClassName]?.create(appContext, workerParameters)
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/SharedImplBindings.kt b/app/main/kotlin/app/aaps/di/metro/SharedImplBindings.kt
new file mode 100644
index 000000000000..252cd5c7034f
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/SharedImplBindings.kt
@@ -0,0 +1,62 @@
+package app.aaps.di.metro
+
+import android.content.Context
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.L
+import app.aaps.core.interfaces.rx.AapsSchedulers
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.sharedPreferences.KeyValueStore
+import app.aaps.core.interfaces.utils.DateUtil
+import app.aaps.core.keys.interfaces.Preferences
+import app.aaps.shared.impl.logging.AAPSLoggerProduction
+import app.aaps.shared.impl.logging.LImpl
+import app.aaps.shared.impl.rx.AapsSchedulersImpl
+import app.aaps.settingsstore.AndroidStorage
+import app.aaps.shared.impl.rx.bus.RxBusImpl
+import app.aaps.shared.impl.utils.DateUtilImpl
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.BindingContainer
+import dev.zacsweers.metro.ContributesTo
+import dev.zacsweers.metro.Provides
+import dev.zacsweers.metro.SingleIn
+
+/**
+ * The phone's half of `:shared:impl`.
+ * Keep this in step with `SharedImplModule` and `LoggerModule`. A binding that only exists on one side
+ * is harmless - the other side fails to compile the moment it needs it. The danger is a binding that
+ * exists on both sides but is *built differently*: change the preferences file name in one and the
+ * phone and the watch quietly disagree, with nothing failing.
+ */
+@ContributesTo(AppScope::class)
+@BindingContainer
+object SharedImplBindings {
+
+ /**
+ * The preference store: the encrypted one [AndroidStorage] opened when the app started, or the empty one
+ * in memory when that failed. Wear keeps its own store, `SPImpl` (see `SharedImplModule`).
+ */
+ @Provides
+ @SingleIn(AppScope::class)
+ fun keyValueStore(context: Context): KeyValueStore = AndroidStorage.open(context).store
+
+ /** Deferred: [L] reads its log settings back out of [Preferences]. */
+ @Provides
+ @SingleIn(AppScope::class)
+ fun l(preferences: () -> Preferences): L = LImpl(preferences)
+
+ @Provides
+ @SingleIn(AppScope::class)
+ fun aapsLogger(l: L): AAPSLogger = AAPSLoggerProduction(l)
+
+ @Provides
+ @SingleIn(AppScope::class)
+ fun dateUtil(context: Context): DateUtil = DateUtilImpl(context)
+
+ @Provides
+ @SingleIn(AppScope::class)
+ fun rxBus(aapsLogger: AAPSLogger): RxBus = RxBusImpl(aapsLogger)
+
+ @Provides
+ @SingleIn(AppScope::class)
+ fun aapsSchedulers(): AapsSchedulers = AapsSchedulersImpl()
+}
diff --git a/app/main/kotlin/app/aaps/di/metro/SyncPluginsBindings.kt b/app/main/kotlin/app/aaps/di/metro/SyncPluginsBindings.kt
new file mode 100644
index 000000000000..0651c587659f
--- /dev/null
+++ b/app/main/kotlin/app/aaps/di/metro/SyncPluginsBindings.kt
@@ -0,0 +1,45 @@
+package app.aaps.di.metro
+
+import app.aaps.core.interfaces.di.NotNSClient
+import app.aaps.core.interfaces.plugin.PluginBase
+import app.aaps.plugins.sync.smsCommunicator.SmsCommunicatorPlugin
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.BindingContainer
+import dev.zacsweers.metro.ContributesTo
+import dev.zacsweers.metro.IntKey
+import dev.zacsweers.metro.IntoMap
+import dev.zacsweers.metro.Provides
+
+/**
+ * The one `:plugins:sync` plugin that cannot register itself.
+ *
+ * ## Why not annotate the class, like the other three
+ *
+ * Its map entry is qualified with [NotNSClient], and a qualifier has to travel with the entry rather
+ * than sit on the class - `@NotNSClient` on `SmsCommunicatorPlugin` would qualify every binding it
+ * has, including the `SmsCommunicator` interface nobody asks for that way. Metro documents putting
+ * the qualifier on the bound type instead, but `binding<@NotNSClient PluginBase>()` is rejected by
+ * the version pinned here:
+ * ```
+ * Inapplicable candidate(s): constructor(scope: KClass<*>, binding: binding<*> = ..., ...)
+ * ```
+ * So the entry stays stated. Worth retrying when Metro is un-pinned from the snapshot - if it is
+ * accepted then, this file goes and the annotation moves onto the class.
+ *
+ * **The previous reason recorded here was wrong.** It quoted `InjectProcessingStep was unable to
+ * process` and `error.NonExistentClass`, which are Dagger/KAPT diagnostics - Metro is a compiler
+ * plugin and has no annotation processor. `NSClientV3Plugin` and `WearPlugin` now carry
+ * `@ContributesIntoMap` and compile, which settles it. The real obstacle for those two was only that
+ * `dev.zacsweers.metro.IntKey` clashes with `app.aaps.core.keys.IntKey`; they import it as
+ * `MetroIntKey`, the same way `LoopPlugin` and `AutotunePlugin` always have.
+ */
+@ContributesTo(AppScope::class)
+@BindingContainer
+object SyncPluginsBindings {
+
+ @Provides
+ @IntoMap
+ @NotNSClient
+ @IntKey(300)
+ fun smsCommunicatorPlugin(plugin: SmsCommunicatorPlugin): PluginBase = plugin
+}
diff --git a/app/main/kotlin/app/aaps/history/HistoryBrowserData.kt b/app/main/kotlin/app/aaps/history/HistoryBrowserData.kt
new file mode 100644
index 000000000000..f93535b64dac
--- /dev/null
+++ b/app/main/kotlin/app/aaps/history/HistoryBrowserData.kt
@@ -0,0 +1,37 @@
+package app.aaps.history
+
+import app.aaps.core.interfaces.iob.IobCobCalculator
+import app.aaps.core.interfaces.overview.OverviewData
+import app.aaps.core.interfaces.overview.graph.OverviewDataCache
+import app.aaps.core.interfaces.workflow.CalculationSignalsEmitter
+import app.aaps.di.metro.HistoryWindowGraph
+import app.aaps.ui.compose.history.HistoryScope
+
+/**
+ * The calculation objects behind the History Browser.
+ *
+ * These are deliberately **not** the app's singletons. The History Browser recalculates over a
+ * different time range, and sharing the live loop's objects would mean browsing history rewrites the
+ * state the loop is running on.
+ *
+ * It asks for one history window and hands back what the window contains. `HistoryWindowGraph` owns
+ * the wiring, `MetroScopingTest` checks the isolation those objects rely on, and the cycle between the
+ * cache and the calculator is expressed with Metro's `Provider` rather than a hand-written lambda.
+ */
+/*
+ * Takes the window itself rather than `MetroGraphs`: asking the graph holder for one would make a
+ * domain class depend on the DI plumbing to reach a single object. `AppAndroidBindings` calls the
+ * extension factory instead, and the scope lives on that provider.
+ */
+class HistoryBrowserData(
+ window: HistoryWindowGraph
+) : HistoryScope {
+
+ override val overviewData: OverviewData = window.overviewData
+ override val signals: CalculationSignalsEmitter = window.signals
+ override val cache: OverviewDataCache = window.cache
+ override val iobCobCalculator: IobCobCalculator = window.iobCobCalculator
+
+ override fun onDestroy() {
+ }
+}
diff --git a/app/main/kotlin/app/aaps/implementations/ConfigImpl.kt b/app/main/kotlin/app/aaps/implementations/ConfigImpl.kt
new file mode 100644
index 000000000000..f3e08e8e6f7b
--- /dev/null
+++ b/app/main/kotlin/app/aaps/implementations/ConfigImpl.kt
@@ -0,0 +1,113 @@
+package app.aaps.implementations
+
+import android.os.Build
+import app.aaps.BuildConfig
+import app.aaps.R
+import app.aaps.core.interfaces.configuration.Config
+import app.aaps.core.interfaces.configuration.ExternalOptions
+import app.aaps.core.interfaces.configuration.InitProgress
+import app.aaps.core.interfaces.maintenance.FileListProvider
+import app.aaps.core.keys.interfaces.AppPlatform
+import app.aaps.core.keys.interfaces.TextRef
+import app.aaps.di.ExternalOptionsOverride
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.ContributesBinding
+import dev.zacsweers.metro.Inject
+import dev.zacsweers.metro.SingleIn
+import dev.zacsweers.metro.binding
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+
+// @Singleton (not @Reusable): Config owns the single app-global init-progress flow that
+// ComposeMainActivity's splash gate observes; a guaranteed single instance keeps that flow shared
+// (also required so an instrumented test can flip initCompleted() on the same instance the UI reads).
+@Suppress("KotlinConstantConditions")
+@ContributesBinding(AppScope::class, binding = binding())
+@SingleIn(AppScope::class)
+@Inject
+class ConfigImpl(
+ private val fileListProvider: () -> FileListProvider,
+ private val externalOptionsOverride: ExternalOptionsOverride
+) : Config {
+
+ override val SUPPORTED_NS_VERSION = 150000 // 15.0.0
+ override val APS = BuildConfig.FLAVOR == "full"
+ override val AAPSCLIENT = BuildConfig.FLAVOR == "aapsclient" || BuildConfig.FLAVOR == "aapsclient2" || BuildConfig.FLAVOR == "aapsclient3"
+ override val AAPSCLIENT1 = BuildConfig.FLAVOR == "aapsclient"
+ override val AAPSCLIENT2 = BuildConfig.FLAVOR == "aapsclient2"
+ override val AAPSCLIENT3 = BuildConfig.FLAVOR == "aapsclient3"
+ override val PUMPCONTROL = BuildConfig.FLAVOR == "pumpcontrol"
+ override val PUMPDRIVERS = BuildConfig.FLAVOR == "full" || BuildConfig.FLAVOR == "pumpcontrol"
+ override val FLAVOR = BuildConfig.FLAVOR
+ override val VERSION_NAME = BuildConfig.VERSION_NAME
+ override val HEAD = BuildConfig.HEAD
+ override val COMMITTED = BuildConfig.COMMITTED.toBoolean()
+ override val BUILD_VERSION = BuildConfig.BUILDVERSION
+ override val REMOTE: String = BuildConfig.REMOTE
+ override val BUILD_TYPE: String = BuildConfig.BUILD_TYPE
+ override val PLATFORM: String = "Android"
+ override val platform: AppPlatform = AppPlatform.Android
+
+ // App languages (LocaleManager) came with Android 13; see MainApp.applyAppLanguage
+ override val supportsAppLanguage: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
+ override val VERSION: String = BuildConfig.VERSION
+ override val APPLICATION_ID: String = BuildConfig.APPLICATION_ID
+ override val DEBUG = BuildConfig.DEBUG
+
+ override val currentDeviceModelString = Build.MANUFACTURER + " " + Build.MODEL + " (" + Build.DEVICE + ")"
+ override val deviceModelForUpload = Build.MANUFACTURER + " " + Build.MODEL
+ // The unit-test android.jar leaves these statics null, and this one is assigned straight to a
+ // non-null String, so it would fail graph creation in every test. The line above survives it only
+ // because string concatenation prints "null".
+ override val deviceManufacturer: String = Build.MANUFACTURER ?: ""
+ override val appName: TextRef = TextRef.AndroidRes(R.string.app_name)
+
+ private val _initProgressFlow = MutableStateFlow(InitProgress())
+ override val initProgressFlow: StateFlow = _initProgressFlow.asStateFlow()
+ override fun updateInitProgress(step: String, current: Int, total: Int) {
+ _initProgressFlow.value = _initProgressFlow.value.copy(step = step, current = current, total = total)
+ }
+
+ override fun initCompleted() {
+ _initProgressFlow.value = _initProgressFlow.value.copy(done = true)
+ }
+
+ override fun initFailed(error: String) {
+ _initProgressFlow.value = _initProgressFlow.value.copy(error = error)
+ }
+
+ // update() rather than a read-modify-write of .value: these are called from the import screen's
+ // dispatcher while other threads read the same flow, and update() retries on conflict.
+ override fun beginReconfiguring() {
+ _initProgressFlow.update { it.enteringReconfigure() }
+ }
+
+ override fun endReconfiguring() {
+ _initProgressFlow.update { it.leavingReconfigure() }
+ }
+
+ private val _initSnackbarFlow = MutableSharedFlow(extraBufferCapacity = 1)
+ override val initSnackbarFlow: SharedFlow = _initSnackbarFlow.asSharedFlow()
+ override fun showInitSnackbar(message: String) {
+ _initSnackbarFlow.tryEmit(message)
+ }
+
+ private val enabledOptionsCache = mutableMapOf()
+
+ override fun isEngineeringModeOrRelease(): Boolean = if (!APS) true else isEngineeringMode() || !isDev()
+ override fun isEngineeringMode(): Boolean = isEnabled(ExternalOptions.ENGINEERING_MODE)
+ override fun isDev(): Boolean = (VERSION.contains("-") || VERSION.matches(Regex(".*[a-zA-Z]+.*"))) && !VERSION.contains("-beta") && !VERSION.contains("-rc")
+ // The override is read first and never cached. The instrumented tests change which options they
+ // want between tests, so a cached answer from the first one would stick for the whole run. The file
+ // lookup below stays cached - that really is fixed for the life of the process.
+ override fun isEnabled(option: ExternalOptions): Boolean =
+ option in externalOptionsOverride.enabled() ||
+ enabledOptionsCache.getOrPut(option) {
+ fileListProvider().ensureExtraDirExists()?.findFile(option.filename) != null
+ }
+}
\ No newline at end of file
diff --git a/app/main/kotlin/app/aaps/implementations/UiInteractionImpl.kt b/app/main/kotlin/app/aaps/implementations/UiInteractionImpl.kt
new file mode 100644
index 000000000000..6906562f3f3c
--- /dev/null
+++ b/app/main/kotlin/app/aaps/implementations/UiInteractionImpl.kt
@@ -0,0 +1,230 @@
+package app.aaps.implementations
+
+import android.content.Context
+import android.content.Intent
+import android.os.Looper
+import android.widget.Toast
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.ProcessLifecycleOwner
+import app.aaps.ComposeMainActivity
+import app.aaps.core.data.model.TE
+import app.aaps.core.data.time.T
+import app.aaps.core.data.ue.Action
+import app.aaps.core.data.ue.Sources
+import app.aaps.core.data.ue.ValueWithUnit
+import app.aaps.core.interfaces.alerts.EatReminder
+import app.aaps.core.interfaces.configuration.Config
+import app.aaps.core.interfaces.db.PersistenceLayer
+import app.aaps.core.interfaces.di.ApplicationScope
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.notifications.AlarmIntent
+import app.aaps.core.interfaces.notifications.AlarmSound
+import app.aaps.core.interfaces.notifications.NotificationManager
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.rx.events.EventAlarmDismissed
+import app.aaps.core.interfaces.rx.events.EventMobileToWear
+import app.aaps.core.interfaces.rx.weardata.EventData
+import app.aaps.core.interfaces.ui.UiInteraction
+import app.aaps.core.objects.extensions.asAnnouncement
+import app.aaps.implementation.androidNotification.AlarmNotificationManager
+import app.aaps.ui.activities.ErrorActivity
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.ContributesBinding
+import dev.zacsweers.metro.Inject
+import dev.zacsweers.metro.SingleIn
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlin.reflect.KClass
+
+@ContributesBinding(AppScope::class)
+@SingleIn(AppScope::class)
+@Inject
+class UiInteractionImpl(
+ private val context: Context,
+ private val alarmNotificationManager: AlarmNotificationManager,
+ private val notificationManager: () -> NotificationManager,
+ private val aapsLogger: AAPSLogger,
+ private val persistenceLayer: PersistenceLayer,
+ private val config: Config,
+ @ApplicationScope private val appScope: CoroutineScope,
+ private val rxBus: RxBus,
+ // A provider: EatReminder needs UiInteraction back to silence its alarm.
+ private val eatReminder: () -> EatReminder
+) : UiInteraction {
+
+ override val mainActivity: KClass<*> = ComposeMainActivity::class
+ override val errorHelperActivity: KClass<*> = ErrorActivity::class
+
+ /**
+ * The alarm shown now is the "time to eat" timer's. There is one full-screen alarm at a time and a newer one
+ * takes its place, so this follows the last [runAlarm]. Stopping, silencing and +5 min of the timer use it to
+ * reach only their own alarm (#5408).
+ */
+ @Volatile private var eatReminderAlarmShown = false
+
+ /** The alarm shown now, for the re-ring of a mute. Null while the eat alarm is shown: it has no mute, +5 min moves its timer. */
+ @Volatile private var lastAlarm: Alarm? = null
+
+ /** The re-ring of a mute, until it rang or a stop or a new alarm ended it. */
+ @Volatile private var reRing: Job? = null
+
+ private class Alarm(val status: String, val title: String, val sound: AlarmSound?)
+
+ override fun runAlarm(status: String, title: String, sound: AlarmSound?) = runAlarm(status, title, sound, eatReminder = false)
+
+ override fun runEatReminderAlarm(status: String, title: String) = runAlarm(status, title, AlarmSound.EAT_REMINDER, eatReminder = true)
+
+ /** [announce] false for the re-ring of a mute: the announcement was written when the alarm first rang. */
+ private fun runAlarm(status: String, title: String, sound: AlarmSound?, eatReminder: Boolean, announce: Boolean = true) {
+ // A new alarm takes the place of a muted one
+ reRing?.cancel()
+ reRing = null
+ lastAlarm = if (eatReminder) null else Alarm(status, title, sound)
+ eatReminderAlarmShown = eatReminder
+ // The watch shows the alarm with Silence and Mute 5 min. It rings the eat alarm by itself, so for that one
+ // only the alarm it takes the place of goes away there.
+ rxBus.send(
+ EventMobileToWear(
+ if (eatReminder) EventData.AlarmStopped(System.currentTimeMillis())
+ else EventData.AlarmRinging(System.currentTimeMillis(), title = title, status = status, canMute = true)
+ )
+ )
+ // Persist the error as an announcement at fire time — gated by the NS-announcement
+ // preference + APS build. Done here (not in ErrorActivity) so the record is written for
+ // every alarm with the true trigger time, regardless of whether/how it is later
+ // acknowledged (phone activity, Wear mute, OS-trimmed notification, or never opened).
+ if (config.APS && announce)
+ appScope.launch {
+ persistenceLayer.insertPumpTherapyEventIfNewByTimestamp(
+ therapyEvent = TE.asAnnouncement(status),
+ action = Action.CAREPORTAL,
+ source = Sources.Aaps,
+ note = status,
+ listValues = listOf(ValueWithUnit.TEType(TE.Type.ANNOUNCEMENT))
+ )
+ }
+
+ // ProcessLifecycleOwner.currentState requires main-thread access (officially @MainThread).
+ // BLE callbacks, RxJava workers, and coroutine non-main dispatchers all call runAlarm
+ // from non-main threads. From those contexts we skip the foreground-direct optimization
+ // entirely and use the FSI path, which is safe from any thread.
+ if (Looper.myLooper() != Looper.getMainLooper()) {
+ aapsLogger.debug(LTag.CORE, "runAlarm (off-main → FSI): $title - $status (sound=$sound)")
+ alarmNotificationManager.postFullScreenAlarm(status = status, title = title, sound = sound, eatReminder = eatReminder)
+ return
+ }
+
+ if (isAppInForeground()) {
+ // Foreground path — launch the activity directly. No notification needed:
+ // • Avoids channel-sound vs activity-ramp conflict.
+ // • Activity opens instantly, owns ramped audio from 0.
+ // • Works because the caller's process is already foreground (Android's
+ // background-activity-start restriction does not apply).
+ aapsLogger.debug(LTag.CORE, "runAlarm (foreground direct): $title - $status (sound=$sound)")
+ val intent = Intent(context, errorHelperActivity.java).apply {
+ putExtra(AlarmIntent.EXTRA_SOUND, sound?.name)
+ putExtra(AlarmIntent.EXTRA_STATUS, status)
+ putExtra(AlarmIntent.EXTRA_TITLE, title)
+ putExtra(AlarmIntent.EXTRA_EAT_REMINDER, eatReminder)
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
+ }
+ try {
+ context.startActivity(intent)
+ } catch (ex: Exception) {
+ // Defensive: if the activity start is rejected for any reason, fall back to
+ // the FSI notification path so the alert is never silently lost.
+ aapsLogger.error(LTag.CORE, "runAlarm: direct startActivity failed, falling back to FSI", ex)
+ postFsiFallback(status, title, sound, eatReminder)
+ }
+ } else {
+ // Background path — the full-screen alarm ("FSI" in the names here, although it no
+ // longer uses a full-screen intent): a notification with channel sound plus the looping
+ // alarm sound, and a setAlarmClock screen wake that brings up the activity when exact
+ // alarms are allowed.
+ aapsLogger.debug(LTag.CORE, "runAlarm (background via FSI): $title - $status (sound=$sound)")
+ alarmNotificationManager.postFullScreenAlarm(status = status, title = title, sound = sound, eatReminder = eatReminder)
+ }
+ }
+
+ override fun stopAlarm(reason: String) {
+ aapsLogger.debug(LTag.CORE, "stopAlarm: $reason")
+ // A muted alarm that is stopped does not come back
+ reRing?.cancel()
+ reRing = null
+ // Every way of stopping the alarm shown comes here (alarm screen, notification Mute or swipe, watch). When it
+ // is the "time to eat" alarm, that is the timer's Stop, as on its bar: the timer ends and only its alarm is
+ // silenced, other alarms keep sounding. Stopping another alarm leaves the timer alone, also a pump alarm that
+ // came in after the eat alarm rang and took its place (#5408).
+ if (eatReminderAlarmShown) {
+ // Only the timer this alarm rang for. A new timer started since then has not rung, and runs on.
+ if (eatReminder().state.value?.alarmRang == true) eatReminder().stop()
+ // Also when the timer is gone or new: this alarm is still shown
+ stopEatReminderAlarm()
+ return
+ }
+ // Route through the registry owner so all audible alarms are actually silenced: clears the
+ // internal AlarmSoundPlayer (Wear snooze used to only cancel the system notification, leaving
+ // the ramping audio playing), stops the full-screen audio, and cancels the notifications.
+ notificationManager().muteAllAlarms()
+ rxBus.send(EventMobileToWear(EventData.AlarmStopped(System.currentTimeMillis())))
+ }
+
+ override fun dismissAlarm(reason: String) {
+ stopAlarm(reason)
+ // The alarm screen is its own activity: it is told, and closes itself
+ rxBus.send(EventAlarmDismissed())
+ }
+
+ override fun muteAlarm(minutes: Int, reason: String) {
+ stopAlarm(reason)
+ val alarm = lastAlarm ?: return
+ reRing = appScope.launch {
+ delay(T.mins(minutes.toLong()).msecs())
+ reRing = null
+ aapsLogger.debug(LTag.CORE, "Alarm rings again after $minutes min: ${alarm.title} - ${alarm.status}")
+ // On the main thread, so with the app in front it goes straight to the alarm screen, as every alarm does
+ withContext(Dispatchers.Main) { runAlarm(alarm.status, alarm.title, alarm.sound, eatReminder = false, announce = false) }
+ }
+ }
+
+ override fun stopEatReminderAlarm() {
+ if (!eatReminderAlarmShown) return
+ eatReminderAlarmShown = false
+ aapsLogger.debug(LTag.CORE, "stopEatReminderAlarm")
+ // The full-screen alarm and its looping sound, nothing in the notification list
+ alarmNotificationManager.cancelAlarm()
+ }
+
+ /**
+ * Posts an FSI alarm notification with an additional last-resort Toast safety net.
+ * If `POST_NOTIFICATIONS` is also revoked, `postFullScreenAlarm`'s catch block already
+ * logs the failure but the alarm is otherwise lost — the Toast provides at least a
+ * visible signal that something tried to alarm. Best-effort; Toast can also fail (e.g.
+ * if a system overlay permission is denied) but it costs nothing to try.
+ */
+ private fun postFsiFallback(status: String, title: String, sound: AlarmSound?, eatReminder: Boolean) {
+ alarmNotificationManager.postFullScreenAlarm(status = status, title = title, sound = sound, eatReminder = eatReminder)
+ // Toast must be created on the main thread (we are — runAlarm guards above).
+ runCatching {
+ Toast.makeText(context, "ALARM: $title — $status", Toast.LENGTH_LONG).show()
+ }.onFailure {
+ aapsLogger.error(LTag.CORE, "runAlarm: Toast fallback also failed; alarm not user-visible", it)
+ }
+ }
+
+ /**
+ * True when the AAPS process has at least one STARTED activity — meaning Android's
+ * background-activity-start restriction does not apply and we can [Context.startActivity]
+ * without going through a notification PendingIntent.
+ *
+ * **Must only be called from the main thread.** `Lifecycle.currentState` is officially
+ * `@MainThread`; callers are guarded in [runAlarm].
+ */
+ private fun isAppInForeground(): Boolean =
+ ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
+}
diff --git a/app/main/kotlin/app/aaps/persistentNotification/DummyService.kt b/app/main/kotlin/app/aaps/persistentNotification/DummyService.kt
new file mode 100644
index 000000000000..146101efd23d
--- /dev/null
+++ b/app/main/kotlin/app/aaps/persistentNotification/DummyService.kt
@@ -0,0 +1,86 @@
+package app.aaps.persistentNotification
+
+import android.app.ForegroundServiceStartNotAllowedException
+import android.app.Notification
+import android.content.Intent
+import android.os.Binder
+import android.os.IBinder
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.notifications.NotificationHolder
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.rx.collectResilient
+import app.aaps.core.interfaces.rx.events.EventAppExit
+import app.aaps.core.interfaces.utils.fabric.FabricPrivacy
+import app.aaps.core.objects.workflow.MetroService
+import dev.zacsweers.metro.Inject
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+
+/**
+ * Keeps AAPS in foreground state, so it won't be terminated by Android nor get restricted by the background execution limits
+ */
+class DummyService : MetroService() {
+
+ @Inject lateinit var rxBus: RxBus
+ @Inject lateinit var aapsLogger: AAPSLogger
+ @Inject lateinit var fabricPrivacy: FabricPrivacy
+ @Inject lateinit var notificationHolder: NotificationHolder
+
+ // App exit is the only thing this listens for, and the service dies with it - so an IO scope
+ // cancelled in onDestroy, matching what the CompositeDisposable did.
+ private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
+
+ inner class LocalBinder : Binder() {
+
+ fun getService(): DummyService = this@DummyService
+ }
+
+ private val binder = LocalBinder()
+ override fun onBind(intent: Intent): IBinder = binder
+
+ override fun onCreate() {
+ super.onCreate()
+ goForeground()
+ rxBus.toFlow(EventAppExit::class)
+ .collectResilient(scope, aapsLogger, LTag.CORE, start = CoroutineStart.UNDISPATCHED) {
+ aapsLogger.debug(LTag.CORE, "EventAppExit received")
+ stopSelf()
+ }
+ }
+
+ override fun onDestroy() {
+ aapsLogger.debug(LTag.CORE, "onDestroy")
+ scope.cancel()
+ super.onDestroy()
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ super.onStartCommand(intent, flags, startId)
+ goForeground()
+ return START_STICKY
+ }
+
+ /**
+ * Puts this service into the foreground with the ongoing notification.
+ *
+ * When Android refuses the foreground state itself - Android 12+ does that for an app in the
+ * background without an exemption - the fallback notification would be refused the same way, and
+ * that second throw would end the app. So a refusal is only logged. `DummyServiceHelper` and
+ * `PersistentNotificationPlugin` start the service again once AAPS is on screen.
+ */
+ private fun goForeground() {
+ try {
+ aapsLogger.debug("Starting DummyService with ID ${notificationHolder.notificationID} notification ${notificationHolder.notification}")
+ startForeground(notificationHolder.notificationID, notificationHolder.notification)
+ } catch (e: ForegroundServiceStartNotAllowedException) {
+ aapsLogger.warn(LTag.CORE, "Android does not allow DummyService into the foreground now: ${e.message}")
+ } catch (e: Exception) {
+ startForeground(4711, Notification())
+ }
+ }
+}
diff --git a/app/main/kotlin/app/aaps/persistentNotification/DummyServiceHelper.kt b/app/main/kotlin/app/aaps/persistentNotification/DummyServiceHelper.kt
new file mode 100644
index 000000000000..e543fc3abcd5
--- /dev/null
+++ b/app/main/kotlin/app/aaps/persistentNotification/DummyServiceHelper.kt
@@ -0,0 +1,100 @@
+package app.aaps.persistentNotification
+
+import android.app.ForegroundServiceStartNotAllowedException
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.ServiceConnection
+import android.os.IBinder
+import android.os.PowerManager
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.notifications.NotificationHolder
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.Inject
+import dev.zacsweers.metro.SingleIn
+
+/*
+ This code replaces following
+ val alarm = Intent(context, DummyService::class.java)
+ alarm.putExtra("soundId", n.soundId)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(alarm) else context.startService(alarm)
+
+ it fails randomly with error
+ Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e317f7e u0 info.nightscout.nsclient/info.nightscout.androidaps.services.DummyService}
+
+ */
+@SingleIn(AppScope::class)
+@Inject
+class DummyServiceHelper(
+ private val notificationHolder: NotificationHolder,
+ private val aapsLogger: AAPSLogger
+) {
+
+ /**
+ * Whether Android lets this app start a foreground service while it is in the background.
+ *
+ * Android 12+ refuses that in general, with a list of exemptions. The one AAPS relies on is the
+ * battery optimisation exemption, which the setup wizard asks for. A foreground service of type
+ * `specialUse`, which DummyService is, has no further "while in use" rule, so the exemption is
+ * enough. A location service is different: it may only start while the app is on screen.
+ */
+ fun mayStartFromBackground(context: Context): Boolean =
+ (context.getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isIgnoringBatteryOptimizations(context.packageName) == true
+
+ /**
+ * Starts DummyService and puts it into the foreground.
+ *
+ * [onNotAllowed] runs when Android refuses the foreground service now, so the caller can try again
+ * later. Without that the refusal would be a throw on the main thread, and the app would end.
+ */
+ fun startService(context: Context, onNotAllowed: () -> Unit = {}) {
+ val connection = object : ServiceConnection {
+ override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
+ // The binder of the service that returns the instance that is created.
+ val binder: DummyService.LocalBinder = service as DummyService.LocalBinder
+
+ val dummyService: DummyService = binder.getService()
+
+ try {
+ context.startForegroundService(Intent(context, DummyService::class.java))
+
+ // This is the key: Without waiting Android Framework to call this method
+ // inside Service.onCreate(), immediately call here to post the notification.
+ dummyService.startForeground(notificationHolder.notificationID, notificationHolder.notification)
+ } catch (e: ForegroundServiceStartNotAllowedException) {
+ notAllowed(e, onNotAllowed)
+ } finally {
+ // Release the connection to prevent leaks.
+ context.unbindService(this)
+ }
+ }
+
+ override fun onServiceDisconnected(name: ComponentName?) {
+ }
+ }
+
+ try {
+ context.bindService(Intent(context, DummyService::class.java), connection, Context.BIND_AUTO_CREATE)
+ } catch (ignored: RuntimeException) {
+ // This is probably a broadcast receiver context even though we are calling getApplicationContext().
+ // Just call startForegroundService instead since we cannot bind a service to a
+ // broadcast receiver context. The service also have to call startForeground in
+ // this case.
+ try {
+ context.startForegroundService(Intent(context, DummyService::class.java))
+ } catch (e: ForegroundServiceStartNotAllowedException) {
+ notAllowed(e, onNotAllowed)
+ }
+ }
+ }
+
+ fun stopService(context: Context) {
+ context.stopService(Intent(context, DummyService::class.java))
+ }
+
+ private fun notAllowed(e: ForegroundServiceStartNotAllowedException, onNotAllowed: () -> Unit) {
+ aapsLogger.warn(LTag.CORE, "Android does not allow DummyService into the foreground now: ${e.message}")
+ onNotAllowed()
+ }
+}
diff --git a/app/main/kotlin/app/aaps/persistentNotification/PersistentNotificationPlugin.kt b/app/main/kotlin/app/aaps/persistentNotification/PersistentNotificationPlugin.kt
new file mode 100644
index 000000000000..5b6013a2b075
--- /dev/null
+++ b/app/main/kotlin/app/aaps/persistentNotification/PersistentNotificationPlugin.kt
@@ -0,0 +1,503 @@
+package app.aaps.persistentNotification
+
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.graphics.BitmapFactory
+import android.graphics.drawable.Icon
+import android.os.Build
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationCompat.Metric
+import androidx.core.app.NotificationCompat.Metric.FixedFloat
+import androidx.core.app.NotificationCompat.Metric.FixedInt
+import androidx.core.app.NotificationCompat.MetricStyle
+import androidx.core.app.RemoteInput
+import androidx.core.os.bundleOf
+import app.aaps.core.data.model.GlucoseUnit
+import app.aaps.core.data.model.TrendArrow
+import app.aaps.core.data.plugin.PluginType
+import app.aaps.core.interfaces.aps.Loop
+import app.aaps.core.interfaces.configuration.Config
+import app.aaps.core.interfaces.db.PersistenceLayer
+import app.aaps.core.interfaces.db.ProcessedTbrEbData
+import app.aaps.core.interfaces.insulin.ConcentrationHelper
+import app.aaps.core.interfaces.iob.GlucoseStatusProvider
+import app.aaps.core.interfaces.iob.IobCobCalculator
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.notifications.NotificationHolder
+import app.aaps.core.interfaces.notifications.NotificationManager
+import app.aaps.core.interfaces.nsclient.ProcessedDeviceStatusData
+import app.aaps.core.interfaces.plugin.ActivePlugin
+import app.aaps.core.interfaces.plugin.EnforcedState
+import app.aaps.core.interfaces.plugin.PluginBase
+import app.aaps.core.interfaces.plugin.PluginDescription
+import app.aaps.core.interfaces.profile.ProfileFunction
+import app.aaps.core.interfaces.profile.ProfileUtil
+import app.aaps.core.interfaces.resources.ResourceHelper
+import app.aaps.core.interfaces.rx.bus.RxBus
+import app.aaps.core.interfaces.rx.collectResilient
+import app.aaps.core.interfaces.rx.events.EventAutosensCalculationFinished
+import app.aaps.core.interfaces.rx.events.EventInitializationChanged
+import app.aaps.core.interfaces.rx.events.EventRefreshOverview
+import app.aaps.core.interfaces.ui.IconsProvider
+import app.aaps.core.interfaces.utils.DateUtil
+import app.aaps.core.interfaces.utils.DecimalFormatter
+import app.aaps.core.interfaces.utils.TrendCalculator
+import app.aaps.core.interfaces.utils.fabric.FabricPrivacy
+import app.aaps.core.keys.interfaces.TextRef
+import app.aaps.core.objects.extensions.apsAdjustedTargetMgdl
+import app.aaps.core.objects.extensions.round
+import app.aaps.core.ui.extensions.generateCOBString
+import app.aaps.core.ui.extensions.toStringShort
+import app.aaps.core.utils.DeferredForegroundStart
+import app.aaps.plugins.main.R
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.ContributesIntoMap
+import dev.zacsweers.metro.Inject
+import dev.zacsweers.metro.IntKey
+import dev.zacsweers.metro.SingleIn
+import dev.zacsweers.metro.binding
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.FlowPreview
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.debounce
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.merge
+import kotlinx.coroutines.flow.receiveAsFlow
+import kotlin.math.round
+import kotlin.time.Duration.Companion.seconds
+import android.app.NotificationManager as AndroidNotificationManager
+import app.aaps.core.interfaces.R as InterfacesR
+import app.aaps.core.ui.R as CoreUiR
+
+@Suppress("PrivatePropertyName", "DEPRECATION")
+// Registers itself into the every-build plugin bucket at order 0, replacing the @Binds @IntKey(0) in
+// PersistentNotificationModule.
+@ContributesIntoMap(AppScope::class, binding = binding())
+@IntKey(0)
+@SingleIn(AppScope::class)
+@Inject
+class PersistentNotificationPlugin(
+ aapsLogger: AAPSLogger,
+ override val rh: ResourceHelper,
+ private val profileFunction: ProfileFunction,
+ private val profileUtil: ProfileUtil,
+ private val fabricPrivacy: FabricPrivacy,
+ private val activePlugins: ActivePlugin,
+ private val iobCobCalculator: IobCobCalculator,
+ private val processedTbrEbData: ProcessedTbrEbData,
+ private val rxBus: RxBus,
+ private val context: Context,
+ private val notificationHolder: NotificationHolder,
+ private val dummyServiceHelper: DummyServiceHelper,
+ private val iconsProvider: IconsProvider,
+ private val glucoseStatusProvider: GlucoseStatusProvider,
+ private val config: Config,
+ private val decimalFormatter: DecimalFormatter,
+ private val ch: ConcentrationHelper,
+ private val loop: Loop,
+ private val persistenceLayer: PersistenceLayer,
+ private val processedDeviceStatusData: ProcessedDeviceStatusData,
+ private val dateUtil: DateUtil,
+ private val trendCalculator: TrendCalculator,
+ notificationManager: NotificationManager
+) : PluginBase(
+ PluginDescription()
+ .mainType(PluginType.GENERAL)
+ .pluginName(TextRef.AndroidRes(R.string.ongoingnotificaction))
+ .enforce(EnforcedState.Enabled)
+ .showInList { false }
+ .description(TextRef.AndroidRes(R.string.description_persistent_notification)),
+ aapsLogger, rh, notificationManager
+) {
+
+ // For Android Auto
+ // Intents are not declared in manifest and not consumed, this is intentionally because actually we can't do anything with
+ private val PACKAGE = "info.nightscout"
+ private val READ_ACTION = "info.nightscout.androidaps.ACTION_MESSAGE_READ"
+ private val REPLY_ACTION = "info.nightscout.androidaps.ACTION_MESSAGE_REPLY"
+ private val CONVERSATION_ID = "conversation_id"
+ private val EXTRA_VOICE_REPLY = "extra_voice_reply"
+ // End Android auto
+
+ // For Samsung Live Notifications / Now Bar
+ private val SAMSUNG_MANUFACTURER = "samsung"
+
+ // "android.ongoingActivityNoti.style" value for Samsung's "Standard" style (primary/secondary
+ // text, no progress bar). This is the only style this plugin needs; Samsung also defines a
+ // "Progress" style (2) and a "Custom" RemoteViews style, not used here.
+ private val SAMSUNG_LIVE_UPDATE_STANDARD_STYLE = 1
+ private val SAMSUNG_EXTRA_STYLE = "android.ongoingActivityNoti.style"
+ private val SAMSUNG_EXTRA_PRIMARY_INFO = "android.ongoingActivityNoti.primaryInfo"
+ private val SAMSUNG_EXTRA_SECONDARY_INFO = "android.ongoingActivityNoti.secondaryInfo"
+ private val SAMSUNG_EXTRA_CHIP_ICON = "android.ongoingActivityNoti.chipIcon"
+
+ // Text of the status bar chip. Without it the chip shows the primary info, which is the long drawer line.
+ private val SAMSUNG_EXTRA_CHIP_EXPANDED_TEXT = "android.ongoingActivityNoti.chipExpandedText"
+ private val SAMSUNG_EXTRA_NOWBAR_PRIMARY_INFO = "android.ongoingActivityNoti.nowbarPrimaryInfo"
+ private val SAMSUNG_EXTRA_NOWBAR_SECONDARY_INFO = "android.ongoingActivityNoti.nowbarSecondaryInfo"
+ // End Samsung Live Notifications / Now Bar
+
+ private var scope: CoroutineScope? = null
+ private val deferredStart = DeferredForegroundStart()
+ private var lastAutoNotificationContent: String = ""
+
+ @OptIn(FlowPreview::class)
+ override suspend fun onStart() {
+ super.onStart()
+ notificationHolder.createNotificationChannel()
+ val newScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
+ scope = newScope
+ // Rare, and the first state matters: updated at once, without the debounce of the frequent events
+ rxBus.toFlow(EventInitializationChanged::class)
+ .collectResilient(newScope, aapsLogger, LTag.CORE, start = CoroutineStart.UNDISPATCHED) { triggerNotificationUpdate() }
+ frequentUpdates(newScope)
+ .collectResilient(newScope, aapsLogger, LTag.CORE) { triggerNotificationUpdate() }
+ /// Android Auto - debounced to prevent rapid pop-ups
+ // Flow's debounce means the same thing as Rx's: emit once the source has been quiet for the
+ // period. UNDISPATCHED is not claimed here - merge subscribes to its sources in child
+ // coroutines that are dispatched, so the window survives it. Harmless for this one: the worst
+ // case is a notification refresh that a later event triggers anyway.
+ merge(
+ rxBus.toFlow(EventRefreshOverview::class).map { },
+ rxBus.toFlow(EventInitializationChanged::class).map { },
+ rxBus.toFlow(EventAutosensCalculationFinished::class).map { }
+ )
+ .debounce(10_000L)
+ .collectResilient(newScope, aapsLogger, LTag.CORE) { triggerNotificationUpdate(includeAuto = true) }
+ /// End Android Auto
+ // The missing half of this plugin's own onStop, which stops DummyService. Until now the service
+ // came back only when the next rxBus event reached triggerNotificationUpdate, so after a stop and
+ // start the process sat without its foreground service for however long that took - and
+ // DummyService is what keeps AAPS out of Android's background execution limits. Starting it here
+ // is idempotent (startService on a running service is a no-op).
+ startDummyService()
+ }
+
+ /**
+ * Starts DummyService, at once when Android allows it from the background, otherwise as soon as
+ * AAPS is on screen.
+ *
+ * At once matters. The process is often started in the background: after an update, or when
+ * Android killed it and a CGM broadcast or a job brings it back. Until the foreground service runs,
+ * Android may freeze the process, and the calculation and the loop then stop until the user opens
+ * AAPS. With the battery optimisation exemption Android allows the start from the background. When
+ * the exemption is missing, or Android refuses anyway, the start waits for the screen as before.
+ */
+ private fun startDummyService() {
+ if (dummyServiceHelper.mayStartFromBackground(context))
+ dummyServiceHelper.startService(context, onNotAllowed = ::startDummyServiceWhenOnScreen)
+ else
+ startDummyServiceWhenOnScreen()
+ }
+
+ private fun startDummyServiceWhenOnScreen() {
+ deferredStart.start { dummyServiceHelper.startService(context) }
+ }
+
+ override suspend fun onStop() {
+ scope?.cancel()
+ scope = null
+ deferredStart.cancel()
+ dummyServiceHelper.stopService(context)
+ super.onStop()
+ }
+
+ /**
+ * The frequent events, one update for a burst of them. After a BG the calculation finishes, often
+ * twice, and the overview is refreshed several times within seconds. Every update reads the running
+ * temporary basal from the database and calculates IOB, so it was done several times for one BG.
+ *
+ * The sources are subscribed here, undispatched, into a channel. `merge` would subscribe a moment
+ * later in its own coroutines, and an event sent before that would be lost (see `collectResilient`).
+ * The channel keeps the request until the debounce reads it.
+ */
+ @OptIn(FlowPreview::class)
+ internal fun frequentUpdates(scope: CoroutineScope): Flow {
+ val requests = Channel(Channel.CONFLATED)
+ rxBus.toFlow(EventRefreshOverview::class)
+ .collectResilient(scope, aapsLogger, LTag.CORE, start = CoroutineStart.UNDISPATCHED) { requests.trySend(Unit) }
+ rxBus.toFlow(EventAutosensCalculationFinished::class)
+ .collectResilient(scope, aapsLogger, LTag.CORE, start = CoroutineStart.UNDISPATCHED) { requests.trySend(Unit) }
+ return requests.receiveAsFlow().debounce(UPDATE_DEBOUNCE)
+ }
+
+ // Called from the collectors, which already run in a coroutine: no runBlocking, which held an IO
+ // thread for the whole update.
+ private suspend fun triggerNotificationUpdate(includeAuto: Boolean = false) {
+ updateNotification(includeAuto)
+ startDummyService()
+ }
+
+ private suspend fun updateNotification(includeAuto: Boolean = false) {
+ if (!config.appInitialized) return
+ val pump = activePlugins.activePump
+ var line1: String?
+ var line1WithDelta: String?
+ var line2: String? = null
+ var line3: String? = null
+ var bgStatusChipText: String? = null
+ var bgMetric: Metric? = null
+ var metricValue: Metric.MetricValue? = null
+ var unreadConversationBuilder: NotificationCompat.CarExtender.UnreadConversation.Builder? = null
+ if (profileFunction.isProfileValid("Notification")) {
+ val lastBG = iobCobCalculator.ads.lastBg()
+ val glucoseStatus = glucoseStatusProvider.glucoseStatusData
+ val units = profileFunction.getUnits()
+ if (lastBG != null) {
+ bgStatusChipText = profileUtil.fromMgdlToStringInUnits(lastBG.recalculated)
+ val fromMgdlToUnits = profileUtil.fromMgdlToUnits(lastBG.recalculated)
+ metricValue = if (units == GlucoseUnit.MMOL) {
+ // Always one decimal. The default minimum is 0, which showed 9.0 as "9" (#5240).
+ FixedFloat(
+ fromMgdlToUnits.round(1).toFloat(),
+ null, // unit
+ 1, // min fraction digits
+ 1 // max fraction digits
+ )
+ } else {
+ FixedInt(
+ fromMgdlToUnits.toInt(),
+ null // unit
+ )
+ }
+ // Show an arrow only when there really is one. This used to fall back to FLAT,
+ // which told the user the glucose was stable whenever the trend was simply not
+ // known yet - for example right after a start, with fewer than two readings.
+ // NONE and the two triples have no glyph in TrendArrow.symbol, only the
+ // placeholders "??" and "X", so they are dropped rather than printed.
+ val trendSymbol = trendCalculator.getTrendArrow(iobCobCalculator.ads)
+ ?.takeIf { it != TrendArrow.NONE && it != TrendArrow.TRIPLE_UP && it != TrendArrow.TRIPLE_DOWN }
+ ?.symbol
+ line1 = bgStatusChipText + (trendSymbol?.let { " $it" } ?: "")
+ line1WithDelta = bgStatusChipText + (trendSymbol?.let { " $it" } ?: "")
+ if (glucoseStatus != null) {
+ line1 += " " + profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.delta)
+ line1WithDelta += " " + profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.delta)
+ } else {
+ line1 += " " + rh.gs(R.string.old_data)
+ }
+ } else {
+ line1 = rh.gs(CoreUiR.string.missed_bg_readings)
+ line1WithDelta = rh.gs(CoreUiR.string.missed_bg_readings)
+ }
+ val activeTemp = processedTbrEbData.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
+ line1 += if (activeTemp != null) {
+ " • " + activeTemp.toStringShort(rh) + " "
+ } else {
+ " • " + rh.gs(CoreUiR.string.pump_base_basal_rate, ch.fromPump(pump.baseBasalRate)) + " "
+ }
+ val profileName = profileFunction.getProfileName()
+ //IOB
+ val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
+ val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
+ val cobInfo = iobCobCalculator.getCobInfo("PersistentNotificationPlugin")
+ val iobText = rh.gs(CoreUiR.string.value_with_unit, rh.gs(CoreUiR.string.treatments_iob_label_string), rh.gs(R.string.notification_iob_short, bolusIob.iob + basalIob.basaliob))
+ val cobText = rh.gs(InterfacesR.string.confirmation_line, rh.gs(CoreUiR.string.cob), cobInfo.generateCOBString(decimalFormatter))
+ line2 = "$iobText • $cobText"
+ metricValue?.let {
+ bgMetric = Metric(
+ it,
+ line2,
+ )
+ }
+ line3 = profileName
+ /// For Android Auto
+ // Only the Auto pass uses this. The phone pass built it every time and threw it away (#5246).
+ if (includeAuto) {
+ val msgReadIntent = Intent()
+ .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
+ .setAction(READ_ACTION)
+ .putExtra(CONVERSATION_ID, notificationHolder.notificationID)
+ .setPackage(PACKAGE)
+ val msgReadPendingIntent = PendingIntent.getBroadcast(
+ context,
+ notificationHolder.notificationID,
+ msgReadIntent,
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ val msgReplyIntent = Intent()
+ .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
+ .setAction(REPLY_ACTION)
+ .putExtra(CONVERSATION_ID, notificationHolder.notificationID)
+ .setPackage(PACKAGE)
+ val msgReplyPendingIntent = PendingIntent.getBroadcast(
+ context,
+ notificationHolder.notificationID,
+ msgReplyIntent,
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ // Build a RemoteInput for receiving voice input from devices
+ val remoteInput = RemoteInput.Builder(EXTRA_VOICE_REPLY).build()
+ // Build Android Auto message: IOB • COB • Target • Profile
+ var aaTarget = ""
+ val tempTarget = persistenceLayer.getTemporaryTargetActiveAt(dateUtil.now())
+ if (tempTarget != null) {
+ // A target without an end (a scene without a duration) shows no remaining time, like the overview chip.
+ val range = profileUtil.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units)
+ aaTarget = if (tempTarget.hasEnd) rh.gs(InterfacesR.string.value_with_detail, range, dateUtil.untilString(tempTarget.end, rh, withParentheses = false))
+ else range
+ } else {
+ profileFunction.getProfile()?.let { profile ->
+ val adjustedTarget = profile.apsAdjustedTargetMgdl(loop, config, processedDeviceStatusData)
+ aaTarget = if (adjustedTarget != null) {
+ profileUtil.toTargetRangeString(adjustedTarget, adjustedTarget, GlucoseUnit.MGDL, units)
+ } else {
+ profileUtil.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units)
+ }
+ }
+ }
+ val aaMsg = rh.gs(InterfacesR.string.format_insulin_units, bolusIob.iob + basalIob.basaliob) +
+ " • " + cobInfo.generateCOBString(decimalFormatter) +
+ " • " + aaTarget +
+ " • " + profileName
+ unreadConversationBuilder = NotificationCompat.CarExtender.UnreadConversation.Builder(rh.gs(config.appName))
+ .setLatestTimestamp(System.currentTimeMillis())
+ .setReadPendingIntent(msgReadPendingIntent)
+ .setReplyAction(msgReplyPendingIntent, remoteInput)
+ unreadConversationBuilder.addMessage(aaMsg)
+ }
+ /// End Android Auto
+ } else {
+ line1 = rh.gs(CoreUiR.string.no_profile_set)
+ line1WithDelta = rh.gs(CoreUiR.string.no_profile_set)
+ }
+ val content = "$line1|$line2|$line3"
+ if (includeAuto && content == lastAutoNotificationContent) return
+ if (includeAuto) lastAutoNotificationContent = content
+ val builder = NotificationCompat.Builder(context, notificationHolder.channelID)
+ builder.setOngoing(true)
+ applyLiveUpdate(
+ builder = builder,
+ bgStatusChipText = bgStatusChipText,
+ line1 = line1,
+ line1WithDelta = line1WithDelta,
+ bgMetric = bgMetric,
+ line2 = line2,
+ line3 = line3
+ )
+ builder.setOnlyAlertOnce(true)
+ builder.setCategory(NotificationCompat.CATEGORY_STATUS)
+ builder.setSmallIcon(iconsProvider.getNotificationIcon())
+ builder.setContentTitle(line1)
+ if (line2 != null) builder.setContentText(line2)
+ if (line3 != null) builder.setSubText(line3)
+ /// Android Auto
+ if (includeAuto && unreadConversationBuilder != null) {
+ builder.extend(
+ NotificationCompat.CarExtender()
+ .setLargeIcon(BitmapFactory.decodeResource(context.resources, iconsProvider.getIcon()))
+ .setUnreadConversation(unreadConversationBuilder.build())
+ )
+ }
+ /// End Android Auto
+ builder.setContentIntent(notificationHolder.openAppIntent())
+ val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as AndroidNotificationManager
+ val notification = builder.build()
+ mNotificationManager.notify(notificationHolder.notificationID, notification)
+ notificationHolder.notification = notification
+ }
+
+ private fun applyLiveUpdate(
+ builder: NotificationCompat.Builder,
+ bgStatusChipText: String?,
+ line1: String?,
+ line1WithDelta: String?,
+ bgMetric: Metric?,
+ line2: String?,
+ line3: String?
+ ) {
+ // Samsung's own system UI (One UI 7+) does not render the standard Android promoted
+ // notification below - it shows the lock-screen "Now Bar" and drawer "Live Notifications"
+ // through its own proprietary extras, so that needs to be applied separately and does not
+ // depend on the Android version gating below.
+ applySamsungLiveUpdate(builder, line1, line1WithDelta, line2, line3)
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA) return
+ builder.setRequestPromotedOngoing(true)
+ if (!bgStatusChipText.isNullOrBlank()) {
+ builder.setShortCriticalText(bgStatusChipText)
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CINNAMON_BUN && bgMetric != null) {
+ builder.setStyle(
+ MetricStyle()
+ .addMetric(bgMetric)
+ .setCriticalMetric(0)
+ )
+ }
+ }
+
+ // Samsung Live Notifications / Now Bar (One UI 7+) are driven by this notification extras
+ // bundle plus the "com.samsung.android.support.ongoing_activity" manifest meta-data, not by
+ // NotificationCompat#setRequestPromotedOngoing(). Harmless on non-Samsung devices, but
+ // restricted to Samsung so no unused extras are attached elsewhere.
+ //
+ // Once these extras are present One UI draws the notification from them and no longer shows
+ // the title, text and sub text set on the builder. So the drawer fields must carry everything
+ // those three lines carry - see samsungLiveTexts.
+ private fun applySamsungLiveUpdate(
+ builder: NotificationCompat.Builder,
+ line1: String?,
+ line1WithDelta: String?,
+ line2: String?,
+ line3: String?
+ ) {
+ if (!Build.MANUFACTURER.equals(SAMSUNG_MANUFACTURER, ignoreCase = true)) return
+ val texts = samsungLiveTexts(line1, line1WithDelta, line2, line3) ?: return
+ val extras = bundleOf(
+ SAMSUNG_EXTRA_STYLE to SAMSUNG_LIVE_UPDATE_STANDARD_STYLE,
+ SAMSUNG_EXTRA_PRIMARY_INFO to texts.primary,
+ SAMSUNG_EXTRA_NOWBAR_PRIMARY_INFO to texts.nowBarPrimary,
+ SAMSUNG_EXTRA_CHIP_EXPANDED_TEXT to texts.nowBarPrimary,
+ SAMSUNG_EXTRA_CHIP_ICON to Icon.createWithResource(context, iconsProvider.getNotificationIcon())
+ )
+ texts.secondary?.let { extras.putString(SAMSUNG_EXTRA_SECONDARY_INFO, it) }
+ texts.nowBarSecondary?.let { extras.putString(SAMSUNG_EXTRA_NOWBAR_SECONDARY_INFO, it) }
+ builder.addExtras(extras)
+ }
+
+ private fun Double.round(decimals: Int): Double {
+ var multiplier = 1.0
+ repeat(decimals) { multiplier *= 10 }
+ return round(this * multiplier) / multiplier
+ }
+
+ /** The four texts One UI shows: two in the notification drawer, two in the Now Bar. */
+ internal data class SamsungLiveTexts(
+ val primary: String,
+ val secondary: String?,
+ val nowBarPrimary: String,
+ val nowBarSecondary: String?
+ )
+
+ internal companion object {
+
+ /** Short, so the notification shows a new BG at once, but long enough for one BG's burst. */
+ val UPDATE_DEBOUNCE = 1.seconds
+
+ /**
+ * Splits the notification content between the drawer and the Now Bar on a Samsung phone.
+ *
+ * The drawer has room and replaces the normal notification, so it gets all of it: [line1]
+ * (BG, delta and the basal rate or temp basal) with [line3] (the profile name) on the first
+ * row, and [line2] (IOB and COB) on the second. One UI has no header or sub text field,
+ * which is where the profile name was shown before, so the first row is the closest place.
+ * The Now Bar and the status bar chip are small, so they get [line1WithDelta] (no basal, no
+ * profile). The parts are joined with the same bullet the lines themselves use.
+ *
+ * @return null when there is nothing to show
+ */
+ fun samsungLiveTexts(line1: String?, line1WithDelta: String?, line2: String?, line3: String?): SamsungLiveTexts? {
+ val nowBarPrimary = line1WithDelta?.trim().takeUnless { it.isNullOrEmpty() } ?: return null
+ val fullLine1 = line1?.trim().takeUnless { it.isNullOrEmpty() } ?: nowBarPrimary
+ val profile = line3?.trim().takeUnless { it.isNullOrEmpty() }
+ val primary = if (profile != null) "$fullLine1 • $profile" else fullLine1
+ return SamsungLiveTexts(primary = primary, secondary = line2, nowBarPrimary = nowBarPrimary, nowBarSecondary = line2)
+ }
+ }
+}
diff --git a/app/main/kotlin/app/aaps/receivers/AutoStartReceiver.kt b/app/main/kotlin/app/aaps/receivers/AutoStartReceiver.kt
new file mode 100644
index 000000000000..982539bae433
--- /dev/null
+++ b/app/main/kotlin/app/aaps/receivers/AutoStartReceiver.kt
@@ -0,0 +1,38 @@
+package app.aaps.receivers
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.content.Intent
+import androidx.annotation.VisibleForTesting
+import app.aaps.core.objects.workflow.MetroBroadcastReceiver
+import app.aaps.persistentNotification.DummyServiceHelper
+import app.aaps.settingsstore.AndroidStorage
+import dev.zacsweers.metro.Inject
+
+class AutoStartReceiver : MetroBroadcastReceiver() {
+
+ @Inject lateinit var dummyServiceHelper: DummyServiceHelper
+
+ @SuppressLint("UnsafeProtectedBroadcastReceiver")
+ override fun onReceive(context: Context, intent: Intent) {
+ super.onReceive(context, intent)
+ processIntent(context, intent)
+ }
+
+ /**
+ * Starts DummyService after a boot and after an update of AAPS.
+ *
+ * After an update nothing else would start the process until a CGM broadcast, a job or the user
+ * opens the app, and the loop does not run until then. Both broadcasts are on Android's list of
+ * moments when an app may start a foreground service from the background.
+ *
+ * Not when the settings cannot be opened: AAPS is not started then, and the service's notification
+ * would say it is running.
+ */
+ @VisibleForTesting
+ fun processIntent(context: Context, intent: Intent) {
+ if (AndroidStorage.failure != null) return
+ if (intent.action == Intent.ACTION_BOOT_COMPLETED || intent.action == Intent.ACTION_MY_PACKAGE_REPLACED)
+ dummyServiceHelper.startService(context)
+ }
+}
\ No newline at end of file
diff --git a/app/main/kotlin/app/aaps/receivers/CarbSuggestionReceiver.kt b/app/main/kotlin/app/aaps/receivers/CarbSuggestionReceiver.kt
new file mode 100644
index 000000000000..51c254561643
--- /dev/null
+++ b/app/main/kotlin/app/aaps/receivers/CarbSuggestionReceiver.kt
@@ -0,0 +1,59 @@
+package app.aaps.receivers
+
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import app.aaps.core.interfaces.aps.Loop
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.ui.CarbSuggestionActions
+import app.aaps.core.objects.workflow.MetroBroadcastReceiver
+import dev.zacsweers.metro.AppScope
+import dev.zacsweers.metro.ContributesBinding
+import dev.zacsweers.metro.Inject
+import dev.zacsweers.metro.SingleIn
+
+/**
+ * Moved here from :plugins:aps so that module could become multiplatform.
+ */
+class CarbSuggestionReceiver : MetroBroadcastReceiver() {
+
+ @Inject lateinit var loop: Loop
+ @Inject lateinit var aapsLogger: AAPSLogger
+
+ override fun onReceive(context: Context, intent: Intent) {
+ super.onReceive(context, intent)
+ val duration = intent.getIntExtra(EXTRA_IGNORE_DURATION, 5)
+ aapsLogger.debug(LTag.CORE, "CarbSuggestion should be disabled for $duration minutes")
+ loop.disableCarbSuggestions(duration)
+ }
+
+ companion object {
+
+ const val EXTRA_IGNORE_DURATION = "ignoreDuration"
+ }
+}
+
+/**
+ * Builds the intents for [CarbSuggestionReceiver], so LoopPlugin does not have to name a class that
+ * no longer lives in its module.
+ */
+// Metro builds this; the @Binds in PersistentNotificationModule is gone.
+@ContributesBinding(AppScope::class)
+@SingleIn(AppScope::class)
+@Inject
+class CarbSuggestionActionsImpl(
+ private val context: Context
+) : CarbSuggestionActions {
+
+ override fun ignoreFor(minutes: Int, requestCode: Int): PendingIntent {
+ val intent = Intent(context, CarbSuggestionReceiver::class.java)
+ .putExtra(CarbSuggestionReceiver.EXTRA_IGNORE_DURATION, minutes)
+ return PendingIntent.getBroadcast(
+ context,
+ requestCode,
+ intent,
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ }
+}
diff --git a/app/main/kotlin/app/aaps/receivers/DataReceiver.kt b/app/main/kotlin/app/aaps/receivers/DataReceiver.kt
new file mode 100644
index 000000000000..10a313420834
--- /dev/null
+++ b/app/main/kotlin/app/aaps/receivers/DataReceiver.kt
@@ -0,0 +1,180 @@
+package app.aaps.receivers
+
+import android.content.Context
+import android.content.Intent
+import android.provider.Telephony
+import androidx.annotation.VisibleForTesting
+import androidx.work.Data
+import androidx.work.ExistingWorkPolicy
+import androidx.work.ListenableWorker
+import androidx.work.WorkManager
+import app.aaps.core.interfaces.logging.AAPSLogger
+import app.aaps.core.interfaces.logging.LTag
+import app.aaps.core.interfaces.receivers.Intents
+import app.aaps.core.interfaces.utils.fabric.FabricPrivacy
+import app.aaps.core.objects.workflow.MetroBroadcastReceiver
+import app.aaps.core.utils.extensions.copyBoolean
+import app.aaps.core.utils.extensions.copyDouble
+import app.aaps.core.utils.extensions.copyLong
+import app.aaps.core.utils.extensions.copyString
+import app.aaps.core.utils.receivers.BundleLogger
+import app.aaps.core.utils.receivers.DataInbox
+import app.aaps.core.utils.receivers.incomingDataWorkRequest
+import app.aaps.implementation.receivers.KeepAliveWorker
+import app.aaps.plugins.source.AidexPlugin
+import app.aaps.plugins.source.DexcomInbox
+import app.aaps.plugins.source.GlimpPlugin
+import app.aaps.plugins.source.MM640gPlugin
+import app.aaps.plugins.source.PatchedSiAppPlugin
+import app.aaps.plugins.source.PatchedSinoAppPlugin
+import app.aaps.plugins.source.PoctechPlugin
+import app.aaps.plugins.source.SyaiPlugin
+import app.aaps.plugins.source.TomatoPlugin
+import app.aaps.plugins.source.XdripInbox
+import app.aaps.plugins.source.instara.InstaraPlugin
+import app.aaps.plugins.sync.smsCommunicator.SmsInbox
+import dev.zacsweers.metro.HasMemberInjections
+import dev.zacsweers.metro.Inject
+
+// Metro reads this class now that interop is on for `:app`. It is `open`, so it has to say its injected
+// fields are meant to be filled - Metro will not infer that for a subclassable type.
+@HasMemberInjections
+open class DataReceiver : MetroBroadcastReceiver() {
+
+ @Inject lateinit var aapsLogger: AAPSLogger
+ @Inject lateinit var dataInbox: DataInbox
+ @Inject lateinit var fabricPrivacy: FabricPrivacy
+ @Inject lateinit var workManager: WorkManager
+
+ override fun onReceive(context: Context, intent: Intent) {
+ super.onReceive(context, intent)
+ processIntent(context, intent)
+ }
+
+ @VisibleForTesting
+ fun processIntent(context: Context, intent: Intent) {
+ val bundle = intent.extras ?: return
+ aapsLogger.debug(LTag.CORE, "onReceive ${intent.action} ${BundleLogger.log(bundle)}")
+ when (intent.action) {
+ Intents.ACTION_NEW_BG_ESTIMATE ->
+ dataInbox.putAndEnqueue(XdripInbox, bundle)
+
+ Intents.POCTECH_BG ->
+ enqueueInline(
+ PoctechPlugin.PoctechWorker::class.java,
+ Data.Builder().also {
+ it.copyString("data", bundle)
+ }.build()
+ )
+
+ Intents.GLIMP_BG ->
+ enqueueInline(
+ GlimpPlugin.GlimpWorker::class.java,
+ Data.Builder().also {
+ it.copyDouble("mySGV", bundle)
+ it.copyString("myTrend", bundle)
+ it.copyLong("myTimestamp", bundle)
+ }.build()
+ )
+
+ Intents.TOMATO_BG ->
+ enqueueInline(
+ TomatoPlugin.TomatoWorker::class.java,
+ Data.Builder().also {
+ it.copyDouble("com.fanqies.tomatofn.Extras.BgEstimate", bundle)
+ it.copyLong("com.fanqies.tomatofn.Extras.Time", bundle)
+ }.build()
+ )
+
+ Intents.NS_EMULATOR ->
+ enqueueInline(
+ MM640gPlugin.MM640gWorker::class.java,
+ Data.Builder().also {
+ it.copyString("collection", bundle)
+ it.copyString("data", bundle)
+ }.build()
+ )
+
+ Intents.OTTAI_APP, Intents.OTTAI_APP_CN,
+ Intents.SYAI_APP ->
+ enqueueInline(
+ SyaiPlugin.SyaiWorker::class.java,
+ Data.Builder().also {
+ it.copyString("collection", bundle)
+ it.copyString("data", bundle)
+ }.build()
+ )
+
+ Intents.SI_APP, Intents.SIB_APP ->
+ enqueueInline(
+ PatchedSiAppPlugin.PatchedSiAppWorker::class.java,
+ Data.Builder().also {
+ it.copyString("collection", bundle)
+ it.copyString("data", bundle)
+ }.build()
+ )
+
+ Intents.SINO_APP ->
+ enqueueInline(
+ PatchedSinoAppPlugin.PatchedSinoAppWorker::class.java,
+ Data.Builder().also {
+ it.copyString("collection", bundle)
+ it.copyString("data", bundle)
+ }.build()
+ )
+
+ Intents.INSTARA_APP ->
+ enqueueInline(
+ InstaraPlugin.InstaraWorker::class.java,
+ Data.Builder().also {
+ it.copyString("collection", bundle)
+ it.copyString("data", bundle)
+ }.build()
+ )
+
+ Telephony.Sms.Intents.SMS_RECEIVED_ACTION ->
+ dataInbox.putAndEnqueue(SmsInbox, bundle)
+
+ Intents.DEXCOM_BG, Intents.DEXCOM_G7_BG ->
+ dataInbox.putAndEnqueue(DexcomInbox, bundle)
+
+ Intents.AIDEX_NEW_BG_ESTIMATE ->
+ enqueueInline(
+ AidexPlugin.AidexWorker::class.java,
+ Data.Builder().also {
+ it.copyLong(Intents.AIDEX_TIMESTAMP, bundle)
+ it.copyString(Intents.AIDEX_BG_TYPE, bundle)
+ it.copyDouble(Intents.AIDEX_BG_VALUE, bundle)
+ it.copyString(Intents.AIDEX_BG_SLOPE_NAME, bundle)
+ it.copyString(Intents.AIDEX_TRANSMITTER_SN, bundle)
+ it.copyString(Intents.AIDEX_SENSOR_ID, bundle)
+ it.copyBoolean(Intents.AIDEX_SENSOR_EXPIRED, bundle)
+ it.copyBoolean(Intents.EXTRA_SENSOR_ERROR, bundle)
+ it.copyBoolean(Intents.EXTRA_SENSOR_STABILIZING, bundle)
+ it.copyBoolean(Intents.EXTRA_REPLACE_SENSOR, bundle)
+ it.copyBoolean(Intents.EXTRA_SIGNAL_LOST, bundle)
+ }.build()
+ )
+
+ }
+
+ // Verify KeepAlive is running
+ // Sometimes the schedule fail
+ KeepAliveWorker.scheduleIfNotRunning(context, aapsLogger, fabricPrivacy)
+ }
+
+ private fun enqueueInline(worker: Class, data: Data) {
+ workManager.enqueueUniqueWork(
+ INLINE_WORK_NAME,
+ ExistingWorkPolicy.APPEND_OR_REPLACE,
+ incomingDataWorkRequest(worker, data)
+ )
+ }
+
+ companion object {
+
+ // Shared unique-work name for receivers whose payloads inline into Data;
+ // preserves the serialization the original DataWorkerStorage.enqueue used.
+ private const val INLINE_WORK_NAME = "data"
+ }
+}
diff --git a/app/main/kotlin/app/aaps/receivers/SmsReceiver.kt b/app/main/kotlin/app/aaps/receivers/SmsReceiver.kt
new file mode 100644
index 000000000000..8becd9b65d67
--- /dev/null
+++ b/app/main/kotlin/app/aaps/receivers/SmsReceiver.kt
@@ -0,0 +1,7 @@
+package app.aaps.receivers
+
+/**
+ * Forward received SMS intents. This is a separate class, because unlike local broadcasts handled by DataReceiver,
+ * receiving SMS requires a special permission in the manifest, which necessitates a separate receiver.
+ */
+class SmsReceiver : DataReceiver()
\ No newline at end of file
diff --git a/app/main/kotlin/app/aaps/settingsstore/AndroidStorage.kt b/app/main/kotlin/app/aaps/settingsstore/AndroidStorage.kt
new file mode 100644
index 000000000000..d8b2dd70a548
--- /dev/null
+++ b/app/main/kotlin/app/aaps/settingsstore/AndroidStorage.kt
@@ -0,0 +1,136 @@
+package app.aaps.settingsstore
+
+import android.content.Context
+import androidx.datastore.core.CorruptionException
+import app.aaps.core.interfaces.sharedPreferences.KeyValueStore
+import app.aaps.shared.impl.sharedPreferences.EncryptedKeyValueStore
+import app.aaps.shared.impl.sharedPreferences.StoreUnreadableException
+import app.aaps.shared.impl.sharedPreferences.defaultPreferences
+import app.aaps.shared.impl.sharedPreferences.openEncryptedStore
+import app.aaps.shared.impl.sharedPreferences.preferencesFileName
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancelAndJoin
+import kotlinx.coroutines.runBlocking
+import java.io.File
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+/**
+ * The phone's settings store, opened once, as the first thing the app does. The counterpart of desktop's
+ * `DesktopStorage` and `IosStorage`.
+ *
+ * One file, encrypted with a key in the Android Keystore ([KeystoreStoreCipher]), in the app's `no_backup`
+ * folder. Android never puts that folder in a backup or in a transfer to a new phone, and the key stays on
+ * this phone anyway. The first open moves the settings over from the old SharedPreferences file
+ * ([SharedPreferencesMigration]).
+ *
+ * ## When the store cannot be opened
+ *
+ * [open] does not throw. The app gets an empty store that lives in memory only, and [Opened.failure] says
+ * why. So nothing crashes, and nothing the app writes can replace the file that could not be read. `MainApp`
+ * then starts nothing - no plugins, so no loop - and `ComposeMainActivity` shows the way out: try again, or
+ * start fresh.
+ */
+object AndroidStorage {
+
+ /** The Keystore alias of the store's key. Different from every `SecureEncrypt` alias. */
+ const val STORE_KEY_ALIAS = "AapsSettingsStore"
+ private const val FILE_NAME = "preferences.store"
+ private const val MOVED_MARKER = "preferences.store.moved"
+
+ /**
+ * The store the app uses, and why it is the empty one in memory when it is.
+ *
+ * @param failure null when the real store is open. Otherwise a [StoreUnreadableException] when the file
+ * does not open with the key this phone has, or what else went wrong, such as the Keystore not
+ * answering.
+ * @param notes what happened while opening, for the log. The app's logger cannot exist yet at that
+ * moment: it reads its own settings from this store.
+ */
+ class Opened internal constructor(val store: KeyValueStore, val failure: Exception?, val notes: List, private val job: Job?) {
+
+ /** For tests: DataStore allows a second store on the same file only after the first is gone. */
+ internal fun close() = runBlocking { job?.cancelAndJoin() }
+ }
+
+ /** Where the store is, where its key is, and where the old settings are. Only tests use another one. */
+ internal class Setup(val directory: File, val keys: KeystoreStoreCipher.Keys, val oldFile: File, val readOld: () -> Map)
+
+ @Volatile private var opened: Opened? = null
+ private var setup: Setup? = null
+
+ /** Told about a save that failed after the start. Set by `MainApp` once its logger exists. */
+ @Volatile var onSaveFailure: (Throwable) -> Unit = {}
+
+ /** Why the settings could not be opened, or null when they were (or have not been opened yet). */
+ val failure: Exception? get() = opened?.failure
+
+ /** Opens the store, or returns it if already open. Never throws: see the class description. */
+ @Synchronized
+ fun open(context: Context): Opened = opened ?: openWith(currentSetup(context)).also { opened = it }
+
+ /**
+ * Sets the unreadable store aside and removes its key, so the next start begins with empty settings. The
+ * file is renamed, not deleted. Only for a start whose store could not be opened.
+ *
+ * Returns the file it was moved to.
+ */
+ @Synchronized
+ fun startFresh(context: Context): File = startFreshWith(currentSetup(context))
+
+ /** For tests that build the app graph without Android: every graph then gets [store]. */
+ @Synchronized
+ internal fun useForTests(store: KeyValueStore) {
+ if (opened == null) opened = Opened(store, null, emptyList(), null)
+ }
+
+ internal fun openWith(setup: Setup): Opened {
+ setup.directory.mkdirs()
+ val notes = mutableListOf()
+ val storeFile = File(setup.directory, FILE_NAME)
+ val cipher = KeystoreStoreCipher(setup.keys)
+ val migration = SharedPreferencesMigration(setup.oldFile, setup.readOld, storeFile, cipher, File(setup.directory, MOVED_MARKER)) { notes += it }
+ val job = SupervisorJob()
+ return try {
+ val store = openEncryptedStore(storeFile.absolutePath, cipher, listOf(migration), CoroutineScope(Dispatchers.IO + job)) { onSaveFailure(it) }
+ Opened(store, null, notes, job)
+ } catch (e: Exception) {
+ // Shut the failed DataStore down completely: a second open of the same file - after "Start
+ // fresh" - is refused while the first one is alive.
+ runBlocking { job.cancelAndJoin() }
+ Opened(EncryptedKeyValueStore.inMemory(CoroutineScope(Dispatchers.IO + SupervisorJob())), classify(e, storeFile), notes, null)
+ }
+ }
+
+ internal fun startFreshWith(setup: Setup): File {
+ val storeFile = File(setup.directory, FILE_NAME)
+ val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ROOT).format(Date())
+ val setAside = File(setup.directory, "$FILE_NAME.unreadable-$stamp")
+ if (storeFile.exists() && !storeFile.renameTo(setAside)) error("Could not rename ${storeFile.path}")
+ setup.keys.delete()
+ return setAside
+ }
+
+ /** Finds what the failure really was: DataStore may wrap it. */
+ internal fun classify(e: Exception, storeFile: File): Exception {
+ var cause: Throwable? = e
+ while (cause != null) {
+ if (cause is CorruptionException) return StoreUnreadableException(storeFile.path, cause)
+ cause = cause.cause
+ }
+ return e
+ }
+
+ private fun currentSetup(context: Context): Setup = setup ?: appSetup(context.applicationContext).also { setup = it }
+
+ private fun appSetup(context: Context) = Setup(
+ directory = context.noBackupFilesDir,
+ keys = AndroidKeystoreKeys(STORE_KEY_ALIAS),
+ oldFile = File(File(context.dataDir, "shared_prefs"), "${preferencesFileName(context)}.xml"),
+ readOld = { defaultPreferences(context).all }
+ )
+}
diff --git a/app/main/kotlin/app/aaps/settingsstore/IdleWorkerFactory.kt b/app/main/kotlin/app/aaps/settingsstore/IdleWorkerFactory.kt
new file mode 100644
index 000000000000..ea33030f4c1d
--- /dev/null
+++ b/app/main/kotlin/app/aaps/settingsstore/IdleWorkerFactory.kt
@@ -0,0 +1,30 @@
+package app.aaps.settingsstore
+
+import android.content.Context
+import androidx.work.ListenableWorker
+import androidx.work.Worker
+import androidx.work.WorkerFactory
+import androidx.work.WorkerParameters
+
+/**
+ * Builds the app's jobs while the settings cannot be opened: each one does nothing and reports it is done.
+ *
+ * So nothing runs on settings that are not the user's. A periodic job, such as the keep-alive, simply comes
+ * again at its next normal time. A one-time job is dropped; a BG reading that arrived meanwhile is lost
+ * anyway, because the inbox that holds it lives in memory. "Retry" instead of "done" would be worse: its
+ * wait doubles each time, up to hours, and the keep-alive would still be waiting after a good start.
+ *
+ * WorkManager's own jobs are left to WorkManager, the same as `MetroWorkerFactory` does.
+ *
+ * @param appJobs the class names of the app's jobs.
+ */
+class IdleWorkerFactory(private val appJobs: () -> Set) : WorkerFactory() {
+
+ override fun createWorker(appContext: Context, workerClassName: String, workerParameters: WorkerParameters): ListenableWorker? =
+ if (workerClassName in appJobs()) IdleWorker(appContext, workerParameters) else null
+
+ private class IdleWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) {
+
+ override fun doWork(): Result = Result.success()
+ }
+}
diff --git a/app/main/kotlin/app/aaps/settingsstore/KeystoreStoreCipher.kt b/app/main/kotlin/app/aaps/settingsstore/KeystoreStoreCipher.kt
new file mode 100644
index 000000000000..1b2f031b6778
--- /dev/null
+++ b/app/main/kotlin/app/aaps/settingsstore/KeystoreStoreCipher.kt
@@ -0,0 +1,143 @@
+package app.aaps.settingsstore
+
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import app.aaps.core.interfaces.sharedPreferences.SealedDataUnreadableException
+import app.aaps.core.interfaces.sharedPreferences.StoreCipher
+import java.security.InvalidKeyException
+import java.security.KeyStore
+import java.security.UnrecoverableEntryException
+import java.security.UnrecoverableKeyException
+import javax.crypto.AEADBadTagException
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+
+/**
+ * AES-256-GCM for the settings store, with the key in the Android Keystore ([AndroidKeystoreKeys]).
+ *
+ * The key cannot be read out of the Keystore, not even by this app, which is why the store asks this class
+ * to do the work instead of asking for a key. It does not need a fingerprint or a PIN, so the loop can use
+ * it in the background, and it is never in a backup. A phone that loses it - a Keystore reset, a broken
+ * Keystore after an update - cannot read the settings any more.
+ *
+ * The same rules as `KeychainStoreCipher` on iOS and `VaultStoreCipher` on desktop:
+ * - The key is looked up once and then kept, so a save does not ask the Keystore for it each time.
+ * - Only a write makes a key when there is none. A read that finds no key reports the data as unreadable
+ * instead: making a key there would replace one that may only be missing for now.
+ * - The Keystore failing is not "no key". It can fail for a moment around boot, so a failure is tried
+ * again a few times before it is passed on.
+ *
+ * ```
+ * sealed = iv (12 bytes) | ciphertext | GCM tag (16 bytes)
+ * ```
+ * The Keystore chooses the IV itself; it does not accept one from the app.
+ */
+class KeystoreStoreCipher(private val keys: Keys) : StoreCipher {
+
+ /** Where the key lives: the Android Keystore in the app, memory in a test. */
+ interface Keys {
+
+ /** The key, or null when there is none. Throws [SealedDataUnreadableException] for a key that exists but cannot be used. */
+ fun load(): SecretKey?
+
+ fun create(): SecretKey
+
+ /** Removes the key. Nothing happens when there is none. */
+ fun delete()
+ }
+
+ @Volatile private var key: SecretKey? = null
+
+ override fun encrypt(plain: ByteArray): ByteArray = withRetry {
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(Cipher.ENCRYPT_MODE, keyForWrite())
+ val iv = cipher.iv
+ check(iv.size == IV_BYTES) { "The Keystore chose an IV of ${iv.size} bytes" }
+ iv + cipher.doFinal(plain)
+ }
+
+ override fun decrypt(sealed: ByteArray): ByteArray {
+ if (sealed.size < IV_BYTES + TAG_BYTES) throw SealedDataUnreadableException("The settings store is too short")
+ return withRetry {
+ val key = key ?: keys.load()?.also { key = it }
+ ?: throw SealedDataUnreadableException("There is no key for the settings store in the Keystore")
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ try {
+ cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BYTES * 8, sealed, 0, IV_BYTES))
+ cipher.doFinal(sealed, IV_BYTES, sealed.size - IV_BYTES)
+ } catch (e: AEADBadTagException) {
+ throw SealedDataUnreadableException("The settings store does not open with the key in the Keystore", e)
+ } catch (e: InvalidKeyException) {
+ // The key is there but cannot be used, which waiting does not change.
+ throw SealedDataUnreadableException("The Keystore key of the settings store cannot be used", e)
+ }
+ }
+ }
+
+ /** Locked, so two first writes cannot each make a key, the second replacing the first. */
+ @Synchronized
+ private fun keyForWrite(): SecretKey = key ?: (keys.load() ?: keys.create()).also { key = it }
+
+ private fun withRetry(block: () -> T): T {
+ var attempt = 0
+ while (true) {
+ try {
+ return block()
+ } catch (e: SealedDataUnreadableException) {
+ throw e
+ } catch (e: Exception) {
+ if (++attempt >= ATTEMPTS) throw e
+ Thread.sleep(RETRY_DELAY_MS * attempt)
+ }
+ }
+ }
+
+ private companion object {
+
+ const val TRANSFORMATION = "AES/GCM/NoPadding"
+ const val IV_BYTES = 12
+ const val TAG_BYTES = 16
+ const val ATTEMPTS = 3
+ const val RETRY_DELAY_MS = 100L
+ }
+}
+
+/**
+ * The key of the settings store in the Android Keystore, under [alias].
+ *
+ * In the trusted environment of the main processor, never in StrongBox: StrongBox is a separate, slow chip
+ * made for small data, and the store encrypts the whole settings file on every save.
+ */
+class AndroidKeystoreKeys(private val alias: String) : KeystoreStoreCipher.Keys {
+
+ private fun keyStore(): KeyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
+
+ override fun load(): SecretKey? = try {
+ (keyStore().getEntry(alias, null) as? KeyStore.SecretKeyEntry)?.secretKey
+ } catch (e: UnrecoverableEntryException) {
+ throw SealedDataUnreadableException("The Keystore key of the settings store cannot be loaded", e)
+ } catch (e: UnrecoverableKeyException) {
+ throw SealedDataUnreadableException("The Keystore key of the settings store cannot be loaded", e)
+ }
+
+ override fun create(): SecretKey {
+ val spec = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setKeySize(256)
+ .build()
+ return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE).apply { init(spec) }.generateKey()
+ }
+
+ override fun delete() {
+ val keyStore = keyStore()
+ if (keyStore.containsAlias(alias)) keyStore.deleteEntry(alias)
+ }
+
+ private companion object {
+
+ const val ANDROID_KEYSTORE = "AndroidKeyStore"
+ }
+}
diff --git a/app/main/kotlin/app/aaps/settingsstore/SettingsUnreadableActivity.kt b/app/main/kotlin/app/aaps/settingsstore/SettingsUnreadableActivity.kt
new file mode 100644
index 000000000000..271ccb980c1f
--- /dev/null
+++ b/app/main/kotlin/app/aaps/settingsstore/SettingsUnreadableActivity.kt
@@ -0,0 +1,76 @@
+package app.aaps.settingsstore
+
+import android.content.Intent
+import android.os.Bundle
+import android.widget.Toast
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.material3.lightColorScheme
+import androidx.compose.ui.res.stringResource
+import app.aaps.ComposeMainActivity
+import app.aaps.R
+import app.aaps.appshell.StartupFailedLabels
+import app.aaps.appshell.StartupFailedScreen
+import app.aaps.plugins.configuration.configBuilder.AndroidAppExit
+import app.aaps.shared.impl.sharedPreferences.StoreUnreadableException
+import app.aaps.core.ui.R as CoreUiR
+
+/**
+ * Shown instead of the app when the settings cannot be opened (see [AndroidStorage]): what happened, and the
+ * two ways out - try again, or start fresh.
+ *
+ * Not injected, and not part of the app's graph, on purpose. AAPS is not started in this case, and this
+ * screen needs nothing of it. `ComposeMainActivity` hands over to it at once, and the notification opens it.
+ */
+class SettingsUnreadableActivity : ComponentActivity() {
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ enableEdgeToEdge()
+ super.onCreate(savedInstanceState)
+ val failure = AndroidStorage.failure
+ if (failure == null) {
+ // The settings are open: the notification was older than the start that opened them.
+ startActivity(Intent(this, ComposeMainActivity::class.java))
+ finish()
+ return
+ }
+ setContent {
+ MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) {
+ val cause = stringResource(
+ if (failure is StoreUnreadableException) R.string.settings_unreadable_key_explanation
+ else R.string.settings_unreadable_keystore_explanation
+ )
+ StartupFailedScreen(
+ title = stringResource(R.string.settings_unreadable_title),
+ explanation = listOf(cause, stringResource(R.string.settings_unreadable_not_running), stringResource(R.string.settings_unreadable_what_to_do)),
+ error = failure,
+ onRetry = ::restart,
+ onStartFresh = {
+ // Said on the screen, not a crash: the file could not be set aside, so a restart would
+ // only find it again.
+ try {
+ AndroidStorage.startFresh(this)
+ restart()
+ } catch (e: Exception) {
+ Toast.makeText(this, e.message ?: e::class.simpleName, Toast.LENGTH_LONG).show()
+ }
+ },
+ labels = StartupFailedLabels(
+ tryAgain = stringResource(CoreUiR.string.retry),
+ startFresh = stringResource(R.string.settings_unreadable_start_fresh),
+ confirmStartFreshTitle = stringResource(R.string.settings_unreadable_confirm_title),
+ confirmStartFreshText = stringResource(R.string.settings_unreadable_confirm_text),
+ cancel = stringResource(CoreUiR.string.cancel)
+ )
+ )
+ }
+ }
+ }
+
+ /** A new process, which opens the store again. The only way: the store of this one is the empty one in memory. */
+ private fun restart() = AndroidAppExit(applicationContext).exit(launchAgain = true)
+}
diff --git a/app/main/kotlin/app/aaps/settingsstore/SettingsUnreadableNotification.kt b/app/main/kotlin/app/aaps/settingsstore/SettingsUnreadableNotification.kt
new file mode 100644
index 000000000000..3fe95ae17727
--- /dev/null
+++ b/app/main/kotlin/app/aaps/settingsstore/SettingsUnreadableNotification.kt
@@ -0,0 +1,51 @@
+package app.aaps.settingsstore
+
+import android.app.NotificationChannel
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import androidx.core.app.NotificationCompat
+import app.aaps.R
+import app.aaps.core.interfaces.notifications.NotificationManager
+import android.app.NotificationManager as AndroidNotificationManager
+import app.aaps.implementation.R as ImplementationR
+
+/**
+ * The notification that says AAPS is not running because its settings cannot be opened.
+ *
+ * It cannot be swiped away: with the app closed, it is the only sign that the loop is not running. It goes
+ * through the channel of the app's other urgent notifications, and opens [SettingsUnreadableActivity].
+ */
+object SettingsUnreadableNotification {
+
+ /** Far from the small numbers the app's own notifications use. */
+ private const val ID = 7_412_001
+
+ fun show(context: Context, smallIcon: Int) {
+ val manager = context.getSystemService(AndroidNotificationManager::class.java)
+ manager.createNotificationChannel(
+ NotificationChannel(NotificationManager.CHANNEL_ID, context.getString(ImplementationR.string.notifications_channel_name), AndroidNotificationManager.IMPORTANCE_HIGH)
+ )
+ val open = PendingIntent.getActivity(
+ context, ID, Intent(context, SettingsUnreadableActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ val text = context.getString(R.string.settings_unreadable_notification)
+ val notification = NotificationCompat.Builder(context, NotificationManager.CHANNEL_ID)
+ .setSmallIcon(smallIcon)
+ .setContentTitle(context.getString(R.string.settings_unreadable_title))
+ .setContentText(text)
+ .setStyle(NotificationCompat.BigTextStyle().bigText(text))
+ .setPriority(NotificationCompat.PRIORITY_MAX)
+ .setCategory(NotificationCompat.CATEGORY_ERROR)
+ .setOngoing(true)
+ .setContentIntent(open)
+ .build()
+ manager.notify(ID, notification)
+ }
+
+ /** Called on every normal start: the notification outlives the process that posted it. */
+ fun cancel(context: Context) {
+ context.getSystemService(AndroidNotificationManager::class.java).cancel(ID)
+ }
+}
diff --git a/app/main/kotlin/app/aaps/settingsstore/SharedPreferencesMigration.kt b/app/main/kotlin/app/aaps/settingsstore/SharedPreferencesMigration.kt
new file mode 100644
index 000000000000..5f79f8c1d25f
--- /dev/null
+++ b/app/main/kotlin/app/aaps/settingsstore/SharedPreferencesMigration.kt
@@ -0,0 +1,100 @@
+package app.aaps.settingsstore
+
+import androidx.datastore.core.DataMigration
+import app.aaps.core.interfaces.sharedPreferences.StoreCipher
+import app.aaps.shared.impl.sharedPreferences.StoreCodec
+import java.io.File
+
+/**
+ * Moves the settings from the plain SharedPreferences file that `SPImpl` wrote (until 2026-10) into the
+ * encrypted store, once.
+ *
+ * The old file is not changed and stays for one release, so an older version installed again still finds
+ * the settings as they were on the day of the move. The release after that deletes it.
+ *
+ * "Once" is the [marker] file. It is written after the first good open, also when there was nothing to
+ * move, and from then on nothing is moved again: not after starting fresh from an unreadable store, and not
+ * when an older version wrote the old file meanwhile. Those settings can be dangerously old - the state of
+ * a pump or a pod that is long gone, for example. One exception: an old file that exists but gives no
+ * settings at all is not marked as moved, so the next start tries again. SharedPreferences answers a
+ * damaged file with an empty map instead of an error.
+ *
+ * DataStore runs it before the store is first read, writes the result, and only then calls [cleanUp]. If
+ * the start is cut short in between, the next start does the same again: values already in the store win,
+ * because they can only be newer. [cleanUp] also reads the written file back and compares every moved value,
+ * and logs the names (never the values) of any that differ.
+ *
+ * Every value keeps its type, with two exceptions:
+ * - A Float becomes a Double through its decimal text. `SPImpl.putDouble` stored a Float, and the plain
+ * conversion would turn 0.1 into 0.10000000149011612.
+ * - A set of strings has no place in the store and is left behind, named in [log]. No current code writes
+ * one, and the old file still has it.
+ */
+class SharedPreferencesMigration(
+ /** The SharedPreferences file itself, only to know whether there is anything to move. */
+ private val oldFile: File,
+ /** Everything in that file, as `SharedPreferences.getAll()` returns it. */
+ private val readOld: () -> Map,
+ private val storeFile: File,
+ private val cipher: StoreCipher,
+ private val marker: File,
+ /** Lines for the log. The app's logger does not exist yet when this runs: it reads its settings from this store. */
+ private val log: (String) -> Unit
+) : DataMigration