various fixes
- Commit
f716d1ae2187655807439ffdcfdee0b189951bde- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-07 14:03 UTC (2 months ago)
- Parents
6693d8e
Diff
appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.ktindex 9c2a6df4f4..e7b2a3cedd 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.kt@@ -6,8 +6,8 @@ import com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepo * The GrapheneOS "Sandboxed Google Play" bundle: Google's own Play components, installed as * ordinary unprivileged user apps rather than as a privileged system blob. *- * These three packages are **not** installable from Google Play, so the store never fetches- * them through the anonymous-Play path. They come from GrapheneOS's app release server+ * These packages are **not** installable from Google Play, so the store never fetches them+ * through the anonymous-Play path. They come from GrapheneOS's app release server * (apps.grapheneos.org), which re-hosts Google's official signed APKs alongside a signed * index — see [com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepository], which is what * supplies the download URLs, the expected signing certificates and the per-APK hashes.@@ -15,12 +15,24 @@ import com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepo * [android.content.pm.PackageInstaller] flow. The gmscompat shim that lets these run without * the privileged access the real Play client expects lives in the OS, not here. *- * Order matters at install. Google Services Framework and Play Services provide the- * accounts, the GSF ID and the provider the store front-end talks to, so they go on before- * Vending — the same order GrapheneOS installs them in.+ * Order matters at install: Play Services provides the compatibility surface the store+ * front-end talks to, so it goes on before Vending. */ object SandboxedGooglePlay {- /** Google Services Framework — the account/provider layer the rest builds on. */+ /**+ * Google Services Framework — deliberately **not** installed.+ *+ * GrapheneOS refuses it outright, in PackageInstallerSession:+ * `INSTALL_FAILED_SESSION_INVALID: GSF installation is not allowed`. Two reasons, both+ * from the OS's own comments: gmscompat does not need GSF, and because GSF is+ * preinstalled on real GMS Android other apps trust anything holding its package name+ * without checking a signature — so allowing an arbitrary GSF would be a spoofing hole.+ * GrapheneOS does not ship it as a preinstalled app either.+ *+ * Kept as a constant because the identity is still worth naming: [GsfVersionProvider]+ * reads its version when spoofing Play device info, falling back to a default when — as+ * here — it is absent.+ */ const val GSF = "com.google.android.gsf" /** Google Play Services — the bulk of the compatibility surface apps call into. */@@ -34,16 +46,15 @@ object SandboxedGooglePlay { /** Human-readable names, shown before the signed index has been fetched. */ val DISPLAY_NAMES: Map<String, String> = mapOf(- GSF to "Google Services Framework", GMS to "Google Play Services", VENDING to "Google Play Store", ) /**- * Install order: framework and services first, the store that depends on them last.+ * Install order: services first, the store that depends on them last. * The curated section and the ordered install both read this, so the two never drift. */- val PACKAGES: List<String> = listOf(GSF, GMS, VENDING)+ val PACKAGES: List<String> = listOf(GMS, VENDING) /** * Stand-in listings for the three packages.
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.ktindex 86de74dd9c..db9bdceaca 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt@@ -5,6 +5,7 @@ import android.util.Log import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.PinnedStampEntity+import com.vayunmathur.appstore.data.SandboxedGooglePlay import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.accrescent.AccrescentRepository import com.vayunmathur.appstore.data.accrescent.IncompatibleDeviceException@@ -221,7 +222,16 @@ class InstallCoordinator( */ private suspend fun installFromGrapheneOS(app: UnifiedApp): SessionInstaller.Outcome = withContext(Dispatchers.IO) {+ // The index is fetched when the home screen loads, so tapping install before that+ // lands - a cold start, or a refresh that failed while the network was down - would+ // otherwise report that GrapheneOS does not vouch for a package it plainly does.+ // Fetch it here rather than fail on the timing: refresh() is mutex-guarded, so a+ // sync already in flight is awaited rather than duplicated. val entry = grapheneOS.packageFor(app.packageName)+ ?: run {+ grapheneOS.refresh(SandboxedGooglePlay.PACKAGES)+ grapheneOS.packageFor(app.packageName)+ } ?: return@withContext SessionInstaller.Outcome( false, VerificationResult.Rejected(
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.ktindex c9aed53c46..672126c6ba 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt@@ -136,7 +136,7 @@ interface HomeActions : AppActions { fun selectCategory(category: String?) {} fun refresh() {} - /** Install the Sandboxed Google Play bundle in dependency order (GSF, GMS, Vending). */+ /** Install the Sandboxed Google Play bundle in dependency order (GMS, then Vending). */ fun installSandboxedGooglePlay() {} companion object {
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex d94eafcfc2..74bf80c1a0 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -344,6 +344,7 @@ class AppStoreViewModel( if (AppSource.PLAYSTORE in enabled) play.restore() loadHome(enabled) refreshPlayInstalledPackages(enabled)+ syncIfNeverSynced(enabled) } viewModelScope.launch { loadAccrescent(settings.readEnabledSources()) } viewModelScope.launch {@@ -566,6 +567,27 @@ class AppStoreViewModel( override fun refresh() = syncSources() + /**+ * Populate the offline catalogues the first time the store is opened.+ *+ * Nothing else fetches them on startup: [loadHome] only refreshes GrapheneOS's index, and+ * the periodic [com.vayunmathur.appstore.work.UpdateCheckWorker] may be hours away. That+ * left a fresh install showing an empty store until the user thought to pull to refresh.+ *+ * Keyed off the catalogue being empty rather than a "first run" flag, so it also recovers+ * a store whose first sync failed or whose data was cleared - and so it stays quiet on+ * every later launch, when re-fetching two full catalogues on the user's connection would+ * be a poor trade for data that is at most a few hours stale.+ */+ private fun syncIfNeverSynced(enabled: Set<AppSource>) {+ if (_recentlyUpdated.value.isNotEmpty()) return+ // Nothing to fetch if both offline sources are switched off; syncSources() would only+ // report "all sources off" at someone who never asked for a sync.+ val offlineSources = setOf(DefaultRepos.FDROID.source, DefaultRepos.MODERN_APPS.source)+ if (enabled.intersect(offlineSources).isEmpty()) return+ syncSources()+ }+ /** Re-download both offline catalogues, then reload the home rows from them. */ fun syncSources() { if (_isSyncing.value) return@@ -820,10 +842,10 @@ class AppStoreViewModel( /** * Install the Sandboxed Google Play bundle in dependency order. *- * Sequential and awaited, like [updateAll]: GSF and GMS provide the accounts and the- * provider Vending talks to, so they must land first, and each first-time install shows- * its own PackageInstaller confirmation — firing them at once would bury the user in- * prompts and let the store client install before the services it needs.+ * Sequential and awaited, like [updateAll]: Play Services provides the provider Vending+ * talks to, so it must land first, and each first-time install shows its own+ * PackageInstaller confirmation - firing them at once would bury the user in prompts and+ * let the store client install before the services it needs. */ override fun installSandboxedGooglePlay() { viewModelScope.launch {
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex 6d73bca52b..eeac1c0409 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -25,7 +25,23 @@ fun readVersionInfo(): Pair<Int, String> { val proguardFile get() = File(rootDir, "proguard-rules.pro") -val (appVersionCode, appVersionName) = readVersionInfo()+val (releaseVersionCode, appVersionName) = readVersionInfo()++/**+ * `-PversionCodeOverride=N` — for sideloading over a preinstalled Modern App on MAOS.+ *+ * The platform refuses to update a system package to the same versionCode, so an APK built+ * from the same `version.txt` as the running OS image can never be installed over it. Passing+ * a higher code makes the dev loop work without touching the release version every time.+ *+ * Keep the bump small (`+1`). The update lives in /data and keeps shadowing the system app+ * across OS flashes until the image's own versionCode overtakes it, so a wild value would+ * pin the sideloaded build in place indefinitely.+ *+ * Read at configuration time, which the configuration cache requires.+ */+val appVersionCode: Int =+ (findProperty("versionCodeOverride") as String?)?.trim()?.toIntOrNull() ?: releaseVersionCode // Adaptive launcher icons are generated at build time from Material Symbols // instead of committing an ic_launcher_foreground.xml per app. Each app declares@@ -198,7 +214,15 @@ configure<com.android.build.api.dsl.ApplicationExtension> { enableV1Signing = true enableV2Signing = true enableV3Signing = true- enableV4Signing = false+ // Emits the `<apk>.idsig` sidecar. PackageInstallerSession calls+ // enableFsVerityToAddedApksWithIdsig() for any non-incremental install that+ // stages one, which is the only way to get fs-verity onto an APK - and+ // GrapheneOS refuses to update a preinstalled system app without it. Incremental+ // install, the other route to fs-verity, is barred for system packages. So+ // without this a preinstalled Modern App can only be changed by a full OS build.+ // The APK itself is unchanged; consumers that copy `*-release.apk` (collect-apks.sh,+ // the F-Droid publish) simply ignore the sidecar.+ enableV4Signing = true } } }
clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.ktindex d7e1846579..805f190c9c 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt@@ -53,6 +53,9 @@ class AlarmActivity : ComponentActivity() { private fun snoozeAlarm() { stopService(Intent(this, AlarmSoundService::class.java))+ // The ring notification is insistent, so it keeps sounding until cancelled. Snoozing+ // used to leave it posted, which only went unnoticed while the service owned the sound.+ getSystemService(NotificationManager::class.java).cancel(alarmId.toInt()) val snoozeTime = Clock.System.now().plus(snoozeMinutes.minutes) val triggerMillis = snoozeTime.toEpochMilliseconds() val intent = Intent(this, AlarmReceiver::class.java).apply { putExtra("ALARM_ID", alarmId); putExtra("IS_SNOOZE", true) }
clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.ktindex 2b8ecf5b9a..e689a6ea5f 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt@@ -1,9 +1,12 @@ package com.vayunmathur.clock.platform+import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent+import android.os.Build+import android.util.Log import androidx.core.app.NotificationCompat import com.vayunmathur.clock.data.ClockRepository import kotlinx.coroutines.CoroutineScope@@ -17,6 +20,7 @@ class AlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { createNotificationChannels(context) val alarmId = intent.getLongExtra("ALARM_ID", -1L)+ Log.i(TAG, "Alarm $alarmId fired (snooze=${intent.getBooleanExtra("IS_SNOOZE", false)})") // 1. Create the Intent for your "Ringing" Activity val ringIntent = Intent(context, AlarmActivity::class.java).apply {@@ -32,8 +36,10 @@ class AlarmReceiver : BroadcastReceiver() { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) - // 3. Build the Notification- val builder = NotificationCompat.Builder(context, "ALARM_CHANNEL_ID")+ // 3. Build the Notification. This is what actually rings: FLAG_INSISTENT below repeats+ // the ring channel's sound until something cancels it, so the alarm sounds even when+ // AlarmSoundService never reaches startForeground.+ val builder = NotificationCompat.Builder(context, ALARM_RING_CHANNEL_ID) .setSmallIcon(R.drawable.baseline_access_alarm_24) .setContentTitle(context.getString(R.string.label_alarm)) .setContentText(context.getString(R.string.alarm_notification_wake_up))@@ -42,6 +48,9 @@ class AlarmReceiver : BroadcastReceiver() { // This is the key: it launches the activity automatically if the phone is locked .setFullScreenIntent(pendingIntent, true) .setAutoCancel(true)+ // Backstop: an insistent notification rings forever, so bound it in case every+ // dismiss path is missed (process killed before the UI ever appeared, say).+ .setTimeoutAfter(RING_TIMEOUT_MS) val repository = ClockRepository.get(context) val pendingResult = goAsync()@@ -53,25 +62,49 @@ class AlarmReceiver : BroadcastReceiver() { } else { AlarmScheduler.schedule(context, alarm) }- } catch (_: Exception) {+ } catch (e: Exception) {+ Log.e(TAG, "Alarm $alarmId: could not reschedule", e) } finally { pendingResult.finish() } } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager- notificationManager.notify(alarmId.toInt(), builder.build())+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&+ !notificationManager.canUseFullScreenIntent()+ ) {+ // Without it the ringing screen can only appear if the background activity start+ // below happens to be allowed, which off-screen it is not.+ Log.w(TAG, "Alarm $alarmId: USE_FULL_SCREEN_INTENT not granted; ringing UI may not appear")+ }+ notificationManager.notify(+ alarmId.toInt(),+ builder.build().apply { flags = flags or Notification.FLAG_INSISTENT },+ ) // 4. Start the Sound Service immediately so we hear it even if Activity doesn't launch val serviceIntent = Intent(context, AlarmSoundService::class.java).apply { putExtra("ALARM_ID", alarmId) }- context.startForegroundService(serviceIntent)+ try {+ context.startForegroundService(serviceIntent)+ } catch (e: Exception) {+ // Losing this used to throw out of onReceive, which took the notification's+ // rescheduling and the activity start below down with it.+ Log.e(TAG, "Alarm $alarmId: could not start AlarmSoundService", e)+ } // 5. Try to start the activity explicitly (useful if screen is already on) try { context.startActivity(ringIntent) } catch (e: Exception) {- // Background activity start restrictions might apply, but fullScreenIntent is our backup+ Log.w(TAG, "Alarm $alarmId: background activity start refused; relying on full-screen intent", e) } }++ private companion object {+ const val TAG = "AlarmReceiver"++ /** How long the insistent notification may ring unattended before the system drops it. */+ const val RING_TIMEOUT_MS = 10 * 60 * 1000L+ } }\ No newline at end of file
clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.ktindex 48235eb2f3..eb5714f4c4 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt@@ -3,6 +3,7 @@ package com.vayunmathur.clock.platform import android.content.BroadcastReceiver import android.content.Context import android.content.Intent+import android.util.Log import com.vayunmathur.clock.data.ClockRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -19,10 +20,14 @@ class BootReceiver : BroadcastReceiver() { val pendingResult = goAsync() CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { try {- repository.getAllAlarms()- .filter { it.enabled }- .forEach { AlarmScheduler.schedule(context, it) }- } catch (_: Exception) {+ val enabled = repository.getAllAlarms().filter { it.enabled }+ enabled.forEach { AlarmScheduler.schedule(context, it) }+ Log.i(TAG, "${intent.action}: rescheduled ${enabled.size} alarm(s)")+ } catch (e: Exception) {+ // Expected at LOCKED_BOOT_COMPLETED: the database lives in+ // credential-encrypted storage, so BOOT_COMPLETED is what actually+ // reschedules. A failure there means no alarm survives the reboot.+ Log.e(TAG, "${intent.action}: could not reschedule alarms", e) } finally { pendingResult.finish() }@@ -30,4 +35,8 @@ class BootReceiver : BroadcastReceiver() { } } }++ private companion object {+ const val TAG = "ClockBootReceiver"+ } }
clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.kt b/clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.ktindex 44b68b97ae..8778ad8e44 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.kt@@ -8,9 +8,36 @@ import android.media.AudioAttributes import android.media.RingtoneManager import com.vayunmathur.clock.R +/**+ * The silent channel the ringing service posts its ongoing notification to. Silent because+ * [ALARM_RING_CHANNEL_ID] is what actually rings, and a sounding channel here would make the+ * service's own foreground notification ring a second time on top of the MediaPlayer.+ *+ * A channel's sound, vibration and DND-bypass are fixed when it is first created; later+ * `createNotificationChannel` calls cannot change them. The original channel was created+ * without [NotificationChannel.setSound]/[NotificationChannel.enableVibration], so bumping the+ * id is the only way to apply the intended configuration to installs that predate them.+ */+const val ALARM_CHANNEL_ID = "alarm_channel_v2"++/**+ * Rings the alarm from the system side, and owns the alarm sound.+ *+ * AlarmSoundService cannot be relied on to reach `startForeground`: the start can be denied+ * outright, or the service can be killed asynchronously for missing the five-second window.+ * Neither failure is visible at the receiver's call site, so there is nothing to catch. A+ * `FLAG_INSISTENT` notification on a channel that owns the sound keeps ringing without any+ * process of ours surviving, and the service cancels it when it does manage to take over.+ */+const val ALARM_RING_CHANNEL_ID = "alarm_ring_channel"++private const val LEGACY_ALARM_CHANNEL_ID = "ALARM_CHANNEL_ID"+ fun createNotificationChannels(context: Context) { val nm = context.getSystemService(NotificationManager::class.java) + nm.deleteNotificationChannel(LEGACY_ALARM_CHANNEL_ID)+ nm.createNotificationChannels(listOf( // 1. Quiet channel for ongoing countdowns NotificationChannel("active_timers_channel", context.getString(R.string.channel_ongoing_timers_name), NotificationManager.IMPORTANCE_LOW).apply {@@ -25,13 +52,8 @@ fun createNotificationChannels(context: Context) { RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM), AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build()) },- NotificationChannel("ALARM_CHANNEL_ID", context.getString(R.string.channel_alarms_name), NotificationManager.IMPORTANCE_HIGH).apply {- description = context.getString(R.string.channel_alarms_description)- setBypassDnd(true)- setSound(null, null) // Service handles sound via MediaPlayer- enableVibration(false)- lockscreenVisibility = Notification.VISIBILITY_PUBLIC- },+ alarmChannel(context),+ alarmRingChannel(context), // 3. Stopwatch channel NotificationChannel("stopwatch_channel", context.getString(R.string.channel_stopwatch_name), NotificationManager.IMPORTANCE_LOW).apply { description = context.getString(R.string.channel_stopwatch_description)@@ -40,3 +62,40 @@ fun createNotificationChannels(context: Context) { } )) }++/**+ * Just the service's own channel. A service has five seconds from `startForegroundService` to+ * reach `startForeground`, so AlarmSoundService creates only what it posts on rather than paying+ * for the delete plus the batched create that [createNotificationChannels] does.+ */+fun createAlarmChannel(context: Context) {+ context.getSystemService(NotificationManager::class.java)+ .createNotificationChannel(alarmChannel(context))+}++private fun alarmChannel(context: Context) = NotificationChannel(+ ALARM_CHANNEL_ID,+ context.getString(R.string.channel_alarm_playing_name),+ NotificationManager.IMPORTANCE_HIGH,+).apply {+ description = context.getString(R.string.channel_alarm_playing_description)+ setBypassDnd(true)+ setSound(null, null) // The ring channel and the MediaPlayer own the sound.+ enableVibration(false) // AlarmSoundService.startVibration honours the per-alarm setting.+ lockscreenVisibility = Notification.VISIBILITY_PUBLIC+}++private fun alarmRingChannel(context: Context) = NotificationChannel(+ ALARM_RING_CHANNEL_ID,+ context.getString(R.string.channel_alarms_name),+ NotificationManager.IMPORTANCE_HIGH,+).apply {+ description = context.getString(R.string.channel_alarms_description)+ setBypassDnd(true)+ setSound(+ RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM),+ AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build(),+ )+ enableVibration(true)+ lockscreenVisibility = Notification.VISIBILITY_PUBLIC+}
clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt b/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.ktindex f680b61026..d52f5e83bb 100644--- a/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt+++ b/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt@@ -1,4 +1,6 @@ package com.vayunmathur.clock.service+import android.app.Notification+import android.app.NotificationManager import android.app.Service import android.content.Intent import android.content.pm.ServiceInfo@@ -9,10 +11,12 @@ import android.net.Uri import android.os.VibrationEffect import android.os.Vibrator import android.os.VibratorManager+import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.net.toUri import com.vayunmathur.clock.R-import com.vayunmathur.clock.platform.createNotificationChannels+import com.vayunmathur.clock.platform.ALARM_CHANNEL_ID+import com.vayunmathur.clock.platform.createAlarmChannel import com.vayunmathur.clock.data.ClockRepository import com.vayunmathur.library.ui.RINGTONE_SILENT import kotlinx.coroutines.CoroutineScope@@ -29,12 +33,24 @@ class AlarmSoundService : Service() { private var started = false private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {- // 1. Create the channel (Safe to call multiple times)- createNotificationChannels(this)+ override fun onCreate() {+ super.onCreate()+ // The five-second startForegroundService deadline is mostly spent before we get here -+ // process fork, class loading, Application.onCreate - so claim the contract immediately+ // and do everything else afterwards. Missing it gets the service killed asynchronously,+ // which the receiver cannot see or catch.+ startForeground(+ NOTIFICATION_ID,+ ongoingNotification(),+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK,+ )+ // AlarmReceiver creates the channels before starting us, so this only matters for a+ // START_STICKY restart that no receiver preceded.+ createAlarmChannel(this)+ } - // 2. Build and show notification FIRST- val notification = NotificationCompat.Builder(this, "ALARM_CHANNEL_ID")+ private fun ongoingNotification(): Notification =+ NotificationCompat.Builder(this, ALARM_CHANNEL_ID) .setSmallIcon(R.drawable.baseline_access_alarm_24) .setContentTitle(getString(R.string.alarm_ringing_notification_title)) .setPriority(NotificationCompat.PRIORITY_MAX)@@ -42,13 +58,19 @@ class AlarmSoundService : Service() { .setOngoing(true) .build() - // 3. This is the "Contract" with the OS. Do this before MediaPlayer.- startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ val alarmId = intent?.getLongExtra("ALARM_ID", -1L) ?: -1L++ // We are alive and foreground, so take the ring off the system before doing anything+ // slow: the insistent notification and the MediaPlayer must not overlap for longer than+ // this handover.+ if (alarmId != -1L) {+ getSystemService(NotificationManager::class.java).cancel(alarmId.toInt())+ } - // 4. Now handle the hardware, using this alarm's per-alarm settings.+ // Now handle the hardware, using this alarm's per-alarm settings. if (!started) { started = true- val alarmId = intent?.getLongExtra("ALARM_ID", -1L) ?: -1L scope.launch { val alarm = if (alarmId != -1L) { runCatching {@@ -62,12 +84,25 @@ class AlarmSoundService : Service() { // setDataSource()/prepare() are blocking; run them on the IO // dispatcher (this coroutine) instead of the main thread.- if (ringtoneUri != RINGTONE_SILENT) {- playAlarm(resolveRingtone(ringtoneUri), gradualSeconds)- }+ //+ // Vibration comes first: a stored ringtone can be a content:// URI owned by+ // another app, and one that no longer resolves used to throw out of playAlarm+ // and take the vibration down with it. if (vibrate) { withContext(Dispatchers.Main) { startVibration() } }+ if (ringtoneUri != RINGTONE_SILENT) {+ runCatching { playAlarm(resolveRingtone(ringtoneUri), gradualSeconds) }+ .onFailure { failure ->+ Log.e(TAG, "Alarm $alarmId: ringtone $ringtoneUri failed to play", failure)+ releasePlayer()+ runCatching { playAlarm(resolveRingtone(null), gradualSeconds) }+ .onFailure { fallbackFailure ->+ Log.e(TAG, "Alarm $alarmId: default ringtone failed too", fallbackFailure)+ releasePlayer()+ }+ }+ } } } @@ -99,6 +134,11 @@ class AlarmSoundService : Service() { if (gradualSeconds > 0) rampVolume(gradualSeconds) } + private fun releasePlayer() {+ runCatching { mediaPlayer?.release() }+ mediaPlayer = null+ }+ /** Fade the alarm in from silent to full over [seconds]. */ private fun rampVolume(seconds: Int) { scope.launch {@@ -132,5 +172,6 @@ class AlarmSoundService : Service() { companion object { const val NOTIFICATION_ID = 1001+ private const val TAG = "AlarmSoundService" } }
clock/src/main/res/values/strings.xml
diff --git a/clock/src/main/res/values/strings.xml b/clock/src/main/res/values/strings.xmlindex 9320ccc5bf..4b4a178544 100644--- a/clock/src/main/res/values/strings.xml+++ b/clock/src/main/res/values/strings.xml@@ -41,6 +41,10 @@ <string name="channel_alarms_name">Alarms</string> <!-- System channel description for alarm notifications, bypasses DND --> <string name="channel_alarms_description">Notifications for scheduled alarms</string>+ <!-- System channel name for the silent notification shown while an alarm is already ringing -->+ <string name="channel_alarm_playing_name">Alarm in progress</string>+ <!-- System channel description for the silent notification shown while an alarm is ringing -->+ <string name="channel_alarm_playing_description">Shown while an alarm is sounding</string> <!-- System channel name for stopwatch --> <string name="channel_stopwatch_name">Stopwatch</string> <!-- System channel description for stopwatch notification -->
euicc/src/main/AndroidManifest.xml
diff --git a/euicc/src/main/AndroidManifest.xml b/euicc/src/main/AndroidManifest.xmlindex 72399a675b..201510d7f7 100644--- a/euicc/src/main/AndroidManifest.xml+++ b/euicc/src/main/AndroidManifest.xml@@ -26,7 +26,25 @@ <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>- <intent-filter android:priority="10">+ </activity>++ <!--+ The LUI the platform opens from Settings. Guarded by BIND_EUICC_SERVICE because+ EuiccConnector.isValidEuiccComponent applies that requirement to the resolving+ activity, not just to the EuiccService - without it the platform finds no LUI and+ the Settings row silently does nothing. It cannot live on MainActivity, since+ android:permission constrains the caller and the launcher holds no signature+ permission. See LuiActivity.+ -->+ <activity+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:name=".platform.LuiActivity"+ android:exported="true"+ android:permission="android.permission.BIND_EUICC_SERVICE"+ android:excludeFromRecents="true"+ android:taskAffinity=""+ android:theme="@style/Theme.General">+ <intent-filter android:priority="100"> <action android:name="android.service.euicc.action.MANAGE_EMBEDDED_SUBSCRIPTIONS" /> <action android:name="android.service.euicc.action.PROVISION_EMBEDDED_SUBSCRIPTION" /> <category android:name="android.intent.category.DEFAULT" />
euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt b/euicc/src/main/java/com/vayunmathur/euicc/Navigation.ktindex e4590ae622..596b45cc4d 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/Navigation.kt@@ -2,14 +2,73 @@ package com.vayunmathur.euicc import androidx.compose.runtime.Composable import com.vayunmathur.euicc.platform.EuiccViewModel-import com.vayunmathur.euicc.ui.EuiccScreen+import com.vayunmathur.euicc.ui.ActivationCodeScreen+import com.vayunmathur.euicc.ui.AddSimScreen+import com.vayunmathur.euicc.ui.DeviceInfoScreen+import com.vayunmathur.euicc.ui.DownloadScreen+import com.vayunmathur.euicc.ui.EuiccHomeScreen+import com.vayunmathur.euicc.ui.ProfileDetailScreen+import com.vayunmathur.euicc.ui.QrScannerScreen import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack @Composable fun Navigation(viewModel: EuiccViewModel) { val backStack = rememberNavBackStack<Route>(Route.Home)++ /**+ * Leaving the activation flow: drop every step of it at once rather than popping back+ * through the scanner and the code entry, and reset the download so re-entering starts+ * clean instead of re-showing the last result.+ */+ fun finishActivation() {+ viewModel.clearDownload()+ backStack.reset(Route.Home)+ }+ MainNavigation(backStack) {- entry<Route.Home> { EuiccScreen(viewModel) }+ entry<Route.Home> {+ EuiccHomeScreen(+ state = viewModel.state,+ backStack = backStack,+ onReload = viewModel::reload,+ onAddSim = { backStack.add(Route.AddSim) },+ )+ }+ entry<Route.ProfileDetail> { route ->+ ProfileDetailScreen(+ iccid = route.iccid,+ state = viewModel.state,+ backStack = backStack,+ onEnable = { viewModel.enable(it.iccid) },+ onDisable = { viewModel.disable(it.iccid) },+ onErase = { viewModel.delete(it.iccid) },+ onRename = { profile, name -> viewModel.rename(profile.iccid, name) },+ )+ }+ entry<Route.DeviceInfo> {+ DeviceInfoScreen(+ state = viewModel.state,+ backStack = backStack,+ onRemoveNotification = viewModel::removeNotification,+ )+ }+ entry<Route.AddSim> { AddSimScreen(backStack = backStack) }+ entry<Route.ScanQr> {+ QrScannerScreen(+ onResult = { backStack.add(Route.Download(it)) },+ onCancel = { backStack.pop() },+ )+ }+ entry<Route.ActivationCode> { ActivationCodeScreen(backStack = backStack) }+ entry<Route.Download> { route ->+ DownloadScreen(+ activationCode = route.activationCode,+ state = viewModel.download,+ backStack = backStack,+ onStart = viewModel::startDownload,+ onDone = ::finishActivation,+ )+ } } }
euicc/src/main/java/com/vayunmathur/euicc/Route.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/Route.kt b/euicc/src/main/java/com/vayunmathur/euicc/Route.ktindex 68d7f5626b..8d686afb4d 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/Route.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/Route.kt@@ -5,6 +5,41 @@ import kotlinx.serialization.Serializable @Serializable sealed interface Route : NavKey {+ /** The profile list - the LUI's landing screen. */ @Serializable data object Home : Route++ /**+ * One profile's detail screen. Keyed by raw ICCID hex rather than by the profile+ * itself so the destination survives a reload: every mutation re-reads the eUICC and+ * replaces the [com.vayunmathur.euicc.data.Profile] instances.+ */+ @Serializable+ data class ProfileDetail(val iccid: String) : Route++ /** EID, eUICC version, and pending notifications. */+ @Serializable+ data object DeviceInfo : Route++ /** Choose how to add a SIM: scan a QR code, or type an activation code. */+ @Serializable+ data object AddSim : Route++ /** Camera viewfinder for an activation-code QR. */+ @Serializable+ data object ScanQr : Route++ /** Manual activation-code entry. */+ @Serializable+ data object ActivationCode : Route++ /**+ * The download itself. One destination for every step - confirm, confirmation code,+ * installing, done, failed - because they are phases of a single eUICC session rather+ * than places the user can navigate between. Which one shows is decided by+ * [com.vayunmathur.euicc.platform.DownloadState], so the screen cannot drift out of+ * sync with the session driving it.+ */+ @Serializable+ data class Download(val activationCode: String) : Route }
euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.kt b/euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.ktnew file mode 100644index 0000000000..284f8fdeb6--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/platform/DownloadState.kt@@ -0,0 +1,50 @@+package com.vayunmathur.euicc.platform++/**+ * Where a profile download has got to.+ *+ * Modelled as a state machine rather than a set of booleans because the steps are ordered+ * and mutually exclusive, and because the eUICC session behind them is too: there is+ * exactly one download in flight at a time, and the screen has to show whichever phase it+ * is actually in.+ *+ * [Confirm] and [AwaitingConfirmationCode] are declared but unreachable until the native+ * core can report profile metadata and pause for a confirmation code - today's+ * `nativeDownloadProfile` is a single atomic call, so a download runs+ * [Preparing] -> [Installing] -> [Complete]/[Failed]. They are here now so the UI that+ * renders them is written once.+ */+sealed interface DownloadState {+ /** No download in flight. */+ data object Idle : DownloadState++ /** Authenticating with the SM-DP+; nothing has touched the eUICC's profile store yet. */+ data object Preparing : DownloadState++ /**+ * The SM-DP+ has named the profile and is waiting for the user to accept it.+ * Unreachable until the native core parses ProfileMetadata.+ */+ data class Confirm(val carrier: String?, val profileName: String?) : DownloadState++ /**+ * The profile is confirmation-code protected. [error] is set after a rejected attempt.+ * Unreachable until the native core threads a confirmation code into PrepareDownload.+ */+ data class AwaitingConfirmationCode(+ val carrier: String?,+ val error: Boolean = false,+ ) : DownloadState++ /**+ * The profile is being written to the eUICC. [progress] is null while the native core+ * reports no progress, which is every download until the BPP segment loop calls back.+ */+ data class Installing(val progress: Float? = null) : DownloadState++ /** Installed. The profile still has to be enabled, which is Settings' job. */+ data class Complete(val carrier: String?) : DownloadState++ /** Gave up. [message] is the native core's or the server's own wording where there is one. */+ data class Failed(val message: String?) : DownloadState+}
euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt b/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.ktindex 42993fc049..db76de7d42 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/platform/EuiccViewModel.kt@@ -39,10 +39,58 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) { var state by mutableStateOf(EuiccScreenState()) private set + /**+ * The activation flow's own state, kept separate from [state] because the two have+ * different lifetimes: [state] mirrors the eUICC and is replaced on every reload,+ * while a download survives across those reloads until the user leaves the screen.+ */+ var download by mutableStateOf<DownloadState>(DownloadState.Idle)+ private set+ init { reload() } + /**+ * Runs the download for [activationCode].+ *+ * Goes straight from [DownloadState.Preparing] to [DownloadState.Installing] because+ * `nativeDownloadProfile` is atomic - it authenticates, binds and installs in one call,+ * with no point in between where it can report the carrier or ask for a confirmation+ * code. Splitting it is what makes those states reachable.+ */+ fun startDownload(activationCode: String) {+ if (download is DownloadState.Preparing || download is DownloadState.Installing) return+ download = DownloadState.Preparing+ viewModelScope.launch {+ download = DownloadState.Installing()+ val outcome = withContext(Dispatchers.IO) {+ runCatching {+ channelManager.withIsdrChannel { EuiccNative.nativeDownloadProfile(activationCode) }+ }+ }+ download = outcome.fold(+ onSuccess = { raw ->+ val result = runCatching { json.decodeFromString<DownloadResult>(raw) }.getOrNull()+ when {+ result == null -> DownloadState.Failed(null)+ result.success -> DownloadState.Complete(null)+ else -> DownloadState.Failed(result.message.ifBlank { null })+ }+ },+ onFailure = { DownloadState.Failed(it.message) },+ )+ // The eUICC changed either way: a success installed a profile, and a failure may+ // still have left a notification behind.+ reload()+ }+ }++ /** Clears the activation flow, so leaving and re-entering it starts clean. */+ fun clearDownload() {+ download = DownloadState.Idle+ }+ /** Reads EID, eUICC info, profiles, and notifications in one channel session. */ fun reload() { val carryMessage = state.message@@ -70,32 +118,6 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) { } } - /** Downloads and installs the profile for an activation code, then reloads. */- fun downloadProfile(activationCode: String) {- state = state.copy(loading = true, error = null, message = null)- viewModelScope.launch {- val outcome = withContext(Dispatchers.IO) {- runCatching {- channelManager.withIsdrChannel { EuiccNative.nativeDownloadProfile(activationCode) }- }- }- outcome.fold(- onSuccess = { raw ->- val result = runCatching { json.decodeFromString<DownloadResult>(raw) }.getOrNull()- when {- result == null -> state = state.copy(loading = false, error = "Download failed")- result.success -> {- state = state.copy(message = result.message)- reload()- }- else -> state = state.copy(loading = false, error = result.message)- }- },- onFailure = { state = state.copy(loading = false, error = it.message ?: "Download failed") },- )- }- }- fun enable(iccid: String) = action { EuiccNative.nativeEnableProfile(iccid) } fun disable(iccid: String) = action { EuiccNative.nativeDisableProfile(iccid) } fun delete(iccid: String) = action { EuiccNative.nativeDeleteProfile(iccid) }
euicc/src/main/java/com/vayunmathur/euicc/platform/LuiActivity.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/platform/LuiActivity.kt b/euicc/src/main/java/com/vayunmathur/euicc/platform/LuiActivity.ktnew file mode 100644index 0000000000..6f72f6d87a--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/platform/LuiActivity.kt@@ -0,0 +1,43 @@+package com.vayunmathur.euicc.platform++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import com.vayunmathur.euicc.Navigation+import com.vayunmathur.library.ui.DynamicTheme++/**+ * The eSIM LUI (Local User Interface) — the entry point the platform opens when the user taps+ * an eSIM option in Settings, rather than when they open this app from the launcher.+ *+ * It exists separately from `MainActivity`, showing the same screen, because of a constraint+ * in how the platform picks an LUI. `EuiccConnector.isValidEuiccComponent` requires the+ * resolving **activity** to be guarded by `BIND_EUICC_SERVICE` — the same rule it applies to+ * the `EuiccService` — and rejects it outright otherwise:+ *+ * E/EuiccConnector: Package com.vayunmathur.euicc does not require the+ * BIND_EUICC_SERVICE permission+ * W/EuiccUiDispatcher: Could not resolve activity for intent: ...+ *+ * `EuiccUiDispatcherActivity` runs under `Theme.NoDisplay`, so a rejection is invisible: the+ * Settings row simply does nothing. That permission cannot go on `MainActivity`, because+ * `android:permission` constrains the *caller* and the launcher does not hold a signature+ * permission — the launcher icon would stop working. Hence a second, system-only activity,+ * which is the same shape Google's own LPA uses.+ *+ * The result code is deliberately left at the default `RESULT_CANCELED`. The dispatcher sets+ * `FLAG_ACTIVITY_FORWARD_RESULT`, so whatever this returns goes back to the original caller,+ * and for a provisioning request that is the honest answer unless a profile was actually+ * installed.+ */+class LuiActivity : ComponentActivity() {+ private val viewModel: EuiccViewModel by viewModels()++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent { DynamicTheme { Navigation(viewModel) } }+ }+}
euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.kt b/euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.ktindex 844f9696cd..f4bbb5dfa6 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/service/EuiccManagerService.kt@@ -11,7 +11,10 @@ import android.service.euicc.GetDownloadableSubscriptionMetadataResult import android.service.euicc.GetEuiccProfileInfoListResult import android.telephony.euicc.DownloadableSubscription import android.telephony.euicc.EuiccInfo as FrameworkEuiccInfo-import android.telephony.euicc.EuiccProfileInfo+// EuiccProfileInfo is in android.service.euicc, not android.telephony.euicc where its+// siblings above live. Importing the latter compiles against the stubs but throws+// ClassNotFoundException the first time the framework asks for the profile list.+import android.service.euicc.EuiccProfileInfo import com.vayunmathur.euicc.EuiccNative import com.vayunmathur.euicc.data.EuiccInfo import com.vayunmathur.euicc.data.Profile
euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.kt b/euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.ktindex bb83481b2b..fe07443019 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/telephony/EuiccChannelManager.kt@@ -3,7 +3,11 @@ package com.vayunmathur.euicc.telephony import android.content.Context import android.telephony.IccOpenLogicalChannelResponse import android.telephony.TelephonyManager+import android.telephony.UiccCardInfo+import android.telephony.UiccPortInfo+import android.util.Log import com.vayunmathur.euicc.EuiccNative+import java.lang.reflect.Method /** Thrown when the eUICC cannot be reached (no eUICC, no privilege, or an APDU error). */ class EuiccException(message: String) : Exception(message)@@ -11,29 +15,73 @@ class EuiccException(message: String) : Exception(message) /** * Opens and drives a logical channel to the eUICC's ISD-R applet. *- * SGP.22 local (ES10) operations run over an ISO-7816 logical channel selected- * onto the ISD-R AID. This wraps the telephony- * `iccOpenLogicalChannel` / `iccTransmitApduLogicalChannel` /- * `iccCloseLogicalChannel` APIs, which require the app to hold carrier- * privileges or be a platform-signed system app (`MODIFY_PHONE_STATE`). The- * native core builds the command APDUs and calls back into- * [EuiccNative.transmitApdu]; [transmit] performs the field-based transmit and- * handles `61xx` GET RESPONSE / `6Cxx` Le-correction chaining.+ * SGP.22 local (ES10) operations run over an ISO-7816 logical channel selected onto the ISD-R+ * AID. This wraps the telephony `iccOpenLogicalChannel` / `iccTransmitApduLogicalChannel` /+ * `iccCloseLogicalChannel` APIs. The native core builds the command APDUs and calls back into+ * [EuiccNative.transmitApdu]; [transmit] performs the field-based transmit and handles+ * `61xx` GET RESPONSE / `6Cxx` Le-correction chaining.+ *+ * Everything here addresses the eUICC by **slot and port**, never by subscription. The+ * subscription-based overloads target the default subId, and an LPA's whole job is to run+ * before any subscription exists - on a phone with no SIM and no installed profile the default+ * subId is INVALID_SUBSCRIPTION_ID, so telephony rejects the call outright:+ *+ * java.lang.IllegalArgumentException: Both subId and slotIndex in request are invalid.+ *+ * (PhoneInterfaceManager.getPhoneFromValidIccLogicalChannelRequest, which falls through to+ * that throw when neither field is set.) The port-based overloads take the `slotIndex` branch+ * instead and need only MODIFY_PHONE_STATE, which this app holds.+ *+ * Those overloads are `@SystemApi`, so they are absent from the public SDK this module builds+ * against and have to be reached reflectively. Telephony still enforces every permission on+ * its side - the reflection buys visibility, not privilege. It additionally restricts ISD-R to+ * the selected LPA, so this only works while this app is the resolved EuiccService. */ class EuiccChannelManager(context: Context) { private val telephony: TelephonyManager = context.applicationContext.getSystemService(TelephonyManager::class.java) ?: throw EuiccException("TelephonyManager unavailable") + /** Physical slot and port of the eUICC, resolved once on first use. */+ private val target: EuiccTarget by lazy { resolveEuiccTarget() }++ private data class EuiccTarget(val slotIndex: Int, val portIndex: Int)++ /**+ * Finds the eUICC's physical slot and port.+ *+ * `getUiccCardsInfo` is public API and needs READ_PRIVILEGED_PHONE_STATE, which this app+ * declares. Unlike the subscription APIs it reports cards that carry no active profile,+ * which is exactly the state an LPA starts from.+ */+ private fun resolveEuiccTarget(): EuiccTarget {+ val cards: List<UiccCardInfo> = try {+ telephony.uiccCardsInfo+ } catch (e: SecurityException) {+ throw EuiccException("cannot read UICC card info - missing privileged permission: $e")+ }++ val euicc = cards.firstOrNull { it.isEuicc }+ ?: throw EuiccException("no eUICC found (${cards.size} UICC card(s) reported)")++ // Port 0 on a card that reports none: a non-MEP eUICC has exactly one implicit port.+ val port: UiccPortInfo? = euicc.ports.firstOrNull()+ val slotIndex = @Suppress("DEPRECATION") euicc.physicalSlotIndex+ if (slotIndex < 0) throw EuiccException("eUICC reports no physical slot index")++ val resolved = EuiccTarget(slotIndex, port?.portIndex ?: 0)+ Log.i(TAG, "eUICC at slot ${resolved.slotIndex} port ${resolved.portIndex}")+ return resolved+ }+ /**- * Opens the ISD-R channel, installs it as [EuiccNative.activeChannel] for the- * duration of [block] (so native ops can transmit), and closes it afterward.+ * Opens the ISD-R channel, installs it as [EuiccNative.activeChannel] for the duration of+ * [block] (so native ops can transmit), and closes it afterward. */ @Synchronized- @Suppress("DEPRECATION") fun <T> withIsdrChannel(block: () -> T): T {- val response: IccOpenLogicalChannelResponse =- telephony.iccOpenLogicalChannel(ISDR_AID, /* p2 = */ 0)+ val response = openChannelByPort(target, ISDR_AID)+ ?: throw EuiccException("telephony returned no response opening ISD-R") if (response.status != IccOpenLogicalChannelResponse.STATUS_NO_ERROR) { throw EuiccException("cannot open ISD-R channel (status=${response.status})") }@@ -44,16 +92,15 @@ class EuiccChannelManager(context: Context) { block() } finally { EuiccNative.activeChannel = null- runCatching { telephony.iccCloseLogicalChannel(channel) }+ runCatching { closeChannelByPort(target, channel) } } } /**- * Transmits one command APDU on [channel] using the field-based telephony- * API, following `61xx`/`6Cxx` chaining, and returns the full response- * (response data followed by the two status bytes).+ * Transmits one command APDU on [channel] using the field-based telephony API, following+ * `61xx`/`6Cxx` chaining, and returns the full response (response data followed by the two+ * status bytes). */- @Suppress("DEPRECATION") private fun transmit(channel: Int, command: ByteArray): ByteArray { require(command.size >= 4) { "APDU too short (${command.size} bytes)" } val cla = command[0].toInt() and 0xFF@@ -80,8 +127,7 @@ class EuiccChannelManager(context: Context) { } val out = StringBuilder()- var response = telephony- .iccTransmitApduLogicalChannel(channel, cla, ins, p1, p2, p3, dataHex).orEmpty()+ var response = transmitByPort(target, channel, cla, ins, p1, p2, p3, dataHex) while (response.length >= 4) { val body = response.substring(0, response.length - 4) val sw1 = response.substring(response.length - 4, response.length - 2).toInt(16)@@ -90,16 +136,12 @@ class EuiccChannelManager(context: Context) { 0x61 -> { // More data available: GET RESPONSE for sw2 bytes. out.append(body)- response = telephony- .iccTransmitApduLogicalChannel(channel, 0x00, 0xC0, 0x00, 0x00, sw2, "")- .orEmpty()+ response = transmitByPort(target, channel, 0x00, 0xC0, 0x00, 0x00, sw2, "") } 0x6C -> { // Wrong Le: resend the original command with Le = sw2. out.setLength(0)- response = telephony- .iccTransmitApduLogicalChannel(channel, cla, ins, p1, p2, sw2, dataHex)- .orEmpty()+ response = transmitByPort(target, channel, cla, ins, p1, p2, sw2, dataHex) } else -> { out.append(body)@@ -111,9 +153,69 @@ class EuiccChannelManager(context: Context) { return out.toString().hexToBytes() } + private fun openChannelByPort(t: EuiccTarget, aid: String): IccOpenLogicalChannelResponse? =+ invoke(OPEN, t.slotIndex, t.portIndex, aid, 0) as IccOpenLogicalChannelResponse?++ private fun transmitByPort(+ t: EuiccTarget, channel: Int, cla: Int, ins: Int, p1: Int, p2: Int, p3: Int, data: String,+ ): String = invoke(+ TRANSMIT, t.slotIndex, t.portIndex, channel, cla, ins, p1, p2, p3, data,+ ) as String? ?: ""++ private fun closeChannelByPort(t: EuiccTarget, channel: Int) {+ invoke(CLOSE, t.slotIndex, t.portIndex, channel)+ }++ /**+ * Unwraps InvocationTargetException so telephony's own error - the SecurityException when+ * this app is not the selected LPA, say - surfaces instead of a reflection wrapper.+ */+ private fun invoke(method: Method, vararg args: Any?): Any? = try {+ method.invoke(telephony, *args)+ } catch (e: java.lang.reflect.InvocationTargetException) {+ throw e.cause ?: EuiccException("${method.name} failed: $e")+ } catch (e: IllegalAccessException) {+ throw EuiccException("${method.name} is not accessible: $e")+ }+ companion object {+ private const val TAG = "EuiccChannelManager"+ /** ISD-R application identifier (SGP.22). */ const val ISDR_AID = "A0000005591010FFFFFFFF8900000100"++ private fun systemApi(name: String, vararg params: Class<*>): Method = try {+ TelephonyManager::class.java.getMethod(name, *params)+ } catch (e: NoSuchMethodException) {+ throw EuiccException("TelephonyManager.$name missing on this build: $e")+ }++ private val OPEN: Method by lazy {+ systemApi(+ "iccOpenLogicalChannelByPort",+ Int::class.javaPrimitiveType!!, Int::class.javaPrimitiveType!!,+ String::class.java, Int::class.javaPrimitiveType!!,+ )+ }++ private val TRANSMIT: Method by lazy {+ systemApi(+ "iccTransmitApduLogicalChannelByPort",+ Int::class.javaPrimitiveType!!, Int::class.javaPrimitiveType!!,+ Int::class.javaPrimitiveType!!, Int::class.javaPrimitiveType!!,+ Int::class.javaPrimitiveType!!, Int::class.javaPrimitiveType!!,+ Int::class.javaPrimitiveType!!, Int::class.javaPrimitiveType!!,+ String::class.java,+ )+ }++ private val CLOSE: Method by lazy {+ systemApi(+ "iccCloseLogicalChannelByPort",+ Int::class.javaPrimitiveType!!, Int::class.javaPrimitiveType!!,+ Int::class.javaPrimitiveType!!,+ )+ } } }
euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.ktnew file mode 100644index 0000000000..fe6a4ea6e9--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/ActivationCodeScreen.kt@@ -0,0 +1,66 @@+package com.vayunmathur.euicc.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.Route+import com.vayunmathur.library.ui.IconSim+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.SetupAction+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack++/**+ * Manual activation-code entry, for when there is no QR code to point a camera at.+ *+ * The code is only sanity-checked, not parsed: an SGP.22 activation code is+ * `LPA:1$<smdp>$<matchingId>`, and the native core does the real parsing. Rejecting+ * anything more aggressively here risks turning a working code into an unexplained+ * refusal.+ */+@Composable+fun ActivationCodeScreen(backStack: NavBackStack<Route>) {+ var code by remember { mutableStateOf("") }+ val trimmed = code.trim()++ SetupScaffold(+ title = stringResource(R.string.activation_code_title),+ subtitle = stringResource(R.string.activation_code_text),+ icon = { IconSim() },+ backStack = backStack,+ primaryAction = SetupAction(+ label = stringResource(R.string.continue_button),+ onClick = { backStack.add(Route.Download(trimmed)) },+ enabled = looksLikeActivationCode(trimmed),+ ),+ secondaryAction = SetupAction(+ label = stringResource(R.string.activation_code_scan_button),+ onClick = { backStack.add(Route.ScanQr) },+ ),+ scrollBehavior = appBarScrollBehavior(),+ ) {+ OutlinedTextField(+ value = code,+ onValueChange = { code = it },+ label = { Text(stringResource(R.string.activation_code_label)) },+ supportingText = { Text(stringResource(R.string.activation_code_hint)) },+ singleLine = true,+ modifier = Modifier.fillMaxWidth(),+ )+ }+}++/**+ * Whether [code] is worth handing to the native parser. Mirrors the scanner's check so a+ * typed code and a scanned one are held to the same standard.+ */+private fun looksLikeActivationCode(code: String): Boolean =+ code.startsWith("LPA:", ignoreCase = true) || code.contains('$')
euicc/src/main/java/com/vayunmathur/euicc/ui/AddSimScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/AddSimScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/AddSimScreen.ktnew file mode 100644index 0000000000..41f38e9e32--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/AddSimScreen.kt@@ -0,0 +1,37 @@+package com.vayunmathur.euicc.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.Route+import com.vayunmathur.library.ui.IconSim+import com.vayunmathur.library.ui.SetupAction+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack++/**+ * How the user wants to add a SIM.+ *+ * The platform LPA splits this across an intro screen and a type picker, because it also+ * has carrier-app and device-transfer entry paths to offer. With only two ways in, a+ * second screen would be a page the user taps through without reading.+ */+@Composable+fun AddSimScreen(backStack: NavBackStack<Route>) {+ SetupScaffold(+ title = stringResource(R.string.add_profile_title),+ subtitle = stringResource(R.string.add_sim_body),+ icon = { IconSim() },+ backStack = backStack,+ primaryAction = SetupAction(+ label = stringResource(R.string.scan_qr_button),+ onClick = { backStack.add(Route.ScanQr) },+ ),+ secondaryAction = SetupAction(+ label = stringResource(R.string.enter_code_button),+ onClick = { backStack.add(Route.ActivationCode) },+ ),+ scrollBehavior = appBarScrollBehavior(),+ )+}
euicc/src/main/java/com/vayunmathur/euicc/ui/DeviceInfoScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/DeviceInfoScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/DeviceInfoScreen.ktnew file mode 100644index 0000000000..3eeac0ae4d--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/DeviceInfoScreen.kt@@ -0,0 +1,76 @@+package com.vayunmathur.euicc.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.Route+import com.vayunmathur.euicc.platform.EuiccScreenState+import com.vayunmathur.euicc.ui.dialogs.EidDialog+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack++/**+ * The eUICC's own identity - EID and SGP.22 version - plus any notifications it is still+ * holding.+ *+ * Notifications live here rather than on the home screen because they are a protocol+ * detail: the eUICC queues one per install/enable/disable/delete for delivery back to the+ * SM-DP+, and a user reading a list of their SIMs has no use for them. They are surfaced+ * at all because a stuck notification is worth being able to see and clear.+ */+@Composable+fun DeviceInfoScreen(state: EuiccScreenState, backStack: NavBackStack<Route>, onRemoveNotification: (Int) -> Unit) {+ var showEidQr by remember { mutableStateOf(false) }+ val eid = state.eid++ DetailScaffold(+ title = stringResource(R.string.device_info_title),+ backStack = backStack,+ scrollBehavior = appBarScrollBehavior(),+ ) {+ SettingsSection(title = stringResource(R.string.euicc_info_title)) {+ SettingsRow(+ title = stringResource(R.string.eid_number),+ supportingText = eid ?: stringResource(R.string.eid_not_found),+ enabled = eid != null,+ onClick = if (eid != null) ({ showEidQr = true }) else null,+ )+ SettingsRow(+ title = stringResource(R.string.sgp22_version),+ supportingText = state.info?.svn?.ifEmpty { null }+ ?: stringResource(R.string.unknown),+ )+ }+ SettingsSection(title = stringResource(R.string.notifications_title)) {+ if (state.notifications.isEmpty()) {+ SettingsRow(title = stringResource(R.string.no_notifications), enabled = false)+ } else {+ for (note in state.notifications) {+ SettingsRow(+ title = "#${note.seqNumber} \u00b7 ${note.operation}",+ supportingText = note.address,+ trailingContent = {+ TextButton(+ onClick = { onRemoveNotification(note.seqNumber) },+ enabled = !state.loading,+ ) { Text(stringResource(R.string.remove)) }+ },+ )+ }+ }+ }+ }++ if (showEidQr && eid != null) {+ EidDialog(eid = eid, onDismiss = { showEidQr = false })+ }+}
euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.ktnew file mode 100644index 0000000000..7c7cb2248a--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/DownloadScreen.kt@@ -0,0 +1,82 @@+package com.vayunmathur.euicc.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.activity.compose.BackHandler+import com.vayunmathur.euicc.Route+import com.vayunmathur.euicc.platform.DownloadState+import com.vayunmathur.euicc.ui.download.CompleteContent+import com.vayunmathur.euicc.ui.download.ConfirmCarrierContent+import com.vayunmathur.euicc.ui.download.ConfirmationCodeContent+import com.vayunmathur.euicc.ui.download.FailedContent+import com.vayunmathur.euicc.ui.download.InstallingContent+import com.vayunmathur.library.ui.SwappedContent+import com.vayunmathur.library.util.NavBackStack++/**+ * The download, from authentication to installed profile.+ *+ * Every phase lives on this one destination rather than on its own route, because they are+ * steps of a single eUICC session: going "back" from installing to the carrier+ * confirmation would leave the session running with nothing driving it. Back is suppressed+ * outright while the eUICC is being written to, which is the one point where interrupting+ * can leave a half-installed profile behind.+ */+@Composable+fun DownloadScreen(+ activationCode: String,+ state: DownloadState,+ backStack: NavBackStack<Route>,+ onStart: (String) -> Unit,+ onDone: () -> Unit,+) {+ LaunchedEffect(activationCode) {+ if (state is DownloadState.Idle) onStart(activationCode)+ }++ val busy = state is DownloadState.Preparing || state is DownloadState.Installing+ BackHandler(enabled = busy) {+ // Deliberately empty: swallow back while the eUICC is mid-write.+ }++ SwappedContent(state) { current ->+ when (current) {+ is DownloadState.Idle, is DownloadState.Preparing ->+ InstallingContent(progress = null)++ is DownloadState.Confirm ->+ ConfirmCarrierContent(+ carrier = current.carrier,+ profileName = current.profileName,+ onConfirm = { onStart(activationCode) },+ onCancel = onDone,+ )++ is DownloadState.AwaitingConfirmationCode ->+ ConfirmationCodeContent(+ carrier = current.carrier,+ error = current.error,+ // The code is accepted by the UI but has nowhere to go until the native+ // core can resume a paused download with it; retrying the whole+ // activation code is the only thing that exists today.+ onSubmit = { onStart(activationCode) },+ onCancel = onDone,+ )++ is DownloadState.Installing -> InstallingContent(progress = current.progress)++ is DownloadState.Complete ->+ CompleteContent(+ carrier = current.carrier,+ onDone = onDone,+ )++ is DownloadState.Failed ->+ FailedContent(+ message = current.message,+ onRetry = { onStart(activationCode) },+ onCancel = onDone,+ )+ }+ }+}
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.ktdeleted file mode 100644index e6de3ecc4f..0000000000--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt+++ /dev/null@@ -1,9 +0,0 @@-package com.vayunmathur.euicc.ui--import androidx.compose.runtime.Composable-import com.vayunmathur.euicc.platform.EuiccViewModel--@Composable-fun EuiccApp(viewModel: EuiccViewModel) {- EuiccScreen(viewModel = viewModel)-}
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.ktnew file mode 100644index 0000000000..7b13fb4e78--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.kt@@ -0,0 +1,118 @@+package com.vayunmathur.euicc.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.Route+import com.vayunmathur.euicc.data.Profile+import com.vayunmathur.euicc.platform.EuiccScreenState+import com.vayunmathur.library.ui.AppBarSize+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.IconSim+import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SetupAction+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack++/**+ * The profile list, and the screen Settings opens for "eSIM".+ *+ * Split into an enabled section and an "Available carriers" section the way the platform's+ * own LPA does, because on a phone the distinction is the whole point: exactly one profile+ * carries service at a time, and the rest are parked.+ *+ * With nothing installed the list would be two empty headings and an "Add SIM" row, so an+ * empty eUICC gets a [SetupScaffold] instead - which is what a new device actually shows.+ */+@Composable+fun EuiccHomeScreen(+ state: EuiccScreenState,+ backStack: NavBackStack<Route>,+ onReload: () -> Unit,+ onAddSim: () -> Unit,+) {+ val enabled = state.profiles.filter { it.isEnabled }+ val disabled = state.profiles.filterNot { it.isEnabled }++ if (state.profiles.isEmpty() && !state.loading && state.error == null) {+ SetupScaffold(+ title = stringResource(R.string.no_profiles_title),+ subtitle = stringResource(R.string.no_profiles_body),+ icon = { IconSim() },+ primaryAction = SetupAction(stringResource(R.string.add_profile_title), onAddSim),+ scrollBehavior = appBarScrollBehavior(),+ )+ return+ }++ AppScaffold(+ title = stringResource(R.string.app_name),+ size = AppBarSize.LargeFlexible,+ actions = {+ IconButton(onClick = onAddSim, enabled = !state.loading) { IconAdd() }+ IconButton(onClick = onReload, enabled = !state.loading) { IconRefresh() }+ },+ scrollBehavior = appBarScrollBehavior(AppBarSize.LargeFlexible),+ ) { pad ->+ Column(+ modifier = Modifier.fillMaxWidth().padding(pad),+ verticalArrangement = Arrangement.spacedBy(Spacing.sm),+ ) {+ if (state.loading) LinearProgressIndicator(modifier = Modifier.fillMaxWidth())+ state.error?.let {+ Text(+ it,+ color = MaterialTheme.colorScheme.error,+ modifier = Modifier.padding(horizontal = Spacing.lg, vertical = Spacing.sm),+ )+ }+ if (enabled.isNotEmpty()) {+ SettingsSection(title = stringResource(R.string.esim_enabled)) {+ for (profile in enabled) ProfileRow(profile, backStack)+ }+ }+ if (disabled.isNotEmpty()) {+ SettingsSection(title = stringResource(R.string.available_carriers)) {+ for (profile in disabled) ProfileRow(profile, backStack)+ }+ }+ SettingsSection {+ SettingsRow(+ title = stringResource(R.string.add_profile_title),+ enabled = !state.loading,+ onClick = onAddSim,+ leadingContent = { IconAdd() },+ )+ SettingsRow(+ title = stringResource(R.string.device_info_title),+ supportingText = state.eid?.let { stringResource(R.string.show_details) },+ onClick = { backStack.add(Route.DeviceInfo) },+ )+ }+ }+ }+}++@Composable+private fun ProfileRow(profile: Profile, backStack: NavBackStack<Route>) {+ SettingsRow(+ title = profile.displayName,+ supportingText = profile.serviceProvider.ifBlank { profile.iccidDisplay },+ onClick = { backStack.add(Route.ProfileDetail(profile.iccid)) },+ leadingContent = { IconSim() },+ )+}
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccScreen.ktdeleted file mode 100644index 64ac4deba3..0000000000--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccScreen.kt+++ /dev/null@@ -1,93 +0,0 @@-package com.vayunmathur.euicc.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.euicc.data.EuiccInfo-import com.vayunmathur.euicc.data.Notification-import com.vayunmathur.euicc.data.Profile-import com.vayunmathur.euicc.platform.EuiccScreenState-import com.vayunmathur.euicc.platform.EuiccViewModel-import com.vayunmathur.euicc.ui.components.EuiccSection-import com.vayunmathur.euicc.ui.components.NotificationsSection-import com.vayunmathur.euicc.ui.components.ProfilesSection-import com.vayunmathur.euicc.ui.dialogs.DownloadDialog-import com.vayunmathur.euicc.ui.dialogs.RenameDialog-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.ConfirmDialog-import com.vayunmathur.library.ui.IconAdd-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconRefresh-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.appBarScrollBehavior--@Composable-fun EuiccScreen(viewModel: EuiccViewModel) {- EuiccScreen(- state = viewModel.state,- onReload = viewModel::reload,- onDownload = viewModel::downloadProfile,- onEnable = { viewModel.enable(it.iccid) },- onDisable = { viewModel.disable(it.iccid) },- onRename = { profile, name -> viewModel.rename(profile.iccid, name) },- onDelete = { viewModel.delete(it.iccid) },- onRemoveNotification = { viewModel.removeNotification(it.seqNumber) },- )-}--@Composable-fun EuiccScreen(- state: EuiccScreenState,- onReload: () -> Unit,- onDownload: (String) -> Unit,- onEnable: (Profile) -> Unit,- onDisable: (Profile) -> Unit,- onRename: (Profile, String) -> Unit,- onDelete: (Profile) -> Unit,- onRemoveNotification: (Notification) -> Unit,-) {- var renameTarget by remember { mutableStateOf<Profile?>(null) }- var deleteTarget by remember { mutableStateOf<Profile?>(null) }- var showDownload by remember { mutableStateOf(false) }- AppScaffold(- title = "EUICC",- actions = {- IconButton(onClick = { showDownload = true }, enabled = !state.loading) { IconAdd() }- IconButton(onClick = onReload, enabled = !state.loading) { IconRefresh() }- },- scrollBehavior = appBarScrollBehavior(),- ) { padding ->- Column(- modifier = Modifier.fillMaxWidth().padding(padding).padding(16.dp).verticalScroll(rememberScrollState()),- verticalArrangement = Arrangement.spacedBy(16.dp),- ) {- if (state.loading) CircularProgressIndicator()- state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }- state.message?.let { Text(it, color = MaterialTheme.colorScheme.primary) }- ProfilesSection(profiles = state.profiles, onEnable = onEnable, onDisable = onDisable, onRename = { renameTarget = it }, onDelete = { deleteTarget = it })- NotificationsSection(notifications = state.notifications, onRemove = onRemoveNotification)- EuiccSection(eid = state.eid, info = state.info)- }- }- renameTarget?.let { profile ->- RenameDialog(profile = profile, onConfirm = { name -> onRename(profile, name); renameTarget = null }, onDismiss = { renameTarget = null })- }- deleteTarget?.let { profile ->- ConfirmDialog(title = "Delete " + profile.displayName + "?", message = "This permanently removes the profile from the eUICC.", confirmLabel = "Delete", destructive = true, onConfirm = { onDelete(profile); deleteTarget = null }, onDismiss = { deleteTarget = null })- }- if (showDownload) {- DownloadDialog(onDownload = { onDownload(it); showDownload = false }, onDismiss = { showDownload = false })- }-}
euicc/src/main/java/com/vayunmathur/euicc/ui/ProfileDetailScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/ProfileDetailScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/ProfileDetailScreen.ktnew file mode 100644index 0000000000..d5fad1bc60--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/ProfileDetailScreen.kt@@ -0,0 +1,151 @@+package com.vayunmathur.euicc.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.Route+import com.vayunmathur.euicc.data.Profile+import com.vayunmathur.euicc.platform.EuiccScreenState+import com.vayunmathur.euicc.ui.dialogs.RenameDialog+import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack++/**+ * One profile: what it is, and the three things that can be done to it.+ *+ * Enable, disable and erase all go through a [ConfirmDialog] because each one drops the+ * device's connection - switching carriers is not undoable from a spinner. The wording is+ * the platform LPA's, so the consequence reads the same as it would on stock.+ *+ * The profile is looked up from [state] by ICCID on every recomposition rather than passed+ * in, so it stays current across the reload that follows each mutation. If the lookup+ * fails the profile was erased, and the screen pops itself.+ */+@Composable+fun ProfileDetailScreen(+ iccid: String,+ state: EuiccScreenState,+ backStack: NavBackStack<Route>,+ onEnable: (Profile) -> Unit,+ onDisable: (Profile) -> Unit,+ onErase: (Profile) -> Unit,+ onRename: (Profile, String) -> Unit,+) {+ val profile = state.profiles.firstOrNull { it.iccid == iccid }+ if (profile == null) {+ // Erased, or the eUICC was re-read and no longer reports it.+ if (!state.loading) backStack.pop()+ return+ }++ var confirmEnable by remember { mutableStateOf(false) }+ var confirmDisable by remember { mutableStateOf(false) }+ var confirmErase by remember { mutableStateOf(false) }+ var renaming by remember { mutableStateOf(false) }++ val label = profile.displayName+ val currentlyEnabled = state.profiles.firstOrNull { it.isEnabled }++ DetailScaffold(+ title = label,+ backStack = backStack,+ actions = {+ TextButton(onClick = { renaming = true }, enabled = !state.loading) {+ Text(stringResource(R.string.rename_profile_title))+ }+ },+ scrollBehavior = appBarScrollBehavior(),+ ) {+ SettingsSection {+ SettingsRow(+ title = stringResource(R.string.profile_status),+ supportingText = stringResource(+ if (profile.isEnabled) R.string.profile_status_enabled+ else R.string.profile_status_disabled,+ ),+ )+ if (profile.serviceProvider.isNotBlank()) {+ SettingsRow(+ title = stringResource(R.string.profile_provider),+ supportingText = profile.serviceProvider,+ )+ }+ SettingsRow(+ title = stringResource(R.string.profile_iccid),+ supportingText = profile.iccidDisplay,+ )+ }+ SettingsSection {+ if (profile.isEnabled) {+ SettingsRow(+ title = stringResource(R.string.disable_profile_title),+ enabled = !state.loading,+ onClick = { confirmDisable = true },+ )+ } else {+ SettingsRow(+ title = stringResource(R.string.enable_profile_title),+ enabled = !state.loading,+ onClick = { confirmEnable = true },+ )+ }+ SettingsRow(+ title = stringResource(R.string.erase_sim_confirm_button),+ enabled = !state.loading,+ onClick = { confirmErase = true },+ )+ }+ }++ if (confirmEnable) {+ ConfirmDialog(+ title = stringResource(R.string.enable_carrier_dialog_title),+ message = currentlyEnabled?.let {+ stringResource(R.string.enable_carrier_dialog_text, label, it.displayName)+ } ?: stringResource(R.string.enable_carrier_dialog_text_no_current, label),+ confirmLabel = stringResource(R.string.enable_profile_title),+ dismissLabel = stringResource(R.string.cancel),+ onConfirm = { onEnable(profile) },+ onDismiss = { confirmEnable = false },+ )+ }+ if (confirmDisable) {+ ConfirmDialog(+ title = stringResource(R.string.disable_carrier_dialog_title),+ message = stringResource(R.string.disable_carrier_dialog_text, label),+ confirmLabel = stringResource(R.string.disable_profile_title),+ dismissLabel = stringResource(R.string.cancel),+ destructive = true,+ onConfirm = { onDisable(profile) },+ onDismiss = { confirmDisable = false },+ )+ }+ if (confirmErase) {+ ConfirmDialog(+ title = stringResource(R.string.erase_sim_dialog_title, label),+ message = stringResource(R.string.erase_sim_dialog_text, label),+ confirmLabel = stringResource(R.string.erase_sim_confirm_button),+ dismissLabel = stringResource(R.string.cancel),+ destructive = true,+ onConfirm = { onErase(profile) },+ onDismiss = { confirmErase = false },+ )+ }+ if (renaming) {+ RenameDialog(+ profile = profile,+ onConfirm = { onRename(profile, it); renaming = false },+ onDismiss = { renaming = false },+ )+ }+}
euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.ktindex f28ccff212..384a6687d5 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.kt@@ -26,6 +26,8 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.core.content.ContextCompat@@ -70,11 +72,11 @@ fun QrScannerScreen(onResult: (String) -> Unit, onCancel: () -> Unit) { verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally, ) {- Text("Camera permission is required to scan a QR code.")+ Text(stringResource(R.string.camera_permission_required)) } } Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.BottomCenter) {- TextButton(onClick = onCancel) { Text("Cancel") }+ TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) } } } }
euicc/src/main/java/com/vayunmathur/euicc/ui/components/EuiccSection.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/components/EuiccSection.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/components/EuiccSection.ktdeleted file mode 100644index e63abaf647..0000000000--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/components/EuiccSection.kt+++ /dev/null@@ -1,18 +0,0 @@-package com.vayunmathur.euicc.ui.components--import androidx.compose.runtime.Composable-import com.vayunmathur.euicc.data.EuiccInfo-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text--@Composable-fun EuiccSection(eid: String?, info: EuiccInfo?) {- SectionCard(title = "eUICC") {- Text("EID", style = MaterialTheme.typography.labelMedium)- Text(eid ?: "unavailable")- if (info != null) {- Text("SGP.22 version", style = MaterialTheme.typography.labelMedium)- Text(info.svn.ifEmpty { "unknown" })- }- }-}
euicc/src/main/java/com/vayunmathur/euicc/ui/components/NotificationsSection.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/components/NotificationsSection.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/components/NotificationsSection.ktdeleted file mode 100644index 6dd3b49b95..0000000000--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/components/NotificationsSection.kt+++ /dev/null@@ -1,32 +0,0 @@-package com.vayunmathur.euicc.ui.components--import androidx.compose.runtime.Composable-import androidx.compose.ui.text.style.TextOverflow-import com.vayunmathur.euicc.data.Notification-import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton--@Composable-fun NotificationsSection(- notifications: List<Notification>,- onRemove: (Notification) -> Unit,-) {- SectionCard(title = "Notifications") {- if (notifications.isEmpty()) {- Text("No pending notifications.")- return@SectionCard- }- for (note in notifications) {- ListItem(- headlineContent = { Text("#" + note.seqNumber + " \u00b7 " + note.operation) },- supportingContent = {- Text(note.address, maxLines = 1, overflow = TextOverflow.Ellipsis)- },- trailingContent = {- TextButton(onClick = { onRemove(note) }) { Text("Remove") }- },- )- }- }-}
euicc/src/main/java/com/vayunmathur/euicc/ui/components/ProfilesSection.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/components/ProfilesSection.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/components/ProfilesSection.ktdeleted file mode 100644index 04b1ff08aa..0000000000--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/components/ProfilesSection.kt+++ /dev/null@@ -1,47 +0,0 @@-package com.vayunmathur.euicc.ui.components--import androidx.compose.runtime.Composable-import androidx.compose.ui.text.style.TextOverflow-import com.vayunmathur.euicc.data.Profile-import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.OverflowMenu-import com.vayunmathur.library.ui.Text--@Composable-fun ProfilesSection(- profiles: List<Profile>,- onEnable: (Profile) -> Unit,- onDisable: (Profile) -> Unit,- onRename: (Profile) -> Unit,- onDelete: (Profile) -> Unit,-) {- SectionCard(title = "Profiles") {- if (profiles.isEmpty()) {- Text("No profiles installed.")- return@SectionCard- }- for (profile in profiles) {- ListItem(- headlineContent = { Text(profile.displayName) },- supportingContent = {- Text(- (if (profile.isEnabled) "Enabled" else "Disabled") + " \u00b7 " + profile.iccidDisplay,- maxLines = 1,- overflow = TextOverflow.Ellipsis,- )- },- trailingContent = {- OverflowMenu {- if (profile.isEnabled) {- Item("Disable") { onDisable(profile) }- } else {- Item("Enable") { onEnable(profile) }- }- Item("Rename") { onRename(profile) }- Item("Delete") { onDelete(profile) }- }- },- )- }- }-}
euicc/src/main/java/com/vayunmathur/euicc/ui/components/SectionCard.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/components/SectionCard.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/components/SectionCard.ktdeleted file mode 100644index b04b8fd6fb..0000000000--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/components/SectionCard.kt+++ /dev/null@@ -1,29 +0,0 @@-package com.vayunmathur.euicc.ui.components--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.runtime.Composable-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text--@Composable-fun SectionCard(title: String, content: @Composable () -> Unit) {- Card(modifier = Modifier.fillMaxWidth()) {- Column(- modifier = Modifier.padding(16.dp).fillMaxWidth(),- verticalArrangement = Arrangement.spacedBy(4.dp),- ) {- Row(verticalAlignment = Alignment.CenterVertically) {- Text(title, style = MaterialTheme.typography.titleMedium)- }- content()- }- }-}
euicc/src/main/java/com/vayunmathur/euicc/ui/dialogs/DownloadDialog.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/dialogs/DownloadDialog.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/dialogs/DownloadDialog.ktdeleted file mode 100644index d20c5cb3df..0000000000--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/dialogs/DownloadDialog.kt+++ /dev/null@@ -1,49 +0,0 @@-package com.vayunmathur.euicc.ui.dialogs--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.unit.dp-import com.vayunmathur.euicc.ui.QrScannerScreen-import com.vayunmathur.library.ui.AlertDialog-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton--@Composable-fun DownloadDialog(onDownload: (String) -> Unit, onDismiss: () -> Unit) {- var code by remember { mutableStateOf("") }- var scanning by remember { mutableStateOf(false) }- if (scanning) {- QrScannerScreen(- onResult = { code = it; scanning = false },- onCancel = { scanning = false },- )- return- }- AlertDialog(- onDismissRequest = onDismiss,- title = { Text("Download profile") },- text = {- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- OutlinedTextField(- value = code,- onValueChange = { code = it },- label = { Text("Activation code") },- )- TextButton(onClick = { scanning = true }) { Text("Scan QR code") }- }- },- confirmButton = {- TextButton(- onClick = { if (code.isNotBlank()) onDownload(code.trim()) },- enabled = code.isNotBlank(),- ) { Text("Download") }- },- dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },- )-}
euicc/src/main/java/com/vayunmathur/euicc/ui/dialogs/EidDialog.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/dialogs/EidDialog.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/dialogs/EidDialog.ktnew file mode 100644index 0000000000..17b782142c--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/dialogs/EidDialog.kt@@ -0,0 +1,129 @@+package com.vayunmathur.euicc.ui.dialogs++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import com.google.zxing.BarcodeFormat+import com.google.zxing.EncodeHintType+import com.google.zxing.common.BitMatrix+import com.google.zxing.qrcode.QRCodeWriter+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel+import com.vayunmathur.euicc.R+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * Shows the eUICC's EID as both a QR code and readable digits, matching what the platform+ * LPA offers: carriers either scan it or ask the user to read it out.+ *+ * The digits are grouped in fours because a 32-character run is impossible to dictate or+ * check by eye.+ */+@Composable+fun EidDialog(eid: String, onDismiss: () -> Unit) {+ val context = LocalContext.current+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.eid_qr_code_dialog_title)) },+ text = {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(Spacing.lg),+ ) {+ EidQrCode(eid)+ Text(+ eid.chunked(4).joinToString(" "),+ style = MaterialTheme.typography.bodyMedium,+ textAlign = TextAlign.Center,+ )+ }+ },+ confirmButton = {+ TextButton(+ onClick = {+ ExternalIntents.copyToClipboard(context, eid, "EID")+ onDismiss()+ },+ ) { Text(stringResource(R.string.copy_action)) }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.done)) }+ },+ )+}++/**+ * Draws [eid] as a QR code.+ *+ * The matrix is rendered straight to a [Canvas] rather than through an intermediate+ * `Bitmap`, so it stays crisp at any size and needs no bitmap recycling. Encoding is+ * [remember]ed on the EID, which never changes for a device - it is a per-eUICC constant.+ */+@Composable+private fun EidQrCode(eid: String) {+ // ERROR_CORRECTION_M is what a printed-label-sized code wants: enough redundancy to+ // survive a mediocre camera without inflating the module count.+ val matrix: BitMatrix? = remember(eid) {+ runCatching {+ QRCodeWriter().encode(+ eid,+ BarcodeFormat.QR_CODE,+ QR_SIZE,+ QR_SIZE,+ mapOf(+ EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M,+ EncodeHintType.MARGIN to QR_QUIET_ZONE,+ ),+ )+ }.getOrNull()+ }+ if (matrix == null) return++ val foreground = MaterialTheme.colorScheme.onSurface+ Canvas(+ modifier = Modifier+ .fillMaxWidth(QR_WIDTH_FRACTION)+ .aspectRatio(1f),+ ) {+ val module = size.width / matrix.width+ for (x in 0 until matrix.width) {+ for (y in 0 until matrix.height) {+ if (!matrix.get(x, y)) continue+ drawRect(+ color = foreground,+ topLeft = Offset(x * module, y * module),+ // A hair over one module so neighbours meet without a seam from+ // fractional rounding.+ size = Size(module + 0.5f, module + 0.5f),+ )+ }+ }+ }+}++/**+ * Requested matrix size. ZXing rounds up to whatever the content needs, so this is a floor+ * rather than an exact module count; the Canvas scales whatever comes back.+ */+private const val QR_SIZE = 256++/** Quiet zone in modules. Four is the QR spec's minimum for reliable detection. */+private const val QR_QUIET_ZONE = 4++/** How much of the dialog's width the code occupies. */+private const val QR_WIDTH_FRACTION = 0.72f
euicc/src/main/java/com/vayunmathur/euicc/ui/download/CompleteContent.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/download/CompleteContent.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/CompleteContent.ktnew file mode 100644index 0000000000..a7e5367674--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/CompleteContent.kt@@ -0,0 +1,33 @@+package com.vayunmathur.euicc.ui.download++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.library.ui.IconCheckCircle+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SetupAction+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * The profile is installed but not enabled.+ *+ * The wording is the platform LPA's, and it is deliberately not a claim that the eSIM is+ * working: SGP.22 install and enable are separate operations, and enabling is the system's+ * decision because it is the thing that has to disconnect whatever is currently connected.+ */+@Composable+fun CompleteContent(carrier: String?, onDone: () -> Unit) {+ SetupScaffold(+ title = stringResource(R.string.download_complete_title),+ subtitle = stringResource(R.string.download_complete_text),+ icon = { IconCheckCircle() },+ primaryAction = SetupAction(stringResource(R.string.done), onDone),+ scrollBehavior = appBarScrollBehavior(),+ ) {+ if (carrier != null) {+ Text(carrier, style = MaterialTheme.typography.titleMedium)+ }+ }+}
euicc/src/main/java/com/vayunmathur/euicc/ui/download/ConfirmCarrierContent.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/download/ConfirmCarrierContent.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/ConfirmCarrierContent.ktnew file mode 100644index 0000000000..891a884c7e--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/ConfirmCarrierContent.kt@@ -0,0 +1,47 @@+package com.vayunmathur.euicc.ui.download++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.library.ui.IconSim+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SetupAction+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * "Confirm your network" - the SM-DP+ has said which profile the activation code resolves+ * to, and the user accepts it before anything is written to the eUICC.+ *+ * This is the last point where backing out costs nothing. Not reachable until the native+ * core parses ProfileMetadata out of the AuthenticateClient response; see+ * [com.vayunmathur.euicc.platform.DownloadState.Confirm].+ */+@Composable+fun ConfirmCarrierContent(+ carrier: String?,+ profileName: String?,+ onConfirm: () -> Unit,+ onCancel: () -> Unit,+) {+ SetupScaffold(+ title = stringResource(R.string.carrier_confirm_title),+ subtitle = stringResource(R.string.carrier_confirm_subtitle),+ icon = { IconSim() },+ primaryAction = SetupAction(stringResource(R.string.download_esim_button), onConfirm),+ secondaryAction = SetupAction(stringResource(R.string.cancel), onCancel),+ scrollBehavior = appBarScrollBehavior(),+ ) {+ if (carrier != null) {+ Text(carrier, style = MaterialTheme.typography.titleLarge)+ }+ if (profileName != null && profileName != carrier) {+ Text(+ profileName,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+}
euicc/src/main/java/com/vayunmathur/euicc/ui/download/ConfirmationCodeContent.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/download/ConfirmationCodeContent.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/ConfirmationCodeContent.ktnew file mode 100644index 0000000000..0f058053da--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/ConfirmationCodeContent.kt@@ -0,0 +1,62 @@+package com.vayunmathur.euicc.ui.download++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.library.ui.IconSim+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.SetupAction+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * Some profiles are confirmation-code protected: the carrier issues a second secret+ * alongside the activation code, and the eUICC refuses PrepareDownload without it.+ *+ * Not reachable until the native core threads the code into PrepareDownload - today it+ * always passes none, so such profiles simply fail. See+ * [com.vayunmathur.euicc.platform.DownloadState.AwaitingConfirmationCode].+ */+@Composable+fun ConfirmationCodeContent(+ carrier: String?,+ error: Boolean,+ onSubmit: (String) -> Unit,+ onCancel: () -> Unit,+) {+ var code by remember { mutableStateOf("") }+ SetupScaffold(+ title = stringResource(R.string.confirmation_code_title),+ subtitle = carrier?.let { stringResource(R.string.confirmation_code_text, it) }+ ?: stringResource(R.string.confirmation_code_text_no_carrier),+ icon = { IconSim() },+ primaryAction = SetupAction(+ label = stringResource(R.string.continue_button),+ onClick = { onSubmit(code.trim()) },+ enabled = code.isNotBlank(),+ ),+ secondaryAction = SetupAction(stringResource(R.string.cancel), onCancel),+ scrollBehavior = appBarScrollBehavior(),+ ) {+ OutlinedTextField(+ value = code,+ onValueChange = { code = it },+ label = { Text(stringResource(R.string.confirmation_code_label)) },+ isError = error,+ supportingText = if (error) {+ { Text(stringResource(R.string.confirmation_code_wrong)) }+ } else {+ null+ },+ singleLine = true,+ modifier = Modifier.fillMaxWidth(),+ )+ }+}
euicc/src/main/java/com/vayunmathur/euicc/ui/download/FailedContent.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/download/FailedContent.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/FailedContent.ktnew file mode 100644index 0000000000..12b2526f31--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/FailedContent.kt@@ -0,0 +1,29 @@+package com.vayunmathur.euicc.ui.download++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.library.ui.IconWarning+import com.vayunmathur.library.ui.SetupAction+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * The download failed.+ *+ * [message] is whatever the SM-DP+ or the native core said, shown in preference to the+ * generic line because it is usually the only clue about which of the many things in an+ * SGP.22 download went wrong - an expired activation code and a DNS failure are both just+ * "couldn't set up eSIM" otherwise.+ */+@Composable+fun FailedContent(message: String?, onRetry: () -> Unit, onCancel: () -> Unit) {+ SetupScaffold(+ title = stringResource(R.string.download_fail_dialog_title),+ subtitle = message ?: stringResource(R.string.download_fail_generic),+ icon = { IconWarning() },+ primaryAction = SetupAction(stringResource(R.string.try_again), onRetry),+ secondaryAction = SetupAction(stringResource(R.string.cancel), onCancel),+ scrollBehavior = appBarScrollBehavior(),+ )+}
euicc/src/main/java/com/vayunmathur/euicc/ui/download/InstallingContent.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/download/InstallingContent.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/InstallingContent.ktnew file mode 100644index 0000000000..c09fadf892--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/download/InstallingContent.kt@@ -0,0 +1,37 @@+package com.vayunmathur.euicc.ui.download++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.euicc.R+import com.vayunmathur.library.ui.IconSim+import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * The eUICC is being written to.+ *+ * No actions at all - not even cancel. Once the Bound Profile Package starts streaming+ * into the eUICC there is no safe way to stop it, and offering a button that cannot honour+ * what it promises is worse than offering none.+ *+ * [progress] is null until the native core reports segment progress, in which case the bar+ * is indeterminate.+ */+@Composable+fun InstallingContent(progress: Float?) {+ SetupScaffold(+ title = stringResource(R.string.installing_title),+ subtitle = stringResource(R.string.installing_text),+ icon = { IconSim() },+ scrollBehavior = appBarScrollBehavior(),+ ) {+ if (progress == null) {+ LinearProgressIndicator(modifier = Modifier.fillMaxWidth())+ } else {+ LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth())+ }+ }+}
euicc/src/main/res/values/strings.xml
diff --git a/euicc/src/main/res/values/strings.xml b/euicc/src/main/res/values/strings.xmlindex c77392a39c..8197e751f8 100644--- a/euicc/src/main/res/values/strings.xml+++ b/euicc/src/main/res/values/strings.xml@@ -1,7 +1,96 @@ <?xml version="1.0" encoding="utf-8"?>+<!--+ Wording follows Google's eSIM LPA (com.google.android.euicc) so a user arriving from+ Settings reads the same phrases MAOS replaced. Strings that exist there are copied+ verbatim; the rest describe behaviour it does not have.+--> <resources> <string name="app_name" translatable="false">EUICC</string>++ <!-- Home / profile list -->+ <string name="esim_enabled">eSIM enabled</string>+ <string name="available_carriers">Available carriers</string>+ <string name="add_profile_title">Add SIM</string>+ <string name="add_new_carrier">Add new carrier</string>+ <string name="show_details">Show details</string>+ <string name="no_profiles_title">Set up an eSIM</string>+ <string name="no_profiles_body">Add a SIM from your carrier to connect this device to a mobile network. You will need a QR code or an activation code.</string>+ <string name="no_euicc">No eUICC available on this device.</string>++ <!-- Profile status -->+ <string name="profile_status_enabled">Enabled</string>+ <string name="profile_status_disabled">Disabled</string>+ <string name="profile_iccid">ICCID</string>+ <string name="profile_status">Status</string>+ <string name="profile_provider">Provider</string>++ <!-- Profile actions -->+ <string name="enable_profile_title">Enable</string>+ <string name="disable_profile_title">Disable</string>+ <string name="erase_sim_confirm_button">Erase</string>+ <string name="rename_profile_title">Rename</string>++ <!-- Confirmations. %1$s is the carrier being switched to, %2$s the one being left. -->+ <string name="enable_carrier_dialog_title">Switch carrier?</string>+ <string name="enable_carrier_dialog_text">This device will connect to %1$s instead of %2$s.</string>+ <string name="enable_carrier_dialog_text_no_current">This device will connect to %1$s.</string>+ <string name="disable_carrier_dialog_title">Disable carrier?</string>+ <string name="disable_carrier_dialog_text">This device will be immediately disconnected from %1$s.</string>+ <string name="erase_sim_dialog_title">Erase %1$s?</string>+ <string name="erase_sim_dialog_text">This removes %1$s service on this device, but your %1$s plan won\'t be canceled.</string>++ <!-- Device info -->+ <string name="device_info_title">Device info</string> <string name="eid_title">EID</string>+ <string name="eid_number">EID number</string>+ <string name="eid_qr_code_dialog_title">Your device EID</string>+ <string name="eid_not_found">Device EID not found</string> <string name="euicc_info_title">eUICC info</string>- <string name="no_euicc">No eUICC available on this device.</string>+ <string name="sgp22_version">SGP.22 version</string>+ <string name="notifications_title">Pending notifications</string>+ <string name="no_notifications">No pending notifications</string>+ <string name="remove">Remove</string>+ <string name="copy_action">Copy</string>+ <string name="unknown">Unknown</string>++ <!-- Add SIM -->+ <string name="add_sim_body">Your carrier can give you a QR code, or an activation code to type in.</string>+ <string name="scan_qr_button">Scan QR code</string>+ <string name="activation_code_scan_button">Scan QR code instead</string>+ <string name="enter_code_button">Enter activation code</string>++ <!-- Activation code entry -->+ <string name="activation_code_title">Enter activation code</string>+ <string name="activation_code_text">You should have a code from your carrier. Enter it to connect to the network.</string>+ <string name="activation_code_hint">Look for a code from your carrier that starts with 1$ or LPA:1$</string>+ <string name="activation_code_label">Activation code</string>+ <string name="continue_button">Continue</string>+ <string name="cancel">Cancel</string>+ <string name="camera_permission_required">Camera permission is required to scan a QR code.</string>+ <string name="done">Done</string>+ <string name="try_again">Try again</string>++ <!-- Carrier confirmation -->+ <string name="carrier_confirm_title">Confirm your network</string>+ <string name="carrier_confirm_subtitle">You should already be signed up with the network</string>+ <string name="download_esim_button">Set up eSIM</string>++ <!-- Confirmation code -->+ <string name="confirmation_code_title">Enter confirmation code</string>+ <string name="confirmation_code_text">%1$s requires a confirmation code to set up this eSIM.</string>+ <string name="confirmation_code_text_no_carrier">Your carrier requires a confirmation code to set up this eSIM.</string>+ <string name="confirmation_code_label">Confirmation code</string>+ <string name="confirmation_code_wrong">That code was not accepted. Check it and try again.</string>++ <!-- Installing -->+ <string name="installing_title">Setting up your eSIM</string>+ <string name="installing_text">This can take a few minutes. Stay connected to the internet.</string>++ <!-- Complete -->+ <string name="download_complete_title">Activate your eSIM</string>+ <string name="download_complete_text">Go to Settings to turn on this eSIM</string>++ <!-- Failure -->+ <string name="download_fail_dialog_title">Couldn\'t set up eSIM</string>+ <string name="download_fail_generic">Something went wrong. Check your connection and your activation code, then try again.</string> </resources>
library/euicc-stubs/src/main/java/android/service/euicc/EuiccProfileInfo.java
diff --git a/library/euicc-stubs/src/main/java/android/telephony/euicc/EuiccProfileInfo.java b/library/euicc-stubs/src/main/java/android/service/euicc/EuiccProfileInfo.javasimilarity index 70%rename from library/euicc-stubs/src/main/java/android/telephony/euicc/EuiccProfileInfo.javarename to library/euicc-stubs/src/main/java/android/service/euicc/EuiccProfileInfo.javaindex d3b88da858..97bf8ea647 100644--- a/library/euicc-stubs/src/main/java/android/telephony/euicc/EuiccProfileInfo.java+++ b/library/euicc-stubs/src/main/java/android/service/euicc/EuiccProfileInfo.java@@ -1,9 +1,15 @@-package android.telephony.euicc;+package android.service.euicc; /** * Compile-only stub of the {@code @SystemApi}- * {@code android.telephony.euicc.EuiccProfileInfo}. Only the members the LPA+ * {@code android.service.euicc.EuiccProfileInfo}. Only the members the LPA * constructs are declared. Not packaged; the framework provides the real class.+ *+ * <p>Note the package: this class lives in {@code android.service.euicc}, unlike its+ * siblings {@code DownloadableSubscription} and {@code EuiccInfo} which really are in+ * {@code android.telephony.euicc}. Declaring the stub in the latter compiles, then fails+ * at runtime with {@code ClassNotFoundException} the first time the framework calls+ * {@code onGetEuiccProfileInfoList}. */ public final class EuiccProfileInfo { public static final int PROFILE_STATE_UNSET = -1;
library/euicc-stubs/src/main/java/android/service/euicc/GetEuiccProfileInfoListResult.java
diff --git a/library/euicc-stubs/src/main/java/android/service/euicc/GetEuiccProfileInfoListResult.java b/library/euicc-stubs/src/main/java/android/service/euicc/GetEuiccProfileInfoListResult.javaindex 4ed1588b18..1e8deec7e2 100644--- a/library/euicc-stubs/src/main/java/android/service/euicc/GetEuiccProfileInfoListResult.java+++ b/library/euicc-stubs/src/main/java/android/service/euicc/GetEuiccProfileInfoListResult.java@@ -1,7 +1,5 @@ package android.service.euicc; -import android.telephony.euicc.EuiccProfileInfo;- /** Compile-only stub of the {@code @SystemApi} ES10 profile-list result. */ public final class GetEuiccProfileInfoListResult { public GetEuiccProfileInfoListResult(int result, EuiccProfileInfo[] profiles, boolean isRemovable) {}
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 571f98c41a..b96c170aca 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -189,6 +189,8 @@ import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Mic import androidx.compose.material.icons.filled.MicOff import androidx.compose.material.icons.filled.MusicNote+import androidx.compose.material.icons.filled.QrCodeScanner+import androidx.compose.material.icons.filled.SimCard import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.MyLocation import androidx.compose.material.icons.filled.Navigation@@ -1388,8 +1390,18 @@ fun IconMine(modifier: Modifier = Modifier, tint: Color = LocalContentColor.curr AppIcon(Icons.Filled.Brightness7, "Mine", modifier, tint) // --- Music detection ---- /** A single quaver - music is playing. */ @Composable fun IconMusicNote(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.MusicNote, "Music", modifier, tint)++// --- eSIM ---+/** A SIM card - an eSIM profile, or the eUICC itself. */+@Composable+fun IconSim(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.SimCard, "SIM", modifier, tint)++/** A QR code in a viewfinder - scan an eSIM activation code. */+@Composable+fun IconQrCode(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.QrCodeScanner, "QR code", modifier, tint)
library/ui/src/main/java/com/vayunmathur/library/ui/SetupScaffold.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/SetupScaffold.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/SetupScaffold.ktnew file mode 100644index 0000000000..83faf8b187--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/SetupScaffold.kt@@ -0,0 +1,149 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey++/** A button in a [SetupScaffold]'s footer. */+data class SetupAction(+ val label: String,+ val onClick: () -> Unit,+ val enabled: Boolean = true,+)++/**+ * The scaffold for a setup step - one screen of a linear flow that explains itself and+ * offers one obvious way forward. Pairing an eSIM, granting a permission, finishing a+ * first run.+ *+ * [AppScaffold] and [DetailScaffold] both assume a titled bar over content the user came+ * looking for. A setup step is the opposite: the heading *is* the content, so the title+ * moves into the body at [displaySmall] with the bar left bare for the back button, and+ * the actions anchor to the bottom where a thumb already is.+ *+ * The proportions follow the platform's own setup screens (icon, large title, supporting+ * text, footer buttons) but the metrics are this repo's [Spacing] scale rather than+ * SetupDesign's, so a step sits next to the rest of an app instead of looking like it was+ * lifted out of another one.+ *+ * [primaryAction] is the way forward and renders filled; [secondaryAction] is the escape+ * hatch and renders as text. Pass neither for a screen the user cannot act on yet - a+ * progress step, say - and the footer disappears rather than showing a dead button.+ */+@Composable+fun SetupScaffold(+ title: String,+ modifier: Modifier = Modifier,+ subtitle: String? = null,+ icon: (@Composable () -> Unit)? = null,+ onNavigateBack: (() -> Unit)? = null,+ onClose: (() -> Unit)? = null,+ primaryAction: SetupAction? = null,+ secondaryAction: SetupAction? = null,+ scrollBehavior: TopAppBarScrollBehavior,+ content: @Composable ColumnScope.() -> Unit = {},+) = AppScaffold(+ title = "",+ modifier = modifier,+ onNavigateBack = onNavigateBack,+ onClose = onClose,+ scrollBehavior = scrollBehavior,+ bottomBar = { SetupFooter(primaryAction, secondaryAction) },+) { pad ->+ SetupColumn(pad, title, subtitle, icon, content)+}++/** [SetupScaffold] for a screen that owns a back stack, wiring the back button to it. */+@Composable+fun <T : NavKey> SetupScaffold(+ title: String,+ backStack: NavBackStack<T>,+ modifier: Modifier = Modifier,+ subtitle: String? = null,+ icon: (@Composable () -> Unit)? = null,+ primaryAction: SetupAction? = null,+ secondaryAction: SetupAction? = null,+ scrollBehavior: TopAppBarScrollBehavior,+ content: @Composable ColumnScope.() -> Unit = {},+) = SetupScaffold(+ title = title,+ modifier = modifier,+ subtitle = subtitle,+ icon = icon,+ onNavigateBack = { backStack.pop() },+ primaryAction = primaryAction,+ secondaryAction = secondaryAction,+ scrollBehavior = scrollBehavior,+ content = content,+)++@Composable+private fun SetupColumn(+ pad: PaddingValues,+ title: String,+ subtitle: String?,+ icon: (@Composable () -> Unit)?,+ content: @Composable ColumnScope.() -> Unit,+) {+ Column(+ modifier = Modifier+ .fillMaxSize()+ .padding(pad)+ .padding(horizontal = paneContentMargin())+ .verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(Spacing.md),+ ) {+ if (icon != null) {+ Spacer(Modifier.padding(top = Spacing.sm))+ icon()+ }+ Text(title, style = MaterialTheme.typography.displaySmall)+ if (subtitle != null) {+ Text(+ subtitle,+ style = MaterialTheme.typography.bodyLarge,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ // The gap between the heading block and whatever the step actually asks for.+ Spacer(Modifier.padding(top = Spacing.sm))+ content()+ Spacer(Modifier.padding(bottom = Spacing.xl))+ }+}++@Composable+private fun SetupFooter(primary: SetupAction?, secondary: SetupAction?) {+ if (primary == null && secondary == null) return+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = paneContentMargin(), vertical = Spacing.md),+ horizontalArrangement = Arrangement.spacedBy(Spacing.sm, Alignment.End),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ if (secondary != null) {+ TextButton(onClick = secondary.onClick, enabled = secondary.enabled) {+ Text(secondary.label)+ }+ }+ if (primary != null) {+ Button(onClick = primary.onClick, enabled = primary.enabled) {+ Text(primary.label)+ }+ }+ }+}
scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rsindex e8bfc66d53..aea6a6a316 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs@@ -37,6 +37,8 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::process::ExitCode;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Mutex; fn main() -> ExitCode { let args: Vec<String> = std::env::args().collect();@@ -339,44 +341,81 @@ fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { let (mut kept, mut without_shape, mut deduped, mut fell_back) = (0usize, 0usize, 0usize, 0usize); let (mut shapes_read, mut merged) = (0usize, 0usize); - for spec in specs {- let feed = read_feed(spec)?;- kept += feed.routes_kept;- without_shape += feed.routes_without_shape;- shapes_read += feed.shapes_read;- let mut new = 0usize;- for line in feed.lines {- // Across feeds as well as within one, so an alignment published by both a city- // feed and the regional feed that merges it draws once.- //- // Keyed on the colour too, which the hash alone was not: two services running- // the same trac
Diff truncated.