Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

Word paragraphs edited in place as a PDF's are; one search and editable cells in sheets; glass photo dials; PDFs shelf holds PDFs

chethan616913a3a8559ee
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.kt
index 9e81f84..f653f75 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
@@ -2409,8 +2409,9 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
/** Where the caret (or the selection) is in [wordEditing]. */
var wordCaret by mutableStateOf<com.chethan616.clearpdf.core.WordCaret?>(null)
- /** Bumped by each tap that places the caret: the keyboard comes up (again) for it. */
- var wordKeyboard by mutableStateOf(0)
+ /** The paragraph open for editing in place (as a PDF's paragraph is), and its text as typed. */
+ var wordPara by mutableStateOf<com.chethan616.clearpdf.core.WordParagraph?>(null)
+ var wordDraft by mutableStateOf("")
/** WordCraft's formatting at the caret (`bold`, `italic`, ... as `format.state` gives it). */
var wordFormat by mutableStateOf(org.json.JSONObject())
@@ -2419,6 +2420,7 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
fun startWordEdit(doc: OpenDocument) {
wordEditing = doc
wordCaret = null
+ wordPara = null
doc.selection.clear()
doc.controller.barsVisible = true
// the keyboard waits for a place to type: a tap on the page puts the caret there
@@ -2428,9 +2430,24 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
/** Leave editing; the changes are saved with the document (as on closing it). */
fun stopWordEdit() {
val doc = wordEditing ?: return
- wordEditing = null
- wordCaret = null
- viewModelScope.launch { save(doc, quiet = true) }
+ viewModelScope.launch {
+ commitWordPara(doc)
+ wordEditing = null
+ wordCaret = null
+ save(doc, quiet = true)
+ }
+ }
+
+ /** The open paragraph's new text into the document (one undoable change), and the box closed. */
+ private suspend fun commitWordPara(doc: OpenDocument) {
+ val para = wordPara ?: return
+ val eng = engine ?: return
+ val text = wordDraft
+ wordPara = null
+ if (text == para.text) return
+ runCatching { eng.command { wordCommand(doc.id, "text.insert", Engine.toJson(mapOf("text" to text)).toString()) } }
+ .onFailure { tell(it.userMessage) }
+ refresh(doc)
}
/** Run WordCraft command [command] on [doc], then show its result: the pages, caret and formatting. */
@@ -2445,9 +2462,16 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
}
/** A tap on [doc]'s page while editing: the caret goes there ([extend]: the selection grows to it). */
- fun wordTap(doc: OpenDocument, at: com.chethan616.clearpdf.ui.viewer.PagePoint, extend: Boolean = false) {
- wordRun(doc, "caret.set", mapOf("page" to at.page, "x" to at.x, "y" to at.y, "extend" to extend))
- wordKeyboard++
+ fun wordTap(doc: OpenDocument, at: com.chethan616.clearpdf.ui.viewer.PagePoint) {
+ val eng = engine ?: return
+ viewModelScope.launch {
+ // the paragraph open before goes in first, then the one tapped opens in its box
+ commitWordPara(doc)
+ val para = runCatching { eng.command { wordParagraphAt(doc.id, at.page.toUInt(), at.x, at.y) } }.getOrNull() ?: return@launch
+ refreshWordCaret(doc)
+ wordDraft = para.text
+ wordPara = para
+ }
}
/** A long press while editing: the word there is selected (to format or replace it). */
@@ -2462,7 +2486,6 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
}
}.onFailure { tell(it.userMessage) }
refreshWordCaret(doc)
- wordKeyboard++
}
}
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.kt
index 6604f8c..511ff69 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
@@ -154,7 +154,9 @@ fun deskItems(filter: DeskFilter, notes: List<Note>, recents: List<FileRow>, day
DeskFilter.Todo -> sorted.filter { it.kind == NoteKind.List }.map { DeskItem.Of(it) }
DeskFilter.Audio -> sorted.filter { it.kind == NoteKind.Voice }.map { DeskItem.Of(it) }
DeskFilter.Images -> sorted.filter { it.images.isNotEmpty() }.map { DeskItem.Picture(it) }
- DeskFilter.Pdfs -> if (recents.isEmpty()) emptyList() else listOf(DeskItem.Files, DeskItem.Pdfs(recents.size)) + recents.map { DeskItem.Doc(it) }
+ // the PDFs shelf holds PDFs only (Word, slides and sheets live in Files)
+ DeskFilter.Pdfs -> recents.filter { com.chethan616.clearpdf.engine.DocumentTypes.kindOf(it.name) == com.chethan616.clearpdf.engine.DocumentTypes.Kind.Pdf }
+ .let { pdfs -> if (pdfs.isEmpty()) emptyList() else listOf(DeskItem.Files, DeskItem.Pdfs(pdfs.size)) + pdfs.map { DeskItem.Doc(it) } }
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt
index 8238761..f408862 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt
@@ -227,16 +227,18 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
private fun Dial(a: Adjust, value: Float, chosen: Boolean, onClick: () -> Unit) {
val span = maxOf(abs(a.min), abs(a.max))
val part = (value / span).coerceIn(-1f, 1f)
- Box(Modifier.size(60.dp).pressable(onClick), contentAlignment = Alignment.Center) {
- Canvas(Modifier.size(58.dp)) {
- val stroke = 2.6.dp.toPx()
+ // the app's glass button, its ring drawn round it
+ Box(Modifier.size(62.dp), contentAlignment = Alignment.Center) {
+ GlassCircle(onClick = onClick, size = 52.dp, label = stringResource(a.label), ink = Color.White) {
+ GlassIcon(a.icon, null, Modifier.size(21.dp), tint = if (chosen) Candy.Lemon else Color.White)
+ }
+ Canvas(Modifier.size(62.dp)) {
+ val stroke = 2.4.dp.toPx()
val inset = stroke / 2
val box = Size(size.width - stroke, size.height - stroke)
- drawCircle(Color.White.copy(alpha = if (chosen) 0.16f else 0.08f), radius = size.minDimension / 2)
- drawArc(Color.White.copy(alpha = 0.22f), 0f, 360f, false, Offset(inset, inset), box, style = Stroke(stroke))
+ drawArc(Color.White.copy(alpha = if (chosen) 0.35f else 0.14f), 0f, 360f, false, Offset(inset, inset), box, style = Stroke(stroke))
if (part != 0f) drawArc(if (chosen) Candy.Lemon else Color.White, -90f, 360f * part, false, Offset(inset, inset), box, style = Stroke(stroke, cap = StrokeCap.Round))
}
- GlassIcon(a.icon, stringResource(a.label), Modifier.size(22.dp), tint = if (chosen) Candy.Lemon else Color.White)
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
index 0cdeff3..1444abe 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
@@ -320,7 +320,7 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
var menuAt by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
var fillMenuAt by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
val topPx = with(density) { WindowInsets.statusBars.getTop(this) + 64.dp.toPx() } +
- with(density) { (if (searching || grid.selected != null) 56.dp else 0.dp).toPx() }
+ with(density) { ((if (searching) 56.dp else 0.dp) + (if (grid.selected != null) 56.dp else 0.dp)).toPx() }
// the chosen cell's contents, for the formula bar
LaunchedEffect(grid.selected, grid.version) {
@@ -354,7 +354,13 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
Box(Modifier.fillMaxSize().layerBackdrop(backdrop)) {
SheetGrid(
grid, top = topPx,
- onCell = { cell -> grid.selected = cell; editing = false },
+ onCell = { cell ->
+ if (cell != null && cell == grid.selected) editing = true
+ else {
+ grid.selected = cell
+ editing = false
+ }
+ },
onDoubleTapCell = { cell -> grid.selected = cell; editing = true },
)
}
@@ -378,7 +384,7 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
) { GlassIcon(LucideIcons.MoreHorizontal, null, Modifier.size(20.dp)) }
}
if (searching) Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically) {
- Row(Modifier.weight(1f).height(48.dp).glassBar().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
+ Row(Modifier.weight(1f).height(48.dp).background(c.frost, com.chethan616.clearpdf.ui.glass.Capsule).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
GlassTextField(
query, { query = it }, stringResource(R.string.viewer_find_in_document), Modifier.weight(1f),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
@@ -399,9 +405,11 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
Spacer(Modifier.size(6.dp))
GlassCircle(onClick = { grid.hit = (grid.hit + 1) % grid.hits.size }, size = 44.dp, label = stringResource(R.string.viewer_find_next)) { GlassIcon(LucideIcons.ChevronDown, null, Modifier.size(18.dp)) }
}
- } else grid.selected?.let { cell ->
+ }
+ if (searching) Spacer(Modifier.height(8.dp))
+ grid.selected?.let { cell ->
// the formula bar: the cell's name, what it holds, and a field to change it
- Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp).height(48.dp).glassBar().padding(horizontal = 6.dp), verticalAlignment = Alignment.CenterVertically) {
+ Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp).height(48.dp).background(c.frost, com.chethan616.clearpdf.ui.glass.Capsule).padding(horizontal = 6.dp), verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.padding(4.dp).glassBar(surface = Candy.Sky.copy(alpha = 0.22f)).padding(horizontal = 10.dp, vertical = 6.dp)) {
Text(columnName(cell.col0.toInt()) + (cell.row0.toInt() + 1), style = ClearType.Label, color = c.ink)
}
@@ -443,7 +451,7 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
}
// the dock: the chosen cell's formatting, else the workbook's tools
Row(
- Modifier.fillMaxWidth().height(76.dp).padding(horizontal = 12.dp, vertical = 8.dp),
+ Modifier.fillMaxWidth().height(64.dp).padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
@@ -453,7 +461,6 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
verticalAlignment = Alignment.CenterVertically,
) {
if (cell == null) {
- DockKey(LucideIcons.Search, stringResource(R.string.viewer_find_in_document)) { searching = true }
DockKey(LucideIcons.FilePdf, stringResource(R.string.office_export_pdf)) { vm.exportOffice(doc, "pdf") }
var saveRect by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }
DockKey(LucideIcons.SaveAs, stringResource(R.string.office_save_as), modifier = Modifier.onGloballyPositioned { saveRect = it.boundsInWindow() }) { menuAt = saveRect }
@@ -479,8 +486,8 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
DockKey(LucideIcons.Trash2, stringResource(R.string.sheet_clear)) { run("edit.clearContents") }
}
}
- if (cell != null) GlassCircle(onClick = { grid.selected = null; editing = false }, size = 60.dp, tint = Candy.Sky, label = stringResource(R.string.common_done)) {
- GlassIcon(LucideIcons.Check, null, Modifier.size(22.dp))
+ if (cell != null) GlassCircle(onClick = { grid.selected = null; editing = false }, size = 48.dp, tint = Candy.Sky, label = stringResource(R.string.common_done)) {
+ GlassIcon(LucideIcons.Check, null, Modifier.size(19.dp))
}
}
Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars))
@@ -507,7 +514,7 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
/** One glyph of a dock, in the glass's ink. */
@Composable
private fun DockKey(icon: ImageVector, label: String, enabled: Boolean = true, modifier: Modifier = Modifier, onClick: () -> Unit) {
- Box(modifier.size(46.dp).pressable({ if (enabled) onClick() }), contentAlignment = Alignment.Center) {
+ Box(modifier.size(40.dp).pressable({ if (enabled) onClick() }), contentAlignment = Alignment.Center) {
GlassIcon(icon, label, Modifier.size(21.dp).graphicsLayer { alpha = if (enabled) 1f else 0.35f })
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt
index 999d6e1..1cd613e 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt
@@ -5,7 +5,17 @@ import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.animateFloat
-import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.width
+import androidx.compose.ui.draw.drawBehind
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontStyle
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -59,102 +69,51 @@ import com.chethan616.clearpdf.ui.theme.Candy
import com.chethan616.clearpdf.ui.theme.clear
/**
- * What the keyboard types into: a field that always holds one sentinel character. Text committed
- * after it goes into the document; the sentinel gone is a backspace. A word still being composed
- * (the keyboard's suggestions) waits until it is committed.
- */
-private const val SENTINEL = "​"
-
-/**
- * Word editing over the pages: the selection's rectangles and a blinking caret, drawn where
- * WordCraft's layout puts them, and the keyboard's field.
+ * Word editing as a PDF's text is edited: the paragraph tapped opens in a box over the page, at the
+ * document's size and weight, outlined in the selection blue; typing happens right there, and the
+ * text goes into the document when another paragraph is tapped or Done is.
*/
@Composable
fun WordEditLayer(vm: AppViewModel, doc: OpenDocument) {
- val caret = vm.wordCaret
- val accent = Candy.Sky
- val blink = rememberInfiniteTransition(label = "caret").animateFloat(1f, 0f, infiniteRepeatable(tween(530), RepeatMode.Reverse), label = "blink")
- Canvas(Modifier.fillMaxSize()) {
- caret ?: return@Canvas
- val v = doc.viewer
- val sel = caret.selection
- var i = 0
- while (i + 4 < sel.size) {
- val page = sel[i].toInt()
- val a = v.pageToScreen(page, sel[i + 1], sel[i + 2])
- val b = v.pageToScreen(page, sel[i + 3], sel[i + 4])
- drawRect(accent.copy(alpha = 0.25f), a, Size(b.x - a.x, b.y - a.y))
- i += 5
- }
- if (sel.isEmpty()) {
- val p = caret.page.toInt()
- val top = v.pageToScreen(p, caret.x, caret.top)
- val bottom = v.pageToScreen(p, caret.x, caret.top + caret.height)
- drawLine(accent.copy(alpha = blink.value.coerceIn(0f, 1f)), top, bottom, 2.2f * density)
- }
- }
-
- // the keyboard's field, out of sight
- val focus = remember { FocusRequester() }
- val keyboard = LocalSoftwareKeyboardController.current
- var field by remember { mutableStateOf(TextFieldValue(SENTINEL, TextRange(SENTINEL.length))) }
- // every tap that places the caret brings the keyboard up, focused on the field
- LaunchedEffect(vm.wordKeyboard) {
- if (vm.wordKeyboard == 0) return@LaunchedEffect
- focus.requestFocus()
- keyboard?.show()
+ val para = vm.wordPara ?: return
+ val v = doc.viewer
+ val density = androidx.compose.ui.platform.LocalDensity.current
+ val a = v.pageToScreen(para.page.toInt(), para.x0, para.y0)
+ val b = v.pageToScreen(para.page.toInt(), para.x1, para.y1)
+ val f = vm.wordFormat
+ val points = f.optDouble("size", 11.0).toFloat().takeIf { it > 0f } ?: 11f
+ val px = points * v.pixelsPerPoint(para.page.toInt())
+ val sp = with(density) { (px / fontScale).toSp() }
+ val focus = remember(para) { FocusRequester() }
+ var value by remember(para) { mutableStateOf(TextFieldValue(vm.wordDraft, TextRange(vm.wordDraft.length))) }
+ LaunchedEffect(para) { focus.requestFocus() }
+ // the box kept in sight above the keyboard and the dock
+ val imeBottom = androidx.compose.foundation.layout.WindowInsets.ime.getBottom(density)
+ LaunchedEffect(para, imeBottom) {
+ val room = v.viewH - imeBottom - with(density) { (BottomBarHeight + 24.dp).toPx() }
+ if (b.y > room) v.setScroll(v.scrollX, v.scrollY + (b.y - room))
}
- // the caret kept in sight above the keyboard (and below the top bar)
- val ime = androidx.compose.foundation.layout.WindowInsets.ime
- val dens = androidx.compose.ui.platform.LocalDensity.current
- val imeBottom = ime.getBottom(dens)
- LaunchedEffect(caret, imeBottom) {
- val c = caret ?: return@LaunchedEffect
- if (c.selection.isNotEmpty()) return@LaunchedEffect
- val v = doc.viewer
- val bottom = v.pageToScreen(c.page.toInt(), c.x, c.top + c.height).y
- val top = v.pageToScreen(c.page.toInt(), c.x, c.top).y
- val room = v.viewH - imeBottom - with(dens) { 96.dp.toPx() }
- when {
- // scrollBy takes a finger's move: the page goes up as a finger moving up takes it
- bottom > room -> v.scrollBy(0f, -(bottom - room))
- top < v.padTop -> v.scrollBy(0f, v.padTop - top)
+ with(density) {
+ Box(
+ Modifier.offset { androidx.compose.ui.unit.IntOffset(a.x.toInt(), a.y.toInt()) }
+ .width((b.x - a.x).toDp() + 6.dp).heightIn(min = (b.y - a.y).toDp() + 6.dp)
+ .background(Color.White).drawBehind { drawRect(Candy.Sky, size = size, style = Stroke(2.dp.toPx())) }
+ .padding(3.dp),
+ ) {
+ BasicTextField(
+ value = value,
+ onValueChange = { value = it; vm.wordDraft = it.text },
+ textStyle = TextStyle(
+ color = Color.Black, fontSize = sp, lineHeight = sp * 1.2f,
+ fontWeight = if (f.optBoolean("bold")) FontWeight.Bold else FontWeight.Normal,
+ fontStyle = if (f.optBoolean("italic")) FontStyle.Italic else FontStyle.Normal,
+ ),
+ cursorBrush = SolidColor(Candy.Sky),
+ keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
+ modifier = Modifier.fillMaxWidth().focusRequester(focus),
+ )
}
}
- DisposableEffect(Unit) { onDispose { keyboard?.hide() } }
- BasicTextField(
- value = field,
- onValueChange = { v ->
- if (v.composition != null) {
- field = v
- return@BasicTextField
- }
- val text = v.text
- when {
- !text.startsWith(SENTINEL) -> vm.wordRun(doc, "text.backspace")
- text.length > SENTINEL.length -> {
- // each line typed is a paragraph of its own
- val typed = text.substring(SENTINEL.length)
- typed.split('\n').forEachIndexed { n, part ->
- if (n > 0) vm.wordRun(doc, "text.newParagraph")
- if (part.isNotEmpty()) vm.wordRun(doc, "text.insert", mapOf("text" to part))
- }
- }
- }
- field = TextFieldValue(SENTINEL, TextRange(SENTINEL.length))
- },
- modifier = Modifier.size(1.dp).graphicsLayer { alpha = 0f }.focusRequester(focus).onPreviewKeyEvent { e ->
- // a hardware keyboard's Delete and Enter
- if (e.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
- when (e.key) {
- Key.Backspace -> { vm.wordRun(doc, "text.backspace"); true }
- Key.Enter -> { vm.wordRun(doc, "text.newParagraph"); true }
- else -> false
- }
- },
- keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences, autoCorrectEnabled = true, imeAction = ImeAction.None),
- keyboardActions = KeyboardActions.Default,
- )
}
/**
@@ -169,11 +128,11 @@ fun WordEditDock(vm: AppViewModel, doc: OpenDocument) {
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
- GlassCircle(onClick = { vm.stopWordEdit() }, size = 60.dp, tint = Candy.Sky, label = stringResource(R.string.common_done)) {
- GlassIcon(LucideIcons.Check, null, Modifier.size(22.dp))
+ GlassCircle(onClick = { vm.stopWordEdit() }, size = 48.dp, tint = Candy.Sky, label = stringResource(R.string.common_done)) {
+ GlassIcon(LucideIcons.Check, null, Modifier.size(19.dp))
}
Row(
- Modifier.weight(1f).fillMaxHeight().glassBar().horizontalScroll(rememberScrollState()).padding(horizontal = 8.dp),
+ Modifier.weight(1f).height(48.dp).glassBar().horizontalScroll(rememberScrollState()).padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(2.dp),
) {
@@ -198,7 +157,7 @@ fun WordEditDock(vm: AppViewModel, doc: OpenDocument) {
private fun EditKey(icon: ImageVector, label: String, enabled: Boolean = true, on: Boolean = false, onClick: () -> Unit) {
val c = clear
Box(
- Modifier.size(44.dp).pressable({ if (enabled) onClick() }).then(
+ Modifier.size(40.dp).pressable({ if (enabled) onClick() }).then(
if (on) Modifier.padding(4.dp).glassBar(surface = Candy.Sky.copy(alpha = 0.28f)) else Modifier,
),
contentAlignment = Alignment.Center,
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index f2f390d..b863df5 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -976,7 +976,7 @@
<string name="sheet_clear">Clear contents</string>
<string name="word_undo">Undo</string>
<string name="word_edit">Edit document</string>
- <string name="word_tap_to_type">Tap where you want to type. Long press a word to select it.</string>
+ <string name="word_tap_to_type">Tap a paragraph to edit it, as in a PDF. Done puts the changes in.</string>
<string name="word_redo">Redo</string>
<string name="word_bold">Bold</string>
<string name="word_italic">Italic</string>
diff --git a/engine/mobile/src/lib.rs b/engine/mobile/src/lib.rs
index a55c245..03e1e43 100644
--- a/engine/mobile/src/lib.rs
+++ b/engine/mobile/src/lib.rs
@@ -33,7 +33,7 @@ mod slides;
pub use photo::PhotoEditor;
pub use sheets::{CellEdge, CellSpan, CellView, SheetAxes, SheetInfo};
-pub use word::WordCaret;
+pub use word::{WordCaret, WordParagraph};
#[cfg(test)]
mod tests;
mod word;
@@ -926,6 +926,12 @@ impl MobileSession {
w.run(&command, &params).map(|v| v.to_string())
}
+ /// The paragraph at a point of Word document `doc`, selected for editing in place.
+ pub fn word_paragraph_at(&self, doc: u64, page: u32, x: f32, y: f32) -> Result<Option<WordParagraph>, MobileError> {
+ let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;
+ d.as_word().ok_or(MobileError::NoDocument(doc))?.paragraph_at(page, x, y)
+ }
+
/// Where Word document `doc`'s caret is, and its selection.
pub fn word_caret(&self, doc: u64) -> Option<WordCaret> {
self.office(doc).and_then(|d| d.as_word().and_then(|w| w.caret()))
diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rs
index 66f9a79..418bc61 100644
--- a/engine/mobile/src/tests.rs
+++ b/engine/mobile/src/tests.rs
@@ -724,3 +724,16 @@ fn a_powerpoint_97_2003_file_opens_with_its_slides_text() {
assert_eq!(s.find_in_page(info.id, 1, "new markets".into(), false, false).unwrap().len(), 1);
assert!(s.render_page(info.id, 0, 0.5, None).is_ok());
}
+
+#[test]
+fn a_word_paragraph_is_edited_in_place() {
+ let s = MobileSession::new();
+ let id = s.open(word_file("First line here\nSecond line", "Para.docx"), None).unwrap().id;
+ let hit = s.find_in_page(id, 0, "First".into(), false, false).unwrap().remove(0);
+ let p = s.word_paragraph_at(id, 0, hit.rects[0] + 2.0, (hit.rects[1] + hit.rects[3]) / 2.0).unwrap().unwrap();
+ assert_eq!(p.text, "First line here");
+ assert!(p.x1 > p.x0 && p.y1 > p.y0);
+ s.word_command(id, "text.insert".into(), r#"{"text":"A new first line"}"#.into()).unwrap();
+ let text = s.page_plain_text(id, 0).unwrap();
+ assert!(text.contains("A new first line") && text.contains("Second line") && !text.contains("First line here"), "{text}");
+}
diff --git a/engine/mobile/src/word.rs b/engine/mobile/src/word.rs
index f110c3a..d5dc6af 100644
--- a/engine/mobile/src/word.rs
+++ b/engine/mobile/src/word.rs
@@ -27,6 +27,17 @@ pub struct WordCaret {
pub selection: Vec<f32>,
}
+/// A paragraph picked for editing in place: its text, and the box it fills on its page (points).
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct WordParagraph {
+ pub text: String,
+ pub page: u32,
+ pub x0: f32,
+ pub y0: f32,
+ pub x1: f32,
+ pub y1: f32,
+}
+
/// Commands that only move the caret or read: the document's version stays.
fn changes_nothing(command: &str) -> bool {
command.starts_with("caret.") || command.starts_with("select.") || command == "format.state" || command == "list.get"
@@ -116,6 +127,30 @@ impl WordDocument {
Ok(out)
}
+ /// The paragraph at point (`x`, `y`) of page `page`, selected (without its paragraph mark), with
+ /// its text and box: what the app edits in place, as it edits a PDF's text.
+ pub(crate) fn paragraph_at(&self, page: u32, x: f32, y: f32) -> Result<Option<WordParagraph>, MobileError> {
+ self.run("caret.set", &serde_json::json!({ "page": page, "x": x, "y": y }))?;
+ self.run("select.paragraph", &serde_json::json!({}))?;
+ // the paragraph mark stays out of the selection: replacing the text keeps the paragraph
+ let mut text = self.lock().session.selected_text();
+ while text.ends_with(['\n', '\r']) {
+ text.pop();
+ self.run("caret.left", &serde_json::json!({ "extend": true }))?;
+ }
+ let Some(c) = self.caret() else { return Ok(None) };
+ let mut rects = c.selection.chunks(5).filter(|r| r.len() == 5);
+ let Some(first) = rects.next() else {
+ return Ok(Some(WordParagraph { text, page: c.page, x0: c.x, y0: c.top, x1: c.x + 1.0, y1: c.top + c.height }));
+ };
+ let page_of = first.first().copied().unwrap_or(0.0) as u32;
+ let mut b = [first[1], first[2], first[3], first[4]];
+ for r in rects.filter(|r| r.first().copied().unwrap_or(-1.0) as u32 == page_of) {
+ b = [b[0].min(r[1]), b[1].min(r[2]), b[2].max(r[3]), b[3].max(r[4])];
+ }
+ Ok(Some(WordParagraph { text, page: page_of, x0: b[0], y0: b[1], x1: b[2], y1: b[3] }))
+ }
+
/// The caret (or the selection) as it is drawn.
pub(crate) fn caret(&self) -> Option<WordCaret> {
let mut s = self.lock();