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.

Two pages, mind maps, field detection, translate, partial bold; alpha.8

chethan616539d090c0a29
diff --git a/HANDOFF.md b/HANDOFF.md
index e645a00..8cc1e6a 100644
--- a/HANDOFF.md
+++ b/HANDOFF.md
@@ -109,6 +109,13 @@ The parts a later session needs to know:
change height, and a stale value put taps on the wrong cell.
- **.ppt** (`engine/mobile/src/ppt.rs`) reads each slide's drawing (text boxes, pictures) through the
persist directory, and falls back to the outline. Only tested on a synthetic file.
+- **alpha.8 additions**: Two pages (`DocLayout.columns`, `ViewerState.showColumns`, View settings);
+ a note as a mind map (`ui/notes/MindMap.kt`: `parseOutline` reads headings, bullets and indentation;
+ one android `Canvas` drawing serves the screen, the PNG and the PDF); Find form fields (the
+ engine's `form_detect_fields`); Translate (a chooser of text-processing apps; the app itself has no
+ network permission and must not gain one); Bold/Italic on the selected words only (`text_edit`
+ `ranges`, UTF-8 byte offsets); photo Crop (LightCraft's `crop.geometry`, which needs `rect` and
+ `angle`); voice notes leave as m4a (`notes/AudioExport.kt`).
- **Releases** build five APKs (`-arm64-v8a`, `-armeabi-v7a`, `-x86`, `-x86_64`, `-universal`); `x86`
is new (`i686-linux-android`, version-code suffix 4). `ci.yml` builds pull requests.
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/notes/AudioExport.kt b/android/app/src/main/java/com/chethan616/clearpdf/notes/AudioExport.kt
new file mode 100644
index 0000000..752d2da
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/notes/AudioExport.kt
@@ -0,0 +1,133 @@
+package com.chethan616.clearpdf.notes
+
+import android.media.MediaCodec
+import android.media.MediaCodecInfo
+import android.media.MediaFormat
+import android.media.MediaMuxer
+import java.io.File
+import java.io.RandomAccessFile
+
+private fun le16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
+
+private fun le32(b: ByteArray, at: Int): Int = le16(b, at) or (le16(b, at + 2) shl 16)
+
+/**
+ * A voice note as other apps expect one: the recording (16-bit PCM in a WAV file, as the recorder
+ * writes it) encoded as AAC in an MPEG-4 file (.m4a) by the phone's own encoder. A minute of
+ * speech comes to about half a megabyte where the WAV is five.
+ *
+ * False when [wav] is not such a file or the phone can't encode it: the caller then shares the
+ * recording as it is. Blocking; call it off the main thread.
+ */
+fun wavToM4a(wav: File, out: File): Boolean = runCatching {
+ RandomAccessFile(wav, "r").use { f ->
+ val head = ByteArray(12)
+ f.readFully(head)
+ if (String(head, 0, 4, Charsets.US_ASCII) != "RIFF" || String(head, 8, 4, Charsets.US_ASCII) != "WAVE") return false
+ var rate = 0
+ var channels = 0
+ var bits = 0
+ var dataAt = -1L
+ var dataLen = 0L
+ val chunk = ByteArray(8)
+ while (f.filePointer + 8 <= f.length()) {
+ f.readFully(chunk)
+ val id = String(chunk, 0, 4, Charsets.US_ASCII)
+ val size = le32(chunk, 4).toLong() and 0xFFFFFFFFL
+ when (id) {
+ "fmt " -> {
+ if (size < 16) return false
+ val b = ByteArray(16)
+ f.readFully(b)
+ // 1: plain PCM
+ if (le16(b, 0) != 1) return false
+ channels = le16(b, 2)
+ rate = le32(b, 4)
+ bits = le16(b, 14)
+ f.seek(f.filePointer + size - 16 + (size and 1))
+ }
+ "data" -> {
+ dataAt = f.filePointer
+ // a recording cut short states more than it holds
+ dataLen = minOf(size, f.length() - dataAt)
+ break
+ }
+ else -> f.seek(f.filePointer + size + (size and 1))
+ }
+ }
+ if (dataAt < 0 || dataLen <= 0 || bits != 16 || channels !in 1..2 || rate !in 8000..96000) return false
+
+ val frame = channels * 2
+ val bytesPerSecond = rate.toLong() * frame
+ val format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, rate, channels).apply {
+ setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)
+ setInteger(MediaFormat.KEY_BIT_RATE, if (channels == 1) 72_000 else 128_000)
+ setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 16 * 1024)
+ }
+ val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC)
+ var muxer: MediaMuxer? = null
+ var started = false
+ try {
+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
+ codec.start()
+ muxer = MediaMuxer(out.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
+ val info = MediaCodec.BufferInfo()
+ val buffer = ByteArray(8 * 1024)
+ var track = -1
+ var read = 0L
+ var inputDone = false
+ var outputDone = false
+ // a stuck encoder must not hang the export
+ var idle = 0
+ f.seek(dataAt)
+ while (!outputDone && idle < 2000) {
+ idle++
+ if (!inputDone) {
+ val i = codec.dequeueInputBuffer(10_000)
+ if (i >= 0) {
+ idle = 0
+ val input = codec.getInputBuffer(i) ?: return false
+ input.clear()
+ // whole frames only
+ val want = (minOf(minOf(buffer.size, input.remaining()).toLong(), dataLen - read).toInt() / frame) * frame
+ val n = if (want > 0) f.read(buffer, 0, want) else -1
+ val time = read * 1_000_000L / bytesPerSecond
+ if (n <= 0) {
+ codec.queueInputBuffer(i, 0, 0, time, MediaCodec.BUFFER_FLAG_END_OF_STREAM)
+ inputDone = true
+ } else {
+ input.put(buffer, 0, n)
+ codec.queueInputBuffer(i, 0, n, time, 0)
+ read += n
+ }
+ }
+ }
+ val o = codec.dequeueOutputBuffer(info, 10_000)
+ if (o == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+ idle = 0
+ track = muxer.addTrack(codec.outputFormat)
+ muxer.start()
+ started = true
+ } else if (o >= 0) {
+ idle = 0
+ val output = codec.getOutputBuffer(o)
+ // the codec's own setup data goes into the track's format, not the samples
+ if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) info.size = 0
+ if (output != null && info.size > 0 && started) {
+ output.position(info.offset)
+ output.limit(info.offset + info.size)
+ muxer.writeSampleData(track, output, info)
+ }
+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) outputDone = true
+ codec.releaseOutputBuffer(o, false)
+ }
+ }
+ started && outputDone
+ } finally {
+ runCatching { codec.stop() }
+ codec.release()
+ if (started) runCatching { muxer?.stop() }
+ runCatching { muxer?.release() }
+ }
+ }
+}.getOrDefault(false).also { ok -> if (!ok) out.delete() }
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt
index eb4f6a0..89e26a1 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt
@@ -93,6 +93,9 @@ object LucideIcons {
val Link: ImageVector get() = Icons.Rounded.Link
val List: ImageVector get() = Icons.AutoMirrored.Rounded.List
val ListChecks: ImageVector get() = Icons.Rounded.Checklist
+ val Languages: ImageVector get() = Icons.Rounded.Translate
+ val Network: ImageVector get() = Icons.Rounded.AccountTree
+ val Columns2: ImageVector get() = Icons.Rounded.ViewColumn
val Lock: ImageVector get() = Icons.Rounded.Lock
val LockOpen: ImageVector get() = Icons.Rounded.LockOpen
val Maximize: ImageVector get() = Icons.Rounded.OpenInFull
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 c45b6f8..cdd3801 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
@@ -225,6 +225,7 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
loadLinks(eng, doc)
doc.controller.nightMode = savedNightMode
if (savedPageMode != doc.viewer.mode) doc.viewer.switchMode(savedPageMode)
+ doc.viewer.showColumns(if (twoPages) 2 else 1)
// a file left in Reading Mode reopens in it, unless it was opened for a tool
readingMode = recent?.reading == true && pendingTool == null
document = doc
@@ -842,6 +843,16 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
private var nightModeDefaultState by mutableStateOf(appPrefs.getBoolean("nightMode", false))
val savedNightMode: Boolean get() = nightModeDefaultState
+ /** Two pages side by side in continuous mode (View settings; remembered app-wide). */
+ var twoPages by mutableStateOf(appPrefs.getBoolean("twoPages", false))
+ private set
+
+ fun setTwoPages(doc: OpenDocument, on: Boolean) {
+ twoPages = on
+ appPrefs.edit().putBoolean("twoPages", on).apply()
+ doc.viewer.showColumns(if (on) 2 else 1)
+ }
+
fun setPageMode(doc: OpenDocument, mode: com.chethan616.clearpdf.ui.viewer.PageMode) {
// leaving Reading Mode: a canvas laid out already followed the page read; else it shows it on layout
if (readingMode && doc.viewer.viewW > 0f) pendingPage = null
@@ -1110,6 +1121,29 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
}
/** Copy the selected text (when the document allows copying). */
+ /**
+ * The selected text handed to a translator the phone has (Google Translate, DeepL, a
+ * dictionary…): the system's own list of apps that take text, so Artefact itself still asks
+ * for no network access.
+ */
+ fun translateSelection(doc: OpenDocument) {
+ if (!doc.info.allowsCopying) {
+ tell(text(R.string.msg_copy_not_allowed))
+ return
+ }
+ viewModelScope.launch {
+ val picked = doc.selection.text()?.trim().orEmpty()
+ if (picked.isEmpty()) return@launch
+ // apps that process a piece of text (the selection toolbar's "Translate"), with the ones
+ // that answer a plain translate request offered first
+ val process = Intent(Intent.ACTION_PROCESS_TEXT).setType("text/plain")
+ .putExtra(Intent.EXTRA_PROCESS_TEXT, picked).putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, true)
+ val translate = Intent(Intent.ACTION_TRANSLATE).putExtra(Intent.EXTRA_TEXT, picked)
+ intents.trySend(Intent.createChooser(process, text(R.string.viewer_translate)).putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(translate)))
+ doc.selection.clear()
+ }
+ }
+
fun copySelection(doc: OpenDocument) {
if (!doc.info.allowsCopying) {
tell(text(R.string.msg_copy_not_allowed))
@@ -1668,6 +1702,30 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
runTool(doc, "text_edit", paraArgs(para) + style + (if (typed != null) mapOf("text" to typed) else emptyMap()))
}
+ /** The part of the paragraph being typed in that is selected (null: none, or a bare caret). */
+ var editRange by mutableStateOf<androidx.compose.ui.text.TextRange?>(null)
+
+ /**
+ * Bold or slanted, only the words selected in the paragraph being typed in: the rest keeps its
+ * face. The engine takes the selection as a byte range of the paragraph's text, in one of its
+ * three built-in families (the paragraph's own kind: serif, monospaced, else sans).
+ */
+ fun styleRange(doc: OpenDocument, para: com.chethan616.clearpdf.ui.viewer.Paragraph, range: androidx.compose.ui.text.TextRange, bold: Boolean, italic: Boolean) {
+ val words = editDraft?.takeIf { editing != null } ?: para.text
+ val start = range.min.coerceIn(0, words.length)
+ val end = range.max.coerceIn(start, words.length)
+ if (start == end) return
+ val bytes = { upTo: Int -> words.substring(0, upTo).toByteArray(Charsets.UTF_8).size }
+ val name = para.font.lowercase()
+ val family = editFont[para.page to para.number] ?: when {
+ "courier" in name || "mono" in name || "consol" in name -> "courier"
+ "times" in name || "serif" in name && "sans" !in name || "roman" in name || "georgia" in name || "garamond" in name -> "times"
+ else -> "helvetica"
+ }
+ val one = mapOf("range" to listOf(bytes(start), bytes(end)), "font" to family, "bold" to bold, "italic" to italic)
+ runTool(doc, "text_edit", paraArgs(para) + mapOf("text" to words, "ranges" to listOf(one)))
+ }
+
/** Move [para] by ([dx], [dy]) points (right and down on screen). */
fun moveParagraph(doc: OpenDocument, para: com.chethan616.clearpdf.ui.viewer.Paragraph, dx: Float, dy: Float) {
runTool(doc, "text_edit", paraArgs(para) + mapOf("dx" to dx.toDouble(), "dy" to -dy.toDouble()))
@@ -2180,6 +2238,30 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
deliver(out, "${doc.title}_unlocked.pdf")
}
+ /**
+ * A form that is only drawn (lines to write on, boxes to tick, no fields of its own): the
+ * engine looks for those places and makes real fields of them, which Fill & Sign then fills
+ * like any form's.
+ */
+ fun detectFields(doc: OpenDocument) {
+ if (doc.info.readOnlyReason != null || (!doc.info.allowsFormFilling && !doc.info.allowsAnnotation)) {
+ tell(doc.info.readOnlyReason ?: text(R.string.msg_tool_blocked_security))
+ return
+ }
+ busy = text(R.string.msg_busy_finding_fields)
+ runTool(doc, "form_detect_fields") { r ->
+ busy = null
+ val found = r.optJSONArray("fields")?.length() ?: 0
+ if (found == 0) tell(text(R.string.msg_no_fields_found))
+ else tell(getApplication<Application>().resources.getQuantityString(R.plurals.msg_fields_found, found, found))
+ }
+ }
+
+ /** A file made for the user (a mind map's picture or PDF) put into Downloads, and said so. */
+ fun deliverFile(file: File, name: String, mime: String) {
+ viewModelScope.launch { runCatching { deliver(file, name, mime) }.onFailure { tell(it.userMessage) } }
+ }
+
/** Crop [page] (or every page) to [rect] (points from the page's top-left). */
fun crop(doc: OpenDocument, page: Int?, rect: FloatArray) {
val args = mutableMapOf<String, Any?>("rect" to rect.map { it.toDouble() })
@@ -2704,8 +2786,18 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
val audio = note.audio ?: return
viewModelScope.launch {
runCatching {
- val source = notes.file(audio)
- val ext = audio.substringAfterLast('.', "wav").lowercase()
+ var source = notes.file(audio)
+ var ext = audio.substringAfterLast('.', "wav").lowercase()
+ // a recording is kept as WAV: it leaves as m4a (AAC), which every player and chat app takes
+ var converted: File? = null
+ if (ext == "wav") {
+ val m4a = tempFile("m4a")
+ if (withContext(Dispatchers.IO) { com.chethan616.clearpdf.notes.wavToM4a(source, m4a) }) {
+ converted = m4a
+ source = m4a
+ ext = "m4a"
+ }
+ }
val mime = when (ext) {
"wav" -> "audio/wav"
"mp3" -> "audio/mpeg"
@@ -2722,6 +2814,7 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
files.saveToDownloads(copy, name, mime)
} finally {
copy.delete()
+ converted?.delete()
}
}
tell(text(R.string.msg_saved_downloads, name))
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt
new file mode 100644
index 0000000..c661e34
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt
@@ -0,0 +1,342 @@
+package com.chethan616.clearpdf.ui.notes
+
+import android.graphics.Bitmap
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.RectF
+import android.graphics.Typeface
+import android.graphics.pdf.PdfDocument
+import android.text.TextPaint
+import android.text.TextUtils
+import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.gestures.detectTransformGestures
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.ui.graphics.nativeCanvas
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.IntSize
+import androidx.compose.ui.unit.dp
+import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.ui.AppViewModel
+import com.chethan616.clearpdf.ui.LucideIcons
+import com.chethan616.clearpdf.ui.glass.GlassBackButton
+import com.chethan616.clearpdf.ui.glass.GlassCircle
+import com.chethan616.clearpdf.ui.glass.GlassIcon
+import com.chethan616.clearpdf.ui.theme.Candy
+import com.chethan616.clearpdf.ui.theme.ClearType
+import com.chethan616.clearpdf.ui.theme.clear
+import java.io.File
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/** One idea of a mind map: its words, how deep it sits, and (once laid out) its box. */
+internal class MapNode(val text: String, val level: Int) {
+ val children = ArrayList<MapNode>()
+ var label: String = text
+ var left = 0f
+ var top = 0f
+ var width = 0f
+ var height = 0f
+ /** Which of the root's branches it belongs to (its colour). */
+ var branch = 0
+ val centerY: Float get() = top + height / 2f
+}
+
+/** The most ideas a map draws (a note is not a database). */
+private const val MAX_NODES = 400
+
+/**
+ * A note's outline as a tree. One idea a line: headings (`#`, `##`…) open branches, and under
+ * them, or with no headings at all, indentation (two spaces or a tab a step) and bullets (`-`,
+ * `*`, `•`, `1.`) nest ideas under the line above. [title] is the map's centre.
+ */
+internal fun parseOutline(title: String, body: String): MapNode {
+ val root = MapNode(title.trim(), -1)
+ val path = ArrayList<MapNode>().apply { add(root) }
+ // where plain lines start counting from: one deeper than the heading they are under
+ var base = 0
+ var count = 0
+ for (raw in body.lines()) {
+ if (raw.isBlank()) continue
+ var indent = 0
+ for (ch in raw) {
+ if (ch == ' ') indent++ else if (ch == '\t') indent += 2 else break
+ }
+ var s = raw.trim()
+ val hashes = s.takeWhile { it == '#' }.length
+ val level: Int
+ if (hashes in 1..6 && s.getOrNull(hashes) == ' ') {
+ level = hashes - 1
+ base = hashes
+ s = s.drop(hashes)
+ } else {
+ Regex("""^([-*•+]|\d{1,3}[.)])\s+""").find(s)?.let { s = s.substring(it.range.last + 1) }
+ level = base + indent / 2
+ }
+ s = s.replace("**", "").replace("__", "").trim()
+ if (s.isEmpty()) continue
+ if (++count > MAX_NODES) break
+ // the line above that is less deep is its parent
+ while (path.size > 1 && path.last().level >= level) path.removeAt(path.lastIndex)
+ val node = MapNode(s, path.last().level + 1)
+ path.last().children.add(node)
+ path.add(node)
+ }
+ return root
+}
+
+/** A map set out: its tree with every box placed, and the room it takes (pixels at [density]). */
+internal class MapLayout(val root: MapNode, val width: Float, val height: Float, val density: Float)
+
+/**
+ * Sets the tree out left to right: the centre at the left, each generation a column further right,
+ * leaves stacked down the page and every parent level with the middle of its children.
+ */
+internal fun layoutMap(root: MapNode, density: Float): MapLayout {
+ val d = density
+ val paint = mapTextPaint(d, bold = false)
+ val bold = mapTextPaint(d, bold = true)
+ val maxText = 230f * d
+ val pad = 24f * d
+ val columns = ArrayList<Float>()
+ fun measure(n: MapNode, depth: Int) {
+ val p = if (depth <= 1) bold else paint
+ n.label = TextUtils.ellipsize(n.text.ifEmpty { " " }, p, maxText, TextUtils.TruncateAt.END).toString()
+ n.width = p.measureText(n.label) + (if (depth == 0) 40f else 28f) * d
+ n.height = (if (depth == 0) 48f else 36f) * d
+ while (columns.size <= depth) columns.add(0f)
+ columns[depth] = maxOf(columns[depth], n.width)
+ n.children.forEach { measure(it, depth + 1) }
+ }
+ measure(root, 0)
+ val x = FloatArray(columns.size)
+ var at = pad
+ for (i in columns.indices) {
+ x[i] = at
+ at += columns[i] + 46f * d
+ }
+ var cursor = pad
+ fun place(n: MapNode, depth: Int, branch: Int) {
+ n.left = x[depth]
+ n.branch = branch
+ if (n.children.isEmpty()) {
+ n.top = cursor
+ cursor += n.height + 12f * d
+ } else {
+ n.children.forEachIndexed { i, c -> place(c, depth + 1, if (depth == 0) i else branch) }
+ n.top = (n.children.first().centerY + n.children.last().centerY) / 2f - n.height / 2f
+ }
+ }
+ place(root, 0, 0)
+ return MapLayout(root, at - 46f * d + pad, cursor - 12f * d + pad, d)
+}
+
+private fun mapTextPaint(density: Float, bold: Boolean) = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = 15f * density
+ typeface = if (bold) Typeface.create(Typeface.DEFAULT, Typeface.BOLD) else Typeface.DEFAULT
+}
+
+private val BranchColors = listOf(Candy.Sky, Candy.Bubblegum, Candy.Mint, Candy.Tangerine, Candy.Grape, Candy.Lemon, Candy.Tomato)
+
+/**
+ * Draws [layout] on [canvas] (the screen, a picture or a PDF page, all alike): soft curves from each
+ * idea to its children in the branch's colour, the centre as a dark capsule, the first ideas as
+ * capsules of colour, the rest as tinted ones.
+ */
+internal fun drawMap(canvas: android.graphics.Canvas, layout: MapLayout, dark: Boolean) {
+ val d = layout.density
+ val ink = if (dark) Color.White else Color(0xFF15171C)
+ val line = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = 2.2f * d
+ strokeCap = Paint.Cap.ROUND
+ }
+ val fill = Paint(Paint.ANTI_ALIAS_FLAG)
+ val plain = mapTextPaint(d, bold = false)
+ val bold = mapTextPaint(d, bold = true)
+ val box = RectF()
+ val path = Path()
+ fun color(n: MapNode) = BranchColors[n.branch % BranchColors.size]
+ fun links(n: MapNode) {
+ for (c in n.children) {
+ val x0 = n.left + n.width
+ val x1 = c.left
+ val mid = (x0 + x1) / 2f
+ path.reset()
+ path.moveTo(x0, n.centerY)
+ path.cubicTo(mid, n.centerY, mid, c.centerY, x1, c.centerY)
+ line.color = color(c).copy(alpha = 0.75f).toArgb()
+ canvas.drawPath(path, line)
+ links(c)
+ }
+ }
+ fun boxes(n: MapNode, depth: Int) {
+ box.set(n.left, n.top, n.left + n.width, n.top + n.height)
+ val text = if (depth <= 1) bold else plain
+ when (depth) {
+ 0 -> {
+ fill.color = (if (dark) Color(0xFFF2F4FA) else Color(0xFF1E2233)).toArgb()
+ text.color = (if (dark) Color(0xFF15171C) else Color.White).toArgb()
+ }
+ 1 -> {
+ fill.color = color(n).toArgb()
+ text.color = Color.White.toArgb()
+ }
+ else -> {
+ fill.color = color(n).copy(alpha = if (dark) 0.26f else 0.16f).toArgb()
+ text.color = ink.toArgb()
+ }
+ }
+ canvas.drawRoundRect(box, n.height / 2f, n.height / 2f, fill)
+ val inset = (if (depth == 0) 20f else 14f) * d
+ canvas.drawText(n.label, n.left + inset, n.centerY - (text.descent() + text.ascent()) / 2f, text)
+ n.children.forEach { boxes(it, depth + 1) }
+ }
+ links(layout.root)
+ boxes(layout.root, 0)
+}
+
+/** [layout] as a picture file (PNG, at most 4096 pixels on its long side) or a one-page PDF. */
+private fun writeMap(layout: MapLayout, dark: Boolean, pdf: Boolean, out: File) {
+ val ground = (if (dark) Color(0xFF14152B) else Color.White).toArgb()
+ if (pdf) {
+ // a page of the map's own size: a density-independent pixel to a point
+ val w = (layout.width / layout.density).toInt().coerceAtLeast(1)
+ val h = (layout.height / layout.density).toInt().coerceAtLeast(1)
+ val doc = PdfDocument()
+ try {
+ val page = doc.startPage(PdfDocument.PageInfo.Builder(w, h, 1).create())
+ page.canvas.drawColor(ground)
+ page.canvas.scale(1f / layout.density, 1f / layout.density)
+ drawMap(page.canvas, layout, dark)
+ doc.finishPage(page)
+ out.outputStream().use { doc.writeTo(it) }
+ } finally {
+ doc.close()
+ }
+ } else {
+ val k = minOf(1f, 4096f / maxOf(layout.width, layout.height))
+ val bitmap = Bitmap.createBitmap((layout.width * k).toInt().coerceAtLeast(1), (layout.height * k).toInt().coerceAtLeast(1), Bitmap.Config.ARGB_8888)
+ val canvas = android.graphics.Canvas(bitmap)
+ canvas.drawColor(ground)
+ canvas.scale(k, k)
+ drawMap(canvas, layout, dark)
+ out.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ bitmap.recycle()
+ }
+}
+
+/**
+ * A note seen as a mind map: its title in the middle, its outline branching out to the right. Drag
+ * to move it, pinch to zoom; the two buttons save it to Downloads as a picture or a PDF. The map is
+ * drawn from the note as it is written (one idea a line, indented under the idea it belongs to), so
+ * it is edited by editing the note, and nothing leaves the phone.
+ */
+@Composable
+fun MindMapScreen(vm: AppViewModel, title: String, body: String, onClose: () -> Unit) {
+ val c = clear
+ val density = LocalDensity.current.density
+ val context = LocalContext.current
+ val scope = rememberCoroutineScope()
+ val fallback = stringResource(R.string.mindmap_title)
+ val layout = remember(title, body, density) { layoutMap(parseOutline(title.ifBlank { fallback }, body), density) }
+ var scale by remember { mutableStateOf(1f) }
+ var pan by remember { mutableStateOf(Offset.Zero) }
+ var fitted by remember(layout) { mutableStateOf(false) }
+ val empty = layout.root.children.isEmpty()
+ BackHandler(onBack = onClose)
+
+ fun save(pdf: Boolean) {
+ val name = title.ifBlank { fallback }.replace(Regex("""[\\/:*?"<>|\n\r]"""), " ").trim().take(60).ifEmpty { fallback }
+ scope.launch {
+ val file = withContext(Dispatchers.Default) {
+ runCatching {
+ File(context.cacheDir, "map-${System.nanoTime()}.${if (pdf) "pdf" else "png"}").also { writeMap(layout, c.dark, pdf, it) }
+ }.getOrNull()
+ }
+ if (file == null) vm.tell(context.getString(R.string.common_file_unreadable))
+ else vm.deliverFile(file, "$name.${if (pdf) "pdf" else "png"}", if (pdf) "application/pdf" else "image/png")
+ }
+ }
+
+ Box(
+ Modifier.fillMaxSize().background(if (c.dark) Color(0xFF14152B) else Color(0xFFF6F7FB)).onSizeChanged { size: IntSize ->
+ // the whole map in view to begin with, never larger than life
+ if (!fitted && size.width > 0 && layout.width > 0f) {
+ val s = minOf(1f, size.width / layout.width, size.height * 0.8f / layout.height).coerceAtLeast(0.3f)
+ scale = s
+ pan = Offset((size.width - layout.width * s) / 2f, (size.height - layout.height * s) / 2f)
+ fitted = true
+ }
+ },
+ ) {
+ if (empty) {
+ Text(
+ stringResource(R.string.mindmap_empty), style = ClearType.Body, color = c.inkSoft, textAlign = TextAlign.Center,
+ modifier = Modifier.align(Alignment.Center).padding(40.dp),
+ )
+ } else {
+ Canvas(
+ Modifier.fillMaxSize().pointerInput(layout) {
+ detectTransformGestures { centroid, move, zoom, _ ->
+ val next = (scale * zoom).coerceIn(0.2f, 4f)
+ pan = (pan - centroid) * (next / scale) + centroid + move
+ scale = next
+ }
+ },
+ ) {
+ drawIntoCanvas { cv ->
+ val native = cv.nativeCanvas
+ native.save()
+ native.translate(pan.x, pan.y)
+ native.scale(scale, scale)
+ drawMap(native, layout, c.dark)
+ native.restore()
+ }
+ }
+ }
+ Row(
+ Modifier.fillMaxWidth().statusBarsPadding().padding(horizontal = 16.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ GlassBackButton(onClose, immediate = true)
+ Text(stringResource(R.string.mindmap_title), style = ClearType.Title, color = c.ink, modifier = Modifier.weight(1f).padding(start = 6.dp))
+ if (!empty) {
+ GlassCircle(onClick = { save(pdf = false) }, label = stringResource(R.string.mindmap_save_image)) {
+ GlassIcon(LucideIcons.ImagePlus, null, Modifier.size(20.dp))
+ }
+ GlassCircle(onClick = { save(pdf = true) }, label = stringResource(R.string.mindmap_save_pdf)) {
+ GlassIcon(LucideIcons.FilePdf, null, Modifier.size(20.dp))
+ }
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/NoteEditor.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/NoteEditor.kt
index 8f85533..7275177 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/NoteEditor.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/NoteEditor.kt
@@ -113,6 +113,9 @@ fun NoteEditor(vm: AppViewModel, id: String) {
val c = clear
var title by remember(id) { mutableStateOf(TextFieldValue(note.title)) }
var body by remember(id) { mutableStateOf(TextFieldValue(note.body)) }
+ // the note drawn as a mind map, over the whole screen
+ var mindMap by remember(id) { mutableStateOf(false) }
+ if (mindMap) com.chethan616.clearpdf.ui.glass.GlassOverlay { MindMapScreen(vm, title.text, body.text) { mindMap = false } }
var items by remember(id) { mutableStateOf(note.items) }
var focusItem by remember { mutableStateOf<String?>(null) }
val titleFocus = remember { FocusRequester() }
@@ -280,6 +283,7 @@ fun NoteEditor(vm: AppViewModel, id: String) {
} else {
ToolButton(LucideIcons.Bold, stringResource(R.string.notes_bold), primary = true) { body = toggleBold(body) }
ToolButton(LucideIcons.Heading, stringResource(R.string.notes_heading)) { body = toggleHeading(body) }
+ ToolButton(LucideIcons.Network, stringResource(R.string.mindmap_title)) { mindMap = true }
}
ToolButton(LucideIcons.Camera, stringResource(R.string.notes_take_photo)) { commit(); vm.takeNotePhoto() }
ToolButton(LucideIcons.ImagePlus, stringResource(R.string.notes_add_photo)) { commit(); vm.pickNotePhoto() }
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 a19a27c..faa2994 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
@@ -117,6 +117,9 @@ private enum class Adjust(
private val TURNS = listOf("Normal", "Rotate90", "Rotate180", "Rotate270")
+/** The shapes Crop steps through (width to height), after "as it is". */
+private val CROPS = listOf(1f to 1f, 4f to 3f, 3f to 4f, 16f to 9f, 9f to 16f)
+
private fun shown(a: Adjust, value: Float): String {
val zero = if (a.decimals > 0) 0.005f else 0.5f
if (abs(value) < zero) return "0"
@@ -143,7 +146,9 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
var comparing by remember { mutableStateOf(false) }
var saving by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
- val changed = values.values.any { it != 0f } || turn != 0
+ // 0: the whole picture; else the shape of CROPS[crop - 1], cut from the middle
+ var crop by remember(name) { mutableStateOf(0) }
+ val changed = values.values.any { it != 0f } || turn != 0 || crop != 0
fun settings(includeAdjustments: Boolean = true): String {
val root = JSONObject()
@@ -154,6 +159,17 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
}
}
if (turn != 0) root.put("orientation", TURNS[turn])
+ val whole = original
+ if (includeAdjustments && crop != 0 && whole != null && whole.width > 0 && whole.height > 0) {
+ // the largest box of the chosen shape, from the middle of the picture as it stands
+ val (cw, ch) = CROPS[crop - 1]
+ val shape = cw / ch
+ val picture = whole.width.toFloat() / whole.height
+ val w = minOf(1f, shape / picture).toDouble()
+ val h = minOf(1f, picture / shape).toDouble()
+ val rect = JSONObject().put("x0", (1 - w) / 2).put("y0", (1 - h) / 2).put("x1", (1 + w) / 2).put("y1", (1 + h) / 2)
+ root.put("crop", JSONObject().put("geometry", JSONObject().put("rect", rect).put("angle", 0.0)))
+ }
return root.toString()
}
@@ -246,8 +262,10 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
changed = changed,
onClose = close,
onDone = done,
- onReset = { values.clear(); turn = 0 },
+ onReset = { values.clear(); turn = 0; crop = 0 },
onRotate = { turn = (turn + 1) % 4 },
+ cropLabel = if (crop == 0) null else CROPS[crop - 1].let { "${it.first.toInt()}:${it.second.toInt()}" },
+ onCrop = { crop = (crop + 1) % (CROPS.size + 1) },
)
Box(Modifier.align(Alignment.BottomCenter)) {
PhotoControls(
@@ -272,6 +290,8 @@ private fun PhotoHeader(
onDone: () -> Unit,
onReset: () -> Unit,
onRotate: () -> Unit,
+ cropLabel: String?,
+ onCrop: () -> Unit,
) {
val ink = rememberGlassInk(Color.White)
Column(Modifier.fillMaxWidth()) {
@@ -292,6 +312,11 @@ private fun PhotoHeader(
Text(stringResource(R.string.photo_reset), style = ClearType.Label, color = Candy.Lemon)
}
}
+ // Crop steps through the shapes (1:1, 4:3, 3:4, 16:9, 9:16) and back to the whole picture
+ GlassCircle(onClick = onCrop, size = 42.dp, ink = Color.White, label = stringResource(R.string.photo_crop)) {
+ if (cropLabel == null) GlassIcon(LucideIcons.Crop, null, Modifier.size(19.dp))
+ else Text(cropLabel, style = ClearType.Label.copy(fontSize = 11.sp), color = Candy.Lemon, maxLines = 1)
+ }
GlassCircle(onClick = onRotate, size = 42.dp, ink = Color.White, label = stringResource(R.string.photo_rotate)) {
GlassIcon(LucideIcons.RotateCw, null, Modifier.size(19.dp))
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DocLayout.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DocLayout.kt
index 267cd8d..e6cd7fe 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DocLayout.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DocLayout.kt
@@ -40,25 +40,43 @@ class DocLayout(
val margin: Float,
val padTop: Float,
val padBottom: Float,
+ /** Continuous mode: how many pages sit side by side in a row (1, or 2 like an open book). */
+ val columns: Int = 1,
) {
val rects: List<LRect>
val width: Float
val height: Float
+ /** Continuous mode: where each page's row ends (rows of two pages may differ in height). */
+ private val rowBottom: FloatArray
+
init {
val out = ArrayList<LRect>(pages.size)
when (mode) {
PageMode.Continuous -> {
val widest = pages.maxOfOrNull { it.width }?.coerceAtLeast(1f) ?: 1f
- val scale = max(1f, viewW - 2 * margin) / widest
+ val cols = columns.coerceIn(1, 2)
+ // side by side, the pages share the width (less the gap between them)
+ val scale = max(1f, (viewW - 2 * margin - (cols - 1) * gap) / cols) / widest
+ val bottoms = FloatArray(pages.size)
var y = padTop
- for (p in pages) {
- val w = p.width.coerceAtLeast(1f) * scale
- val h = p.height.coerceAtLeast(1f) * scale
- val x = (viewW - w) / 2f
- out.add(LRect(x, y, x + w, y + h))
- y += h + gap
+ var i = 0
+ while (i < pages.size) {
+ val row = pages.subList(i, min(i + cols, pages.size))
+ val rowW = row.sumOf { (it.width.coerceAtLeast(1f) * scale).toDouble() }.toFloat() + (row.size - 1) * gap
+ val rowH = row.maxOf { it.height.coerceAtLeast(1f) * scale }
+ var x = (viewW - rowW) / 2f
+ for ((k, p) in row.withIndex()) {
+ val w = p.width.coerceAtLeast(1f) * scale
+ val h = p.height.coerceAtLeast(1f) * scale
+ out.add(LRect(x, y, x + w, y + h))
+ bottoms[i + k] = y + rowH
+ x += w + gap
+ }
+ y += rowH + gap
+ i += row.size
}
+ rowBottom = bottoms
width = viewW
height = if (pages.isEmpty()) viewH else y - gap + padBottom
}
@@ -82,6 +100,7 @@ class DocLayout(
out.add(LRect(x, y, x + w, y + h))
tallest = max(tallest, y + h + margin + padBottom)
}
+ rowBottom = FloatArray(0)
width = max(viewW, pages.size * viewW)
height = tallest
}
@@ -116,7 +135,7 @@ class DocLayout(
var hi = rects.lastIndex
while (lo < hi) {
val mid = (lo + hi) / 2
- if (rects[mid].bottom + gap < y) lo = mid + 1 else hi = mid
+ if (rowBottom[mid] + gap < y) lo = mid + 1 else hi = mid
}
return lo
}
@@ -132,7 +151,9 @@ class DocLayout(
if (rects.isEmpty()) return 0
return when (mode) {
PageMode.Continuous -> {
- val i = firstAtOrBelow(y)
+ var i = firstAtOrBelow(y)
+ // side by side: the page of the row that [x] is nearest
+ while (i + 1 < rects.size && rects[i + 1].top == rects[i].top && x > (rects[i].right + rects[i + 1].left) / 2f) i++
val r = rects[i]
when {
// in the gap below page i: whichever edge is closer
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt
index c613887..a0fd4ff 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt
@@ -199,8 +199,17 @@ private fun EditFormatBar(vm: AppViewModel, doc: OpenDocument, para: Paragraph)
) {
val underline = vm.editUnderline[para.page to para.number] == true
// the reference draws these as serif T's: heavy, slanted, underlined, and a small t beside a big one
- LetterButton("T", stringResource(R.string.edit_bold), para.bold, weight = FontWeight.Black) { vm.styleParagraph(doc, para, mapOf("bold" to !para.bold)) }
- LetterButton("T", stringResource(R.string.edit_italic), para.italic, italic = true) { vm.styleParagraph(doc, para, mapOf("italic" to !para.italic)) }
+ // with words selected in the paragraph, Bold and Italic change only those; else all of it
+ LetterButton("T", stringResource(R.string.edit_bold), para.bold, weight = FontWeight.Black) {
+ val picked = vm.editRange?.takeIf { vm.editing != null }
+ if (picked != null) vm.styleRange(doc, para, picked, bold = !para.bold, italic = para.italic)
+ else vm.styleParagraph(doc, para, mapOf("bold" to !para.bold))
+ }
+ LetterButton("T", stringResource(R.string.edit_italic), para.italic, italic = true) {
+ val picked = vm.editRange?.takeIf { vm.editing != null }
+ if (picked != null) vm.styleRange(doc, para, picked, bold = para.bold, italic = !para.italic)
+ else vm.styleParagraph(doc, para, mapOf("italic" to !para.italic))
+ }
LetterButton("T", stringResource(R.string.edit_underline), underline, underline = true) {
vm.editUnderline[para.page to para.number] = !underline
vm.styleParagraph(doc, para, mapOf("underline" to !underline))
@@ -524,6 +533,9 @@ private fun BoxScope.InlineEditor(vm: AppViewModel, doc: OpenDocument, para: Par
if (b.y > clear) v.setScroll(v.scrollX, v.scrollY + (b.y - clear))
}
LaunchedEffect(value.text) { vm.editDraft = value.text }
+ // what is selected in the paragraph, for Bold and Italic to take only that
+ LaunchedEffect(value.selection) { vm.editRange = value.selection.takeIf { !it.collapsed } }
+ androidx.compose.runtime.DisposableEffect(para) { onDispose { vm.editRange = null } }
// misspelled words, checked a moment after typing stops, underlined in red (as the reference does)
val context = androidx.compose.ui.platform.LocalContext.current
val speller = remember { SpellCheck(context) }
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.kt
index 40d8175..e70c203 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
@@ -88,6 +88,7 @@ enum class QuickTool(val id: String, @StringRes val label: Int, @StringRes val t
Text("text", R.string.toolbar_label_add_text, R.string.toolbar_tool_text, LucideIcons.Type, ToolHues.text),
Scan("scan", R.string.common_tool_scan, R.string.common_tool_scan, LucideIcons.Camera, ToolHues.scan),
ReadAloud("readaloud", R.string.common_tool_read_aloud, R.string.common_tool_read_aloud, LucideIcons.Volume2, ToolHues.read),
+ FindFields("findfields", R.string.toolbar_label_find_fields, R.string.tool_find_fields, LucideIcons.ScanText, ToolHues.sign),
// office documents' own tools (their engines: WordCraft, DeckCraft)
Present("present", R.string.office_present, R.string.office_present, LucideIcons.Presentation, ToolHues.read),
@@ -177,6 +178,7 @@ fun AppViewModel.runQuickTool(doc: OpenDocument, tool: QuickTool) {
}
QuickTool.Crop -> openCrop(doc)
QuickTool.Ocr -> recognizeText(doc)
+ QuickTool.FindFields -> detectFields(doc)
QuickTool.Create -> openCreate()
QuickTool.Scan -> startScan()
QuickTool.ReadAloud -> startReadAloud(doc)
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 0a410af..8b0ddc8 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
@@ -245,6 +245,7 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)
vm.enterTool(doc, ViewerTool.Edit)
}
if (doc.info.allowsCopying) MenuRow(LucideIcons.Copy, stringResource(R.string.viewer_copy_text)) { vm.copySelection(doc) }
+ if (doc.info.allowsCopying) MenuRow(LucideIcons.Languages, stringResource(R.string.viewer_translate)) { vm.translateSelection(doc) }
// while reading aloud, the reading moves to the selection (the reference's "from here")
MenuRow(LucideIcons.Volume2, stringResource(if (vm.readAloud != null) R.string.viewer_read_from_here else R.string.common_tool_read_aloud)) {
vm.startReadAloud(doc, fromSelection = true)
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt
index 216d9fe..1c8ead9 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt
@@ -178,14 +178,22 @@ fun ViewSettingsSheet(vm: AppViewModel, doc: OpenDocument) {
SheetBackHeader(stringResource(R.string.sheet_view_settings), onBack = { ctl.sheet = ViewerSheet.More })
// how the pages run, as three cards to choose from (the chosen one lit in blue)
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- LayoutChoice(LucideIcons.GalleryVerticalEnd, stringResource(R.string.sheet_continuous), doc.viewer.mode == PageMode.Continuous && !vm.readingMode) {
+ LayoutChoice(LucideIcons.GalleryVerticalEnd, stringResource(R.string.sheet_continuous), doc.viewer.mode == PageMode.Continuous && !vm.twoPages && !vm.readingMode) {
vm.setPageMode(doc, PageMode.Continuous)
+ vm.setTwoPages(doc, false)
ctl.sheet = ViewerSheet.None
}
LayoutChoice(LucideIcons.File, stringResource(R.string.sheet_single_page), doc.viewer.mode == PageMode.SinglePage && !vm.readingMode) {
vm.setPageMode(doc, PageMode.SinglePage)
ctl.sheet = ViewerSheet.None
}
+ LayoutChoice(LucideIcons.Columns2, stringResource(R.string.sheet_two_pages), doc.viewer.mode == PageMode.Continuous && vm.twoPages && !vm.readingMode) {
+ // two pages side by side, scrolled together like an open book; chosen again, one column
+ val on = !(vm.twoPages && doc.viewer.mode == PageMode.Continuous)
+ vm.setPageMode(doc, PageMode.Continuous)
+ vm.setTwoPages(doc, on)
+ ctl.sheet = ViewerSheet.None
+ }
LayoutChoice(LucideIcons.BookOpenText, stringResource(R.string.sheet_reading_mode), vm.readingMode) {
ctl.sheet = ViewerSheet.None
vm.openReadingMode(doc)
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerState.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerState.kt
index 0e5cf79..4efbaad 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerState.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerState.kt
@@ -51,10 +51,26 @@ class ViewerState(pages: List<PageSize>) {
val layout: DocLayout
get() {
val c = cachedLayout
- if (c != null && c.pages === pages && c.mode == mode && c.viewW == viewW && c.viewH == viewH && c.padTop == padTop && c.padBottom == padBottom) return c
- return DocLayout(pages, mode, viewW, viewH, gap, margin, padTop, padBottom).also { cachedLayout = it }
+ if (c != null && c.pages === pages && c.mode == mode && c.viewW == viewW && c.viewH == viewH && c.padTop == padTop && c.padBottom == padBottom && c.columns == columns) return c
+ return DocLayout(pages, mode, viewW, viewH, gap, margin, padTop, padBottom, columns).also { cachedLayout = it }
}
+ /** Continuous mode: pages in one column, or two side by side. */
+ var columns by androidx.compose.runtime.mutableIntStateOf(1)
+ private set
+
+ /** One column or two; the reader stays on the page it was on. */
+ fun showColumns(n: Int) {
+ val to = n.coerceIn(1, 2)
+ if (to == columns) return
+ val page = if (viewW > 0f) currentPage else 0
+ columns = to
+ if (viewW > 0f) {
+ if (mode == PageMode.Continuous) zoom = 1f
+ goToPage(page)
+ }
+ }
+
/** Continuous pages zoom out past fit-width; single-page mode rests on one page filling the width. */
val minZoom: Float get() = if (mode == PageMode.Continuous) ZOOM_OUT_LIMIT else MIN_ZOOM
val maxZoom: Float get() = MAX_ZOOM
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 9c6c00d..658b914 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -425,6 +425,7 @@
<string name="viewer_search_count">%1$d of %2$d</string>
<string name="viewer_read_from_here">Read from here</string>
<string name="viewer_copy_text">Copy text</string>
+ <string name="viewer_translate">Translate</string>
<!-- Translator note: accessibility labels of the two handles at the ends of selected text. -->
<string name="viewer_selection_start">Selection start</string>
<string name="viewer_selection_end">Selection end</string>
@@ -654,6 +655,7 @@
<!-- Viewer sheets: View settings -->
<string name="sheet_continuous">Continuous</string>
<string name="sheet_single_page">Single page</string>
+ <string name="sheet_two_pages">Two pages</string>
<string name="sheet_reading_mode">Reading Mode</string>
<string name="sheet_night_mode">Night Mode</string>
@@ -769,6 +771,14 @@
<string name="toolbar_label_crop">Crop</string>
<!-- Note: the Recognize text tool's short name on the toolbar -->
<string name="toolbar_label_recognize">Recognize</string>
+ <string name="toolbar_label_find_fields">Find fields</string>
+ <string name="tool_find_fields">Find form fields</string>
+ <string name="msg_busy_finding_fields">Looking for places to fill in…</string>
+ <string name="msg_no_fields_found">No places to fill in were found on this document</string>
+ <plurals name="msg_fields_found">
+ <item quantity="one">%1$d field found. Tap it to fill it in.</item>
+ <item quantity="other">%1$d fields found. Tap one to fill it in.</item>
+ </plurals>
<!-- Note: the tool that types text onto the page, as named on the toolbar -->
<string name="toolbar_label_add_text">Add text</string>
<!-- Note: the same tool's name in More tools, and its one sub-tool (text typed onto the page) -->
@@ -1033,6 +1043,7 @@
<string name="photo_vibrance">Vibrance</string>
<string name="photo_saturation">Saturation</string>
<string name="photo_straighten">Straighten</string>
+ <string name="photo_crop">Crop</string>
<string name="photo_whites">Whites</string>
<string name="photo_blacks">Blacks</string>
<string name="photo_clarity">Clarity</string>
@@ -1384,6 +1395,10 @@
<string name="create_voice">Record a voice note</string>
<string name="voice_saved">Voice note saved</string>
<string name="voice_import">Import audio</string>
+ <string name="mindmap_title">Mind map</string>
+ <string name="mindmap_empty">Write the note as an outline: one idea a line, indented under the idea it belongs to. It is drawn here as a map.</string>
+ <string name="mindmap_save_image">Save as image</string>
+ <string name="mindmap_save_pdf">Save as PDF</string>
<string name="voice_imported">Audio added to your desk</string>
<string name="voice_export">Save to Downloads</string>
<string name="voice_export_name">Voice note</string>
diff --git a/android/app/src/test/java/com/chethan616/clearpdf/ui/TwoPagesAndOutlineTest.kt b/android/app/src/test/java/com/chethan616/clearpdf/ui/TwoPagesAndOutlineTest.kt
new file mode 100644
index 0000000..bbfd860
--- /dev/null
+++ b/android/app/src/test/java/com/chethan616/clearpdf/ui/TwoPagesAndOutlineTest.kt
@@ -0,0 +1,55 @@
+package com.chethan616.clearpdf.ui
+
+import com.chethan616.clearpdf.ui.notes.parseOutline
+import com.chethan616.clearpdf.ui.viewer.DocLayout
+import com.chethan616.clearpdf.ui.viewer.PageMode
+import com.chethan616.clearpdf.ui.viewer.PageSize
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class TwoPagesAndOutlineTest {
+ private val pages = List(5) { PageSize(600f, 800f) }
+
+ @Test
+ fun twoPagesShareTheWidthInRows() {
+ val l = DocLayout(pages, PageMode.Continuous, 1000f, 1600f, gap = 20f, margin = 10f, padTop = 0f, padBottom = 0f, columns = 2)
+ // (1000 less the margins and the gap between the two) halved
+ assertEquals(480f, l.rects[0].width, 0.5f)
+ assertEquals(l.rects[0].top, l.rects[1].top, 0f)
+ assertEquals(20f, l.rects[1].left - l.rects[0].right, 0.5f)
+ assertTrue(l.rects[2].top > l.rects[0].bottom)
+ // the odd page out stands alone in the last row, centred
+ assertEquals(500f, (l.rects[4].left + l.rects[4].right) / 2f, 0.5f)
+ }
+
+ @Test
+ fun aPointFindsThePageOfItsColumn() {
+ val l = DocLayout(pages, PageMode.Continuous, 1000f, 1600f, gap = 20f, margin = 10f, padTop = 0f, padBottom = 0f, columns = 2)
+ assertEquals(0, l.nearestPage(100f, 100f))
+ assertEquals(1, l.nearestPage(900f, 100f))
+ assertEquals(1, l.pageAt(l.rects[1].left + 5f, l.rects[1].top + 5f))
+ assertEquals(3, l.nearestPage(900f, l.rects[2].top + 10f))
+ assertEquals(4, l.nearestPage(500f, l.rects[4].top + 10f))
+ assertEquals(0..1, l.visible(0f, 0f, 1000f, 100f))
+ // one column lays out as it always did
+ val one = DocLayout(pages, PageMode.Continuous, 1000f, 1600f, gap = 20f, margin = 10f, padTop = 0f, padBottom = 0f)
+ assertEquals(980f, one.rects[0].width, 0.5f)
+ assertEquals(1, one.nearestPage(500f, one.rects[1].top + 10f))
+ }
+
+ @Test
+ fun anOutlineBecomesATree() {
+ val root = parseOutline("Trip", "# Before\n- Tickets\n - Train\n - Hotel\n- Pack\n# There\n1. Museum\n\n**Food**")
+ assertEquals("Trip", root.text)
+ assertEquals(listOf("Before", "There"), root.children.map { it.text })
+ val before = root.children[0]
+ assertEquals(listOf("Tickets", "Pack"), before.children.map { it.text })
+ assertEquals(listOf("Train", "Hotel"), before.children[0].children.map { it.text })
+ assertEquals(listOf("Museum", "Food"), root.children[1].children.map { it.text })
+ // no headings: indentation alone nests
+ val plain = parseOutline("", "Fruit\n Apples\n Pears\nBread")
+ assertEquals(listOf("Fruit", "Bread"), plain.children.map { it.text })
+ assertEquals(listOf("Apples", "Pears"), plain.children[0].children.map { it.text })
+ }
+}
diff --git a/android/gradle.properties b/android/gradle.properties
index 6bb364a..ce82087 100644
--- a/android/gradle.properties
+++ b/android/gradle.properties
@@ -12,5 +12,5 @@ artefact.abis=arm64-v8a,x86_64
# The app's version and its version code (before the ABI digit: see app/build.gradle.kts, the build
# checks the two agree). Set both to the release's before tagging it: the release workflow refuses a
# tag that differs, and F-Droid's update check reads them from here.
-artefact.version=3.0.0-alpha.7
-artefact.versionCode=3000007
+artefact.version=3.0.0-alpha.8
+artefact.versionCode=3000008
diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rs
index 96e8739..6adc353 100644
--- a/engine/mobile/src/tests.rs
+++ b/engine/mobile/src/tests.rs
@@ -829,4 +829,8 @@ fn the_photo_editors_tools_are_settings_lightcraft_reads() {
assert_eq!(s.effects.clarity, 30.0);
assert_eq!(s.detail.sharpen_amount, 60.0);
assert_eq!(s.vignette.amount, -40.0);
+ // Crop: a box of the picture, as fractions of it
+ let crop: lightcraft_develop::DevelopSettings =
+ serde_json::from_str(r#"{"crop":{"geometry":{"rect":{"x0":0.125,"y0":0.0,"x1":0.875,"y1":1.0},"angle":0.0}}}"#).unwrap();
+ assert_eq!((crop.crop.geometry.rect.x0, crop.crop.geometry.rect.x1), (0.125, 0.875));
}
diff --git a/fastlane/metadata/android/en-US/changelogs/30000080.txt b/fastlane/metadata/android/en-US/changelogs/30000080.txt
new file mode 100644
index 0000000..d226d68
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/30000080.txt
@@ -0,0 +1,10 @@
+More tools, fewer taps
+* Two pages side by side (View settings)
+* A note's outline as a mind map, saved as image or PDF
+* Find form fields on forms that have none
+* Translate selected text with your translator app
+* Bold or italic for only the selected words of a PDF
+* Photo editor: crop to a shape
+* Voice notes export as m4a
+* Menus grow from their button; Adaptive luminance
+* Better spreadsheets, PowerPoint fonts, old .ppt files
diff --git a/fastlane/metadata/android/en-US/changelogs/30000081.txt b/fastlane/metadata/android/en-US/changelogs/30000081.txt
new file mode 100644
index 0000000..d226d68
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/30000081.txt
@@ -0,0 +1,10 @@
+More tools, fewer taps
+* Two pages side by side (View settings)
+* A note's outline as a mind map, saved as image or PDF
+* Find form fields on forms that have none
+* Translate selected text with your translator app
+* Bold or italic for only the selected words of a PDF
+* Photo editor: crop to a shape
+* Voice notes export as m4a
+* Menus grow from their button; Adaptive luminance
+* Better spreadsheets, PowerPoint fonts, old .ppt files
diff --git a/fastlane/metadata/android/en-US/changelogs/30000082.txt b/fastlane/metadata/android/en-US/changelogs/30000082.txt
new file mode 100644
index 0000000..d226d68
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/30000082.txt
@@ -0,0 +1,10 @@
+More tools, fewer taps
+* Two pages side by side (View settings)
+* A note's outline as a mind map, saved as image or PDF
+* Find form fields on forms that have none
+* Translate selected text with your translator app
+* Bold or italic for only the selected words of a PDF
+* Photo editor: crop to a shape
+* Voice notes export as m4a
+* Menus grow from their button; Adaptive luminance
+* Better spreadsheets, PowerPoint fonts, old .ppt files
diff --git a/fastlane/metadata/android/en-US/changelogs/30000083.txt b/fastlane/metadata/android/en-US/changelogs/30000083.txt
new file mode 100644
index 0000000..d226d68
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/30000083.txt
@@ -0,0 +1,10 @@
+More tools, fewer taps
+* Two pages side by side (View settings)
+* A note's outline as a mind map, saved as image or PDF
+* Find form fields on forms that have none
+* Translate selected text with your translator app
+* Bold or italic for only the selected words of a PDF
+* Photo editor: crop to a shape
+* Voice notes export as m4a
+* Menus grow from their button; Adaptive luminance
+* Better spreadsheets, PowerPoint fonts, old .ppt files
diff --git a/fastlane/metadata/android/en-US/changelogs/30000084.txt b/fastlane/metadata/android/en-US/changelogs/30000084.txt
new file mode 100644
index 0000000..d226d68
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/30000084.txt
@@ -0,0 +1,10 @@
+More tools, fewer taps
+* Two pages side by side (View settings)
+* A note's outline as a mind map, saved as image or PDF
+* Find form fields on forms that have none
+* Translate selected text with your translator app
+* Bold or italic for only the selected words of a PDF
+* Photo editor: crop to a shape
+* Voice notes export as m4a
+* Menus grow from their button; Adaptive luminance
+* Better spreadsheets, PowerPoint fonts, old .ppt files