communicate: find contacts from the dialpad with T9 (#553)
- Commit
6ac0d9afe2fad508f83ae22df50a9acd0d67f10c- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 14:52 UTC (3 months ago)
- Parents
64a4b9c
Diff
communicate/src/main/java/com/vayunmathur/communicate/data/T9.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/T9.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/T9.ktnew file mode 100644index 0000000000..df841a8968--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/T9.kt@@ -0,0 +1,82 @@+package com.vayunmathur.communicate.data++import java.text.Normalizer++/**+ * T9 matching for the dialpad: typing 5673 finds "José", typing 76 finds "Smith".+ *+ * Names are folded before mapping (NFD, combining marks stripped, uppercased) so accented+ * letters reach the key they are printed on — the same normalisation the contacts app uses+ * to pick a name's section header, for the same reason.+ *+ * Deliberately free of `android.*` so it can be unit-tested on the JVM.+ */+object T9 {++ private val DIACRITICS = Regex("\\p{InCombiningDiacriticalMarks}+")++ /** Split on what `initialsFor` splits on, so a token here is a token there. */+ private val DELIMITERS = charArrayOf(' ', '+', '-', '_')++ /**+ * The keypad marking for [c], or null when the character has none. Scripts that were never+ * printed on a keypad (CJK, Cyrillic, Arabic, Hebrew) fall in the null case; such contacts+ * are reachable through their phone number instead of being mapped to an invented key.+ */+ fun digitFor(c: Char): Char? = when (c) {+ in '0'..'9' -> c+ 'A', 'B', 'C' -> '2'+ 'D', 'E', 'F' -> '3'+ 'G', 'H', 'I' -> '4'+ 'J', 'K', 'L' -> '5'+ 'M', 'N', 'O' -> '6'+ 'P', 'Q', 'R', 'S' -> '7'+ 'T', 'U', 'V' -> '8'+ 'W', 'X', 'Y', 'Z' -> '9'+ else -> null+ }++ /** The keys that spell [text], with unmappable characters dropped. */+ fun keysFor(text: String): String {+ val folded = Normalizer.normalize(text, Normalizer.Form.NFD)+ .replace(DIACRITICS, "")+ .uppercase()+ return buildString(folded.length) {+ folded.forEach { c -> digitFor(c)?.let { append(it) } }+ }+ }++ /** Keeps only what can be matched against: `*`, `#` and `+` dial but don't spell. */+ fun normalizeQuery(raw: String): String = raw.filter { it.isDigit() }++ /**+ * One contact's precomputed keys. Built once per contact list so filtering costs one pass+ * over the contacts per keystroke rather than re-folding every name.+ */+ class Entry(+ val nameKeys: List<String>,+ val initialsKey: String,+ val phoneDigits: String,+ )++ fun entryFor(name: String, phoneNumber: String): Entry {+ val tokens = name.split(*DELIMITERS).filter { it.isNotBlank() }+ return Entry(+ nameKeys = tokens.map { keysFor(it) }.filter { it.isNotEmpty() },+ initialsKey = keysFor(tokens.mapNotNull { it.firstOrNull() }.joinToString("")),+ phoneDigits = phoneNumber.filter { it.isDigit() },+ )+ }++ /**+ * True when [query] (already through [normalizeQuery]) prefixes any word of the name or the+ * run of its initials, or appears anywhere in the phone number. The phone clause mirrors the+ * recipient picker's filter so both as-you-type searches behave the same.+ */+ fun matches(entry: Entry, query: String): Boolean {+ if (query.isEmpty()) return true+ return entry.nameKeys.any { it.startsWith(query) } ||+ entry.initialsKey.startsWith(query) ||+ entry.phoneDigits.contains(query)+ }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.ktindex 81532b2113..3beb5f634f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt@@ -40,6 +40,7 @@ import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateContact import com.vayunmathur.communicate.data.CommunicateRepository import com.vayunmathur.communicate.data.LineChoice+import com.vayunmathur.communicate.data.T9 import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager import com.vayunmathur.communicate.telephony.GoogleVoiceTelecom@@ -126,13 +127,27 @@ fun DialerScreen() { val contacts = produceState<List<CommunicateContact>?>(initialValue = null, roleRevision, permissionRevision) { value = withContext(Dispatchers.IO) { CommunicateRepository.loadContacts(context) } }- when (val rows = contacts.value) {- null -> com.vayunmathur.library.ui.LoadingState(Modifier.weight(1f))- emptyList<CommunicateContact>() -> EmptyState(+ // Keyed on the contact list only: the query must never re-run the provider query.+ val rows = contacts.value+ val entries = remember(rows) { rows.orEmpty().map { T9.entryFor(it.name, it.phoneNumber) } }+ val query = T9.normalizeQuery(number)+ val filtered = remember(rows, query) {+ val all = rows.orEmpty()+ if (query.isEmpty()) all+ else all.filterIndexed { index, _ -> T9.matches(entries[index], query) }+ }+ when {+ rows == null -> com.vayunmathur.library.ui.LoadingState(Modifier.weight(1f))+ rows.isEmpty() -> EmptyState( title = stringResource(R.string.empty_contacts), icon = { IconContacts() }, modifier = Modifier.weight(1f), )+ filtered.isEmpty() -> EmptyState(+ title = stringResource(R.string.empty_contacts_for_digits),+ icon = { IconContacts() },+ modifier = Modifier.weight(1f),+ ) else -> LazyColumn( modifier = Modifier.weight(1f), contentPadding = PaddingValues(bottom = 8.dp),@@ -145,7 +160,7 @@ fun DialerScreen() { fontWeight = FontWeight.SemiBold, ) }- items(rows, key = { "${it.id}-${it.phoneNumber}" }) { contact ->+ items(filtered, key = { "${it.id}-${it.phoneNumber}" }) { contact -> ContactRow(contact) { place(contact.phoneNumber) }@@ -186,11 +201,12 @@ private fun DialPad( onPaste: () -> Unit, onCall: () -> Unit, ) {+ // Letters are the physical keycap markings from ITU E.161, not translatable copy. val keys = listOf(- listOf("1", "2", "3"),- listOf("4", "5", "6"),- listOf("7", "8", "9"),- listOf("*", "0", "#"),+ listOf("1" to "", "2" to "ABC", "3" to "DEF"),+ listOf("4" to "GHI", "5" to "JKL", "6" to "MNO"),+ listOf("7" to "PQRS", "8" to "TUV", "9" to "WXYZ"),+ listOf("*" to "", "0" to "", "#" to ""), ) Surface( tonalElevation = 2.dp,@@ -225,9 +241,10 @@ private fun DialPad( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), ) {- row.forEach { digit ->+ row.forEach { (digit, letters) -> DialKey( digit = digit,+ letters = letters, onClick = { onAppend(digit) }, modifier = Modifier.weight(1f), )@@ -254,15 +271,27 @@ private fun DialPad( } @Composable-private fun DialKey(digit: String, onClick: () -> Unit, modifier: Modifier = Modifier) {+private fun DialKey(digit: String, letters: String, onClick: () -> Unit, modifier: Modifier = Modifier) { Surface( onClick = onClick, shape = RoundedCornerShape(14.dp), color = MaterialTheme.colorScheme.surfaceVariant,- modifier = modifier.height(44.dp),+ modifier = modifier.height(52.dp), ) {- Box(contentAlignment = Alignment.Center) {+ Column(+ modifier = Modifier.fillMaxSize(),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) { Text(digit, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Medium)+ if (letters.isNotEmpty()) {+ Text(+ letters,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 1,+ )+ } } } }
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex a6bd7a9411..b40287f927 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -22,6 +22,7 @@ <string name="grant_permission">Grant permission</string> <string name="empty_messages">No conversations yet</string> <string name="empty_contacts">No contacts found</string>+ <string name="empty_contacts_for_digits">No contacts match those keys</string> <string name="empty_call_logs">No recent calls found</string> <string name="new_message">New message</string> <string name="compose_message">Compose message</string>
communicate/src/test/java/com/vayunmathur/communicate/data/T9Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/T9Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/T9Test.ktnew file mode 100644index 0000000000..3695e78b76--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/T9Test.kt@@ -0,0 +1,75 @@+package com.vayunmathur.communicate.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Vectors for dialpad T9 matching. Pure JVM — [T9] deliberately has no `android.*` dependency.+ */+class T9Test {++ private fun matches(name: String, phone: String, typed: String): Boolean =+ T9.matches(T9.entryFor(name, phone), T9.normalizeQuery(typed))++ @Test+ fun `maps letters to their ITU keys`() {+ assertEquals("22233344455566677778889999", T9.keysFor("abcdefghijklmnopqrstuvwxyz"))+ assertEquals('7', T9.digitFor('S'))+ assertEquals('9', T9.digitFor('Z'))+ assertEquals('0', T9.digitFor('0'))+ }++ @Test+ fun `drops characters with no keypad marking`() {+ assertNull(T9.digitFor('#'))+ assertNull(T9.digitFor('李'))+ assertEquals("", T9.keysFor("李小龍"))+ assertEquals("46", T9.keysFor("h. m."))+ }++ @Test+ fun `folds accents onto the printed letter`() {+ assertEquals("5673", T9.keysFor("José"))+ assertTrue(matches("José", "5551234", "5673"))+ assertTrue(matches("Ångström", "5551234", "2"))+ }++ @Test+ fun `matches any word of a multi-word name`() {+ assertTrue(matches("Robert Smith", "5551234", "76"))+ assertTrue(matches("Robert Smith", "5551234", "762"))+ assertTrue(matches("Mary-Jane Watson", "5551234", "5"))+ assertFalse(matches("Robert Smith", "5551234", "999"))+ }++ @Test+ fun `matches the run of initials`() {+ assertTrue(matches("Robert James Smith", "5551234", "757"))+ assertTrue(matches("Robert James Smith", "5551234", "75"))+ assertFalse(matches("Robert James Smith", "5551234", "758"))+ }++ @Test+ fun `matches digits anywhere in the phone number`() {+ assertTrue(matches("李小龍", "+1 (555) 867-5309", "8675"))+ assertTrue(matches("李小龍", "+1 (555) 867-5309", "555"))+ assertFalse(matches("李小龍", "+1 (555) 867-5309", "4321"))+ }++ @Test+ fun `ignores dial-only characters in the query`() {+ assertEquals("", T9.normalizeQuery("*#+"))+ assertEquals("76", T9.normalizeQuery("*7#6+"))+ assertTrue(matches("Robert Smith", "5551234", "*#+"))+ assertTrue(matches("Robert Smith", "5551234", "*76#"))+ }++ @Test+ fun `an empty query matches everything`() {+ assertTrue(matches("Robert Smith", "5551234", ""))+ assertTrue(matches("", "", ""))+ }+}