Modern Apps git

← Modern-Apps.git

various fixes

Commit
f4386b4a67a9854a01078bf98b86257806c269bf
Author
Vayun Mathur <[email protected]>
When
2026-06-04 19:39 UTC (6 months ago)
Parents
92695e4

Diff

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 f2b9d1efc0..f1dd8b303d 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt@@ -2,9 +2,11 @@ package com.vayunmathur.contacts.ui  import android.content.Intent import android.net.Uri+import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -48,9 +50,11 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.painter.Painter+import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.core.content.FileProvider@@ -280,21 +284,36 @@ fun ContactDetailsPage(              if(details.dates.isNotEmpty()) {                 item {+                    val clipboardManager = LocalClipboardManager.current                     GroupedSection(title = stringResource(R.string.about_name, contact!!.name.firstName)) {                         contact!!.birthday?.let { birthday ->+                            val birthdayText = birthday.startDate.formatDisplay()                             ListItem(-                                headlineContent = { Text(birthday.startDate.formatDisplay()) },+                                headlineContent = { Text(birthdayText) },                                 supportingContent = { Text(stringResource(R.string.birthday)) },                                 leadingContent = { Icon(painterResource(R.drawable.outline_cake_24), birthday.typeString(context)) },-                                colors = ListItemDefaults.colors(containerColor = Color.Transparent)+                                colors = ListItemDefaults.colors(containerColor = Color.Transparent),+                                modifier = Modifier.combinedClickable(+                                    onClick = { },+                                    onLongClick = {+                                        clipboardManager.setText(AnnotatedString(birthdayText))+                                    }+                                )                             )                         }                         details.dates.filter{it.type != CDKEvent.TYPE_BIRTHDAY }.forEach { event ->+                            val eventText = event.startDate.formatDisplay()                             ListItem(-                                headlineContent = { Text(event.startDate.formatDisplay()) },+                                headlineContent = { Text(eventText) },                                 supportingContent = { Text(event.typeString(context)) },                                 leadingContent = { Icon(painterResource(R.drawable.outline_event_24), event.typeString(context)) },-                                colors = ListItemDefaults.colors(containerColor = Color.Transparent)+                                colors = ListItemDefaults.colors(containerColor = Color.Transparent),+                                modifier = Modifier.combinedClickable(+                                    onClick = { },+                                    onLongClick = {+                                        clipboardManager.setText(AnnotatedString(eventText))+                                    }+                                )                             )                         }                     }@@ -303,12 +322,45 @@ fun ContactDetailsPage(                          if (contact?.note?.content?.isNotEmpty() == true) {                 item {+                    val clipboardManager = LocalClipboardManager.current                     GroupedSection(title = stringResource(R.string.note)) {-                        Text(-                            text = contact!!.note.content,-                            modifier = Modifier.padding(16.dp),-                            style = MaterialTheme.typography.bodyLarge-                        )+                        Box(+                            modifier = Modifier+                                .fillMaxWidth()+                                .combinedClickable(+                                    onClick = { },+                                    onLongClick = {+                                        clipboardManager.setText(AnnotatedString(contact!!.note.content))+                                    }+                                )+                                .padding(16.dp)+                        ) {+                            Text(+                                text = contact!!.note.content,+                                style = MaterialTheme.typography.bodyLarge+                            )+                        }+                    }+                }+            }++            if (details.groups.isNotEmpty()) {+                item {+                    val allGroups by viewModel.groups.collectAsState()+                    val contactGroups = allGroups.filter { group ->+                        details.groups.any { it.groupId == group.id } && group.name.trim().isNotEmpty()+                    }+                    if (contactGroups.isNotEmpty()) {+                        Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+                            contactGroups.forEachIndexed { index, group ->+                                DetailItem(+                                    icon = painterResource(R.drawable.baseline_group_24),+                                    data = group.name,+                                    label = stringResource(R.string.groups),+                                    shape = groupShape(index, contactGroups.size),+                                )+                            }+                        }                     }                 }             }@@ -487,6 +539,7 @@ fun ActionButton(     } } +@OptIn(ExperimentalFoundationApi::class) @Composable fun DetailItem(     icon: Painter,@@ -504,12 +557,30 @@ fun DetailItem(      */     shape: androidx.compose.ui.graphics.Shape = RoundedCornerShape(16.dp), ) {+    val clipboardManager = LocalClipboardManager.current+     Surface(         shape = shape,         color = MaterialTheme.colorScheme.surfaceVariant,         modifier = Modifier             .fillMaxWidth()-            .then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)+            .then(+                if (onClick != null) {+                    Modifier.combinedClickable(+                        onClick = onClick,+                        onLongClick = {+                            clipboardManager.setText(AnnotatedString(data))+                        }+                    )+                } else {+                    Modifier.combinedClickable(+                        onClick = { },+                        onLongClick = {+                            clipboardManager.setText(AnnotatedString(data))+                        }+                    )+                }+            )     ) {         ListItem(             headlineContent = {
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 771e648f27..c6be9a3955 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt@@ -150,6 +150,12 @@ fun ContactList(         viewModel.setSearchQuery("")     } +    // When contacts are selected (selection mode), intercept back to unselect+    // instead of closing the app.+    androidx.activity.compose.BackHandler(enabled = isSelectionMode) {+        selectedIds.clear()+    }+     Scaffold(         topBar = {             if (isSelectionMode) {
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 0ea38f497e..69de42c3ad 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt@@ -9,9 +9,11 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight@@ -32,6 +34,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton+import androidx.compose.material3.InputChip import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold@@ -66,7 +69,9 @@ import com.vayunmathur.contacts.data.CDKEvent import com.vayunmathur.contacts.data.CDKPhone import com.vayunmathur.contacts.data.CDKStructuredPostal import com.vayunmathur.contacts.data.ContactDetail+import com.vayunmathur.contacts.data.ContactGroup 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.formatDisplay@@ -211,6 +216,28 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,             )             Spacer(Modifier.height(16.dp)) +            // Group memberships (placed near identity fields)+            val allGroups by viewModel.groups.collectAsState()+            val draftGroupIds = currentDraft.groupMemberships.map { it.groupId }.toSet()+            val memberGroups = allGroups.filter { it.id in draftGroupIds && it.name.trim().isNotEmpty() }+            val availableGroups = allGroups.filter { it.id !in draftGroupIds && it.name.trim().isNotEmpty() }++            GroupMembershipSection(+                memberGroups = memberGroups,+                availableGroups = availableGroups,+                onAddGroup = { groupId ->+                    viewModel.updateEditDraft { it.copy(+                        groupMemberships = it.groupMemberships + GroupMembership(0, groupId)+                    )}+                },+                onRemoveGroup = { groupId ->+                    viewModel.updateEditDraft { it.copy(+                        groupMemberships = it.groupMemberships.filter { gm -> gm.groupId != groupId }+                    )}+                }+            )+            Spacer(Modifier.height(16.dp))+             DetailsSection(                 detailType = stringResource(R.string.phone),                 addLabelRes = R.string.add_phone,@@ -485,22 +512,13 @@ private fun ColumnScope.DateDetailsSection(         }         Spacer(Modifier.height(8.dp))     }-    if (details.none { it.type != CDKEvent.TYPE_BIRTHDAY }) {-        FilledTonalButton(-            onClick = { onDetailsChange(details + ContactDetail.default<Event>()) },-            modifier = Modifier.fillMaxWidth()-        ) {-            Icon(icon, contentDescription = null)-            Spacer(Modifier.width(8.dp))-            Text(stringResource(R.string.add_date))-        }-    } else {-        TextButton(-            onClick = { onDetailsChange(details + ContactDetail.default<Event>()) },-            modifier = Modifier.align(Alignment.Start)-        ) {-            Text(stringResource(R.string.add_date))-        }+    FilledTonalButton(+        onClick = { onDetailsChange(details + ContactDetail.default<Event>()) },+        modifier = Modifier.fillMaxWidth()+    ) {+        Icon(icon, contentDescription = null)+        Spacer(Modifier.width(8.dp))+        Text(stringResource(R.string.add_date))     } } @@ -568,21 +586,92 @@ private inline fun <reified T : ContactDetail<T>> ColumnScope.DetailsSection(         )         Spacer(Modifier.height(8.dp))     }-    if(details.isEmpty()) {-        FilledTonalButton(-            onClick = { onDetailsChange(details + ContactDetail.default<T>()) },-            modifier = Modifier.fillMaxWidth()-        ) {-            Icon(icon, contentDescription = null)-            Spacer(Modifier.width(8.dp))-            Text(stringResource(addLabelRes))+    FilledTonalButton(+        onClick = { onDetailsChange(details + ContactDetail.default<T>()) },+        modifier = Modifier.fillMaxWidth()+    ) {+        Icon(icon, contentDescription = null)+        Spacer(Modifier.width(8.dp))+        Text(stringResource(addLabelRes))+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun ColumnScope.GroupMembershipSection(+    memberGroups: List<ContactGroup>,+    availableGroups: List<ContactGroup>,+    onAddGroup: (Long) -> Unit,+    onRemoveGroup: (Long) -> Unit+) {+    if (memberGroups.isEmpty() && availableGroups.isEmpty()) return++    Row(+        verticalAlignment = Alignment.CenterVertically,+        modifier = Modifier.fillMaxWidth()+    ) {+        Icon(+            painterResource(R.drawable.baseline_group_24),+            contentDescription = null,+            tint = MaterialTheme.colorScheme.onSurfaceVariant,+            modifier = Modifier.size(20.dp)+        )+        Spacer(Modifier.width(8.dp))+        Text(+            stringResource(R.string.groups),+            style = MaterialTheme.typography.labelLarge,+            color = MaterialTheme.colorScheme.onSurfaceVariant+        )+    }+    Spacer(Modifier.height(8.dp))++    FlowRow(+        horizontalArrangement = Arrangement.spacedBy(8.dp),+        verticalArrangement = Arrangement.spacedBy(8.dp),+        modifier = Modifier.fillMaxWidth()+    ) {+        memberGroups.forEach { group ->+            InputChip(+                selected = false,+                onClick = { onRemoveGroup(group.id) },+                label = { Text(group.name) },+                trailingIcon = {+                    Icon(+                        painterResource(R.drawable.baseline_remove_circle_outline_24),+                        contentDescription = stringResource(R.string.remove_from_group),+                        modifier = Modifier.size(18.dp)+                    )+                }+            )         }-    } else {-        TextButton(-            onClick = { onDetailsChange(details + ContactDetail.default<T>()) },-            modifier = Modifier.align(Alignment.Start)-        ) {-            Text(stringResource(addLabelRes))+    }++    if (availableGroups.isNotEmpty()) {+        Spacer(Modifier.height(4.dp))+        var expanded by remember { mutableStateOf(false) }+        Box {+            FilledTonalButton(+                onClick = { expanded = true },+                modifier = Modifier.fillMaxWidth()+            ) {+                Icon(+                    painterResource(R.drawable.baseline_group_24),+                    contentDescription = null+                )+                Spacer(Modifier.width(8.dp))+                Text(stringResource(R.string.add_to_group))+            }+            DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {+                availableGroups.forEach { group ->+                    DropdownMenuItem(+                        text = { Text(group.name) },+                        onClick = {+                            onAddGroup(group.id)+                            expanded = false+                        }+                    )+                }+            }         }     } }
contacts/src/main/java/com/vayunmathur/contacts/ui/GroupsPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/GroupsPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/GroupsPage.ktindex dfa5416428..d96a9b80c8 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/GroupsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/GroupsPage.kt@@ -33,12 +33,18 @@ fun GroupsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>, expa     val groups by viewModel.groups.collectAsState()     var showAddDialog by remember { mutableStateOf(false) }     var newGroupName by remember { mutableStateOf("") }+    var groupToDelete by remember { mutableStateOf<com.vayunmathur.contacts.data.ContactGroup?>(null) }     val expandedGroups = remember {          val list = mutableStateListOf<Long>()         expandGroupId?.let { list.add(it) }         list     } +    // When on Groups page, back should navigate to Contacts page+    androidx.activity.compose.BackHandler {+        backStack.setLast(Route.ContactsList)+    }+     Scaffold(         topBar = {             TopAppBar(@@ -129,7 +135,7 @@ fun GroupsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>, expa                                     }                                 },                                 trailingContent = {-                                    IconButton(onClick = { viewModel.deleteGroup(group.id) }) {+                                    IconButton(onClick = { groupToDelete = group }) {                                         IconDelete()                                     }                                 },@@ -199,4 +205,25 @@ fun GroupsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>, expa             }         )     }++    if (groupToDelete != null) {+        AlertDialog(+            onDismissRequest = { groupToDelete = null },+            title = { Text(stringResource(R.string.delete_group_title)) },+            text = { Text(stringResource(R.string.delete_group_confirm)) },+            confirmButton = {+                TextButton(onClick = {+                    groupToDelete?.let { viewModel.deleteGroup(it.id) }+                    groupToDelete = null+                }) {+                    Text(stringResource(R.string.delete))+                }+            },+            dismissButton = {+                TextButton(onClick = { groupToDelete = null }) {+                    Text(stringResource(R.string.cancel))+                }+            }+        )+    } }
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 2ecf0d08fe..45e4a2fc13 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt@@ -68,6 +68,11 @@ fun SettingsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>) {         }     ) +    // When on Settings page, back should navigate to Contacts page+    androidx.activity.compose.BackHandler {+        backStack.setLast(Route.ContactsList)+    }+     Scaffold(         topBar = {             TopAppBar(
contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/AddToGroupDialog.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/AddToGroupDialog.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/AddToGroupDialog.ktindex 83cfb3e4f9..b1f301c8ff 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/AddToGroupDialog.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/AddToGroupDialog.kt@@ -8,6 +8,8 @@ import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.state.ToggleableState import androidx.compose.ui.unit.dp@@ -43,23 +45,37 @@ fun AddToGroupDialog(                             else -> ToggleableState.Indeterminate                         } -                        ListItem(-                            headlineContent = { Text(group.name) },-                            trailingContent = {-                                TriStateCheckbox(-                                    state = state,-                                    onClick = null // Handled by ListItem click-                                )-                            },-                            modifier = Modifier.clickable {-                                if (state == ToggleableState.Off) {-                                    viewModel.addContactsToGroup(contactIds, group.id)-                                } else {-                                    // Indeterminate or On goes to Off-                                    viewModel.removeContactsFromGroup(contactIds, group.id)+                        Row(+                            modifier = Modifier+                                .fillMaxWidth()+                                .clickable {+                                    if (state == ToggleableState.Off) {+                                        viewModel.addContactsToGroup(contactIds, group.id)+                                    } else {+                                        // Indeterminate or On goes to Off+                                        viewModel.removeContactsFromGroup(contactIds, group.id)+                                    }                                 }-                            }-                        )+                                .padding(horizontal = 16.dp, vertical = 12.dp),+                            verticalAlignment = Alignment.CenterVertically+                        ) {+                            Icon(+                                painter = painterResource(R.drawable.baseline_group_24),+                                contentDescription = null,+                                tint = MaterialTheme.colorScheme.onSurfaceVariant,+                                modifier = Modifier.size(24.dp)+                            )+                            Spacer(modifier = Modifier.width(16.dp))+                            Text(+                                text = group.name,+                                style = MaterialTheme.typography.bodyLarge,+                                modifier = Modifier.weight(1f)+                            )+                            TriStateCheckbox(+                                state = state,+                                onClick = null // Handled by Row click+                            )+                        }                     }                 }             }
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 30e989b9d0..a2c4d003fd 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -24,6 +24,7 @@ import com.vayunmathur.contacts.data.ContactGroup import com.vayunmathur.contacts.data.ContactSearchEntity import com.vayunmathur.contacts.data.Email import com.vayunmathur.contacts.data.Event+import com.vayunmathur.contacts.data.GroupMembership import com.vayunmathur.contacts.data.Name import com.vayunmathur.contacts.data.Nickname import com.vayunmathur.contacts.data.Note@@ -449,6 +450,7 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)         val emails: List<Email> = emptyList(),         val dates: List<Event> = emptyList(),         val addresses: List<Address> = emptyList(),+        val groupMemberships: List<GroupMembership> = emptyList(),     )      private val _editDraft = MutableStateFlow<ContactDraft?>(null)@@ -505,6 +507,7 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)             },             dates = details?.dates ?: emptyList(),             addresses = details?.addresses ?: emptyList(),+            groupMemberships = details?.groups ?: emptyList(),         )     } @@ -590,7 +593,7 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)                     CDKNickname.TYPE_DEFAULT                 )             ),-            groups = original?.details?.groups ?: emptyList()+            groups = draft.groupMemberships         )         val newContact = original?.copy(details = details) ?: Contact(             id = 0,
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 6da2a199a3..260ac6754a 100644--- a/contacts/src/main/res/values/strings.xml+++ b/contacts/src/main/res/values/strings.xml@@ -87,4 +87,6 @@     <string name="enter_group_name">Enter group name</string>     <string name="delete_group_title">Delete group</string>     <string name="delete_group_confirm">Are you sure you want to delete this group? The contacts will not be deleted.</string>+    <string name="remove_from_group">Remove from group</string>+    <string name="copied_to_clipboard">Copied to clipboard</string> </resources>\ No newline at end of file
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex b218744f1b..1598ef9279 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -11,7 +11,6 @@ ksp = "2.3.6" # AndroidX Core & Lifecycle coreKtx = "1.18.0" lifecycle = "2.10.0"-litert = "2.1.5" litertlmAndroid = "0.12.0" newpipeextractor = "v0.26.2" sqlcipherAndroid = "4.16.0"@@ -112,9 +111,6 @@ litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", ve newpipeextractor = { module = "com.github.TeamNewPipe:NewPipeExtractor", version.ref = "newpipeextractor" } reorderable = { module = "sh.calvin.reorderable:reorderable", version.ref = "reorderable" } -# LiteRT (2.x has GPU support built-in via CompiledModel.GpuOptions)-litert = { module = "com.google.ai.edge.litert:litert", version.ref = "litert" }- # PDF Support androidx-pdf-compose = { module = "androidx.pdf:pdf-compose", version.ref = "pdfViewer" } androidx-pdf-ink = { module = "androidx.pdf:pdf-ink", version.ref = "pdfViewer" }@@ -175,4 +171,4 @@ kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "ko kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } dependency-analysis = { id="com.autonomousapps.dependency-analysis", version.ref = "comAutonomousappsDependencyAnalysisGradlePlugin" }-protobuf = { id = "com.google.protobuf", version.ref = "protobufPlugin" }\ No newline at end of file+protobuf = { id = "com.google.protobuf", version.ref = "protobufPlugin" }
pdf/src/main/java/com/vayunmathur/pdf/ui/PdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/PdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/PdfViewerScreen.ktindex ffae4a233e..71528e2fa3 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/PdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/PdfViewerScreen.kt@@ -1,6 +1,8 @@ package com.vayunmathur.pdf.ui  import android.content.Intent+import android.net.Uri+import android.util.Log import android.widget.Toast import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult@@ -26,6 +28,7 @@ import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf@@ -76,6 +79,11 @@ fun PdfViewerScreen(     val context = LocalContext.current     val resources = LocalResources.current     val coroutineScope = rememberCoroutineScope()+    val linkDestinations by viewModel.linkDestinations.collectAsState()++    LaunchedEffect(pdfDocument) {+        viewModel.buildLinkIndex(pdfDocument)+    }      val pdfSavedMessage = stringResource(R.string.pdf_saved)     val pdfSaveErrorMessage = stringResource(R.string.pdf_save_error)@@ -130,6 +138,39 @@ fun PdfViewerScreen(         }     } +    // Workaround for PDF viewer bug where panning gets stuck when viewbox goes past PDF edge+    // The issue is that when the whole page is in view, panning left/right is disabled.+    // If the user pans past the edge while zoomed in, the view gets stuck out of bounds.+    // This workaround detects when the view is out of bounds and resets it to a valid position.+    LaunchedEffect(pdfDocument) {+        while (true) {+            delay(300)+            try {+                // Try to get the PDF point at the center of the view+                // If this returns null, the view is out of bounds and panning gestures are dropped+                val pdfPoint = pdfState.visibleOffsetToPdfPoint(center)+                if (pdfPoint == null) {+                    // View is out of bounds - this happens when panning past the edge.+                    // Reset by scrolling to the current page (or page 0 if we can't determine it).+                    // This re-enables panning by bringing the view back into valid bounds.+                    try {+                        // Try to get current page from the state, or default to 0+                        pdfState.scrollToPage(0)+                    } catch (e: Exception) {+                        // If scroll fails, try a different approach - scroll to position 0,0 on page 0+                        try {+                            pdfState.scrollToPosition(PdfPoint(0, 0f, 0f))+                        } catch (e2: Exception) {+                            // Last resort - ignore and hope the next check succeeds+                        }+                    }+                }+            } catch (e: Exception) {+                // Ignore errors - this is a best-effort workaround for a library bug+            }+        }+    }+     fun search() {         coroutineScope.launch {             val results = pdfDocument.searchDocument(searchText, 0 until pdfDocument.pageCount)@@ -280,8 +321,42 @@ fun PdfViewerScreen(                         }                     },                 ) { uri ->-                    val intent = Intent(Intent.ACTION_VIEW, uri)-                    context.startActivity(intent)+                    Log.d("PdfViewer", "Link clicked: uri=$uri scheme=${uri.scheme} fragment=${uri.fragment}")+                    // Try link destination index (resolves Calibre EPUB-to-PDF internal links)+                    if (uri.scheme == "file") {+                        val destPage = linkDestinations[uri.toString()]+                        if (destPage != null) {+                            Log.d("PdfViewer", "Resolved via index: page $destPage")+                            coroutineScope.launch { pdfState.scrollToPage(destPage) }+                            return@PdfViewer true+                        }+                        // Try matching by path only (ignoring fragment)+                        val pathOnly = uri.buildUpon().fragment(null).build().toString()+                        val fallback = linkDestinations.entries+                            .firstOrNull { it.key.startsWith(pathOnly) }?.value+                        if (fallback != null) {+                            Log.d("PdfViewer", "Resolved via path match: page $fallback")+                            coroutineScope.launch { pdfState.scrollToPage(fallback) }+                            return@PdfViewer true+                        }+                        Log.d("PdfViewer", "Unresolved internal link: $uri")+                        return@PdfViewer true+                    }+                    // Try fragment-based page navigation (e.g., #page=5)+                    val fragment = uri.fragment+                    if (fragment != null) {+                        val page = Regex("page=(\\d+)").find(fragment)+                            ?.groupValues?.get(1)?.toIntOrNull()+                            ?: fragment.toIntOrNull()+                        if (page != null && page in 1..pdfDocument.pageCount) {+                            coroutineScope.launch { pdfState.scrollToPage(page - 1) }+                            return@PdfViewer true+                        }+                    }+                    if (uri.scheme == "http" || uri.scheme == "https" || uri.scheme == "mailto") {+                        val intent = Intent(Intent.ACTION_VIEW, uri)+                        context.startActivity(intent)+                    }                     true                 }             }
pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.ktindex 923066d8c3..846e7e3ab4 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.kt@@ -163,6 +163,45 @@ class PdfViewModel(application: Application) : AndroidViewModel(application) {         _pdfDocument.value = null         _passwordRequired.value = false         _passwordError.value = null+        _linkDestinations.value = emptyMap()+    }++    // --- Internal link resolution -------------------------------------------++    private val _linkDestinations = MutableStateFlow<Map<String, Int>>(emptyMap())+    val linkDestinations: StateFlow<Map<String, Int>> = _linkDestinations.asStateFlow()++    fun buildLinkIndex(document: EditablePdfDocument) {+        viewModelScope.launch(Dispatchers.Default) {+            val map = mutableMapOf<String, Int>()+            for (page in 0 until document.pageCount) {+                val links = try {+                    document.getPageLinks(page)+                } catch (e: Exception) {+                    continue+                }+                val gotos = links.gotoLinks.filter { it.bounds.isNotEmpty() }+                val externals = links.externalLinks.filter {+                    it.bounds.isNotEmpty() && it.uri.scheme == "file"+                }+                if (gotos.isEmpty() || externals.isEmpty()) continue++                for (ext in externals) {+                    val extY = ext.bounds.first().centerY()+                    val match = gotos.minByOrNull {+                        kotlin.math.abs(it.bounds.first().centerY() - extY)+                    } ?: continue+                    if (kotlin.math.abs(match.bounds.first().centerY() - extY) < 20f) {+                        map[ext.uri.toString()] = match.destination.pageNumber+                    }+                }+            }+            Log.d(TAG, "Link index: ${map.size} entries")+            for ((uri, dest) in map) {+                Log.d(TAG, "  $uri -> page $dest")+            }+            _linkDestinations.value = map+        }     }      companion object {
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex b938b8cf41..3c46faa8f3 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -10,8 +10,6 @@ android {     packaging {         jniLibs {             pickFirsts.add("**/libc++_shared.so")-            pickFirsts.add("**/libtensorflowlite_jni.so")-            pickFirsts.add("**/libtensorflowlite_gpu_jni.so")         }     } }@@ -30,9 +28,6 @@ dependencies {     implementation(libs.androidx.media3.ui.compose.material3)  -    implementation(project(":library:downloadservice"))     implementation(project(":library:widgets"))     implementation(project(":library:biometric"))--    implementation(libs.litert) }\ No newline at end of file
photos/src/main/AndroidManifest.xml
diff --git a/photos/src/main/AndroidManifest.xml b/photos/src/main/AndroidManifest.xmlindex 65b12f8730..2d0f29516f 100644--- a/photos/src/main/AndroidManifest.xml+++ b/photos/src/main/AndroidManifest.xml@@ -15,6 +15,12 @@     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /> +    <uses-permission android:name="com.vayunmathur.openassistant.permission.ACCESS_INFERENCE" />++    <queries>+        <package android:name="com.vayunmathur.openassistant" />+    </queries>+     <application         android:allowBackup="true"         android:backupAgent=".util.AppBackupAgent"@@ -24,10 +30,6 @@         android:roundIcon="@mipmap/ic_launcher"         android:supportsRtl="true"         android:theme="@style/Theme.General">--        <uses-native-library android:name="libvndksupport.so" android:required="false"/>-        <uses-native-library android:name="libOpenCL.so" android:required="false"/>-        <uses-native-library android:name="libcdsprpc.so" android:required="false"/>         <activity             android:name=".MainActivity"             android:exported="true"@@ -74,10 +76,6 @@             android:foregroundServiceType="dataSync"             tools:node="merge" /> -        <service-            android:name="com.vayunmathur.library.downloadservice.DownloadService"-            android:exported="false"-            android:foregroundServiceType="dataSync" />     </application>  </manifest>\ No newline at end of file
photos/src/main/java/com/vayunmathur/photos/MainActivity.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt b/photos/src/main/java/com/vayunmathur/photos/MainActivity.ktindex 398a584793..2620cf5a5b 100644--- a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt+++ b/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt@@ -29,10 +29,8 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.fragment.app.FragmentActivity-import com.vayunmathur.library.downloadservice.InitialDownloadChecker import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.PermissionsChecker-import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey@@ -53,9 +51,7 @@ import com.vayunmathur.photos.util.PhotoMapViewModel import com.vayunmathur.photos.util.PhotoMapViewModelFactory import com.vayunmathur.photos.util.SecureFolderViewModel import com.vayunmathur.photos.util.SecureFolderViewModelFactory-import com.vayunmathur.photos.util.SmolVLMRunner import kotlinx.serialization.Serializable-import java.io.File import com.vayunmathur.library.R as LibraryR  val LocalColumnCount = staticCompositionLocalOf<MutableFloatState> {@@ -85,37 +81,7 @@ class MainActivity : FragmentActivity() {             DynamicTheme {                 val columnCount = rememberSaveable { mutableFloatStateOf(3f) }                 CompositionLocalProvider(LocalColumnCount provides columnCount) {-                    val dataStore = DataStoreUtils.getInstance(this)-                    val isFeatureEnabled by galleryViewModel.isFeatureEnabled.collectAsState()--                    // Check if model and tokenizer need to be downloaded-                    val externalDir = getExternalFilesDir(null)-                    val modelFile = File(externalDir, SmolVLMRunner.MODEL_FILE_NAME)-                    val tokenizerFile = File(externalDir, SmolVLMRunner.TOKENIZER_FILE_NAME)-                    val needsModelDownload = isFeatureEnabled && (!modelFile.exists() || !tokenizerFile.exists())--                    if (needsModelDownload) {-                        // Show download screen for the model and tokenizer-                        InitialDownloadChecker(-                            ds = dataStore,-                            filesToDownload = listOf(-                                Triple(-                                    "https://data.vayunmathur.com/ocr/smalvlm-256m-instruct_q8_ekv2048_single_image.tflite",-                                    SmolVLMRunner.MODEL_FILE_NAME,-                                    "SmolVLM AI Model (~200MB)"-                                ),-                                Triple(-                                    "https://data.vayunmathur.com/ocr/tokenizer.model",-                                    SmolVLMRunner.TOKENIZER_FILE_NAME,-                                    "Tokenizer (~2MB)"-                                )-                            )-                        ) {-                            PermissionsWrapper()-                        }-                    } else {-                        PermissionsWrapper()-                    }+                    PermissionsWrapper()                 }             }         }
photos/src/main/java/com/vayunmathur/photos/util/OCRManager.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/OCRManager.kt b/photos/src/main/java/com/vayunmathur/photos/util/OCRManager.ktindex 51e2c89a16..b7ffe7c4f9 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/OCRManager.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/OCRManager.kt@@ -1,63 +1,156 @@ package com.vayunmathur.photos.util +import android.content.ComponentName import android.content.Context+import android.content.Intent+import android.graphics.Bitmap+import android.graphics.BitmapFactory import android.net.Uri+import android.os.Bundle+import android.os.Handler+import android.os.Looper import android.util.Log-import kotlinx.coroutines.delay-import kotlinx.coroutines.withTimeoutOrNull--import kotlinx.coroutines.withContext+import androidx.core.content.FileProvider+import com.vayunmathur.library.util.SecureResultReceiver import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import java.io.File+import kotlin.coroutines.resume  class OCRManager(private val context: Context) { -    private val smolVLMRunner = SmolVLMRunner(context)+    companion object {+        private const val TAG = "OCRManager"+        private const val OA_PACKAGE = "com.vayunmathur.openassistant"+        private const val OA_SERVICE = "$OA_PACKAGE.util.InferenceService"+        private const val MAX_IMAGE_DIMENSION = 512+        private const val SCHEMA = """{"type":"object","properties":{"ocr_text":{"type":"string","description":"All visible text extracted from the image"},"description":{"type":"string","description":"A brief description of the image contents"}},"required":["ocr_text","description"]}"""+    }      suspend fun runOCR(uri: Uri): Pair<String, String>? {-        var attempts = 0-        Log.d("OCRManager", "Starting OCR")+        Log.d(TAG, "Starting OCR via OpenAssistant") -        // Check if model is available-        if (!smolVLMRunner.isModelAvailable()) {-            Log.e("OCRManager", "Model file not available")+        if (!isAvailable()) {+            Log.e(TAG, "OpenAssistant is not installed")             return null         } -        while (attempts < 3) {-            attempts++-            val result = withTimeoutOrNull(120000) { // 2 minute timeout per photo (model inference can be slow)-                performInference(uri)-            }-            if (result != null) {-                return result-            }-            Log.w("OCRManager", "Inference timed out for $uri (Attempt $attempts)")-            if (attempts < 3) {-                delay(5000) // Wait 5 seconds before retry+        return withTimeoutOrNull(60000) {+            try {+                val resizedFile = withContext(Dispatchers.IO) { resizeImage(uri) } ?: return@withTimeoutOrNull null+                try {+                    dispatchInference(resizedFile)+                } finally {+                    resizedFile.delete()+                }+            } catch (e: Exception) {+                Log.e(TAG, "Error running OCR", e)+                null             }         }-        return null     } -    private suspend fun performInference(uri: Uri): Pair<String, String>? = withContext(Dispatchers.IO) {+    private fun resizeImage(uri: Uri): File? {         try {-            val result = smolVLMRunner.runInference(uri)-            if (result != null) {-                Pair(result.ocrText, result.description)+            val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }+            context.contentResolver.openInputStream(uri)?.use {+                BitmapFactory.decodeStream(it, null, options)+            }++            val width = options.outWidth+            val height = options.outHeight+            if (width <= 0 || height <= 0) return null++            var sampleSize = 1+            while (width / sampleSize > MAX_IMAGE_DIMENSION * 2 || height / sampleSize > MAX_IMAGE_DIMENSION * 2) {+                sampleSize *= 2+            }++            val decodeOptions = BitmapFactory.Options().apply { inSampleSize = sampleSize }+            val bitmap = context.contentResolver.openInputStream(uri)?.use {+                BitmapFactory.decodeStream(it, null, decodeOptions)+            } ?: return null++            val scaledBitmap = if (bitmap.width > MAX_IMAGE_DIMENSION || bitmap.height > MAX_IMAGE_DIMENSION) {+                val scale = MAX_IMAGE_DIMENSION.toFloat() / maxOf(bitmap.width, bitmap.height)+                val newWidth = (bitmap.width * scale).toInt()+                val newHeight = (bitmap.height * scale).toInt()+                Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true).also {+                    if (it !== bitmap) bitmap.recycle()+                }             } else {-                null+                bitmap+            }++            val file = File(context.cacheDir, "ocr_tmp_${System.nanoTime()}.jpg")+            file.outputStream().use { out ->+                scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out)             }+            scaledBitmap.recycle()+            return file         } catch (e: Exception) {-            Log.e("OCRManager", "Error running inference", e)-            null+            Log.e(TAG, "Failed to resize image", e)+            return null         }     } -    fun isModelAvailable(): Boolean {-        return smolVLMRunner.isModelAvailable()-    }+    private suspend fun dispatchInference(file: File): Pair<String, String>? =+        suspendCancellableCoroutine { cont ->+            val receiver = SecureResultReceiver(Handler(Looper.getMainLooper())) { code, data ->+                if (code == 0) {+                    val json = data?.getString("json_result")+                    if (json != null) {+                        try {+                            val obj = Json.parseToJsonElement(json).jsonObject+                            val ocrText = obj["ocr_text"]?.jsonPrimitive?.content ?: ""+                            val description = obj["description"]?.jsonPrimitive?.content ?: ""+                            cont.resume(Pair(ocrText, description))+                        } catch (e: Exception) {+                            Log.e(TAG, "Failed to parse JSON result: $json", e)+                            cont.resume(null)+                        }+                    } else {+                        cont.resume(null)+                    }+                } else {+                    val error = data?.getString("error") ?: "Unknown error"+                    Log.e(TAG, "Inference failed: $error")+                    cont.resume(null)+                }+            }++            val fileUri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file) -    fun cleanup() {-        smolVLMRunner.close()+            val intent = Intent().apply {+                component = ComponentName(OA_PACKAGE, OA_SERVICE)+                putExtra("user_text", "Extract all visible text from this image and describe what the image shows.")+                putParcelableArrayListExtra("image_uris", arrayListOf(fileUri))+                putExtra("schema", SCHEMA)+                putExtra("RECEIVER", receiver as android.os.ResultReceiver)+            }++            try {+                context.grantUriPermission(OA_PACKAGE, fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION)+                context.startForegroundService(intent)+            } catch (e: Exception) {+                Log.e(TAG, "Failed to start InferenceService", e)+                cont.resume(null)+            }+        }++    fun isAvailable(): Boolean {+        return try {+            context.packageManager.getPackageInfo(OA_PACKAGE, 0)+            true+        } catch (_: Exception) {+            false+        }     }++    fun cleanup() {} }
photos/src/main/java/com/vayunmathur/photos/util/SentencePieceTokenizer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SentencePieceTokenizer.kt b/photos/src/main/java/com/vayunmathur/photos/util/SentencePieceTokenizer.ktdeleted file mode 100644index c8484ae930..0000000000--- a/photos/src/main/java/com/vayunmathur/photos/util/SentencePieceTokenizer.kt+++ /dev/null@@ -1,221 +0,0 @@-package com.vayunmathur.photos.util--import android.util.Log-import java.io.File-import java.io.InputStream-import java.nio.ByteBuffer-import java.nio.ByteOrder--/**- * Minimal SentencePiece tokenizer that parses a `.model` protobuf file- * and provides encode/decode using greedy longest-match.- *- * The `.model` format is a serialized `ModelProto` with:- *   field 1 = TrainerSpec (message)- *   field 2 = NormalizerSpec (message)- *   field 3 = repeated SentencePiece (message), each containing:- *       field 1 = piece (string)- *       field 2 = score (float)- *       field 3 = type (enum: NORMAL=1, UNKNOWN=2, CONTROL=3, USER_DEFINED=4, BYTE=6)- */-class SentencePieceTokenizer {--    private val pieceToId = mutableMapOf<String, Int>()-    private val idToPiece = mutableMapOf<Int, String>()-    private var unknownId = 0-    private var bosId = 1-    private var eosId = 2--    companion object {-        private const val TAG = "SentencePieceTokenizer"-        // SentencePiece uses U+2581 (▁) as the word-boundary marker-        private const val SPACE_SYMBOL = "\u2581"-    }--    /**-     * Load vocabulary from a SentencePiece .model file.-     * Returns true if loading succeeded.-     */-    fun load(file: File): Boolean {-        return try {-            file.inputStream().use { load(it) }-        } catch (e: Exception) {-            Log.e(TAG, "Failed to load tokenizer model", e)-            false-        }-    }--    fun load(inputStream: InputStream): Boolean {-        return try {-            val data = inputStream.readBytes()-            parseModelProto(data)-            Log.i(TAG, "Loaded ${pieceToId.size} vocabulary pieces")-            true-        } catch (e: Exception) {-            Log.e(TAG, "Failed to parse tokenizer model", e)-            false-        }-    }--    /**-     * Encode text into token IDs using greedy longest-match.-     */-    fun encode(text: String): IntArray {-        // Prepend space symbol and replace spaces with the SentencePiece marker-        val normalized = SPACE_SYMBOL + text.replace(" ", SPACE_SYMBOL)-        val tokens = mutableListOf<Int>()-        var i = 0--        while (i < normalized.length) {-            var bestLen = 0-            var bestId = unknownId--            // Greedy longest match-            for (len in minOf(normalized.length - i, 64) downTo 1) {-                val candidate = normalized.substring(i, i + len)-                val id = pieceToId[candidate]-                if (id != null) {-                    bestLen = len-                    bestId = id-                    break-                }-            }--            if (bestLen == 0) {-                // Fallback: try byte-level encoding for unknown character-                val ch = normalized[i]-                val byteToken = pieceToId["<0x${"%02X".format(ch.code.toByte())}>"]-                if (byteToken != null) {-                    tokens.add(byteToken)-                } else {-                    tokens.add(unknownId)-                }-                i++-            } else {-                tokens.add(bestId)-                i += bestLen-            }-        }--        return tokens.toIntArray()-    }--    /**-     * Decode token IDs back into text.-     */-    fun decode(tokens: IntArray): String {-        val sb = StringBuilder()-        for (id in tokens) {-            if (id == eosId || id == bosId) continue-            val piece = idToPiece[id] ?: continue--            // Skip byte-fallback tokens that look like <0xHH>-            if (piece.startsWith("<0x") && piece.endsWith(">") && piece.length == 6) {-                val byte = piece.substring(3, 5).toIntOrNull(16)-                if (byte != null) {-                    sb.append(byte.toChar())-                    continue-                }-            }--            sb.append(piece)-        }-        // Replace SentencePiece space markers with actual spaces and trim leading space-        return sb.toString().replace(SPACE_SYMBOL, " ").trimStart()-    }--    val vocabSize: Int get() = pieceToId.size-    val eosTokenId: Int get() = eosId-    val bosTokenId: Int get() = bosId--    // --- Raw protobuf parsing -----    private fun parseModelProto(data: ByteArray) {-        val buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)-        var pieceIndex = 0--        while (buf.hasRemaining()) {-            val tag = readVarInt(buf).toInt()-            val fieldNumber = tag ushr 3-            val wireType = tag and 0x7--            when (wireType) {-                0 -> readVarInt(buf) // varint - skip-                1 -> buf.position(buf.position() + 8) // 64-bit - skip-                2 -> { // length-delimited-                    val length = readVarInt(buf).toInt()-                    if (fieldNumber == 3) {-                        // This is a SentencePiece entry-                        val pieceData = ByteArray(length)-                        buf.get(pieceData)-                        parseSentencePiece(pieceData, pieceIndex)-                        pieceIndex++-                    } else {-                        // Skip other fields-                        buf.position(buf.position() + length)-                    }-                }-                5 -> buf.position(buf.position() + 4) // 32-bit - skip-                else -> break-            }-        }--        // Identify special token IDs-        pieceToId["<unk>"]?.let { unknownId = it }-        pieceToId["<s>"]?.let { bosId = it }-        pieceToId["</s>"]?.let { eosId = it }-    }--    private fun parseSentencePiece(data: ByteArray, index: Int) {-        val buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)-        var piece: String? = null--        while (buf.hasRemaining()) {-            val tag = readVarInt(buf).toInt()-            val fieldNumber = tag ushr 3-            val wireType = tag and 0x7--            when (wireType) {-                0 -> readVarInt(buf) // varint (type field, etc.) - skip value-                1 -> buf.position(buf.position() + 8)-                2 -> {-                    val length = readVarInt(buf).toInt()-                    if (fieldNumber == 1) {-                        // piece string-                        val strBytes = ByteArray(length)-                        buf.get(strBytes)-                        piece = String(strBytes, Charsets.UTF_8)-                    } else {-                        buf.position(buf.position() + length)-                    }-                }-                5 -> {-                    if (fieldNumber == 2) {-                        // score float - skip (we don't need it for greedy matching)-                        buf.position(buf.position() + 4)-                    } else {-                        buf.position(buf.position() + 4)-                    }-                }-                else -> break-            }-        }--        if (piece != null) {-            pieceToId[piece] = index-            idToPiece[index] = piece-        }-    }--    private fun readVarInt(buf: ByteBuffer): Long {-        var result = 0L-        var shift = 0-        while (buf.hasRemaining()) {-            val b = buf.get().toInt() and 0xFF-            result = result or ((b and 0x7F).toLong() shl shift)-            if (b and 0x80 == 0) break-            shift += 7-        }-        return result-    }-}
photos/src/main/java/com/vayunmathur/photos/util/SmolVLMRunner.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SmolVLMRunner.kt b/photos/src/main/java/com/vayunmathur/photos/util/SmolVLMRunner.ktdeleted file mode 100644index 0f3ed433e8..0000000000--- a/photos/src/main/java/com/vayunmathur/photos/util/SmolVLMRunner.kt+++ /dev/null@@ -1,248 +0,0 @@-package com.vayunmathur.photos.util--import android.content.Context-import android.graphics.Bitmap-import android.graphics.BitmapFactory-import android.net.Uri-import android.util.Log-import com.google.ai.edge.litert.Accelerator-import com.google.ai.edge.litert.CompiledModel-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitive-import java.io.File--/**- * Result from SmolVLM model inference containing OCR text and scene description.- */-data class SmolVLMResult(-    val ocrText: String,-    val description: String,-)--/**- * Runner for SmolVLM-256M-Instruct TFLite model.- * Handles loading the model, preprocessing images, and running inference for OCR and scene description.- */-class SmolVLMRunner(private val context: Context) {-    private var model: CompiledModel? = null-    private var tokenizer: SentencePieceTokenizer? = null-    private val json = Json { ignoreUnknownKeys = true }--    companion object {-        private const val TAG = "SmolVLMRunner"-        const val MODEL_FILE_NAME = "smalvlm-256m-instruct_q8_ekv2048_single_image.tflite"-        const val TOKENIZER_FILE_NAME = "tokenizer.model"-        private const val IMAGE_SIZE = 512-        private const val MAX_TOKENS = 256-    }--    /**-     * Initialize the CompiledModel and load the tokenizer.-     * Returns true if successful, false otherwise.-     */-    suspend fun initialize(): Boolean = withContext(Dispatchers.IO) {-        try {-            val externalDir = context.getExternalFilesDir(null)-            val modelFile = File(externalDir, MODEL_FILE_NAME)-            val tokenizerFile = File(externalDir, TOKENIZER_FILE_NAME)--            if (!modelFile.exists()) {-                Log.e(TAG, "Model file not found: ${modelFile.absolutePath}")-                return@withContext false-            }-            if (!tokenizerFile.exists()) {-                Log.e(TAG, "Tokenizer file not found: ${tokenizerFile.absolutePath}")-                return@withContext false-            }--            // Load tokenizer-            val tok = SentencePieceTokenizer()-            if (!tok.load(tokenizerFile)) {-                Log.e(TAG, "Failed to load tokenizer")-                return@withContext false-            }-            tokenizer = tok-            Log.i(TAG, "Tokenizer loaded with ${tok.vocabSize} pieces")--            // Load model using LiteRT 2.x API-            val options = CompiledModel.Options(Accelerator.CPU).apply {-                cpuOptions = CompiledModel.CpuOptions(numThreads = 4)-            }-            model = CompiledModel.create(modelFile.absolutePath, options)-            Log.i(TAG, "SmolVLM model initialized successfully")-            true-        } catch (e: Exception) {-            Log.e(TAG, "Failed to initialize SmolVLM model", e)-            false-        }-    }--    /**-     * Run inference on an image to extract OCR text and scene description.-     * @param uri URI of the image to process-     * @return SmolVLMResult containing ocrText and description, or null if failed-     */-    suspend fun runInference(uri: Uri): SmolVLMResult? = withContext(Dispatchers.IO) {-        try {-            val compiledModel = model ?: run {-                if (!initialize()) {-                    Log.e(TAG, "Failed to initialize model")-                    return@withContext null-                }-                model!!-            }-            val tok = tokenizer ?: run {-                Log.e(TAG, "Tokenizer not initialized")-                return@withContext null-            }--            // Load and preprocess image-            val bitmap = loadAndPreprocessImage(uri) ?: run {-                Log.e(TAG, "Failed to load image: $uri")-                return@withContext null-            }--            // Prepare image buffer-            val imageData = preprocessBitmap(bitmap)-            bitmap.recycle()--            // Tokenize prompt-            val prompt = "<image>\nExtract all visible text from this image and provide a brief scene description. Return JSON with 'text' and 'description' fields."-            val promptTokenIds = tok.encode(prompt)-            val paddedTokens = IntArray(MAX_TOKENS)-            promptTokenIds.copyInto(paddedTokens, endIndex = minOf(promptTokenIds.size, MAX_TOKENS))--            // Create input buffers and write data-            val inputBuffers = compiledModel.createInputBuffers()-            inputBuffers[0].writeFloat(imageData)-            inputBuffers[1].writeInt(paddedTokens)--            // Run inference (creates output buffers automatically and returns them)-            val outputBuffers = compiledModel.run(inputBuffers)--            // Read output tokens-            val outputTokens = outputBuffers[0].readInt()--            // Clean up buffers-            inputBuffers.forEach { it.close() }-            outputBuffers.forEach { it.close() }--            // Decode output tokens to text, stripping padding and EOS-            val validTokens = outputTokens.takeWhile { it != 0 && it != tok.eosTokenId }-            val outputText = tok.decode(validTokens.toIntArray())-            Log.d(TAG, "Model output: $outputText")--            // Parse JSON output-            parseOutput(outputText)-        } catch (e: Exception) {-            Log.e(TAG, "Error running inference", e)-            null-        }-    }--    /**-     * Load and preprocess image from URI.-     */-    private fun loadAndPreprocessImage(uri: Uri): Bitmap? {-        return try {-            context.contentResolver.openInputStream(uri)?.use { inputStream ->-                val options = BitmapFactory.Options().apply {-                    inJustDecodeBounds = true-                }-                BitmapFactory.decodeStream(inputStream, null, options)--                // Calculate sample size for memory efficiency-                var sampleSize = 1-                while (options.outWidth / sampleSize > IMAGE_SIZE * 2 || options.outHeight / sampleSize > IMAGE_SIZE * 2) {-                    sampleSize *= 2-                }--                val decodeOptions = BitmapFactory.Options().apply {-                    inSampleSize = sampleSize-                }--                context.contentResolver.openInputStream(uri)?.use { stream ->-                    val original = BitmapFactory.decodeStream(stream, null, decodeOptions)-                    original?.let {-                        Bitmap.createScaledBitmap(it, IMAGE_SIZE, IMAGE_SIZE, true).also { scaled ->-                            if (scaled != it) it.recycle()-                        }-                    }-                }-            }-        } catch (e: Exception) {-            Log.e(TAG, "Error loading image", e)-            null-        }-    }--    /**-     * Preprocess bitmap into a float array for model input.-     * Normalizes pixels to [0, 1] in RGB order.-     */-    private fun preprocessBitmap(bitmap: Bitmap): FloatArray {-        val pixels = IntArray(IMAGE_SIZE * IMAGE_SIZE)-        bitmap.getPixels(pixels, 0, IMAGE_SIZE, 0, 0, IMAGE_SIZE, IMAGE_SIZE)--        val floatArray = FloatArray(IMAGE_SIZE * IMAGE_SIZE * 3)-        for (i in pixels.indices) {-            val pixel = pixels[i]-            floatArray[i * 3] = ((pixel shr 16) and 0xFF) / 255.0f-            floatArray[i * 3 + 1] = ((pixel shr 8) and 0xFF) / 255.0f-            floatArray[i * 3 + 2] = (pixel and 0xFF) / 255.0f-        }-        return floatArray-    }--    /**-     * Parse model output JSON into SmolVLMResult.-     */-    private fun parseOutput(outputText: String): SmolVLMResult? {-        return try {-            val jsonStart = outputText.indexOf('{')-            val jsonEnd = outputText.lastIndexOf('}')-            if (jsonStart >= 0 && jsonEnd > jsonStart) {-                val jsonStr = outputText.substring(jsonStart, jsonEnd + 1)-                val element = json.parseToJsonElement(jsonStr).jsonObject-                val text = element["text"]?.jsonPrimitive?.content ?: ""-                val description = element["description"]?.jsonPrimitive?.content ?: ""-                SmolVLMResult(text, description)-            } else {-                SmolVLMResult("", outputText.trim())-            }-        } catch (e: Exception) {-            Log.e(TAG, "Error parsing output", e)-            null-        }-    }--    /**-     * Check if both model and tokenizer files exist.-     */-    fun isModelAvailable(): Boolean {-        val externalDir = context.getExternalFilesDir(null)-        val modelFile = File(externalDir, MODEL_FILE_NAME)-        val tokenizerFile = File(externalDir, TOKENIZER_FILE_NAME)-        return modelFile.exists() && modelFile.length() > 0-            && tokenizerFile.exists() && tokenizerFile.length() > 0-    }--    /**-     * Get the model file path.-     */-    fun getModelFile(): File {-        return File(context.getExternalFilesDir(null), MODEL_FILE_NAME)-    }--    /**-     * Clean up resources.-     */-    fun close() {-        model?.close()-        model = null-        tokenizer = null-    }-}
photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.ktindex 458154806f..a192c754ae 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt@@ -34,6 +34,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock@@ -359,8 +360,8 @@ suspend fun runOCR(photos: List<Photo>, database: PhotoDatabase, context: Contex     val ocrManager = OCRManager(context)      // Check if model is available before processing-    if (!ocrManager.isModelAvailable()) {-        Log.w("SyncWorker", "OCR model not available, skipping OCR processing")+    if (!ocrManager.isAvailable()) {+        Log.w("SyncWorker", "OpenAssistant not installed, skipping OCR processing")         ocrManager.cleanup()         return@coroutineScope     }@@ -369,10 +370,9 @@ suspend fun runOCR(photos: List<Photo>, database: PhotoDatabase, context: Contex         ensureActive()         if (!dataStore.getBoolean("image_understanding_enabled", false)) {             ocrManager.cleanup()-            return@forEach+            return@coroutineScope         } -        // Double check if another thread/worker finished this photo while we were waiting         val alreadyExists = database.query(SimpleSQLiteQuery("SELECT EXISTS(SELECT 1 FROM PhotoOCR WHERE rowid = ${photo.id})"), null).use { cursor ->             cursor.moveToFirst() && cursor.getInt(0) == 1         }@@ -385,13 +385,13 @@ suspend fun runOCR(photos: List<Photo>, database: PhotoDatabase, context: Contex                 photoDao.upsertOCR(PhotoOCR(photo.id, ocrText, description))                 Log.i("SyncWorker", "OCR for ${photo.id} produced text: ${ocrText.take(50)}, description: ${description.take(50)}")             } else {-                // Insert empty entry so this photo isn't retried-                photoDao.upsertOCR(PhotoOCR(photo.id, "", ""))-                Log.w("SyncWorker", "OCR for ${photo.id} returned null, marking as processed")+                Log.w("SyncWorker", "OCR for ${photo.id} returned null, will retry later")             }         } catch (e: Exception) {-            Log.e("SyncWorker", "Error running OCR for photo ${photo.id}", e)+            Log.e("SyncWorker", "Error running OCR for photo ${photo.id}, will retry later", e)         }++        delay(30000)     }      ocrManager.cleanup()
proguard-rules.pro
diff --git a/proguard-rules.pro b/proguard-rules.proindex f22143f592..c8e21cc923 100644--- a/proguard-rules.pro+++ b/proguard-rules.pro@@ -16,6 +16,9 @@ # LiteRT LM / Gemma 4 -keep class com.google.ai.edge.litertlm.** { *; } +# LiteRT Core - prevent R8 from deleting LiteRT classes used via reflection+-keep class com.google.ai.edge.litert.** { *; }+ -keepclasseswithmembernames class * {     native <methods>; }\ No newline at end of file
version.txt
diff --git a/version.txt b/version.txtindex 1b14b46bd1..f46b35d8e0 100644--- a/version.txt+++ b/version.txt@@ -1,2 +1,2 @@-20260603-v2.5.1+20260604+v2.5.2
weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.ktindex 54195c5cdb..7d0163e220 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/HomePage.kt@@ -170,7 +170,7 @@ private fun LocationPage(         ) {             SummaryCard(forecast = forecast, tempUnit = tempUnit)             if (forecast.hourly != null) {-                HourlyCard(hourly = forecast.hourly, tempUnit = tempUnit)+                HourlyCard(hourly = forecast.hourly, tempUnit = tempUnit, utcOffsetSeconds = forecast.utcOffsetSeconds)             }             if (daily != null) {                 DailyCard(daily = daily, tempUnit = tempUnit)
weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.kt b/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.ktindex 33da7b1d87..f592dd023d 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/components/HourlyCard.kt@@ -18,7 +18,6 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.toShape import androidx.compose.runtime.Composable-import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha@@ -29,7 +28,10 @@ import com.vayunmathur.weather.network.Hourly import com.vayunmathur.weather.util.TemperatureUnit import com.vayunmathur.weather.util.formatTemperatureCompact import com.vayunmathur.weather.util.weatherConditionForCode+import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone+import kotlinx.datetime.UtcOffset+import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Instant @@ -41,23 +43,21 @@ import kotlin.time.Instant  * `primary`.  */ @Composable-fun HourlyCard(hourly: Hourly, tempUnit: TemperatureUnit) {+fun HourlyCard(hourly: Hourly, tempUnit: TemperatureUnit, utcOffsetSeconds: Int = 0) {     val nowSec = System.currentTimeMillis() / 1000-    val cells = remember(hourly) {-        hourly.time.indices-            .mapNotNull { i ->-                val ts = parseIsoToEpochSec(hourly.time.getOrNull(i)) ?: return@mapNotNull null-                if (ts < nowSec - 3600) return@mapNotNull null-                HourCell(-                    epochSec = ts,-                    temperature = hourly.temperature.getOrNull(i) ?: 0.0,-                    weatherCode = hourly.weatherCode.getOrNull(i) ?: 0,-                    precip = hourly.precipitationProbability.getOrNull(i) ?: 0,-                    isDay = (hourly.isDay.getOrNull(i) ?: 1) == 1,-                )-            }-            .take(24)-    }+    val cells = hourly.time.indices+        .mapNotNull { i ->+            val ts = parseIsoToEpochSec(hourly.time.getOrNull(i), utcOffsetSeconds) ?: return@mapNotNull null+            if (ts < nowSec - 3600) return@mapNotNull null+            HourCell(+                epochSec = ts,+                temperature = hourly.temperature.getOrNull(i) ?: 0.0,+                weatherCode = hourly.weatherCode.getOrNull(i) ?: 0,+                precip = hourly.precipitationProbability.getOrNull(i) ?: 0,+                isDay = (hourly.isDay.getOrNull(i) ?: 1) == 1,+            )+        }+        .take(24)     if (cells.isEmpty()) return      Surface(@@ -147,9 +147,17 @@ private data class HourCell(     val isDay: Boolean, ) -private fun parseIsoToEpochSec(iso: String?): Long? {+private fun parseIsoToEpochSec(iso: String?, utcOffsetSeconds: Int = 0): Long? {     if (iso == null) return null-    return runCatching { Instant.parse("$iso:00Z").epochSeconds }.getOrNull()+    // Open-Meteo returns local time strings when timezone=auto+    // We need to parse them as local time and apply the UTC offset+    return runCatching {+        // Parse as local datetime, then convert to instant using the offset+        val localDateTime = kotlinx.datetime.LocalDateTime.parse(iso)+        val offset = kotlinx.datetime.UtcOffset(seconds = utcOffsetSeconds)+        localDateTime.toInstant(offset).epochSeconds+    }.getOrNull()+        ?: runCatching { Instant.parse("$iso:00Z").epochSeconds }.getOrNull()         ?: runCatching { Instant.parse(iso).epochSeconds }.getOrNull() }