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.

Tester fixes: comment bar above the nav bar, search keyboard closes, heading lines kept

chethan616c1f59843dc56
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt b/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt
index f326839..060f064 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt
@@ -127,7 +127,11 @@ internal fun QuickPreviewScreen(
PdfcraftTheme(theme) {
ProvideGlassHaptics {
CompositionLocalProvider(LocalGlassOverlayHost provides overlays) {
- Preview(state, onClose, onExpand, onShare, onOpenWith, onSaveCopy, onPassword, setBlur)
+ // as in the viewer, the glass buttons read the screen behind them: white icons over a
+ // dark page or picture, dark over a light one (and adaptive glass while it is on)
+ com.chethan616.clearpdf.ui.glass.ProvideScreenInk {
+ Preview(state, onClose, onExpand, onShare, onOpenWith, onSaveCopy, onPassword, setBlur)
+ }
}
}
}
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 3f551c6..e5641d3 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
@@ -1694,12 +1694,14 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
val rect = o.optJSONArray("rect") ?: return@mapNotNull null
val font = o.optString("font")
com.chethan616.clearpdf.ui.viewer.Paragraph(
- page = page, number = o.optInt("paragraph"), text = o.optString("text"),
+ // the rows the source ended on purpose (a heading, a line of its own) stay their own
+ // lines, so typing at the end never pulls them together (#144)
+ page = page, number = o.optInt("paragraph"), text = o.optString("edit_text").ifEmpty { o.optString("text") },
box = FloatArray(4) { k -> rect.optDouble(k).toFloat() }, font = font, size = o.optDouble("size", 12.0).toFloat(),
bold = if (o.has("bold")) o.optBoolean("bold") else font.contains("Bold", true) || font.contains("Black", true) || font.contains("Heavy", true),
italic = if (o.has("italic")) o.optBoolean("italic") else font.contains("Italic", true) || font.contains("Oblique", true),
color = o.optString("color").takeIf { it.startsWith("#") },
- runs = styleRuns(o),
+ runs = styleRuns(o, o.optString("edit_text").ifEmpty { o.optString("text") }),
)
}
editSelection?.takeIf { it.page == page }?.let { sel -> editSelection = paragraphs[page]?.firstOrNull { it.number == sel.number } }
@@ -1788,11 +1790,11 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
* ranges of its text. The two differ only where rows break (a newline for a space); anything
* else (a hyphen joined across rows) and the runs are left out rather than misplaced.
*/
- private fun styleRuns(o: org.json.JSONObject): List<com.chethan616.clearpdf.ui.viewer.StyleRun> {
+ private fun styleRuns(o: org.json.JSONObject, text: String): List<com.chethan616.clearpdf.ui.viewer.StyleRun> {
val arr = o.optJSONArray("runs") ?: return emptyList()
if (arr.length() == 0) return emptyList()
val editor = o.optString("editor_text")
- if (editor.replace('\n', ' ') != o.optString("text")) return emptyList()
+ if (editor.replace('\n', ' ') != text.replace('\n', ' ')) return emptyList()
// byte offset to character offset
val total = editor.toByteArray(Charsets.UTF_8).size
val charAt = IntArray(total + 1)
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt
index 963c739..1cb91b4 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt
@@ -210,9 +210,22 @@ fun FileListItem(vm: AppViewModel, r: FileRow, recent: Boolean, modifier: Modifi
val c = clear
val selecting = vm.selectedFiles.isNotEmpty()
val ticked = r.key in vm.selectedFiles
+ // opening a file ends any typing (a search): its keyboard never stays up over the document (#145)
+ val focus = androidx.compose.ui.platform.LocalFocusManager.current
+ val keyboard = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
Row(
modifier.fillMaxWidth()
- .pressable(onClick = { if (selecting) vm.toggleSelected(r) else r.open() }, onLongClick = { vm.toggleSelected(r) })
+ .pressable(
+ onClick = {
+ if (selecting) vm.toggleSelected(r)
+ else {
+ focus.clearFocus(force = true)
+ keyboard?.hide()
+ r.open()
+ }
+ },
+ onLongClick = { vm.toggleSelected(r) },
+ )
.background(if (ticked) Candy.Sky.copy(alpha = 0.14f) else Color.Transparent)
.padding(start = 14.dp, end = 2.dp, top = 10.dp, bottom = 10.dp),
verticalAlignment = Alignment.CenterVertically,
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt
index 295cdd6..5edecc5 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt
@@ -23,6 +23,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
@@ -328,7 +329,10 @@ private fun InlineNoteBar(hint: String, onDismiss: () -> Unit, onPost: (String)
shape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp),
wash = if (c.dark) Color(0xFF0D0D10).copy(alpha = 0.64f) else Color.White.copy(alpha = 0.76f),
blur = 18.dp,
- ),
+ )
+ // with the keyboard down the bar sits above the navigation bar (its glass runs on under
+ // it); with it up, imePadding has already lifted it and this adds nothing (#143)
+ .navigationBarsPadding(),
) {
BasicTextField(
value = text, onValueChange = { text = it }, maxLines = 3,
diff --git a/engine/crates/automation/src/lib.rs b/engine/crates/automation/src/lib.rs
index 31dec9e..ac62f09 100644
--- a/engine/crates/automation/src/lib.rs
+++ b/engine/crates/automation/src/lib.rs
@@ -603,8 +603,9 @@ impl Automation {
let r = |x: f32| (x as f64 * 100.0).round() / 100.0;
let current = doc.text_blocks(page);
let id = doc.id;
- // the page's lines, read only when a paragraph mixes lines (its runs' styles come from them)
- let lines = if current.iter().any(|b| b.spans.iter().any(|(_, l)| Some(*l) != b.spans.first().map(|(_, f)| *f))) {
+ // the page's lines, read only when a paragraph mixes lines (its runs' styles come from
+ // them) or has several rows (where each row ends says which breaks are its own)
+ let lines = if current.iter().any(|b| b.rows.len() > 1 || b.spans.iter().any(|(_, l)| Some(*l) != b.spans.first().map(|(_, f)| *f))) {
doc.text_lines(page)
} else {
Vec::new()
@@ -619,6 +620,9 @@ impl Automation {
"paragraph": i + 1,
"text": b.text,
"editor_text": b.editor_text,
+ // The text to edit: rows the source wrapped joined by a space, a row it
+ // ended on purpose (a heading, a line of its own) kept as a line break.
+ "edit_text": edit_text(b, &lines),
"rows": b.rows.iter().map(|row| row.iter().map(|i| i + 1).collect::<Vec<_>>()).collect::<Vec<_>>(),
"lines": b.lines.iter().map(|l| l + 1).collect::<Vec<_>>(),
"rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))],
@@ -2905,6 +2909,52 @@ fn write_atomic_synced(
/// A paragraph's bold and italic runs over its `editor_text` (byte ranges), adjacent runs of one
/// style merged; empty when the whole paragraph is one style (or its lines were not read).
+/// A paragraph's text for an editor, which sends it back to `text_edit`. Rows the source wrapped
+/// (the next row's first word would not have fit after this one) join with a space, so an edit
+/// rewraps them as before. A row the source ended early on purpose (a heading over its text, a short
+/// line of its own, a hyphen at its end) keeps its break as a newline, which the rewrite keeps: adding
+/// a word to such a paragraph never pulls the next line up beside a heading or a short line (#144).
+/// The same bytes as `editor_text` but for the joined breaks, so `runs` ranges hold for it too.
+fn edit_text(b: &pdfcraft_engine::TextBlock, lines: &[pdfcraft_engine::TextLine]) -> String {
+ let rows: Vec<&str> = b.editor_text.split('\n').collect();
+ if rows.len() < 2 || rows.len() != b.rows.len() || lines.is_empty() {
+ return b.text.clone();
+ }
+ let row_lines = |r: &Vec<usize>| r.iter().filter_map(|i| lines.get(*i)).collect::<Vec<_>>();
+ let all: Vec<Vec<&pdfcraft_engine::TextLine>> = b.rows.iter().map(row_lines).collect();
+ // turned text: its boxes don't measure along its rows, so leave it as one paragraph
+ if b.rotation.abs() > 0.01 || all.iter().any(|r| r.is_empty()) {
+ return b.text.clone();
+ }
+ let width = |r: &[&pdfcraft_engine::TextLine]| {
+ let left = r.iter().map(|l| l.rect[0]).fold(f64::INFINITY, f64::min);
+ let right = r.iter().map(|l| l.rect[2]).fold(f64::NEG_INFINITY, f64::max);
+ right - left
+ };
+ let full = all.iter().map(|r| width(r)).fold(0.0, f64::max);
+ let mut out = String::with_capacity(b.editor_text.len());
+ for (k, text) in rows.iter().enumerate() {
+ out.push_str(text);
+ let (Some(this), Some(next), Some(next_text)) = (all.get(k), all.get(k + 1), rows.get(k + 1)) else { continue };
+ let (Some(a), Some(n)) = (this.first(), next.first()) else { continue };
+ let size = a.size.max(n.size).max(1.0);
+ let restyled = (a.size - n.size).abs() > size * 0.05 || a.bold != n.bold || a.italic != n.italic;
+ // the next row's first word, its share of that row's width
+ let next_trim = next_text.trim();
+ let word = next_trim.split_whitespace().next().unwrap_or_default();
+ let share = word.chars().count() as f64 / next_trim.chars().count().max(1) as f64;
+ let room = full - width(this) - n.size * 0.3 - width(next) * share;
+ // only a clear fit (a whole size to spare) counts: a near miss stays a wrap, as before
+ let ended = room > size;
+ if restyled || ended || text.trim_end().ends_with('-') {
+ out.push('\n');
+ } else {
+ out.push(' ');
+ }
+ }
+ out
+}
+
fn style_runs(b: &pdfcraft_engine::TextBlock, lines: &[pdfcraft_engine::TextLine]) -> Vec<Value> {
if lines.is_empty() {
return Vec::new();
diff --git a/engine/crates/automation/tests/it/automation.rs b/engine/crates/automation/tests/it/automation.rs
index 3b1435b..d6a9d57 100644
--- a/engine/crates/automation/tests/it/automation.rs
+++ b/engine/crates/automation/tests/it/automation.rs
@@ -9303,3 +9303,35 @@ fn bold_range_is_one_word_and_listed_as_a_run() {
assert_eq!(bold.trim(), "Bold", "{listed}");
std::fs::remove_dir_all(dir).unwrap();
}
+
+/// A heading over a short line and two body lines, read as one paragraph: adding a word at its end
+/// keeps the heading and the short line on rows of their own (#144). The editor's text breaks
+/// where the source ended a row on purpose and joins the rows it wrapped.
+#[test]
+fn appending_to_a_heading_and_its_lines_keeps_their_rows() {
+ use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};
+ use std::sync::Arc;
+ let dir = workdir("heading-rows");
+ let content = "BT /F1 18 Tf 20 270 Td (AT PAGE 1) Tj ET \
+ BT /F1 9 Tf 20 248 Td (Marker 73142) Tj ET \
+ BT /F1 9 Tf 20 236 Td (The blue notebook contains seven pages.) Tj ET \
+ BT /F1 9 Tf 20 224 Td (Unicode control: cafe, naive.) Tj ET";
+ let mut doc = Document::open(Arc::new(fixture(1))).unwrap();
+ doc.set(ObjRef::new(5, 0), Object::Stream(Stream::flate(Dict::new(), content.as_bytes())));
+ std::fs::write(dir.join("rows.pdf"), write_full(&doc, &SaveOptions::default()).unwrap()).unwrap();
+ let mut a = auto(&dir);
+ let id = ok(&mut a, "doc_open", json!({"path":"rows.pdf"}))["doc"].as_u64().unwrap();
+ let listed = ok(&mut a, "text_paragraphs", json!({"doc":id,"page":1}));
+ let p = &listed["paragraphs"][0];
+ assert_eq!(p["rows"].as_array().unwrap().len(), 4, "the heading and its lines are one paragraph: {listed}");
+ let text = p["edit_text"].as_str().unwrap();
+ assert_eq!(text, "AT PAGE 1\nMarker 73142\nThe blue notebook contains seven pages. Unicode control: cafe, naive.", "{listed}");
+ assert_eq!(text.len(), p["editor_text"].as_str().unwrap().len(), "runs index both alike");
+ ok(&mut a, "text_edit", json!({"doc":id,"page":1,"paragraph":1,"text": format!("{text} X")}));
+ let lines = ok(&mut a, "text_lines", json!({"doc":id,"page":1}));
+ let shown: Vec<String> = lines["lines"].as_array().unwrap().iter().map(|l| l["text"].as_str().unwrap().trim().to_owned()).collect();
+ assert!(shown.iter().any(|t| t == "AT PAGE 1"), "{shown:?}");
+ assert!(shown.iter().any(|t| t == "Marker 73142"), "{shown:?}");
+ assert!(shown.iter().any(|t| t.ends_with("naive. X")), "{shown:?}");
+ std::fs::remove_dir_all(dir).unwrap();
+}