MainActivity.kt

9.4 KB · raw

1package com.peachpasswords23import android.content.Intent4import android.graphics.Color as AndroidColor5import android.graphics.drawable.ColorDrawable6import android.os.Bundle7import androidx.activity.compose.setContent8import androidx.activity.enableEdgeToEdge9import androidx.compose.runtime.SideEffect10import androidx.compose.ui.unit.dp11import androidx.compose.ui.unit.Density12import androidx.compose.ui.unit.Dp13import androidx.compose.ui.platform.LocalDensity14import androidx.compose.ui.Modifier15import androidx.compose.runtime.CompositionLocalProvider16import androidx.compose.runtime.Composable17import androidx.compose.foundation.layout.fillMaxSize18import androidx.compose.foundation.layout.BoxWithConstraints19import androidx.compose.runtime.collectAsState20import androidx.compose.runtime.getValue21import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen22import androidx.core.view.WindowCompat23import androidx.fragment.app.FragmentActivity24import dagger.hilt.android.AndroidEntryPoint25import javax.inject.Inject26import com.peachpasswords.autofill.AutofillIntents27import com.peachpasswords.autofill.AutofillNavRepository28import com.peachpasswords.ui.PeachAppNavHost29import com.peachpasswords.ui.components.Favicons30import com.peachpasswords.ui.components.LocalFavicons31import com.peachpasswords.ui.components.LocalFaviconsEnabled32import com.peachpasswords.ui.components.QaFlags33import com.peachpasswords.ui.components.SecureWindowPolicy34import com.peachpasswords.ui.onboarding.ONBOARD_KEY35import com.peachpasswords.ui.onboarding.ONBOARD_PREFS36import com.peachpasswords.ui.onboarding.onboardingStartDestination37import com.peachpasswords.ui.theme.ACCENT_COLORS38import com.peachpasswords.ui.theme.DEFAULT_ACCENT39import com.peachpasswords.ui.theme.PeachTheme40import com.peachpasswords.updates.EXTRA_OPEN_UPDATE41import com.peachpasswords.updates.UpdateRepository42import com.peachpasswords.vault.VaultLockTimer43import com.peachpasswords.vault.VaultRepository44import com.peachpasswords.vault.faviconsAllowed4546// FragmentActivity (not ComponentActivity) so androidx BiometricPrompt can attach.47@AndroidEntryPoint48class MainActivity : FragmentActivity() {49    @Inject lateinit var vault: VaultRepository50    @Inject lateinit var favicons: Favicons51    @Inject lateinit var lockTimer: VaultLockTimer52    @Inject lateinit var updates: UpdateRepository53    @Inject lateinit var autofillNav: AutofillNavRepository5455    // Every touch/key event resets the idle auto-lock countdown (CF-1).56    override fun onUserInteraction() {57        super.onUserInteraction()58        lockTimer.poke()59    }6061    // launchMode="singleTask" reuses this instance across `adb shell am start`62    // relaunches, so the QA capture-bypass extra (see onCreate) needs to be63    // re-read here too, not just once at process start.64    override fun onNewIntent(intent: Intent) {65        super.onNewIntent(intent)66        setIntent(intent)67        routeIntent(intent)68        if (BuildConfig.DEBUG) {69            QaFlags.disableSecureCaptureForQa = intent.getBooleanExtra(70                QaFlags.EXTRA_DISABLE_SECURE_CAPTURE,71                false,72            )73        }74    }7576    override fun onCreate(savedInstanceState: Bundle?) {77        installSplashScreen()78        super.onCreate(savedInstanceState)7980        // Cold launch from the update notification (the warm case is onNewIntent).81        routeIntent(intent)8283        // Match the window fill to --bg so launch never flashes a lighter colour84        // before Compose draws, whatever the device's own day/night mode is.85        window.setBackgroundDrawable(ColorDrawable(AndroidColor.parseColor("#0C0A06")))8687        enableEdgeToEdge()8889        // Default to FLAG_SECURE immediately (before Compose draws) so there is90        // never an unprotected flash. The user's "allow screenshots" preference91        // is applied reactively inside setContent once settings are available.92        if (!BuildConfig.DEBUG) {93            SecureWindowPolicy.setUserSecure(window, true)94        } else {95            QaFlags.disableSecureCaptureForQa = intent.getBooleanExtra(96                QaFlags.EXTRA_DISABLE_SECURE_CAPTURE,97                false,98            )99        }100101        // Onboarding runs once, only on a fresh install with no vault yet.102        val onboarded = getSharedPreferences(ONBOARD_PREFS, MODE_PRIVATE)103            .getBoolean(ONBOARD_KEY, false)104        val start = onboardingStartDestination(hasVault = vault.hasVault(), onboarded = onboarded)105106        setContent {107            val settings by vault.settings.collectAsState()108            // enableEdgeToEdge() picks bar icon appearance from the device's own109            // day/night mode. Peach is always dark, so on a device in light mode110            // the icons would render dark-on-dark and vanish against our111            // background — reading as if the app ran under the status bar.112            SideEffect {113                WindowCompat.getInsetsController(window, window.decorView).apply {114                    isAppearanceLightStatusBars = false115                    isAppearanceLightNavigationBars = false116                }117            }118            val accent = ACCENT_COLORS[settings.accentColor] ?: DEFAULT_ACCENT119            SideEffect {120                if (!(BuildConfig.DEBUG && QaFlags.disableSecureCaptureForQa)) {121                    SecureWindowPolicy.setUserSecure(window, !settings.allowScreenshots)122                }123            }124            CompositionLocalProvider(125                LocalFavicons provides favicons,126                LocalFaviconsEnabled provides faviconsAllowed(settings),127            ) {128                PeachTheme(129                    accent = accent,130                    reduceMotion = settings.reduceMotion,131                    textSize = settings.textSize,132                ) {133                    WideScreenScale(scalePreference = settings.uiScale) {134                        PeachAppNavHost(startDestination = start, isUnlocked = vault.isUnlocked, uiGateLocked = vault.uiGateLocked)135                    }136                }137            }138        }139    }140}141142/** Layout width a phone gives us; anything past this is "extra" to spend. */143private val BASE_WIDTH = 411.dp144145/**146 * The single place a launch intent is interpreted, shared by cold launch147 * (`onCreate`) and warm relaunch (`onNewIntent`) — launchMode="singleTask" means148 * either can be the one that carries a shortcut tap, and the two paths silently149 * drifting apart is how the shortcut actions went unhandled in the first place.150 *151 * Everything here only records a request; nothing navigates. The nav host acts on152 * it once the vault is unlocked.153 */154private fun MainActivity.routeIntent(intent: Intent) {155    if (intent.getBooleanExtra(EXTRA_OPEN_UPDATE, false)) updates.requestOpen()156    forwardNewEntryRequest(intent)157    routeAction(intent.action)?.let(PendingActionQueue::request)158}159160/**161 * Pick up the "+ Create new entry" launcher from the autofill picker and stash162 * the prefill payload in [autofillNav]. The NavHost observes that flow and163 * navigates to the new-entry editor, mirroring the UpdateRepository pattern.164 */165private fun MainActivity.forwardNewEntryRequest(intent: Intent) {166    if (!intent.getBooleanExtra(AutofillIntents.EXTRA_OPEN_NEW_ENTRY, false)) return167    // F3: MainActivity is exported; only accept the prefill payload when the168    // one-time token proves the launch came from the in-process picker.169    if (!AutofillIntents.consumeNewEntryToken(intent.getStringExtra(AutofillIntents.EXTRA_NEW_ENTRY_TOKEN))) return170    autofillNav.requestNewEntry(171        url = intent.getStringExtra(AutofillIntents.EXTRA_NEW_ENTRY_URL),172        username = intent.getStringExtra(AutofillIntents.EXTRA_NEW_ENTRY_USERNAME),173        email = intent.getStringExtra(AutofillIntents.EXTRA_NEW_ENTRY_EMAIL),174    )175}176177/** Cap on the up-scale — past this, big text stops reading as deliberate. */178private const val MAX_SCALE = 1.35f179180/**181 * On a foldable's inner screen the app was a stretched phone: phone-sized type182 * and rows with the surplus width absorbed as empty space. Scaling the density183 * grows every dp and sp together, so the same single-column layout simply reads184 * as a bigger screen — no per-screen breakpoints to keep in sync.185 *186 * Auto mode keeps the existing foldable treatment but leaves tablet-like187 * windows at phone density; Compact and Large are explicit overrides.188 * No-op at or below [BASE_WIDTH], so phones are untouched.189 */190@Composable191private fun WideScreenScale(192    scalePreference: String = "auto",193    content: @Composable () -> Unit,194) {195    BoxWithConstraints(Modifier.fillMaxSize()) {196        val base = LocalDensity.current197        val scale = wideScreenScaleFor(scalePreference, maxWidth, maxHeight)198        if (scale == 1f) {199            content()200        } else {201            CompositionLocalProvider(202                LocalDensity provides Density(base.density * scale, base.fontScale),203                content = content,204            )205        }206    }207}208209internal fun wideScreenScaleFor(preference: String, width: Dp, height: Dp): Float {210    val phoneScale = (width / BASE_WIDTH).coerceIn(1f, MAX_SCALE)211    return when (preference) {212        "compact" -> 1f213        "large" -> phoneScale214        else -> if (isTabletLike(width, height)) 1f else phoneScale215    }216}217218private fun isTabletLike(width: Dp, height: Dp): Boolean {219    val shortest = minOf(width.value, height.value)220    val longest = maxOf(width.value, height.value)221    return shortest >= 720f || (shortest >= 600f && longest / shortest >= 1.45f)222}