contacts: make each SIM a virtual ContactAccount
- Commit
0373333038b4ac735611fe34298d04461c32bec6- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 19:39 UTC (3 months ago)
- Parents
45dd371
Each active SIM subscription becomes a normal ContactAccount (type com.vayunmathur.contacts.sim, name=subId) with display label SIM N - <Carrier> derived from SubscriptionInfo simSlotIndex + carrierName/displayName, fallback SIM N. SIM contacts are projected into the unified contacts flow as synthetic Contact objects (stable negative ids) backed by ICC ADN per subId; reads merge device + SIM in syncFromSystem, writes/deletes route by accountType to SimContactsDataSource vs ContactsContract. Each SIM appears in accounts Visible Accounts list and is hideable independently via hidden_accounts keyed by type|name. Remove parallel SIM path: delete SimContactsSection, SimContactsActions, ContactDraftTarget, separate _simContacts/simSearchResults/hasSim/simSubscriptions/defaultContactTarget flows, SimTargetChooser, sim slot picker, Settings SIM row + default SIM toggle, ContactDetails export-to-SIM. Update strings (keep sim_limited_fields_hint).
Diff
contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.ktindex c7f304c570..4ab3b8afed 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt@@ -25,6 +25,10 @@ data class SimContact( val subscriptionId: Int? = null ) +const val SIM_ACCOUNT_TYPE = "com.vayunmathur.contacts.sim"++fun isSimAccountType(type: String?): Boolean = type == SIM_ACCOUNT_TYPE+ object SimContactsDataSource { private const val TAG = "SimContacts"@@ -203,4 +207,151 @@ object SimContactsDataSource { getActiveSubscriptionIds(context).isNotEmpty() } catch (_: Exception) { false } }++ // --- Virtual SIM accounts ---++ data class SimSubscriptionInfo(+ val subscriptionId: Int,+ val slotIndex: Int,+ val displayName: String?,+ val carrierName: CharSequence?+ )++ /**+ * Returns one entry per active SIM subscription, with slot/carrier info.+ * Falls back to [getActiveSubscriptionIds]-based entries when SubscriptionInfo+ * read needs unavailable permission.+ */+ fun getSimSubscriptionInfos(context: Context): List<SimSubscriptionInfo> {+ return try {+ val subMgr = context.getSystemService(SubscriptionManager::class.java) ?: return emptyList()+ val list = try {+ subMgr.activeSubscriptionInfoList+ } catch (e: SecurityException) {+ Log.w(TAG, "No permission for activeSubscriptionInfoList", e)+ null+ } catch (e: Exception) {+ Log.w(TAG, "Failed to get active subscriptions (infos)", e)+ null+ } ?: return getActiveSubscriptionIds(context).mapIndexed { idx, sid ->+ SimSubscriptionInfo(sid, idx, null, null)+ }+ list.mapNotNull { info ->+ try {+ SimSubscriptionInfo(+ subscriptionId = info.subscriptionId,+ slotIndex = info.simSlotIndex,+ displayName = info.displayName?.toString(),+ carrierName = info.carrierName+ )+ } catch (_: Exception) {+ SimSubscriptionInfo(info.subscriptionId, 0, null, null)+ }+ }+ } catch (e: Exception) {+ Log.w(TAG, "getSimSubscriptionInfos failed", e)+ emptyList()+ }+ }++ fun getSimAccountDisplayLabel(info: SimSubscriptionInfo): String {+ val slotNum = if (info.slotIndex >= 0) info.slotIndex + 1 else 1+ val base = "SIM $slotNum"+ val carrier = info.carrierName?.toString()?.trim()?.takeIf { it.isNotEmpty() }+ ?: info.displayName?.trim()?.takeIf { it.isNotEmpty() && !it.equals(base, ignoreCase = true) }+ return if (carrier != null) "$base — $carrier" else base+ }++ /**+ * Stable virtual account name for a subscription — the subId string.+ * The display label is [getSimAccountDisplayLabel]; the stored account name+ * must be opaque and survive carrier renames, so we key on subId.+ */+ fun accountNameFor(info: SimSubscriptionInfo): String = info.subscriptionId.toString()++ /**+ * Account name for a raw SimContact. Falls back to subId string or empty.+ */+ fun accountNameForSimContact(sc: SimContact): String = sc.subscriptionId?.toString() ?: ""++ // ---- Projection into unified Contact model ----++ private const val SIM_SYNTHETIC_ID_BASE: Long = -1_000_000_000L++ /**+ * Deterministic stable negative id for a SIM-backed Contact so it never+ * collides with real RawContacts ids and survives remove+reinsert of+ * a different row before it in the cursor. Hash is on (subId|name|number|email).+ */+ fun syntheticIdFor(sc: SimContact): Long {+ val h = "${sc.subscriptionId}|${sc.name}|${sc.number}|${sc.emails}".hashCode()+ // Map signed int hash into a negative Long away from -1..-N used by AutoIncrement edge.+ return SIM_SYNTHETIC_ID_BASE - (h.toLong() and 0xFFFFFFFFL)+ }++ /**+ * Projects ICC ADN rows into synthetic [com.vayunmathur.contacts.data.Contact]+ * objects carrying accountType=SIM_ACCOUNT_TYPE and accountName=subId string.+ * Only name+phone+email survive on SIM; other details are defaulted/empty.+ */+ fun simContactsAsContacts(context: Context): List<com.vayunmathur.contacts.data.Contact> {+ val sims = listSimContacts(context)+ if (sims.isEmpty()) return emptyList()+ return sims.map { sc -> simContactToContact(sc) }+ }++ fun simContactToContact(sc: SimContact): com.vayunmathur.contacts.data.Contact {+ val syntheticId = syntheticIdFor(sc)+ val display = sc.name.trim()+ // Split on first space for given/family fallback; full value preserved via Name.value join.+ val first = display.substringBefore(" ").ifEmpty { display }+ val last = if (" " in display) display.substringAfter(" ") else ""+ // Even an unnamed SIM still has firstName/lastName split; Name.value is blank if both empty.+ val nameObj = com.vayunmathur.contacts.data.Name(0, "", first, "", last, "")+ val phones = if (sc.number.isNotBlank())+ listOf(com.vayunmathur.contacts.data.PhoneNumber(0, sc.number, android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE))+ else emptyList()+ val emails = sc.emails?.takeIf { it.isNotBlank() }?.let {+ listOf(com.vayunmathur.contacts.data.Email(0, it, android.provider.ContactsContract.CommonDataKinds.Email.TYPE_HOME))+ } ?: emptyList()+ val details = com.vayunmathur.contacts.data.ContactDetails(+ phoneNumbers = phones,+ emails = emails,+ addresses = emptyList(),+ dates = emptyList(),+ photos = emptyList(),+ names = listOf(nameObj),+ orgs = listOf(com.vayunmathur.contacts.data.Organization(0, "")),+ notes = listOf(com.vayunmathur.contacts.data.Note(0, "")),+ nicknames = listOf(com.vayunmathur.contacts.data.Nickname(0, "", android.provider.ContactsContract.CommonDataKinds.Nickname.TYPE_DEFAULT)),+ groups = emptyList()+ )+ return com.vayunmathur.contacts.data.Contact(+ id = syntheticId,+ accountType = SIM_ACCOUNT_TYPE,+ accountName = accountNameForSimContact(sc),+ isFavorite = false,+ details = details+ )+ }++ /**+ * Finds the SimContact backing a synthetic Contact (by match on synthetic id),+ * or by (name|number) scan when id was not produced by [syntheticIdFor].+ */+ fun findBackingSimContact(context: Context, contact: com.vayunmathur.contacts.data.Contact): SimContact? {+ if (!isSimAccountType(contact.accountType)) return null+ val all = listSimContacts(context)+ val byId = all.firstOrNull { syntheticIdFor(it) == contact.id }+ if (byId != null) return byId+ // Fallback: match on accountName (subId) + first phone + display name+ val subId = contact.accountName?.toIntOrNull()+ val phone = contact.details.phoneNumbers.firstOrNull()?.number?.trim() ?: ""+ val disp = contact.name.value.trim()+ return all.firstOrNull {+ (subId == null || it.subscriptionId == subId) &&+ (phone.isEmpty() || it.number.trim() == phone) &&+ (disp.isEmpty() || it.name.trim() == disp)+ } ?: all.firstOrNull { it.subscriptionId?.toString() == contact.accountName }+ } }
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.ktindex cbef29c1c3..50f40f50ee 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt@@ -122,7 +122,6 @@ fun ContactDetailsPage( val context = LocalContext.current val contactsList by viewModel.contacts.collectAsStateWithLifecycle() val contactFromFlow by remember { viewModel.getContactFlow(contactId) }.collectAsStateWithLifecycle(initialValue = null)- // Fall back to direct provider query if not in memory list yet (e.g., cold start via intent, or hidden account filter race) val contactFromProvider by produceState<Contact?>(initialValue = null, contactId, contactsList.size) { value = withContext(Dispatchers.IO) { viewModel.getContact(contactId) ?: com.vayunmathur.contacts.data.Contact.getContact(context, contactId)@@ -131,7 +130,6 @@ fun ContactDetailsPage( val contact = contactFromFlow ?: contactFromProvider if (contact == null) {- // Show loading while contacts list is still populating, only show "not found" once list is loaded if (contactsList.isEmpty()) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = androidx.compose.ui.Alignment.Center) { CircularProgressIndicator()@@ -144,8 +142,6 @@ fun ContactDetailsPage( return } - // Which messaging apps know this contact is a package-manager question, so it is- // resolved here rather than inside the screen. val platforms by produceState(ContactPlatforms(), contactId, contact.details) { value = withContext(Dispatchers.IO) { PackageUtils.getContactPlatforms(context, contactId) } }@@ -153,13 +149,9 @@ fun ContactDetailsPage( value = withContext(Dispatchers.IO) { PackageUtils.isGoogleMeetInstalled(context) } } val groups by viewModel.groups.collectAsStateWithLifecycle()- val hasSim by viewModel.hasSim.collectAsStateWithLifecycle() val scope = rememberCoroutineScope()- val messenger = rememberMessenger() val shareContactLabel = stringResource(R.string.share_contact)- val simExportSuccess = stringResource(R.string.sim_export_success)- val simExportFailed = stringResource(R.string.sim_export_failed) ContactDetailsScreen( state = ContactDetailsUiState(@@ -180,18 +172,12 @@ fun ContactDetailsPage( } }, showBackButton = showBackButton,- hasSim = hasSim,- onExportToSim = { c ->- viewModel.exportContactToSim(c) { ok ->- messenger.show(if (ok) simExportSuccess else simExportFailed)- }- }, ) } /** * The contact details page, with no dependency on the ViewModel so it can be rendered from- * a `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.+ * a `@Preview`. */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -199,8 +185,6 @@ fun ContactDetailsScreen( state: ContactDetailsUiState, actions: ContactsActions, showBackButton: Boolean = true,- hasSim: Boolean = false,- onExportToSim: ((Contact) -> Unit)? = null, ) { val context = LocalContext.current val contact = state.contact@@ -226,12 +210,6 @@ fun ContactDetailsScreen( }) { IconShare() }- OverflowMenu(icon = { IconMoreVert() }) {- Item(- text = stringResource(R.string.export_to_sim),- enabled = hasSim,- ) { onExportToSim?.invoke(contact) }- } IconButton(onClick = { actions.confirmDeleteContact(contact) }) { IconDelete() }@@ -679,11 +657,6 @@ fun DetailItem( onClick: (() -> Unit)? = null, dropdownContent: (@Composable () -> Unit)? = null, trailingDropdownContent: (@Composable () -> Unit)? = null,- /**- * Outer shape of the card. Pass [groupShape] when this item is part of a- * vertically stacked sibling group so corners between siblings are- * squared off while the group's outer corners stay rounded.- */ shape: androidx.compose.ui.graphics.Shape = RoundedCornerShape(16.dp), ) { val clipboard = LocalClipboard.current@@ -724,10 +697,6 @@ fun DetailItem( enum class CommunicationType { CALL, SMS } -/**- * Outer shape for a card that sits at a given [index] inside a vertically- * stacked sibling group of [size] items.- */ fun groupShape( index: Int, size: Int,
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.ktindex efa04202fa..0ea272121e 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt@@ -66,7 +66,6 @@ import com.vayunmathur.contacts.util.ContactSorting.groupKey import com.vayunmathur.contacts.util.ContactSorting.sortedLocale import com.vayunmathur.contacts.util.ContactViewModel import com.vayunmathur.contacts.util.ContactsActions-import com.vayunmathur.contacts.util.SimContactsActions import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext@@ -99,15 +98,12 @@ fun ContactList( LaunchedEffect(Unit) { viewModel.loadContacts() viewModel.loadAccounts()- viewModel.loadSimContacts() } val contacts by viewModel.contacts.collectAsStateWithLifecycle() val groups by viewModel.groups.collectAsStateWithLifecycle() val showAccountLabels by viewModel.showAccountLabels.collectAsStateWithLifecycle() val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()- val simContacts by viewModel.simSearchResults.collectAsStateWithLifecycle()- val hasSim by viewModel.hasSim.collectAsStateWithLifecycle() val last = backStack.last() @@ -123,8 +119,6 @@ fun ContactList( else -> null }, showAddButton = last !is Route.EditContact,- simContacts = simContacts,- hasSim = hasSim, ), actions = object : ContactsActions by viewModel { override fun openContact(contact: Contact) = onContactClick(contact)@@ -139,12 +133,6 @@ fun ContactList( shareContactsAsVcf(scope, context, contacts, filename, resources.getString(R.string.share_contact)) } },- simActions = object : SimContactsActions {- override fun importSimContact(simContact: com.vayunmathur.contacts.data.SimContact) { viewModel.importSimContact(simContact) }- override fun deleteSimContact(simContact: com.vayunmathur.contacts.data.SimContact) { viewModel.deleteSimContact(simContact) }- override fun importAllSimContacts() { viewModel.importAllSimContacts() }- override fun refreshSim() { viewModel.loadSimContacts() }- } ) } @@ -154,7 +142,7 @@ fun ContactList( */ @OptIn(ExperimentalMaterial3Api::class) @Composable-fun ContactListScreen(state: ContactListUiState, actions: ContactsActions, simActions: com.vayunmathur.contacts.util.SimContactsActions = com.vayunmathur.contacts.util.SimContactsActions.Noop) {+fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) { val contacts = state.contacts val selectedIds = remember { mutableStateListOf<Long>() } val isSelectionMode = selectedIds.isNotEmpty()@@ -199,14 +187,10 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions, simAc val selectedID = state.openContactId - // While the search bar has text, intercept back to clear it instead of- // popping the screen. Empty search → back propagates normally. androidx.activity.compose.BackHandler(enabled = state.searchQuery.isNotEmpty() && !isSelectionMode) { actions.setSearchQuery("") } - // When contacts are selected (selection mode), intercept back to unselect- // instead of closing the app. androidx.activity.compose.BackHandler(enabled = isSelectionMode) { selectedIds.clear() }@@ -246,12 +230,7 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions, simAc placeholder = stringResource(R.string.search_contacts), padding = PaddingValues(0.dp), modifier = Modifier- // Start non-focusable so the field doesn't grab- // focus (and raise the keyboard) on screen entry. .focusProperties { canFocus = isFocusableBySystem }- // Enable focus on the initial press, before the- // text field's own tap handling runs, without- // consuming the event so the tap still focuses it. .pointerInput(Unit) { awaitPointerEventScope { while (true) {@@ -260,7 +239,6 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions, simAc } } }- // Block automatic focus again once focus is lost. .onFocusChanged { focusState -> if (!focusState.isFocused) { isFocusableBySystem = false@@ -335,18 +313,6 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions, simAc } } }-- item(key = "sim-section") {- SimContactsSection(- simContacts = state.simContacts,- hasSim = state.hasSim,- onImportOne = { simActions.importSimContact(it) },- onDeleteOne = { simActions.deleteSimContact(it) },- onImportAll = { simActions.importAllSimContacts() },- onRefresh = { simActions.refreshSim() },- modifier = Modifier.padding(top = 8.dp)- )- } } } }@@ -463,7 +429,7 @@ fun FavoritesHeader(modifier: Modifier = Modifier) { fun LetterHeader(letter: Char, modifier: Modifier = Modifier) { Text( text = letter.toString(),- modifier = modifier.padding(vertical = 8.dp, horizontal = 4.dp), // Add slight horizontal padding+ modifier = modifier.padding(vertical = 8.dp, horizontal = 4.dp), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurfaceVariant@@ -483,15 +449,6 @@ fun getAvatarColor(id: Long): Color { return colors[index] } -/**- * Grouped-cards pattern: each row is its own rounded [Surface], but the- * corners that meet a sibling in the same group are flattened so the group- * reads as one section while remaining visually distinct cards. Mirrors what- * [DetailItem]+[groupShape] does on the contact details page.- *- * [row] should render a flat row (e.g. [ContactItem] with `embeddedInCard =- * true`) — the outer Surface handles the background and clipping.- */ @Composable fun GroupedContactSection( count: Int,@@ -519,7 +476,6 @@ fun ContactItem( showAccountLabels: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier,- /** Every group in the app; the row labels itself with the ones this contact is in. */ allGroups: List<ContactGroup> = emptyList(), decodePhoto: ((String) -> Bitmap?)? = null, onLongClick: (() -> Unit)? = null,@@ -557,10 +513,6 @@ fun ContactItem( embeddedInCard -> Color.Transparent else -> MaterialTheme.colorScheme.surfaceVariant }- // A plain Row/Column layout is used instead of Material3 ListItem- // because ListItem queries its children's baseline alignment lines,- // which throws a framework NPE when remeasured inside the Navigation3- // adaptive lookahead pass on configuration change (rotation). Row( modifier = itemModifier .fillMaxWidth()
contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.ktindex 83c0d1c194..a564cb3e46 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt@@ -36,7 +36,6 @@ import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FilledTonalButton-import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.FormDetailGroup import com.vayunmathur.library.ui.FormSection import com.vayunmathur.library.ui.IconButton@@ -83,6 +82,7 @@ import com.vayunmathur.contacts.data.Event import com.vayunmathur.contacts.data.GroupMembership import com.vayunmathur.contacts.data.PhoneNumber import com.vayunmathur.contacts.data.Photo+import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE import com.vayunmathur.contacts.data.formatDisplay import com.vayunmathur.contacts.util.ContactAccount import com.vayunmathur.contacts.util.ContactViewModel@@ -105,8 +105,6 @@ import kotlin.io.encoding.Base64 fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, editRoute: Route.EditContact, onExit: () -> Unit = { backStack.pop() }) { val contactId = editRoute.contactId val context = LocalContext.current- val hasSim by viewModel.hasSim.collectAsStateWithLifecycle()- val simSubs by viewModel.simSubscriptions.collectAsStateWithLifecycle() var saveError by remember { mutableStateOf<String?>(null) } var isSaving by remember { mutableStateOf(false) } @@ -119,6 +117,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, } val draft by viewModel.editDraft.collectAsStateWithLifecycle() val accounts by viewModel.accounts.collectAsStateWithLifecycle()+ val simLabels by viewModel.simAccountLabels.collectAsStateWithLifecycle() val isNewContact = contactId == null val pickMedia = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->@@ -129,6 +128,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, } val currentDraft = draft ?: return+ val isSimAccount = currentDraft.accountType == SIM_ACCOUNT_TYPE // Markdown note editor backed by the shared ODF editor; stored content stays markdown. val noteController = key(contactId) { com.vayunmathur.library.ui.rememberOdfMarkdownEditorController(initialMarkdown = currentDraft.noteContent) { content ->@@ -150,13 +150,6 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, actions = { Button(onClick = { if (isSaving) return@Button- // Validate duplicate behavior handled by editor- if (currentDraft.target == ContactViewModel.ContactDraftTarget.SIM) {- if (currentDraft.simName.isBlank() && currentDraft.simPhone.isBlank()) {- saveError = context.getString(R.string.sim_name_or_phone_required)- return@Button- }- } isSaving = true viewModel.saveEditDraft { ok, err -> isSaving = false@@ -169,7 +162,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, ) }, bottomBar = {- if (currentDraft.target == ContactViewModel.ContactDraftTarget.DEVICE && noteController.focused) {+ if (noteController.focused) { com.vayunmathur.library.ui.OdfMarkdownEditorToolbar(noteController) } }@@ -187,55 +180,30 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, Spacer(Modifier.height(8.dp)) } - // Storage target chooser (new contacts only, when SIM available)+ // Account chooser for new contacts (SIM accounts appear here as normal accounts) if (isNewContact) {- SimTargetChooser(- selected = currentDraft.target,- enabled = hasSim,- simSubscriptions = simSubs,- selectedSubId = currentDraft.simSubscriptionId,- onTargetChange = { t -> viewModel.updateEditDraft { it.copy(target = t) } },- onSubIdChange = { id -> viewModel.updateEditDraft { it.copy(simSubscriptionId = id) } }- )- Spacer(Modifier.height(12.dp))- // Account chooser only for Device target- if (currentDraft.target == ContactViewModel.ContactDraftTarget.DEVICE) {- AccountChooser(currentDraft.accountName, accounts) { name, type ->- viewModel.updateEditDraft { it.copy(accountName = name, accountType = type) }- viewModel.setLastSelectedAccount(name, type)- }- Spacer(Modifier.height(16.dp))+ AccountChooser(currentDraft.accountName, currentDraft.accountType, accounts, simLabels) { name, type ->+ viewModel.updateEditDraft { it.copy(accountName = name, accountType = type) }+ viewModel.setLastSelectedAccount(name, type) }- }-- // SIM mode: limited form only- if (currentDraft.target == ContactViewModel.ContactDraftTarget.SIM && isNewContact) {+ Spacer(Modifier.height(16.dp))+ if (isSimAccount) {+ Text(+ stringResource(R.string.sim_limited_fields_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.fillMaxWidth()+ )+ Spacer(Modifier.height(8.dp))+ }+ } else if (isSimAccount) { Text( stringResource(R.string.sim_limited_fields_hint), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.fillMaxWidth() )- FormSection {- LabeledTextField(- value = currentDraft.simName,- onValueChange = { v -> viewModel.updateEditDraft { it.copy(simName = v) } },- label = stringResource(R.string.sim_name),- )- LabeledTextField(- value = currentDraft.simPhone,- onValueChange = { v -> viewModel.updateEditDraft { it.copy(simPhone = v) } },- label = stringResource(R.string.sim_phone),- keyboardType = KeyboardType.Phone,- )- LabeledTextField(- value = currentDraft.simEmail,- onValueChange = { v -> viewModel.updateEditDraft { it.copy(simEmail = v) } },- label = stringResource(R.string.sim_email),- keyboardType = KeyboardType.Email,- )- }- return@Column+ Spacer(Modifier.height(8.dp)) } Spacer(Modifier.height(8.dp))@@ -421,14 +389,23 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, @Composable fun AccountChooser( accountName: String,+ accountType: String, accounts: List<ContactAccount>,+ simLabels: Map<String, String> = emptyMap(), onAccountChange: (String, String) -> Unit ) { var expanded by remember { mutableStateOf(false) } val onDevice = stringResource(R.string.on_device)+ val currentKey = "${accountType}|${accountName}"+ val displayValue = when {+ accountName.isEmpty() && accountType.isEmpty() -> onDevice+ simLabels.containsKey(currentKey) -> simLabels[currentKey]!!+ accountName.isNotEmpty() -> accountName+ else -> onDevice+ } Box(Modifier.fillMaxWidth()) { OutlinedTextField(- value = accountName.ifEmpty { onDevice },+ value = displayValue, onValueChange = {}, readOnly = true, label = { Text(stringResource(R.string.account)) },@@ -450,8 +427,10 @@ fun AccountChooser( ) } accounts.forEach { account ->+ val key = "${account.type}|${account.name}"+ val label = simLabels[key] ?: account.name.ifEmpty { onDevice } DropdownMenuItem(- text = { Text(stringResource(R.string.account_display_format, account.name.ifEmpty { onDevice }, account.type)) },+ text = { Text(if (simLabels.containsKey(key)) label else stringResource(R.string.account_display_format, label, account.type)) }, onClick = { onAccountChange(account.name, account.type) expanded = false@@ -703,65 +682,6 @@ private fun ColumnScope.GroupMembershipSection( } } -@OptIn(ExperimentalMaterial3Api::class)-@Composable-private fun SimTargetChooser(- selected: ContactViewModel.ContactDraftTarget,- enabled: Boolean,- simSubscriptions: List<Int>,- selectedSubId: Int?,- onTargetChange: (ContactViewModel.ContactDraftTarget) -> Unit,- onSubIdChange: (Int?) -> Unit-) {- Column(Modifier.fillMaxWidth()) {- Text(- stringResource(R.string.save_to),- style = MaterialTheme.typography.labelMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant- )- Spacer(Modifier.height(8.dp))- Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {- FilterChip(- selected = selected == ContactViewModel.ContactDraftTarget.DEVICE,- onClick = { onTargetChange(ContactViewModel.ContactDraftTarget.DEVICE) },- label = { Text(stringResource(R.string.device)) }- )- FilterChip(- selected = selected == ContactViewModel.ContactDraftTarget.SIM,- onClick = { if (enabled) onTargetChange(ContactViewModel.ContactDraftTarget.SIM) },- enabled = enabled,- label = { Text(stringResource(R.string.sim_card)) }- )- }- if (!enabled) {- Text(- stringResource(R.string.no_sim_available),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant- )- } else if (selected == ContactViewModel.ContactDraftTarget.SIM && simSubscriptions.size > 1) {- Spacer(Modifier.height(8.dp))- var expanded by remember { mutableStateOf(false) }- Box {- OutlinedTextField(- value = selectedSubId?.let { "SIM $it" } ?: "SIM ${simSubscriptions.first()}",- onValueChange = {},- readOnly = true,- label = { Text(stringResource(R.string.sim_slot)) },- trailingIcon = { IconButton(onClick = { expanded = true }) { IconArrowDropDown() } },- modifier = Modifier.fillMaxWidth()- )- DropdownMenu(expanded, { expanded = false }) {- simSubscriptions.forEach { sid ->- DropdownMenuItem(text = { Text("SIM $sid") }, onClick = { onSubIdChange(sid); expanded = false })- }- }- Box(Modifier.matchParentSize().clickable { expanded = true })- }- }- }-}- @Composable private fun AddPictureSection( photo: String?,@@ -778,7 +698,6 @@ private fun AddPictureSection( contentAlignment = Alignment.Center ) { if (photo != null) {- // Decode once via the VM cache, not on every recomposition. val bitmap = remember(photo) { viewModel.decodePhoto(photo) } if (bitmap != null) { Image(
contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.ktindex 995acf1265..c6e11cf17f 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt@@ -6,7 +6,6 @@ import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.clickable 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.height@@ -40,6 +39,7 @@ fun SettingsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>) { val hiddenAccounts by viewModel.hiddenAccounts.collectAsStateWithLifecycle() val isCalendarSyncEnabled by viewModel.isCalendarSyncEnabled.collectAsStateWithLifecycle() val contacts by viewModel.contacts.collectAsStateWithLifecycle()+ val simLabels by viewModel.simAccountLabels.collectAsStateWithLifecycle() val context = LocalContext.current val coroutineScope = rememberCoroutineScope()@@ -53,11 +53,6 @@ fun SettingsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>) { } } - val hasSim by viewModel.hasSim.collectAsStateWithLifecycle()- val simContacts by viewModel.simContacts.collectAsStateWithLifecycle()- val defaultTarget by viewModel.defaultContactTarget.collectAsStateWithLifecycle()- var simMessage by remember { mutableStateOf<String?>(null) }- val exportLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.CreateDocument("text/vcard"), onResult = { uri ->@@ -181,66 +176,6 @@ fun SettingsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>) { } ) HorizontalDivider()- // SIM import/export- ListItem(- content = { Text(stringResource(R.string.sim_contacts)) },- supportingContent = {- Text(- if (!hasSim) stringResource(R.string.no_sim_inserted)- else if (simContacts.isEmpty()) stringResource(R.string.no_sim_contacts)- else "${simContacts.size} " + stringResource(R.string.sim_contacts)- )- },- trailingContent = {- Row {- IconButton(onClick = { viewModel.loadSimContacts() }) { IconRefresh() }- IconButton(- enabled = hasSim && simContacts.isNotEmpty(),- onClick = {- viewModel.importAllSimContacts { count ->- simMessage = if (count > 0) context.getString(R.string.sim_import_success, count) else context.getString(R.string.sim_import_failed)- }- }- ) { IconDownload() }- }- }- )- if (simMessage != null) {- Text(simMessage!!, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(start = 16.dp, top = 4.dp))- }- HorizontalDivider()- }-- item {- Spacer(modifier = Modifier.height(16.dp))- Text(- text = stringResource(R.string.default_save_location),- style = MaterialTheme.typography.titleMedium,- fontWeight = FontWeight.Bold,- modifier = Modifier.padding(bottom = 8.dp)- )- SettingsSelectRow(- title = stringResource(R.string.default_save_location),- selected = defaultTarget,- options = listOf(ContactViewModel.ContactDraftTarget.DEVICE, ContactViewModel.ContactDraftTarget.SIM),- label = { target ->- when (target) {- ContactViewModel.ContactDraftTarget.DEVICE -> stringResource(R.string.device)- ContactViewModel.ContactDraftTarget.SIM -> stringResource(R.string.sim_card)- else -> target.name- }- },- onSelect = { target ->- if (target == ContactViewModel.ContactDraftTarget.SIM && !hasSim) return@SettingsSelectRow- viewModel.setDefaultContactTarget(target)- },- supportingText = stringResource(R.string.default_save_location_summary),- enabled = hasSim || defaultTarget == ContactViewModel.ContactDraftTarget.DEVICE,- )- if (!hasSim) {- Text(stringResource(R.string.no_sim_available), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))- }- HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) } item {@@ -253,15 +188,20 @@ fun SettingsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>) { ) } items(accounts, key = { "${it.type}|${it.name}" }) { account ->- val isVisible = account.name !in hiddenAccounts+ val key = "${account.type}|${account.name}"+ val legacyKey = account.name+ val isHidden = key in hiddenAccounts || legacyKey in hiddenAccounts+ val isVisible = !isHidden val onDevice = stringResource(R.string.on_device)+ val simLabel = simLabels[key]+ val displayName = simLabel ?: account.name.ifEmpty { onDevice } ListItem(- content = { Text(account.name.ifEmpty { onDevice }) },+ content = { Text(displayName) }, supportingContent = { Text(account.type) }, trailingContent = { Checkbox( checked = isVisible,- onCheckedChange = { viewModel.setAccountVisibility(account.name, it) }+ onCheckedChange = { viewModel.setAccountVisibility(account, it) } ) } )
contacts/src/main/java/com/vayunmathur/contacts/ui/SimContactsSection.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/SimContactsSection.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/SimContactsSection.ktdeleted file mode 100644index 31c5cd5e44..0000000000--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/SimContactsSection.kt+++ /dev/null@@ -1,133 +0,0 @@-package com.vayunmathur.contacts.ui--import androidx.compose.foundation.background-import androidx.compose.foundation.layout.*-import androidx.compose.foundation.shape.CircleShape-import androidx.compose.foundation.shape.RoundedCornerShape-import androidx.compose.runtime.*-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.clip-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.text.style.TextOverflow-import androidx.compose.ui.unit.dp-import com.vayunmathur.contacts.R-import com.vayunmathur.contacts.data.SimContact-import com.vayunmathur.library.ui.*--@Composable-fun SimContactsSection(- simContacts: List<SimContact>,- hasSim: Boolean,- onImportOne: (SimContact) -> Unit,- onDeleteOne: (SimContact) -> Unit,- onImportAll: () -> Unit,- onRefresh: () -> Unit,- modifier: Modifier = Modifier-) {- Column(modifier) {- Row(- Modifier.fillMaxWidth().padding(vertical = 8.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween- ) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {- // Use Sim-like icon: contacts + card- IconContacts(tint = MaterialTheme.colorScheme.onSurfaceVariant)- Text(- stringResource(R.string.sim_contacts),- style = MaterialTheme.typography.titleSmall,- fontWeight = FontWeight.Bold,- color = MaterialTheme.colorScheme.onSurfaceVariant- )- if (simContacts.isNotEmpty()) {- Surface(shape = CircleShape, color = MaterialTheme.colorScheme.primaryContainer) {- Text(- "${simContacts.size}",- style = MaterialTheme.typography.labelSmall,- modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)- )- }- }- }- Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {- if (simContacts.isNotEmpty()) {- TextButton(onClick = onImportAll) { Text(stringResource(R.string.import_all)) }- }- IconButton(onClick = onRefresh) { IconRefresh() }- }- }- if (!hasSim) {- Text(- stringResource(R.string.no_sim_inserted),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(bottom = 8.dp)- )- return- }- if (simContacts.isEmpty()) {- Text(- stringResource(R.string.no_sim_contacts),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(bottom = 8.dp)- )- return- }- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- simContacts.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.name.ifEmpty { it.number } }).forEachIndexed { index, sc ->- SimContactRow(- simContact = sc,- onImport = { onImportOne(sc) },- onDelete = { onDeleteOne(sc) },- shape = groupShape(index, simContacts.size)- )- }- }- }-}--@Composable-private fun SimContactRow(- simContact: SimContact,- onImport: () -> Unit,- onDelete: () -> Unit,- shape: androidx.compose.ui.graphics.Shape = RoundedCornerShape(16.dp)-) {- Surface(shape = shape, color = MaterialTheme.colorScheme.surfaceVariant, modifier = Modifier.fillMaxWidth()) {- Row(- Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Box(- Modifier.size(40.dp).clip(CircleShape).background(MaterialTheme.colorScheme.secondaryContainer),- contentAlignment = Alignment.Center- ) {- Text(- simContact.name.firstOrNull()?.uppercase() ?: simContact.number.firstOrNull()?.toString() ?: "#",- style = MaterialTheme.typography.titleMedium,- fontWeight = FontWeight.Bold,- color = MaterialTheme.colorScheme.onSecondaryContainer- )- }- Spacer(Modifier.width(12.dp))- Column(Modifier.weight(1f)) {- val title = simContact.name.ifEmpty { simContact.number.ifEmpty { stringResource(R.string.no_name) } }- Text(title, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)- if (simContact.number.isNotBlank()) {- Text(simContact.number, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)- }- if (!simContact.emails.isNullOrBlank()) {- Text(simContact.emails!!, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)- }- if (simContact.subscriptionId != null) {- Text("SIM ${simContact.subscriptionId}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary)- }- }- IconButton(onClick = onImport) { IconDownload() }- IconButton(onClick = onDelete) { IconDelete() }- }- }-}
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.ktindex 09788a7b28..35d036e015 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -32,8 +32,10 @@ import com.vayunmathur.contacts.data.Organization import com.vayunmathur.contacts.data.PhoneNumber import com.vayunmathur.contacts.data.Photo import com.vayunmathur.contacts.data.PrefillValue+import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE import com.vayunmathur.contacts.data.SimContact import com.vayunmathur.contacts.data.SimContactsDataSource+import com.vayunmathur.contacts.data.isSimAccountType import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.awaitClose@@ -71,7 +73,7 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) private val dataStore = DataStoreUtils.getInstance(application) // Provider-backed in-memory contact list (no local DB). Populated by- // syncFromSystem() from the system Contacts provider and refreshed via the+ // syncFromSystem() from the system Contacts provider + SIM ADN and refreshed via the // ContentObserver registered in init. private val _allContacts = MutableStateFlow<List<Contact>>(emptyList()) @@ -81,43 +83,27 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) val hiddenAccounts: StateFlow<Set<String>> = dataStore.stringSetFlow("hidden_accounts") .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet()) + private fun accountKey(type: String?, name: String?): String = "${type ?: ""}|${name ?: ""}"+ val contacts: StateFlow<List<com.vayunmathur.contacts.data.Contact>> = combine( _allContacts, _searchQuery, hiddenAccounts ) { all, query, hidden ->- filterBySearch(all.filter { it.accountName !in hidden }, query)- }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())-- // Where the draft should be persisted when saved via saveEditDraft.- enum class ContactDraftTarget { DEVICE, SIM }-- // ---- SIM contacts ----- private val _simContacts = MutableStateFlow<List<SimContact>>(emptyList())- val simContacts: StateFlow<List<SimContact>> = _simContacts.asStateFlow()-- private val _simSubscriptions = MutableStateFlow<List<Int>>(emptyList())- val simSubscriptions: StateFlow<List<Int>> = _simSubscriptions.asStateFlow()-- val hasSim: StateFlow<Boolean> = _simSubscriptions.map { it.isNotEmpty() }- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)-- val simSearchResults: StateFlow<List<SimContact>> = combine(_simContacts, _searchQuery) { all, query ->- val tokens = query.trim().lowercase().split(Regex("\\s+")).filter { it.isNotBlank() }- if (tokens.isEmpty()) return@combine all- all.filter { c ->- val hay = "${c.name} ${c.number} ${c.emails.orEmpty()}".lowercase()- tokens.all { hay.contains(it) }+ val filtered = all.filter { c ->+ val key = accountKey(c.accountType, c.accountName)+ // Support legacy hidden entries that stored only accountName+ key !in hidden && c.accountName !in hidden }+ filterBySearch(filtered, query) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) - val defaultContactTarget: StateFlow<ContactDraftTarget> = dataStore.stringFlow("default_contact_target")- .map { v -> if (v == "sim") ContactDraftTarget.SIM else ContactDraftTarget.DEVICE }- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ContactDraftTarget.DEVICE)+ // Virtual SIM account display labels: key is "type|name" -> "SIM N — Carrier"+ private val _simAccountLabels = MutableStateFlow<Map<String, String>>(emptyMap())+ val simAccountLabels: StateFlow<Map<String, String>> = _simAccountLabels.asStateFlow() - fun setDefaultContactTarget(target: ContactDraftTarget) {- viewModelScope.launch { dataStore.setString("default_contact_target", if (target == ContactDraftTarget.SIM) "sim" else "device") }- }+ fun simDisplayLabel(account: ContactAccount): String? = _simAccountLabels.value["${account.type}|${account.name}"]+ fun simDisplayLabelFor(type: String?, name: String?): String? = _simAccountLabels.value["${type ?: ""}|${name ?: ""}"] val groups: StateFlow<List<ContactGroup>> = callbackFlow { val resolver = getApplication<Application>().contentResolver@@ -192,7 +178,6 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) } loadAccounts() loadLastSelectedAccount()- loadSimContacts() } override fun setSearchQuery(query: String) {@@ -251,164 +236,86 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) private suspend fun syncFromSystem() = withContext(Dispatchers.IO) { try {- _allContacts.value = com.vayunmathur.contacts.data.Contact.getAllContacts(getApplication())+ val app = getApplication<Application>()+ val device = com.vayunmathur.contacts.data.Contact.getAllContacts(app)+ val sim = SimContactsDataSource.simContactsAsContacts(app)+ _allContacts.value = device + sim+ // Refresh SIM account labels for UI (type|name -> display)+ val infos = SimContactsDataSource.getSimSubscriptionInfos(app)+ val labels = infos.associate { info ->+ val acc = ContactAccount(SimContactsDataSource.accountNameFor(info), SIM_ACCOUNT_TYPE)+ "${acc.type}|${acc.name}" to SimContactsDataSource.getSimAccountDisplayLabel(info)+ }+ _simAccountLabels.value = labels+ // Also refresh the accounts list to include current SIM accounts (in case SIM inserted/removed)+ // Do it by launching loadAccounts() if needed; but we can update _accounts directly+ // to avoid double query. However loadAccounts() also merges DataStore saved accounts,+ // so we trigger it.+ // Use a direct call to avoid extra launch overhead: we are already on IO, but+ // loadAccounts() launches its own coroutine, so just trigger it.+ // To keep accounts in sync, launch a refresh:+ launch { loadAccountsInternal() } } catch (e: Exception) { Log.e("ContactViewModel", "Error loading contacts", e) } } - // ---- SIM helpers ----- fun loadSimContacts() {- viewModelScope.launch(Dispatchers.IO) {- try {- _simSubscriptions.value = SimContactsDataSource.getActiveSubscriptionIds(getApplication())- _simContacts.value = SimContactsDataSource.listSimContacts(getApplication())- } catch (e: Exception) {- Log.e("ContactViewModel", "Error loading SIM contacts", e)- _simContacts.value = emptyList()+ private suspend fun loadAccountsInternal() {+ val app = getApplication<Application>()+ val uri = ContactsContract.RawContacts.CONTENT_URI+ val projection = arrayOf(+ ContactsContract.RawContacts.ACCOUNT_NAME,+ ContactsContract.RawContacts.ACCOUNT_TYPE+ )+ val accountSet = mutableSetOf<ContactAccount>()+ try {+ val cursor = app.contentResolver.query(uri, projection, null, null, null)+ cursor?.use {+ while (it.moveToNext()) {+ val name = it.getString(0) ?: ""+ val type = it.getString(1) ?: ""+ accountSet.add(ContactAccount(name, type))+ } }+ } catch (e: Exception) {+ Log.e("ContactViewModel", "Error querying raw contacts for accounts", e) }- }-- fun insertSimContact(name: String, number: String, email: String? = null, subscriptionId: Int? = null, onResult: (Boolean) -> Unit = {}) {- viewModelScope.launch(Dispatchers.IO) {- val ok = SimContactsDataSource.insertSimContact(getApplication(), name, number, email, subscriptionId)- if (ok) {- _simContacts.value = SimContactsDataSource.listSimContacts(getApplication())+ val legacyAccounts = dataStore.getString("extra_accounts").orEmpty()+ if (legacyAccounts.isNotBlank()) {+ legacyAccounts.split(",").map { it.trim() }.filter { it.isNotEmpty() }.forEach {+ dataStore.addStringToSetIfAbsent("extra_accounts_set", it) }- withContext(Dispatchers.Main) { onResult(ok) }+ dataStore.setString("extra_accounts", "") }- }-- fun deleteSimContact(simContact: SimContact, onResult: (Boolean) -> Unit = {}) {- viewModelScope.launch(Dispatchers.IO) {- val ok = SimContactsDataSource.deleteSimContact(getApplication(), simContact)- if (ok) {- _simContacts.value = SimContactsDataSource.listSimContacts(getApplication())+ val savedAccounts = dataStore.stringSetFlow("extra_accounts_set").first().mapNotNull { entry ->+ val parts = entry.split("|")+ parts.firstOrNull()?.takeIf { it.isNotEmpty() }?.let { name ->+ ContactAccount(name, parts.getOrElse(1) { "com.vayunmathur.contacts.local" }) }- withContext(Dispatchers.Main) { onResult(ok) } }- }-- /**- * Import a SIM contact into device storage as a proper [Contact].- * Uses [accountName]/[accountType] if provided, otherwise uses last-selected or null.- */- fun importSimContact(simContact: SimContact, onDone: (Boolean) -> Unit = {}) {- val app = getApplication<Application>()- viewModelScope.launch(Dispatchers.IO) {- try {- val draftName = simContact.name.trim()- val first = draftName.substringBefore(" ").ifEmpty { draftName }- val last = if (draftName.contains(" ")) draftName.substringAfter(" ") else ""- val details = ContactDetails(- phoneNumbers = listOfNotNull(simContact.number.takeIf { it.isNotBlank() }?.let { PhoneNumber(0, it, CDKPhone.TYPE_MOBILE) }),- emails = listOfNotNull(simContact.emails?.takeIf { it.isNotBlank() }?.let { Email(0, it, CDKEmail.TYPE_HOME) }),- addresses = emptyList(),- dates = emptyList(),- photos = emptyList(),- names = listOf(Name(0, "", first, "", last, "")),- orgs = listOf(Organization(0, "")),- notes = listOf(Note(0, "")),- nicknames = listOf(Nickname(0, "", CDKNickname.TYPE_DEFAULT)),- groups = emptyList()- )- val lastAcc = _lastSelectedAccount.value- val contact = Contact(0, lastAcc?.type?.ifEmpty { null }, lastAcc?.name?.ifEmpty { null }, false, details)- contact.save(app, details, ContactDetails.empty())- withContext(Dispatchers.Main) { onDone(true) }- } catch (e: Exception) {- Log.e("ContactViewModel", "importSimContact failed", e)- withContext(Dispatchers.Main) { onDone(false) }- }+ // Virtual SIM accounts+ val simInfos = SimContactsDataSource.getSimSubscriptionInfos(app)+ val simAccounts = simInfos.map { info ->+ ContactAccount(SimContactsDataSource.accountNameFor(info), SIM_ACCOUNT_TYPE) }- }-- fun importAllSimContacts(onDone: (Int) -> Unit = {}) {- val snapshot = _simContacts.value.toList()- if (snapshot.isEmpty()) { onDone(0); return }- viewModelScope.launch(Dispatchers.IO) {- var imported = 0- val app = getApplication<Application>()- val lastAcc = _lastSelectedAccount.value- for (sim in snapshot) {- try {- val draftName = sim.name.trim()- val first = draftName.substringBefore(" ").ifEmpty { draftName }- val last = if (draftName.contains(" ")) draftName.substringAfter(" ") else ""- val details = ContactDetails(- phoneNumbers = listOfNotNull(sim.number.takeIf { it.isNotBlank() }?.let { PhoneNumber(0, it, CDKPhone.TYPE_MOBILE) }),- emails = listOfNotNull(sim.emails?.takeIf { it.isNotBlank() }?.let { Email(0, it, CDKEmail.TYPE_HOME) }),- addresses = emptyList(), dates = emptyList(), photos = emptyList(),- names = listOf(Name(0, "", first, "", last, "")),- orgs = listOf(Organization(0, "")), notes = listOf(Note(0, "")),- nicknames = listOf(Nickname(0, "", CDKNickname.TYPE_DEFAULT)), groups = emptyList()- )- Contact(0, lastAcc?.type?.ifEmpty { null }, lastAcc?.name?.ifEmpty { null }, false, details)- .save(app, details, ContactDetails.empty())- imported++- } catch (e: Exception) { Log.w("ContactViewModel", "import one SIM failed", e) }- }- withContext(Dispatchers.Main) { onDone(imported) }+ val simLabels = simInfos.associate { info ->+ val acc = ContactAccount(SimContactsDataSource.accountNameFor(info), SIM_ACCOUNT_TYPE)+ "${acc.type}|${acc.name}" to SimContactsDataSource.getSimAccountDisplayLabel(info) }- }+ _simAccountLabels.value = simLabels - fun exportContactToSim(contact: Contact, subscriptionId: Int? = null, onDone: (Boolean) -> Unit = {}) {- viewModelScope.launch(Dispatchers.IO) {- val name = contact.name.value.ifBlank { contact.nickname.nickname }.ifBlank { contact.details.phoneNumbers.firstOrNull()?.number ?: "" }- val number = contact.details.phoneNumbers.firstOrNull()?.number ?: ""- val email = contact.details.emails.firstOrNull()?.address- // SIM may have capacity limits — attempt insert as-is and report failure gracefully- val ok = if (number.isBlank() && name.isBlank()) false else SimContactsDataSource.insertSimContact(- getApplication(), name, number, email, subscriptionId ?: _simSubscriptions.value.firstOrNull()- )- if (ok) _simContacts.value = SimContactsDataSource.listSimContacts(getApplication())- withContext(Dispatchers.Main) { onDone(ok) }- }+ // Sort: SIM accounts by display label, others by name+ val all = (accountSet + savedAccounts + simAccounts).toList()+ val collator = ContactSorting.collator()+ _accounts.value = all.sortedWith(compareBy(collator) { acc ->+ if (acc.type == SIM_ACCOUNT_TYPE) _simAccountLabels.value["${acc.type}|${acc.name}"] ?: acc.name+ else acc.name+ }) } fun loadAccounts() { viewModelScope.launch(Dispatchers.IO) {- val app = getApplication<Application>()- val uri = ContactsContract.RawContacts.CONTENT_URI- val projection = arrayOf(- ContactsContract.RawContacts.ACCOUNT_NAME,- ContactsContract.RawContacts.ACCOUNT_TYPE- )- val accountSet = mutableSetOf<ContactAccount>()- try {- val cursor = app.contentResolver.query(uri, projection, null, null, null)- cursor?.use {- while (it.moveToNext()) {- val name = it.getString(0) ?: ""- val type = it.getString(1) ?: ""- accountSet.add(ContactAccount(name, type))- }- }- } catch (e: Exception) {- Log.e("ContactViewModel", "Error querying raw contacts for accounts", e)- }- // Also include any accounts from DataStore that might not have contacts yet.- // Stored as a string set of "name|type" entries to avoid the comma/pipe- // corruption of the previous single comma-joined string.- // Backward-compat: older builds stored these as a single comma-joined- // String under "extra_accounts". Reading that String through a string-set- // key throws, so migrate it once into the new set key, then blank the old one.- val legacyAccounts = dataStore.getString("extra_accounts").orEmpty()- if (legacyAccounts.isNotBlank()) {- legacyAccounts.split(",").map { it.trim() }.filter { it.isNotEmpty() }.forEach {- dataStore.addStringToSetIfAbsent("extra_accounts_set", it)- }- dataStore.setString("extra_accounts", "")- }- val savedAccounts = dataStore.stringSetFlow("extra_accounts_set").first().mapNotNull { entry ->- val parts = entry.split("|")- parts.firstOrNull()?.takeIf { it.isNotEmpty() }?.let { name ->- ContactAccount(name, parts.getOrElse(1) { "com.vayunmathur.contacts.local" })- }- }-- _accounts.value = (accountSet + savedAccounts).toList().sortedByNameLocale { it.name }+ loadAccountsInternal() } } @@ -426,11 +333,27 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) } } - fun setAccountVisibility(accountName: String, visible: Boolean) {+ fun setAccountVisibility(account: ContactAccount, visible: Boolean) {+ val key = "${account.type}|${account.name}" if (visible) {- dataStore.removeStringFromSet("hidden_accounts", accountName)+ dataStore.removeStringFromSet("hidden_accounts", key)+ // Also clear legacy entry if it exists (migration)+ dataStore.removeStringFromSet("hidden_accounts", account.name)+ } else {+ dataStore.addStringToSet("hidden_accounts", key)+ }+ }++ // Backward-compatible overload used by old call sites that only knew name+ fun setAccountVisibility(accountName: String, visible: Boolean) {+ // Try to resolve type from current accounts list+ val matched = _accounts.value.firstOrNull { it.name == accountName }+ if (matched != null) {+ setAccountVisibility(matched, visible) } else {- dataStore.addStringToSet("hidden_accounts", accountName)+ // Fallback: treat as legacy name-only key+ if (visible) dataStore.removeStringFromSet("hidden_accounts", accountName)+ else dataStore.addStringToSet("hidden_accounts", accountName) } } @@ -486,12 +409,27 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) viewModelScope.launch { withContext(Dispatchers.IO) { try {- contacts.forEach { contact ->- val toSave = contact.copy(- accountName = accountName,- accountType = accountType- )- toSave.save(app, toSave.details, ContactDetails.empty())+ // If target is a SIM account, route each contact via SIM data source+ if (isSimAccountType(accountType)) {+ val subId = accountName.toIntOrNull()+ contacts.forEach { contact ->+ val name = contact.name.value.trim().ifEmpty { contact.details.phoneNumbers.firstOrNull()?.number ?: "" }+ val number = contact.details.phoneNumbers.firstOrNull()?.number?.trim() ?: ""+ val email = contact.details.emails.firstOrNull()?.address?.trim()?.takeIf { it.isNotEmpty() }+ if (name.isNotBlank() || number.isNotBlank()) {+ SimContactsDataSource.insertSimContact(app, name, number, email, subId)+ }+ }+ // Refresh unified list+ withContext(Dispatchers.Main) { loadContacts() }+ } else {+ contacts.forEach { contact ->+ val toSave = contact.copy(+ accountName = accountName,+ accountType = accountType+ )+ toSave.save(app, toSave.details, ContactDetails.empty())+ } } } catch (e: Exception) { android.util.Log.e("ContactViewModel", "Error importing contacts", e)@@ -503,16 +441,24 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) } fun getContact(contactId: Long): Contact? {- return contacts.value.find { it.id == contactId }+ return contacts.value.find { it.id == contactId } ?: _allContacts.value.find { it.id == contactId } } override fun deleteContact(contact: com.vayunmathur.contacts.data.Contact) { viewModelScope.launch(Dispatchers.IO) {- com.vayunmathur.contacts.data.Contact.delete(getApplication(), contact)- if (isCalendarSyncEnabled.value) {- CalendarSyncHelper.syncContact(getApplication(), contact.copy(details = contact.details.copy(dates = emptyList())))+ if (isSimAccountType(contact.accountType)) {+ val sc = SimContactsDataSource.findBackingSimContact(getApplication(), contact)+ ?: SimContact(-1, contact.name.value, contact.details.phoneNumbers.firstOrNull()?.number ?: "", contact.details.emails.firstOrNull()?.address, contact.accountName?.toIntOrNull())+ val toDelete = if (sc.subscriptionId == null) sc.copy(subscriptionId = contact.accountName?.toIntOrNull()) else sc+ SimContactsDataSource.deleteSimContact(getApplication(), toDelete)+ syncFromSystem()+ } else {+ com.vayunmathur.contacts.data.Contact.delete(getApplication(), contact)+ if (isCalendarSyncEnabled.value) {+ CalendarSyncHelper.syncContact(getApplication(), contact.copy(details = contact.details.copy(dates = emptyList())))+ } }- // The system-contacts ContentObserver picks up the delete and re-syncs.+ // The system-contacts ContentObserver picks up device deletes and re-syncs; SIM path already synced. } } @@ -523,7 +469,6 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) val values = android.content.ContentValues().apply { put(ContactsContract.Groups.TITLE, name) put(ContactsContract.Groups.GROUP_VISIBLE, 1)- // Optionally add account info if needed } resolver.insert(ContactsContract.Groups.CONTENT_URI, values) }@@ -538,9 +483,15 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) fun addContactsToGroup(contactIds: List<Long>, groupId: Long) { viewModelScope.launch(Dispatchers.IO) {+ // Filter out SIM contacts (they don't support groups)+ val deviceIds = contactIds.filter { id ->+ val c = _allContacts.value.find { it.id == id }+ c == null || !isSimAccountType(c.accountType)+ }+ if (deviceIds.isEmpty()) return@launch val resolver = getApplication<Application>().contentResolver val ops = ArrayList<ContentProviderOperation>()- contactIds.forEach { contactId ->+ deviceIds.forEach { contactId -> ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValue(ContactsContract.Data.RAW_CONTACT_ID, contactId) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)@@ -573,26 +524,49 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) } fun getContactFlow(contactId: Long): Flow<Contact?> {- return contacts.map { contacts -> contacts.find { it.id == contactId } }+ return contacts.map { contacts -> contacts.find { it.id == contactId } ?: _allContacts.value.find { it.id == contactId } } } override fun saveContact(contact: com.vayunmathur.contacts.data.Contact) { viewModelScope.launch(Dispatchers.IO) {- val contactId = contact.id- val details = contact.details- val oldDetails = contacts.value.find { it.id == contactId }?.details ?: com.vayunmathur.contacts.data.ContactDetails.empty()- contact.save(getApplication(), details, oldDetails)- // The system-contacts ContentObserver picks up the write and re-syncs.+ if (isSimAccountType(contact.accountType)) {+ val subId = contact.accountName?.toIntOrNull()+ val name = contact.name.value.trim().ifEmpty { contact.nickname.nickname.trim().ifEmpty { contact.details.phoneNumbers.firstOrNull()?.number?.trim() ?: "" } }+ val number = contact.details.phoneNumbers.firstOrNull()?.number?.trim() ?: ""+ val email = contact.details.emails.firstOrNull()?.address?.trim()?.takeIf { it.isNotEmpty() }+ if (name.isBlank() && number.isBlank()) {+ Log.w("ContactViewModel", "SIM save skipped: name and number empty")+ return@launch+ }+ val isExisting = contact.id < 0+ var oldSc: SimContact? = null+ if (isExisting) {+ oldSc = SimContactsDataSource.listSimContacts(getApplication()).firstOrNull { SimContactsDataSource.syntheticIdFor(it) == contact.id }+ if (oldSc == null) oldSc = SimContactsDataSource.findBackingSimContact(getApplication(), contact)+ if (oldSc != null) {+ // Skip if no actual change+ if (oldSc.name == name && oldSc.number == number && oldSc.emails == email && oldSc.subscriptionId == subId) {+ return@launch+ }+ SimContactsDataSource.deleteSimContact(getApplication(), oldSc)+ }+ }+ val ok = SimContactsDataSource.insertSimContact(getApplication(), name, number, email, subId)+ if (!ok) Log.e("ContactViewModel", "Failed to insert SIM contact")+ syncFromSystem()+ } else {+ val contactId = contact.id+ val details = contact.details+ val oldDetails = contacts.value.find { it.id == contactId }?.details+ ?: _allContacts.value.find { it.id == contactId }?.details+ ?: com.vayunmathur.contacts.data.ContactDetails.empty()+ contact.save(getApplication(), details, oldDetails)+ } } } // --------------------------------------------------------------------- // Base64 photo decode cache.- //- // Decoding Base64 + BitmapFactory.decodeByteArray on every recomposition- // is wasteful: the same contact photo strings appear repeatedly in the- // contact list, details page, and edit page. Cache the decoded Bitmaps- // in a small LRU keyed by the raw Base64 string so we decode once. // --------------------------------------------------------------------- private val photoCache = LruCache<String, Bitmap>(32)@@ -618,11 +592,6 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) // --------------------------------------------------------------------- // EditContactPage form draft state.- //- // Previously every form field lived in compose-local `remember { mutableStateOf(...) }`- // / `mutableStateListOf(...)`. Hoisting it to the VM means the draft survives- // configuration changes and recompositions, and lets the build-and-save logic- // live alongside the rest of the contact write path. // --------------------------------------------------------------------- data class ContactDraft(@@ -643,12 +612,6 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) val dates: List<Event> = emptyList(), val addresses: List<Address> = emptyList(), val groupMemberships: List<GroupMembership> = emptyList(),- val target: ContactDraftTarget = ContactDraftTarget.DEVICE,- val simSubscriptionId: Int? = null,- // SIM-only simplified fields (when target == SIM, only these 3 are used)- val simName: String = "",- val simPhone: String = "",- val simEmail: String = "", ) private val _editDraft = MutableStateFlow<ContactDraft?>(null)@@ -661,11 +624,6 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) /** True once a draft has been initialized at all (distinguishes "new contact" from "uninitialized"). */ private var editingInitialized: Boolean = false - /**- * Initializes the edit-form draft from an existing contact (if [contactId] is non-null)- * and/or prefilled fields from a navigation intent. No-op if a draft for the same- * [contactId] already exists — so the user's unsaved edits survive rotation.- */ private fun normalizePhoneForCompare(raw: String): String { return raw.filter { it.isDigit() || it == '+' }.trim() }@@ -676,21 +634,12 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) ) { if (editingInitialized && editingContactId == contactId && _editDraft.value != null) return val contact = contactId?.let {- getContact(it) ?: Contact.getContact(getApplication(), it)+ getContact(it) ?: Contact.getContact(getApplication(), it) ?: _allContacts.value.find { c -> c.id == it } } val details = contact?.details editingOriginal = contact editingContactId = contactId editingInitialized = true- // For new contacts, honor default target preference; editing existing always Device.- val initialTarget = if (contactId == null) {- val raw = dataStore.getString("default_contact_target")- if (raw == "sim") ContactDraftTarget.SIM else ContactDraftTarget.DEVICE- } else ContactDraftTarget.DEVICE- val defaultSubId = _simSubscriptions.value.firstOrNull()- val initialSimName = prefill?.name ?: contact?.name?.value ?: ""- val initialSimPhone = prefill?.primaryPhone ?: details?.phoneNumbers?.firstOrNull()?.number ?: ""- val initialSimEmail = prefill?.primaryEmail ?: details?.emails?.firstOrNull()?.address ?: "" _editDraft.value = ContactDraft( namePrefix = contact?.name?.namePrefix ?: "", firstName = contact?.name?.firstName ?: prefill?.name ?: "",@@ -709,11 +658,6 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) dates = details?.dates ?: emptyList(), addresses = mergeAddresses(details?.addresses ?: emptyList(), prefill?.postals ?: emptyList()), groupMemberships = details?.groups ?: emptyList(),- target = initialTarget,- simSubscriptionId = defaultSubId,- simName = initialSimName,- simPhone = initialSimPhone,- simEmail = initialSimEmail, ) } @@ -770,22 +714,41 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) viewModelScope.launch(Dispatchers.IO) { try { val app = getApplication<Application>()- // Fetch fresh from provider to avoid stale filtered list.- val existing = Contact.getContact(app, contactId) ?: _allContacts.value.find { it.id == contactId }+ val existing = Contact.getContact(app, contactId) ?: _allContacts.value.find { it.id == contactId } ?: contacts.value.find { it.id == contactId } if (existing == null) { withContext(Dispatchers.Main) { onComplete() } return@launch }- val normalizedNew = normalizePhoneForCompare(phone)- val alreadyHas = existing.details.phoneNumbers.any { normalizePhoneForCompare(it.number) == normalizedNew }- if (alreadyHas) {- withContext(Dispatchers.Main) { onComplete() }- return@launch+ if (isSimAccountType(existing.accountType)) {+ val subId = existing.accountName?.toIntOrNull()+ val normalizedNew = normalizePhoneForCompare(phone)+ val alreadyHas = existing.details.phoneNumbers.any { normalizePhoneForCompare(it.number) == normalizedNew }+ if (alreadyHas) {+ withContext(Dispatchers.Main) { onComplete() }+ return@launch+ }+ val name = existing.name.value+ if (existing.details.phoneNumbers.isEmpty()) {+ val oldSc = SimContactsDataSource.findBackingSimContact(app, existing)+ if (oldSc != null) SimContactsDataSource.deleteSimContact(app, oldSc)+ SimContactsDataSource.insertSimContact(app, name.ifEmpty { phone }, phone, null, subId)+ } else {+ // SIM can hold only one number; store the new number as an additional SIM entry+ SimContactsDataSource.insertSimContact(app, name.ifEmpty { phone }, phone, null, subId)+ }+ syncFromSystem()+ } else {+ val normalizedNew = normalizePhoneForCompare(phone)+ val alreadyHas = existing.details.phoneNumbers.any { normalizePhoneForCompare(it.number) == normalizedNew }+ if (alreadyHas) {+ withContext(Dispatchers.Main) { onComplete() }+ return@launch+ }+ val newDetails = existing.details.copy(+ phoneNumbers = existing.details.phoneNumbers + PhoneNumber(0, phone, type)+ )+ existing.save(app, newDetails, existing.details) }- val newDetails = existing.details.copy(- phoneNumbers = existing.details.phoneNumbers + PhoneNumber(0, phone, type)- )- existing.save(app, newDetails, existing.details) } catch (e: Exception) { Log.e("ContactViewModel", "Failed to add phone to contact $contactId", e) }@@ -809,9 +772,7 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) /** * Decodes the picked image URI off the main thread, scales it to 500x500,- * Base64-encodes it, and updates [editDraft]'s photo. Errors are logged- * and the draft is left unchanged so the picker callback never blocks the- * UI thread (large gallery photos can take 100+ ms to decode).+ * Base64-encodes it, and updates [editDraft]'s photo. */ fun setEditDraftPhotoFromBitmap(bitmap: Bitmap) { viewModelScope.launch(Dispatchers.IO) {@@ -830,33 +791,19 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) } /**- * Persists the current draft. When target==SIM (new-contact only), writes- * via the SIM data source (name/phone/email only). Otherwise builds a- * [Contact] and persists via [saveContact].- * Returns true if the draft was handled as SIM (caller should not double-save).+ * Persists the current draft via the unified save path.+ * SIM vs device routing is handled by [saveContact] based on draft.accountType. */ fun saveEditDraft(onResult: ((Boolean, String?) -> Unit)? = null) { val draft = _editDraft.value ?: return- if (draft.target == ContactDraftTarget.SIM && editingOriginal == null) {- // SIM path: only 3 fields- val name = draft.simName.trim()- val phone = draft.simPhone.trim()- val email = draft.simEmail.trim().ifEmpty { null }- if (name.isEmpty() && phone.isEmpty()) {+ // For SIM accounts, validate SIM limits: at least name or phone needed, and SIM can't store extra fields+ if (isSimAccountType(draft.accountType)) {+ val nameVal = listOfNotNull(draft.namePrefix.ifEmpty { null }, draft.firstName.ifEmpty { null }, draft.middleName.ifEmpty { null }, draft.lastName.ifEmpty { null }, draft.nameSuffix.ifEmpty { null }).joinToString(" ").trim()+ val phoneVal = draft.phoneNumbers.firstOrNull()?.number?.trim() ?: ""+ if (nameVal.isEmpty() && phoneVal.isEmpty()) { onResult?.invoke(false, "Name or phone required") return }- viewModelScope.launch(Dispatchers.IO) {- val ok = SimContactsDataSource.insertSimContact(- getApplication(), name, phone, email, draft.simSubscriptionId- )- if (ok) _simContacts.value = SimContactsDataSource.listSimContacts(getApplication())- withContext(Dispatchers.Main) {- if (ok) clearEditDraft()- onResult?.invoke(ok, if (ok) null else "Failed to write to SIM (full or not available)")- }- }- return } val original = editingOriginal val birthdayId = original?.birthday?.id ?: 0L@@ -891,7 +838,12 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) ), groups = draft.groupMemberships )- val newContact = original?.copy(details = details) ?: Contact(+ // For existing SIM contacts, keep synthetic id so saveContact can locate old row+ val newContact = original?.copy(+ accountType = draft.accountType.ifEmpty { null }?.let { it },+ accountName = draft.accountName.ifEmpty { null },+ details = details+ ) ?: Contact( id = 0, accountType = draft.accountType.ifEmpty { null }, accountName = draft.accountName.ifEmpty { null },@@ -902,4 +854,4 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) clearEditDraft() onResult?.invoke(true, null) }-}\ No newline at end of file+}
contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.ktindex 0a55831626..08853cd3dc 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.kt@@ -4,21 +4,6 @@ import android.graphics.Bitmap import com.vayunmathur.contacts.data.Contact import com.vayunmathur.contacts.data.ContactGroup -/**- * The UI contract between [ContactViewModel] and the three screens the store listing is- * shot from (contact list, contact details, groups).- *- * Those screens take a state value plus an actions interface rather than the ViewModel- * itself, so they can be rendered by a `@Preview` — which is what the listing images are- * generated from. It lives in `util` rather than `ui` so the dependency runs one way:- * `ui` depends on `util`, and the ViewModel implements [ContactsActions].- *- * There is one actions interface rather than one per screen because the screens genuinely- * share callbacks (the bottom nav, opening a contact, decoding a photo); splitting it would- * mean the same defaulted member declared in several interfaces, which the ViewModel would- * then have to disambiguate by hand.- */- /** Bottom-nav destination. */ enum class ContactsTab { Contacts, Groups, Settings } @@ -34,18 +19,8 @@ data class ContactListUiState( /** Contact open in the detail pane, highlighted in the list on a wide screen. */ val openContactId: Long? = null, val showAddButton: Boolean = true,- val simContacts: List<com.vayunmathur.contacts.data.SimContact> = emptyList(),- val hasSim: Boolean = false, ) -interface SimContactsActions {- fun importSimContact(simContact: com.vayunmathur.contacts.data.SimContact) {}- fun deleteSimContact(simContact: com.vayunmathur.contacts.data.SimContact) {}- fun importAllSimContacts() {}- fun refreshSim() {}- companion object { val Noop: SimContactsActions = object : SimContactsActions {} }-}- /** Everything the contact details page draws. */ data class ContactDetailsUiState( val contact: Contact,@@ -63,8 +38,6 @@ data class GroupsUiState( /** * Contact screen callbacks. Every method has a no-op default so a preview can render a * screen without supplying behaviour — [Noop] is the whole implementation a preview needs.- * The navigating and `Context`-dependent ones are supplied by each screen's binder; the- * rest are implemented by [ContactViewModel] directly. */ interface ContactsActions { fun setSearchQuery(query: String) {}
contacts/src/main/res/values/strings.xml
diff --git a/contacts/src/main/res/values/strings.xml b/contacts/src/main/res/values/strings.xmlindex 38f91d0767..57950cb00b 100644--- a/contacts/src/main/res/values/strings.xml+++ b/contacts/src/main/res/values/strings.xml@@ -207,31 +207,8 @@ <!-- Placeholder / description for entering custom label --> <string name="enter_custom_label">Enter custom label</string> - <!-- SIM contacts -->- <string name="sim_contacts">SIM contacts</string>- <string name="sim_card">SIM card</string>- <string name="device">Device</string>- <string name="save_to">Save to</string>- <string name="sim_slot">SIM slot</string>- <string name="sim_name">Name</string>- <string name="sim_phone">Phone</string>- <string name="sim_email">Email</string>+ <!-- SIM contacts (now virtual accounts) --> <string name="sim_limited_fields_hint">SIM contacts only store name, phone, and email.</string>- <string name="sim_name_or_phone_required">Enter a name or phone number</string> <string name="save_failed">Save failed</string>- <string name="no_sim_available">No SIM card available</string>- <string name="no_sim_inserted">No SIM card inserted or permission not granted.</string>- <string name="no_sim_contacts">No contacts on SIM.</string>- <string name="import_all">Import all</string>- <string name="export_to_sim">Export to SIM</string>- <string name="import_from_sim">Import from SIM</string>- <string name="default_save_location">Default save location</string>- <string name="default_save_location_summary">Where new contacts are saved by default</string>- <string name="import_sim_contacts">Import SIM contacts</string> <string name="importing">Importing…</string>- <string name="exporting_to_sim">Exporting to SIM…</string>- <string name="sim_import_success">Imported %1$d contact(s) from SIM</string>- <string name="sim_import_failed">Failed to import from SIM</string>- <string name="sim_export_success">Exported to SIM</string>- <string name="sim_export_failed">Failed to export to SIM (full or unavailable)</string> </resources>