Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
Desk cards can be dragged into place; the toolbar holds five
chethan616b689f95c177f
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.ktindex cd8e73c..3f551c6 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt@@ -3198,6 +3198,20 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrif (deskPages.isNotEmpty()) deskPages.removeAt(deskPages.lastIndex)}+ /** Bumped when the desk's hand-made order changes (the desk reads it again). */+ var deskOrderVersion by mutableStateOf(0)+ private set++ /** The order the user dragged [filter]'s cards into (their keys), or empty: the desk's own. */+ fun deskOrder(filter: com.chethan616.clearpdf.ui.home.DeskFilter): List<String> =+ appPrefs.getString("deskOrder_${filter.name}", null)?.split('\n')?.filter { it.isNotBlank() }.orEmpty()++ /** Keep [keys] as [filter]'s order (a card dropped in a new place). */+ fun saveDeskOrder(filter: com.chethan616.clearpdf.ui.home.DeskFilter, keys: List<String>) {+ appPrefs.edit().putString("deskOrder_${filter.name}", keys.joinToString("\n")).apply()+ deskOrderVersion+++ }+/** The desk turns to this shelf (asked from a desk page), then forgets it. */var deskShelf by mutableStateOf<com.chethan616.clearpdf.ui.home.DeskFilter?>(null)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/DeskDrag.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/DeskDrag.ktnew file mode 100644index 0000000..211bff4--- /dev/null+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/DeskDrag.kt@@ -0,0 +1,175 @@+package com.chethan616.clearpdf.ui.home++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridItemInfo+import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.unit.dp+import androidx.compose.ui.zIndex+import kotlinx.coroutines.withTimeoutOrNull++/**+ * The desk's cards in the order the user dragged them to (keys, saved per shelf), over [items] as the+ * desk would set them: the saved cards take the places saved cards have, in the saved order; a card+ * not yet placed by hand (a new note) keeps its own place.+ */+fun arrangeDesk(items: List<DeskItem>, saved: List<String>): List<DeskItem> {+ if (saved.isEmpty()) return items+ val rank = saved.withIndex().associate { it.value to it.index }+ val placed = items.filter { it.key in rank }.sortedBy { rank.getValue(it.key) }.iterator()+ return items.map { if (it.key in rank) placed.next() else it }+}++/** A card being carried across the desk: which, where the finger holds it and is, and the order as it goes. */+@Stable+class DeskDrag {+ var key by mutableStateOf<String?>(null)+ private set++ /** The order while a card is carried (null otherwise): the desk shows this. */+ var live by mutableStateOf<List<String>?>(null)+ private set++ /** Where the finger is, in the grid. */+ var pointer by mutableStateOf(Offset.Zero)+ internal set++ /** Where on the card the finger took hold of it. */+ var grab = Offset.Zero+ private set++ /** The card last traded places with, so a pair of different heights never flips back and forth. */+ internal var lastOver: String? = null++ internal fun start(k: String, at: Offset, finger: Offset, order: List<String>) {+ key = k+ grab = at+ pointer = finger+ live = order+ lastOver = null+ }++ /** The carried card takes [over]'s place, the cards between moving one along. */+ internal fun moveTo(over: String) {+ val k = key ?: return+ val list = live?.toMutableList() ?: return+ val from = list.indexOf(k)+ val to = list.indexOf(over)+ if (from < 0 || to < 0 || from == to) return+ list.removeAt(from)+ list.add(to, k)+ live = list+ lastOver = over+ }++ internal fun end(): List<String>? {+ val order = live+ key = null+ live = null+ lastOver = null+ return order+ }+}++private fun LazyStaggeredGridItemInfo.contains(p: Offset, inset: Float = 0f): Boolean {+ val ix = size.width * inset+ val iy = size.height * inset+ return p.x >= offset.x + ix && p.x < offset.x + size.width - ix && p.y >= offset.y + iy && p.y < offset.y + size.height - iy+}++/**+ * Cards are dragged to new places on the desk, as icons on a home screen: a card held still opens its+ * menu (its own long press, untouched); moved while held, the menu gives way ([onLift]) and the card+ * lifts and follows the finger, the others making room as it passes over them; near the top or the+ * bottom the desk scrolls along; let go, the new order is kept ([onDrop]). Only cards whose keys are in+ * [draggable] move. Watched before the cards see the touch, so a tap, a scroll and a plain long press+ * are theirs exactly as before.+ */+fun Modifier.deskDragging(+ grid: LazyStaggeredGridState,+ drag: DeskDrag,+ draggable: () -> Set<String>,+ order: () -> List<String>,+ onLift: () -> Unit,+ onDrop: (List<String>) -> Unit,+): Modifier = pointerInput(Unit) {+ val slop = viewConfiguration.touchSlop+ val longPress = viewConfiguration.longPressTimeoutMillis+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)+ val hit = grid.layoutInfo.visibleItemsInfo.firstOrNull { it.contains(down.position) } ?: return@awaitEachGesture+ val key = hit.key as? String ?: return@awaitEachGesture+ if (key !in draggable()) return@awaitEachGesture+ // held still for a long press (moved or lifted first: a scroll or a tap, not ours)+ val gaveUp = withTimeoutOrNull(longPress) {+ while (true) {+ val ev = awaitPointerEvent(PointerEventPass.Initial)+ val c = ev.changes.firstOrNull { it.id == down.id } ?: return@withTimeoutOrNull true+ if (!c.pressed || (c.position - down.position).getDistance() > slop) return@withTimeoutOrNull true+ }+ @Suppress("UNREACHABLE_CODE")+ true+ }+ if (gaveUp != null) return@awaitEachGesture+ // held: let go now and it was just the long press (the card's menu is open); move and it lifts+ var finger = down.position+ while (true) {+ val ev = awaitPointerEvent(PointerEventPass.Initial)+ val c = ev.changes.firstOrNull { it.id == down.id } ?: return@awaitEachGesture+ if (!c.pressed) return@awaitEachGesture+ finger = c.position+ if ((finger - down.position).getDistance() > slop) break+ }+ val now = grid.layoutInfo.visibleItemsInfo.firstOrNull { it.key == key } ?: hit+ drag.start(key, down.position - Offset(now.offset.x.toFloat(), now.offset.y.toFloat()), finger, order())+ onLift()+ val edge = 96.dp.toPx()+ try {+ while (true) {+ val ev = awaitPointerEvent(PointerEventPass.Initial)+ val c = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (!c.pressed) break+ c.consume()+ drag.pointer = c.position+ // over another card's middle: it makes room (each pair trades once until the finger moves on)+ val over = grid.layoutInfo.visibleItemsInfo.firstOrNull { it.key != key && it.contains(c.position, 0.18f) }?.key as? String+ if (over == null) drag.lastOver = null+ else if (over != drag.lastOver && over in draggable()) drag.moveTo(over)+ // near an edge the desk scrolls along+ val h = size.height.toFloat()+ val dy = when {+ c.position.y < edge -> -(edge - c.position.y) * 0.22f+ c.position.y > h - edge -> (c.position.y - (h - edge)) * 0.22f+ else -> 0f+ }+ if (dy != 0f) grid.dispatchRawDelta(dy)+ }+ } finally {+ drag.end()?.let(onDrop)+ }+ }+}++/** The carried card: above the others, a touch larger with its shadow, under the finger where it took hold. */+fun Modifier.carried(drag: DeskDrag, key: String, grid: LazyStaggeredGridState): Modifier =+ if (drag.key != key) this else this.zIndex(1f).graphicsLayer {+ val info = grid.layoutInfo.visibleItemsInfo.firstOrNull { it.key == key }+ if (info != null) {+ translationX = drag.pointer.x - drag.grab.x - info.offset.x+ translationY = drag.pointer.y - drag.grab.y - info.offset.y+ }+ scaleX = 1.05f+ scaleY = 1.05f+ shadowElevation = 18.dp.toPx()+ shape = CardShape+ clip = false+ }diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.ktindex 28342c3..2cfe3ad 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt@@ -197,8 +197,15 @@ fun HomeScreen(vm: AppViewModel, desk: DeskState) {// covers the desk (nothing of it drawn) or has gone.val held = remember { arrayOf(fresh) }if (vm.deskStill) held[0] = fresh- val items = held[0]+ // the cards in the order the user dragged them to (per shelf), and, while one is carried, as it goes+ val drag = remember { DeskDrag() }+ val saved = remember(filter, vm.deskOrderVersion) { vm.deskOrder(filter) }+ val arranged = remember(held[0], saved) { arrangeDesk(held[0], saved) }+ val items = drag.live?.let { keys -> keys.mapNotNull { k -> arranged.firstOrNull { it.key == k } } } ?: arrangedval grid = rememberLazyStaggeredGridState()+ val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()+ // the gesture runs from the first frame on: it reads the cards as they are now, not as they were then+ val itemsNow by androidx.compose.runtime.rememberUpdatedState(items)LaunchedEffect(filter) { grid.animateScrollToItem(0) }// the cards rise in when the desk (or a chip) first shows them, never while scrollingvar intro by remember { mutableStateOf(true) }@@ -223,7 +230,23 @@ fun HomeScreen(vm: AppViewModel, desk: DeskState) {columns = StaggeredGridCells.Fixed(2),state = grid,// glass in the scrolling desk samples the soft wallpaper: while it scrolls, ten times a second is plenty- modifier = Modifier.fillMaxSize().throttleBackdrops { grid.isScrollInProgress },+ modifier = Modifier.fillMaxSize().throttleBackdrops { grid.isScrollInProgress }+ // a card held and moved goes where it is put, as icons on a home screen+ .deskDragging(+ grid, drag,+ draggable = { itemsNow.map { it.key }.toSet() },+ order = { itemsNow.map { it.key } },+ onLift = {+ // the long press's menu gives way to the card being carried+ actionsFor = null+ vm.fileMenu = null+ feel(com.chethan616.clearpdf.ui.glass.Feel.Press)+ },+ onDrop = { keys ->+ feel(com.chethan616.clearpdf.ui.glass.Feel.Confirm)+ vm.saveDeskOrder(filter, keys)+ },+ ),contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = DeskDockClearance + 40.dp),verticalItemSpacing = 12.dp,horizontalArrangement = Arrangement.spacedBy(12.dp),@@ -239,7 +262,10 @@ fun HomeScreen(vm: AppViewModel, desk: DeskState) {FilterChips(filter) { filter = it }}itemsIndexed(items, key = { _, it -> it.key }) { i, item ->- val m = Modifier.fillMaxWidth().riseIn(i, active = intro).onGloballyPositioned { bounds[item.key] = it.boundsInWindow() }+ // the others glide aside as a carried card passes; the carried one follows the finger+ val m = Modifier.animateItem(fadeInSpec = null, fadeOutSpec = null, placementSpec = if (drag.key == item.key) null else androidx.compose.animation.core.spring<androidx.compose.ui.unit.IntOffset>(0.82f, 420f))+ .carried(drag, item.key, grid)+ .fillMaxWidth().riseIn(i, active = intro).onGloballyPositioned { bounds[item.key] = it.boundsInWindow() }val long: (Note) -> Unit = { n -> actionsAnchor = bounds[item.key] ?: Rect.Zero; actionsFor = n }when (item) {is DeskItem.Of -> when (item.note.kind) {diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.ktindex 7abd045..4b5c8de 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt@@ -99,8 +99,8 @@ enum class QuickTool(val id: String, @StringRes val label: Int, @StringRes val tPrint("print", R.string.sheet_print, R.string.sheet_print, LucideIcons.Printer, ToolHues.export);companion object {- /** The bar as it comes: the reference's default tools and order. */- val DEFAULT_BAR = listOf(Edit, Comment, Highlight, Draw, FillSign, Export)+ /** The bar as it comes: the reference's default tools and order, the five a phone's bar holds (Export is in More tools). */+ val DEFAULT_BAR = listOf(Edit, Comment, Highlight, Draw, FillSign)/** A Word document's bar: its engine reads it aloud, exports and converts it, and prints it. */val WORD = listOf(Edit, ReadAloud, ExportPdf, SaveAs, Print)@@ -120,11 +120,7 @@ enum class QuickTool(val id: String, @StringRes val label: Int, @StringRes val t}/** How many tools fit on the bar beside More tools at a screen [widthDp] wide. */-fun toolbarSlots(widthDp: Int): Int = when {- widthDp >= 768 -> 8- widthDp >= 460 -> 7- else -> 6-}+fun toolbarSlots(widthDp: Int): Int = dockSlots(widthDp)/** The bar's tools and More tools' order, as the user arranged them (kept in the app's preferences). */@Stablediff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.ktindex b60cb2e..fcee4dc 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt@@ -334,7 +334,7 @@ private fun StepButton(icon: ImageVector, label: String, enabled: Boolean, onCli}/** How many tools fit in the dock at a screen [widthDp] wide (More tools takes its own bubble). */-private fun dockSlots(widthDp: Int): Int = when {+internal fun dockSlots(widthDp: Int): Int = when {widthDp >= 768 -> 8widthDp >= 460 -> 6else -> 5diff --git a/android/app/src/test/java/com/chethan616/clearpdf/ui/QuickToolbarTest.kt b/android/app/src/test/java/com/chethan616/clearpdf/ui/QuickToolbarTest.ktindex 04ae060..c20ddbc 100644--- a/android/app/src/test/java/com/chethan616/clearpdf/ui/QuickToolbarTest.kt+++ b/android/app/src/test/java/com/chethan616/clearpdf/ui/QuickToolbarTest.kt@@ -10,8 +10,9 @@ import org.junit.Testclass QuickToolbarTest {@Testfun slotsGrowWithTheScreen() {- assertEquals(6, toolbarSlots(411))- assertEquals(7, toolbarSlots(460))+ // as many as the bar on the page shows: five on a phone (a sixth came out too small)+ assertEquals(5, toolbarSlots(411))+ assertEquals(6, toolbarSlots(460))assertEquals(8, toolbarSlots(800))// the default bar fits a phone held uprightassertTrue(QuickTool.DEFAULT_BAR.size <= toolbarSlots(360))