Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
feat: second round of reader features and fixes
Josh38bb296df897
diff --git a/apps/pdfcraft-android/android/app/src/main/AndroidManifest.xml b/apps/pdfcraft-android/android/app/src/main/AndroidManifest.xmlindex b32decf..539f622 100644--- a/apps/pdfcraft-android/android/app/src/main/AndroidManifest.xml+++ b/apps/pdfcraft-android/android/app/src/main/AndroidManifest.xml@@ -14,6 +14,10 @@granting it makes Android refuse IMAGE_CAPTURE. --><uses-feature android:name="android.hardware.camera.any" android:required="false" />+ <!-- Read aloud keeps reading with PdfCraft in the background (a media notification) -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />+<applicationandroid:name=".PdfcraftApplication"android:allowBackup="false"@@ -53,6 +57,11 @@</intent-filter></activity>+ <service+ android:name=".ReadAloudService"+ android:exported="false"+ android:foregroundServiceType="mediaPlayback" />+<!-- Files of PdfCraft's handed to other apps (share, print, open in) --><providerandroid:name="androidx.core.content.FileProvider"diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.ktindex 1b93e47..be521be 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt@@ -118,6 +118,10 @@ class MainActivity : ComponentActivity() {private var lastTouch = System.currentTimeMillis()+ // a keyboard (or desktop mode): keys the viewer takes when no text field has them+ override fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean =+ vm.viewerKey(keyCode, event.isCtrlPressed) || super.onKeyDown(keyCode, event)+override fun onUserInteraction() {super.onUserInteraction()lastTouch = System.currentTimeMillis()diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ReadAloudService.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ReadAloudService.ktnew file mode 100644index 0000000..54b4ebe--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ReadAloudService.kt@@ -0,0 +1,149 @@+package io.github.artcraftandroid.pdfcraft++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.graphics.drawable.Icon+import android.media.session.MediaSession+import android.media.session.PlaybackState+import android.os.Build+import android.os.IBinder++/**+ * Keeps Read aloud going when PdfCraft leaves the screen, as the reference's reading service does:+ * a foreground media service with a notification (and lock-screen and headset controls) to play,+ * pause, skip 15 seconds and stop. The voice itself stays in the app's `ReadAloud`; this service+ * only holds the process in the foreground and passes the controls back through [controls].+ */+class ReadAloudService : Service() {+ /** What the notification's buttons do: set by the app while reading is on. */+ interface Controls {+ fun play()+ fun pause()+ fun skip(forward: Boolean)+ fun stop()+ }++ private var session: MediaSession? = null++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onCreate() {+ super.onCreate()+ val nm = getSystemService(NotificationManager::class.java)+ nm?.createNotificationChannel(NotificationChannel(CHANNEL, "Read aloud", NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })+ session = MediaSession(this, "PdfCraft read aloud").apply {+ setCallback(object : MediaSession.Callback() {+ override fun onPlay() { controls?.play() }+ override fun onPause() { controls?.pause() }+ override fun onSkipToNext() { controls?.skip(true) }+ override fun onSkipToPrevious() { controls?.skip(false) }+ override fun onFastForward() { controls?.skip(true) }+ override fun onRewind() { controls?.skip(false) }+ override fun onStop() { controls?.stop() }+ })+ isActive = true+ }+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ when (intent?.action) {+ ACTION_PLAY -> controls?.play()+ ACTION_PAUSE -> controls?.pause()+ ACTION_BACK -> controls?.skip(false)+ ACTION_FORWARD -> controls?.skip(true)+ ACTION_STOP -> {+ controls?.stop()+ stopSelf()+ return START_NOT_STICKY+ }+ }+ val title = intent?.getStringExtra(EXTRA_TITLE) ?: lastTitle+ val playing = intent?.getBooleanExtra(EXTRA_PLAYING, lastPlaying) ?: lastPlaying+ lastTitle = title+ lastPlaying = playing+ session?.setPlaybackState(+ PlaybackState.Builder()+ .setActions(PlaybackState.ACTION_PLAY or PlaybackState.ACTION_PAUSE or PlaybackState.ACTION_PLAY_PAUSE or PlaybackState.ACTION_REWIND or PlaybackState.ACTION_FAST_FORWARD or PlaybackState.ACTION_STOP)+ .setState(if (playing) PlaybackState.STATE_PLAYING else PlaybackState.STATE_PAUSED, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 1f)+ .build(),+ )+ val notification = notification(title, playing)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ startForeground(NOTIFICATION, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)+ } else {+ startForeground(NOTIFICATION, notification)+ }+ return START_NOT_STICKY+ }++ private fun notification(title: String, playing: Boolean): Notification {+ fun action(icon: Int, label: String, action: String) = Notification.Action.Builder(+ Icon.createWithResource(this, icon), label,+ PendingIntent.getService(this, action.hashCode(), Intent(this, ReadAloudService::class.java).setAction(action), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT),+ ).build()+ val open = PendingIntent.getActivity(+ this, 0, Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ return Notification.Builder(this, CHANNEL)+ .setSmallIcon(R.drawable.ic_stat_read_aloud)+ .setContentTitle(title)+ .setContentText(if (playing) "Reading aloud" else "Paused")+ .setContentIntent(open)+ .setOngoing(playing)+ .setDeleteIntent(PendingIntent.getService(this, 1, Intent(this, ReadAloudService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_IMMUTABLE))+ .addAction(action(android.R.drawable.ic_media_rew, "Back 15 seconds", ACTION_BACK))+ .addAction(if (playing) action(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE) else action(android.R.drawable.ic_media_play, "Play", ACTION_PLAY))+ .addAction(action(android.R.drawable.ic_media_ff, "Forward 15 seconds", ACTION_FORWARD))+ .addAction(action(android.R.drawable.ic_menu_close_clear_cancel, "Stop", ACTION_STOP))+ .setStyle(Notification.MediaStyle().setMediaSession(session?.sessionToken).setShowActionsInCompactView(0, 1, 2))+ .build()+ }++ override fun onTaskRemoved(rootIntent: Intent?) {+ // swiped away from recents: reading stops with the app+ controls?.stop()+ stopSelf()+ super.onTaskRemoved(rootIntent)+ }++ override fun onDestroy() {+ session?.release()+ session = null+ super.onDestroy()+ }++ companion object {+ private const val CHANNEL = "readAloud"+ private const val NOTIFICATION = 7+ private const val ACTION_PLAY = "io.github.artcraftandroid.pdfcraft.readaloud.PLAY"+ private const val ACTION_PAUSE = "io.github.artcraftandroid.pdfcraft.readaloud.PAUSE"+ private const val ACTION_BACK = "io.github.artcraftandroid.pdfcraft.readaloud.BACK"+ private const val ACTION_FORWARD = "io.github.artcraftandroid.pdfcraft.readaloud.FORWARD"+ private const val ACTION_STOP = "io.github.artcraftandroid.pdfcraft.readaloud.STOP"+ private const val EXTRA_TITLE = "title"+ private const val EXTRA_PLAYING = "playing"+ private var lastTitle = ""+ private var lastPlaying = false++ /** The app's reading, while there is one. */+ @Volatile+ var controls: Controls? = null++ /** Show or update the notification (starting the service the first time). */+ fun show(context: Context, title: String, playing: Boolean) {+ val i = Intent(context, ReadAloudService::class.java).putExtra(EXTRA_TITLE, title).putExtra(EXTRA_PLAYING, playing)+ runCatching { context.startForegroundService(i) }+ }++ fun hide(context: Context) {+ context.stopService(Intent(context, ReadAloudService::class.java))+ }+ }+}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/DocumentFiles.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/DocumentFiles.ktindex 9c20656..43a175a 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/DocumentFiles.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/DocumentFiles.kt@@ -120,6 +120,17 @@ class DocumentFiles(private val context: Context) {return FileProvider.getUriForFile(context, "${context.packageName}.files", copy)}+ /** Several files to hand to another app at once (pictures of pages), each under its own name. */+ fun shareableAll(files: List<Pair<File, String>>): List<Uri> {+ shareDir.listFiles()?.forEach { it.deleteRecursively() }+ val dir = File(shareDir, System.nanoTime().toString()).apply { mkdirs() }+ return files.map { (file, name) ->+ val copy = File(dir, name.replace(Regex("[\\\\/:*?\"<>|\\p{Cntrl}]"), "_").ifBlank { file.name })+ file.copyTo(copy, overwrite = true)+ FileProvider.getUriForFile(context, "${context.packageName}.files", copy)+ }+ }+/** A new file in the app's own space for a document it makes, named [name] (made unique). */fun newCreated(name: String): File {val base = safeName(name).removeSuffix(".pdf")diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/RecentFiles.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/RecentFiles.ktindex 840f357..fc54c4a 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/RecentFiles.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/RecentFiles.kt@@ -18,6 +18,10 @@ data class RecentFile(val starred: Boolean = false,/** It was left in Reading Mode, to reopen that way (the reference remembers it for each file). */val reading: Boolean = false,+ /** Where the screen's top-left was on [lastPage] (points) and the zoom, to reopen at the same spot; x < 0: unknown. */+ val lastX: Float = -1f,+ val lastY: Float = -1f,+ val lastZoom: Float = 1f,)/**@@ -31,7 +35,10 @@ class RecentFiles(private val file: File) {fun touch(entry: RecentFile) = synchronized(lock) {val old = read().firstOrNull { it.uri == entry.uri }- val merged = entry.copy(starred = old?.starred ?: entry.starred, reading = old?.reading ?: entry.reading)+ val merged = entry.copy(+ starred = old?.starred ?: entry.starred, reading = old?.reading ?: entry.reading,+ lastX = old?.lastX ?: entry.lastX, lastY = old?.lastY ?: entry.lastY, lastZoom = old?.lastZoom ?: entry.lastZoom,+ )write(listOf(merged) + read().filter { it.uri != entry.uri })}@@ -58,6 +65,9 @@ class RecentFiles(private val file: File) {lastPage = o.optInt("lastPage"),starred = o.optBoolean("starred"),reading = o.optBoolean("reading"),+ lastX = o.optDouble("lastX", -1.0).toFloat(),+ lastY = o.optDouble("lastY", -1.0).toFloat(),+ lastZoom = o.optDouble("lastZoom", 1.0).toFloat(),)}}.getOrDefault(emptyList())@@ -68,7 +78,8 @@ class RecentFiles(private val file: File) {for (r in list.take(MAX)) {a.put(JSONObject().put("uri", r.uri).put("name", r.name).put("opened", r.opened).put("pages", r.pages)- .put("size", r.size).put("lastPage", r.lastPage).put("starred", r.starred).put("reading", r.reading),+ .put("size", r.size).put("lastPage", r.lastPage).put("starred", r.starred).put("reading", r.reading)+ .put("lastX", r.lastX.toDouble()).put("lastY", r.lastY.toDouble()).put("lastZoom", r.lastZoom.toDouble()),)}val tmp = File(file.parentFile, file.name + ".tmp")diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/UserBookmarks.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/UserBookmarks.ktindex 424da80..37f217e 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/UserBookmarks.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/UserBookmarks.kt@@ -61,6 +61,14 @@ class UserBookmarks(private val file: File) {save()}+ /** The file was renamed: its bookmarks go with it (as the reference moves them). */+ fun move(from: String, to: String) = synchronized(lock) {+ if (from == to) return@synchronized+ val list = byDoc.remove(from) ?: return@synchronized+ byDoc[to] = list+ save()+ }+fun clear(key: String) = synchronized(lock) {byDoc.remove(key)save()diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.ktindex 41d05d8..6b18110 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt@@ -165,6 +165,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {document = docstartPendingTool(doc)pendingPage = recent?.lastPage?.takeIf { it in 0 until info.pages.size }+ pendingSpot = recent?.takeIf { pendingPage != null && it.lastX >= 0f && it.lastY >= 0f }?.let { Triple(it.lastX, it.lastY, it.lastZoom) }withContext(Dispatchers.IO) {recents.touch(RecentFile(uri.toString(), info.name, System.currentTimeMillis(), info.pages.size, file.length(), recent?.lastPage ?: 0))}@@ -181,6 +182,9 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {/** The page to show once the viewer has laid the document out (reopening where the reader left off). */var pendingPage: Int? = null+ /** With [pendingPage]: the spot (points) at the screen's top-left and the zoom it was left at. */+ var pendingSpot: Triple<Float, Float, Float>? = null+/** Intents for the activity to start (share, open a link): the view model has no activity. */val intents = Channel<Intent>(Channel.BUFFERED)@@ -235,10 +239,18 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {private suspend fun saveAndClose(eng: Engine, doc: OpenDocument) {val reading = readingModeval pending = pendingPage+ // the spot at the screen's top-left and the zoom, to reopen there (as the reference does)+ val v = doc.viewer+ val spot = if (pending == null && v.mode == io.github.artcraftandroid.pdfcraft.ui.viewer.PageMode.Continuous) v.screenToPage(androidx.compose.ui.geometry.Offset(0f, v.padTop), nearest = true) else null+ val zoom = v.zoomwithContext(Dispatchers.IO) {// in Reading Mode the page canvas has no layout: the page read is the pending one- val page = pending ?: doc.viewer.currentPage- doc.source?.let { src -> recents.update(src.toString()) { it.copy(lastPage = page, reading = reading) } }+ val page = pending ?: spot?.page ?: v.currentPage+ doc.source?.let { src ->+ recents.update(src.toString()) {+ it.copy(lastPage = page, reading = reading, lastX = spot?.x ?: -1f, lastY = spot?.y ?: -1f, lastZoom = if (spot != null) zoom else 1f)+ }+ }}save(doc)closeQuietly(eng, doc)@@ -318,12 +330,18 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {}}+ /** Undo: inside a tool that keeps its own history (Draw) only that; else the document's last edit, named in a message. */fun undo(doc: OpenDocument) {- if (doc.undoTool?.invoke() == true) return- runTool(doc, "edit_undo")+ doc.localUndo?.let { it.undo(); return }+ val label = doc.info.undo ?: return+ runTool(doc, "edit_undo") { tell("$label undone") }}- fun redo(doc: OpenDocument) = runTool(doc, "edit_redo")+ fun redo(doc: OpenDocument) {+ doc.localUndo?.let { it.redo(); return }+ val label = doc.info.redo ?: return+ runTool(doc, "edit_redo") { tell("$label redone") }+ }/** Switch the viewer to [tool], unless the document forbids what it does. */fun enterTool(doc: OpenDocument, tool: ViewerTool) {@@ -421,7 +439,17 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {fun whenSearchDone(doc: OpenDocument) {viewModelScope.launch {snapshotFlow { doc.search.running }.first { !it }- if (doc.search.hits.isEmpty() && doc.search.query.isNotEmpty()) tell("No matches for “${doc.search.query}”")+ if (doc.search.hits.isEmpty() && doc.search.query.isNotEmpty()) {+ val eng = engine+ val textless = eng != null && (0 until minOf(doc.pageCount, 5)).all { p ->+ runCatching { withContext(eng.commands) { eng.session.glyphCount(doc.id, p.toUInt()) } }.getOrDefault(1u) == 0u+ }+ if (textless) {+ tell("This file's words are pictures, so they can't be searched yet.", "Recognize text") { recognizeText(doc) }+ } else {+ tell("No matches for “${doc.search.query}”")+ }+ }}}@@ -439,6 +467,31 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {}}+ /**+ * Keys in the viewer, as the reference takes them: N or Page Down for the next page, P or Page+ * Up for the previous one, the arrows to scroll, Ctrl+P to print, Ctrl and + or − to zoom.+ */+ fun viewerKey(keyCode: Int, ctrl: Boolean): Boolean {+ val doc = document ?: return false+ if (toolScreen != null || readingMode) return false+ val v = doc.viewer+ val center = androidx.compose.ui.geometry.Offset(v.viewW / 2f, v.viewH / 2f)+ when {+ ctrl && keyCode == android.view.KeyEvent.KEYCODE_P -> print(doc)+ ctrl && (keyCode == android.view.KeyEvent.KEYCODE_EQUALS || keyCode == android.view.KeyEvent.KEYCODE_PLUS || keyCode == android.view.KeyEvent.KEYCODE_NUMPAD_ADD) -> v.zoomTo(v.zoom + 0.25f, center)+ ctrl && (keyCode == android.view.KeyEvent.KEYCODE_MINUS || keyCode == android.view.KeyEvent.KEYCODE_NUMPAD_SUBTRACT) -> v.zoomTo(v.zoom - 0.25f, center)+ ctrl -> return false+ keyCode == android.view.KeyEvent.KEYCODE_N || keyCode == android.view.KeyEvent.KEYCODE_PAGE_DOWN -> v.goToPage(v.currentPage + 1)+ keyCode == android.view.KeyEvent.KEYCODE_P || keyCode == android.view.KeyEvent.KEYCODE_PAGE_UP -> v.goToPage(v.currentPage - 1)+ keyCode == android.view.KeyEvent.KEYCODE_DPAD_DOWN -> v.setScroll(v.scrollX, v.scrollY + v.viewH * 0.1f)+ keyCode == android.view.KeyEvent.KEYCODE_DPAD_UP -> v.setScroll(v.scrollX, v.scrollY - v.viewH * 0.1f)+ keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> v.setScroll(v.scrollX + v.viewW * 0.1f, v.scrollY)+ keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT -> v.setScroll(v.scrollX - v.viewW * 0.1f, v.scrollY)+ else -> return false+ }+ return true+ }+/** Print [doc] through Android's print framework. */fun print(doc: OpenDocument) {if (!doc.info.allowsPrinting) {@@ -447,10 +500,28 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {}viewModelScope.launch {save(doc)- prints.trySend(doc.file to doc.name)+ // the system's printing can't open a password-protected file: print an unlocked copy+ val file = if (doc.info.encrypted) unlockedCopy(doc) ?: doc.file else doc.file+ prints.trySend(file to doc.name)}}+ /** A temporary copy of [doc] without its password, for printing; null if the security can't be removed. */+ private suspend fun unlockedCopy(doc: OpenDocument): File? {+ val eng = engine ?: return null+ return runCatching {+ val out = tempFile("pdf")+ val copy = eng.tool("doc_open", mapOf("path" to doc.file.absolutePath, "password" to doc.password)).optLong("doc")+ try {+ eng.tool("doc_unprotect", mapOf("doc" to copy))+ eng.tool("doc_save", mapOf("doc" to copy, "path" to out.absolutePath, "full" to true))+ } finally {+ runCatching { eng.tool("doc_close", mapOf("doc" to copy, "discard_changes" to true)) }+ }+ out+ }.getOrNull()+ }+/** Where Save a copy is asked to write (the activity opens the system's file creator with this name). */val saveCopyRequests = Channel<String>(Channel.BUFFERED)private var afterCopy: (() -> Unit)? = null@@ -494,6 +565,25 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {var readAloud by mutableStateOf<ReadAloud?>(null)private set+ /** The reading notification follows Read aloud: shown while it reads or is paused, gone when it stops. */+ private val readAloudNotice = viewModelScope.launch {+ snapshotFlow { readAloud to (readAloud?.playing == true) }.collect { (ra, playing) ->+ val ctx = getApplication<Application>()+ if (ra == null) {+ io.github.artcraftandroid.pdfcraft.ReadAloudService.controls = null+ io.github.artcraftandroid.pdfcraft.ReadAloudService.hide(ctx)+ } else {+ io.github.artcraftandroid.pdfcraft.ReadAloudService.controls = object : io.github.artcraftandroid.pdfcraft.ReadAloudService.Controls {+ override fun play() { readAloud?.play() }+ override fun pause() { readAloud?.pause() }+ override fun skip(forward: Boolean) { readAloud?.skip(forward) }+ override fun stop() { readAloud?.stop() }+ }+ io.github.artcraftandroid.pdfcraft.ReadAloudService.show(ctx, ra.title, playing)+ }+ }+ }+fun startReadAloud(doc: OpenDocument, fromSelection: Boolean = false) {if (doc.info.encrypted) {tell("Read aloud isn't available for password-protected documents.")@@ -501,8 +591,25 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {}readAloud?.stop()val eng = engine ?: return- val start = if (fromSelection) doc.selection.selection?.range?.page?.toInt() else null- readAloud = ReadAloud(getApplication(), eng, doc, viewModelScope, start ?: doc.viewer.currentPage) { readAloud = null }+ val key = docKey(doc)+ val sel = if (fromSelection) doc.selection.selection?.range else null+ if (sel != null) {+ // from the selection's first word+ readAloud = ReadAloud(getApplication(), eng, doc, viewModelScope, sel.page.toInt(), { readAloud = null }, key, startGlyph = sel.start)+ return+ }+ val saved = ReadAloud.savedPosition(getApplication(), key)?.takeIf { it.first in 0 until doc.pageCount }+ if (saved != null) {+ readAloud = ReadAloud(getApplication(), eng, doc, viewModelScope, saved.first, { readAloud = null }, key, resumeAt = saved.second to saved.third)+ tell("Reading on from where you stopped", "Start over") {+ ReadAloud.forgetPosition(getApplication(), key)+ readAloud?.stop()+ ReadAloud.forgetPosition(getApplication(), key)+ readAloud = ReadAloud(getApplication(), eng, doc, viewModelScope, 0, { readAloud = null }, key)+ }+ return+ }+ readAloud = ReadAloud(getApplication(), eng, doc, viewModelScope, doc.viewer.currentPage, { readAloud = null }, key)}// ---- Tools' remembered settings, bookmarks, stars --------------------------------------@@ -514,6 +621,27 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {private val appPrefs = app.getSharedPreferences("app", android.content.Context.MODE_PRIVATE)private val bookmarkStore = UserBookmarks(File(app.filesDir, "bookmarks.json"))+ /** The Search tab's last searches, newest first (kept on the phone, as the reference keeps them). */+ var recentSearches by mutableStateOf(appPrefs.getString("recentSearches", null)?.split('\n')?.filter { it.isNotBlank() } ?: emptyList())+ private set++ fun addRecentSearch(q: String) {+ val t = q.trim()+ if (t.isEmpty()) return+ recentSearches = (listOf(t) + recentSearches.filterNot { it.equals(t, ignoreCase = true) }).take(10)+ appPrefs.edit().putString("recentSearches", recentSearches.joinToString("\n")).apply()+ }++ fun removeRecentSearch(q: String) {+ recentSearches = recentSearches - q+ appPrefs.edit().putString("recentSearches", recentSearches.joinToString("\n")).apply()+ }++ fun clearRecentSearches() {+ recentSearches = emptyList()+ appPrefs.edit().remove("recentSearches").apply()+ }+/** The key a document's own data (bookmarks, stars, last page) is kept under: where it came from. */fun docKey(doc: OpenDocument): String = doc.source?.toString() ?: doc.file.absolutePath@@ -693,17 +821,18 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {if (text.isBlank()) returnval at = prompt.atval size = toolPrefs.textSize- val lines = text.lines()- val width = (lines.maxOf { it.length } * size * 0.55f + size).coerceAtLeast(size * 2)- val height = lines.size * size * 1.25f + size * 0.5fval page = prompt.doc.info.pages.getOrNull(at.page) ?: return+ // as the reference: lines that wrap where the page ends become real line breaks, and the box+ // is as wide as its longest line (measured as the engine draws it, so it doesn't wrap again)+ val (lines, width, height) = FreeTextLayout.layout(text, size, (page.width - at.x - 6f).coerceAtLeast(size * 4))+ val wrapped = lines.joinToString("\n")val x1 = (at.x + width).coerceAtMost(page.width)val y1 = (at.y + height).coerceAtMost(page.height)runTool(prompt.doc, "comment_add",mapOf("page" to at.page + 1, "type" to "textbox", "rect" to listOf(at.x, at.y, x1, y1).map { it.toDouble() },- "contents" to text, "color" to toolPrefs.color(StyledTool.FreeText).hex(), "font_size" to size.toDouble(), "author" to author,+ "contents" to wrapped, "color" to toolPrefs.color(StyledTool.FreeText).hex(), "font_size" to size.toDouble(), "author" to author,),)}@@ -1029,6 +1158,12 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {addTextPrompt = TextPrompt(doc, at)return}+ if (editMode == io.github.artcraftandroid.pdfcraft.ui.viewer.EditMode.AddImage) {+ editMode = io.github.artcraftandroid.pdfcraft.ui.viewer.EditMode.Select+ editSelection = null+ addImageAt(doc, at)+ return+ }val hit = paragraphs[at.page].orEmpty().firstOrNull { p -> at.x in (p.box[0] - 4)..(p.box[2] + 4) && at.y in (p.box[1] - 4)..(p.box[3] + 4) }editSelection = hitif (hit == null) selectImageAt(doc, at)@@ -1064,6 +1199,16 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {private fun paraArgs(para: io.github.artcraftandroid.pdfcraft.ui.viewer.Paragraph) = mapOf<String, Any?>("page" to para.page + 1, "paragraph" to para.number)+ /** Make [para] a list of [style] (or plain again), with any typing so far. */+ fun listParagraph(doc: OpenDocument, para: io.github.artcraftandroid.pdfcraft.ui.viewer.Paragraph, style: io.github.artcraftandroid.pdfcraft.ui.viewer.ListStyle) {+ val typing = editing != null && editing?.number == para.number && editing?.page == para.page+ val base = if (typing) editDraft ?: para.text else para.text+ val text = io.github.artcraftandroid.pdfcraft.ui.viewer.ListStyle.apply(base, style)+ if (text == base) return+ if (typing) editDraft = text+ runTool(doc, "text_edit", paraArgs(para) + ("text" to text))+ }+/** A formatting change to [para], applied to the page at once (with any typing so far). */fun styleParagraph(doc: OpenDocument, para: io.github.artcraftandroid.pdfcraft.ui.viewer.Paragraph, style: Map<String, Any?>) {val typed = editDraft?.takeIf { editing != null && it != para.text }@@ -1101,20 +1246,44 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {}private fun selectImageAt(doc: OpenDocument, at: PagePoint) {+ viewModelScope.launch { imageUnder(doc, at)?.let { editImage = it } }+ }++ /** The picture drawn under [at], topmost first, if any. */+ private suspend fun imageUnder(doc: OpenDocument, at: PagePoint): io.github.artcraftandroid.pdfcraft.ui.viewer.EditImage? {+ val eng = engine ?: return null+ val r = runCatching { eng.tool("page_images", mapOf("doc" to doc.id, "page" to at.page + 1)) }.getOrNull() ?: return null+ val arr = r.optJSONArray("images") ?: return null+ for (i in arr.length() - 1 downTo 0) {+ val o = arr.optJSONObject(i) ?: continue+ val rect = (o.optJSONArray("visible_rect") ?: o.optJSONArray("rect")) ?: continue+ val box = FloatArray(4) { k -> rect.optDouble(k).toFloat() }+ if (at.x in box[0]..box[2] && at.y in box[1]..box[3]) {+ val full = o.optJSONArray("rect") ?: rect+ return io.github.artcraftandroid.pdfcraft.ui.viewer.EditImage(at.page, o.optInt("image"), FloatArray(4) { k -> full.optDouble(k).toFloat() })+ }+ }+ return null+ }++ /** The menu a long press on an empty part of a page opens. */+ var pageMenu by mutableStateOf<io.github.artcraftandroid.pdfcraft.ui.viewer.PageMenu?>(null)++ /**+ * A long press where no word is: on a picture, Edit PDF with the picture selected (the+ * reference's picture menu leads to editing it); elsewhere, the page menu at that point.+ */+ fun longPressPage(doc: OpenDocument, at: PagePoint, screen: androidx.compose.ui.geometry.Offset) {val eng = engine ?: returnviewModelScope.launch {- val r = runCatching { eng.tool("page_images", mapOf("doc" to doc.id, "page" to at.page + 1)) }.getOrNull() ?: return@launch- val arr = r.optJSONArray("images") ?: return@launch- for (i in arr.length() - 1 downTo 0) {- val o = arr.optJSONObject(i) ?: continue- val rect = (o.optJSONArray("visible_rect") ?: o.optJSONArray("rect")) ?: continue- val box = FloatArray(4) { k -> rect.optDouble(k).toFloat() }- if (at.x in box[0]..box[2] && at.y in box[1]..box[3]) {- val full = o.optJSONArray("rect") ?: rect- editImage = io.github.artcraftandroid.pdfcraft.ui.viewer.EditImage(at.page, o.optInt("image"), FloatArray(4) { k -> full.optDouble(k).toFloat() })- return@launch- }+ val img = imageUnder(doc, at)+ if (img != null) {+ enterTool(doc, io.github.artcraftandroid.pdfcraft.ui.viewer.ViewerTool.Edit)+ if (doc.controller.tool == io.github.artcraftandroid.pdfcraft.ui.viewer.ViewerTool.Edit) editImage = img+ return@launch}+ val glyphs = runCatching { withContext(eng.commands) { eng.session.glyphCount(doc.id, at.page.toUInt()) } }.getOrDefault(1u)+ pageMenu = io.github.artcraftandroid.pdfcraft.ui.viewer.PageMenu(doc, at, screen, pageHasText = glyphs > 0u)}}@@ -1152,11 +1321,41 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {val imagePicks = Channel<OpenDocument>(Channel.BUFFERED)private var imageFor: OpenDocument? = null+ /** Where the picture being picked goes (centred there); null: the current page as before. */+ private var imageAt: PagePoint? = null+fun pickEditImage(doc: OpenDocument) {imageFor = docimagePicks.trySend(doc)}+ /** Add image at a tapped point (Edit PDF's Add image mode, or the page menu): first, from where. */+ fun addImageAt(doc: OpenDocument, at: PagePoint) {+ imageSource = doc to at+ }++ /** Asking where the picture comes from (photos or the camera), as the reference's menu does. */+ var imageSource by mutableStateOf<Pair<OpenDocument, PagePoint>?>(null)++ fun addImageFrom(camera: Boolean) {+ val (doc, at) = imageSource ?: return+ imageSource = null+ imageAt = at+ if (!camera) {+ pickEditImage(doc)+ return+ }+ imageFor = doc+ val dir = File(getApplication<Application>().cacheDir, "camera").apply { mkdirs() }+ val f = File(dir, "image-${System.nanoTime()}.jpg")+ shotFile = f+ imageShot = true+ cameraShots.trySend(f)+ }++ /** The camera's photo is for Add image, not a scan. */+ private var imageShot = false+fun addImage(uri: Uri?) {val doc = imageFor ?: returnimageFor = null@@ -1176,7 +1375,25 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {return@launch}val eng = engine ?: return@launch- eng.tool("page_add_image", mapOf("doc" to doc.id, "page" to doc.viewer.currentPage + 1, "path" to f.absolutePath))+ val at = imageAt+ imageAt = null+ val args = mutableMapOf<String, Any?>("doc" to doc.id, "page" to (at?.page ?: doc.viewer.currentPage) + 1, "path" to f.absolutePath)+ // centred on the tapped point, a third of the page wide, kept on the page+ val page = at?.let { doc.info.pages.getOrNull(it.page) }+ val bounds = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }+ android.graphics.BitmapFactory.decodeFile(f.absolutePath, bounds)+ if (at != null && page != null && bounds.outWidth > 0 && bounds.outHeight > 0) {+ var w = page.width / 3f+ var h = w * bounds.outHeight / bounds.outWidth+ if (h > page.height / 2f) {+ h = page.height / 2f+ w = h * bounds.outWidth / bounds.outHeight+ }+ val x0 = (at.x - w / 2f).coerceIn(0f, (page.width - w).coerceAtLeast(0f))+ val y0 = (at.y - h / 2f).coerceIn(0f, (page.height - h).coerceAtLeast(0f))+ args["rect"] = listOf(x0, y0, x0 + w, y0 + h).map { it.toDouble() }+ }+ eng.tool("page_add_image", args)refresh(doc)} catch (e: Exception) {tell(e.userMessage)@@ -1211,11 +1428,37 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {"radio" -> w.export?.let { fillField(doc, w.field, it) }"text", "combo", "list" -> fieldEdit = io.github.artcraftandroid.pdfcraft.ui.viewer.FieldEdit(doc, w)"signature" -> signaturePad = io.github.artcraftandroid.pdfcraft.ui.viewer.SignaturePad(false, doc, PagePoint(at.page, (w.rect[0] + w.rect[2]) / 2f - 40f, (w.rect[1] + w.rect[3]) / 2f - 10f))+ "button" -> pressButton(doc, w)else -> return false}return true}+ /**+ * A form button: does what its release action says, as far as a reader does on a phone:+ * clear the form (or the fields it names), open a web address after asking, or go to a page.+ * Scripts and sending the form online aren't run.+ */+ private fun pressButton(doc: OpenDocument, w: io.github.artcraftandroid.pdfcraft.core.WidgetInfo) {+ val eng = engine ?: return+ viewModelScope.launch {+ val r = runCatching { eng.tool("form_actions", mapOf("doc" to doc.id, "field" to w.field)) }.getOrNull() ?: return@launch+ val acts = r.optJSONArray("actions") ?: return@launch+ val all = (0 until acts.length()).mapNotNull { acts.optJSONObject(it) }+ val act = all.firstOrNull { it.optString("trigger") == "mouse_up" } ?: all.firstOrNull() ?: return@launch+ when {+ act.has("reset") -> {+ val names = act.optJSONArray("reset")?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()+ runTool(doc, "form_reset", if (names.isEmpty()) emptyMap() else mapOf("fields" to names)) { tell("Form cleared") }+ }+ act.has("url") -> linkPrompt = act.optString("url")+ act.has("page") -> doc.viewer.goToPage((act.optInt("page") - 1).coerceIn(0, doc.pageCount - 1))+ act.has("submit") -> tell("This button sends the form online, which PdfCraft doesn't do.")+ act.has("javascript") -> tell("This button runs a script, which PdfCraft doesn't run.")+ }+ }+ }+fun fillField(doc: OpenDocument, field: String, value: Any) {runTool(doc, "form_fill", mapOf("values" to mapOf(field to value)))}@@ -1335,7 +1578,12 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {"discard_thumbnails" to true, "remove_unreferenced_dests" to true,))toolScreen = null- if (out.length() >= doc.info.fileSize.toLong()) tell("This file is already compressed.")+ if (out.length() >= doc.info.fileSize.toLong()) {+ // as the reference: nothing is saved when the file can't get any smaller+ out.delete()+ tell("This file is already as small as it can be.")+ return@job+ }deliver(out, "${doc.title}_compressed.pdf")}@@ -1393,11 +1641,27 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {}/** Every page of [doc] as an image (200 dpi) in Pictures/PdfCraft. */- fun exportImages(doc: OpenDocument, ext: String) = job("Exporting images…") { eng ->+ /** Export to images: the format chosen, while its pages are being picked in the page grid. */+ var imageExport by mutableStateOf<String?>(null)++ /** The image format last exported to, offered first next time (as the reference remembers it). */+ val lastImageFormat: String get() = appPrefs.getString("imageFormat", "jpg") ?: "jpg"++ /** Export to images: remember the format, then pick the pages in the page grid (Save or Share there). */+ fun exportImages(doc: OpenDocument, ext: String) {+ appPrefs.edit().putString("imageFormat", ext).apply()+ toolScreen = null+ imageExport = ext+ organizing = true+ doc.controller.pagesOpen = true+ }++ /** Pictures of [pages] (0-based) at 200 dpi, saved to Pictures/PdfCraft or handed to the share sheet. */+ fun writeImages(doc: OpenDocument, ext: String, pages: List<Int>, share: Boolean) = job("Exporting images…") { eng ->val mime = if (ext == "png") "image/png" else "image/jpeg"- var saved = 0- for (i in 0 until doc.pageCount) {- busy = "Exporting page ${i + 1} of ${doc.pageCount}…"+ val made = mutableListOf<Pair<File, String>>()+ for ((n, i) in pages.withIndex()) {+ busy = "Exporting page ${n + 1} of ${pages.size}…"val img = withContext(eng.renders) { eng.session.renderPage(doc.id, i.toUInt(), 200f / 72f, null) }val out = tempFile(ext)withContext(Dispatchers.IO) {@@ -1409,13 +1673,30 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {c.drawBitmap(bmp, 0f, 0f, null)}out.outputStream().use { flat.compress(if (ext == "png") android.graphics.Bitmap.CompressFormat.PNG else android.graphics.Bitmap.CompressFormat.JPEG, 90, it) }- files.saveToPictures(out, "${doc.title}_${i + 1}.$ext", mime)- out.delete()}- saved+++ made += out to "${doc.title}_${i + 1}.$ext"+ }+ imageExport = null+ organizing = false+ doc.controller.pagesOpen = false+ if (share) {+ val uris = withContext(Dispatchers.IO) { files.shareableAll(made) }+ made.forEach { it.first.delete() }+ val send = if (uris.size == 1) {+ Intent(Intent.ACTION_SEND).setType(mime).putExtra(Intent.EXTRA_STREAM, uris.first())+ } else {+ Intent(Intent.ACTION_SEND_MULTIPLE).setType(mime).putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris))+ }+ intents.trySend(Intent.createChooser(send.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), null))+ } else {+ withContext(Dispatchers.IO) {+ for ((f, name) in made) {+ files.saveToPictures(f, name, mime)+ f.delete()+ }+ }+ tell(if (made.size == 1) "1 image saved to Pictures/PdfCraft" else "${made.size} images saved to Pictures/PdfCraft")}- toolScreen = null- tell(if (saved == 1) "1 image saved to Pictures/PdfCraft" else "$saved images saved to Pictures/PdfCraft")}/** Create PDF from picked files (images, text, Office documents, PDFs), combined in order, then open it. */@@ -1455,6 +1736,27 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {fun onScanPhoto(ok: Boolean) {val f = shotFile ?: returnshotFile = null+ if (imageShot) {+ imageShot = false+ if (!ok || !f.isFile || f.length() == 0L) {+ imageFor = null+ imageAt = null+ return+ }+ // turned upright as the camera meant it (the page keeps no orientation tag), then placed+ viewModelScope.launch {+ val upright = withContext(Dispatchers.IO) {+ runCatching {+ val bmp = android.graphics.BitmapFactory.decodeFile(f.absolutePath)?.let { rotateForExif(f, it) } ?: return@runCatching f+ val out = File(f.parentFile, "upright-${f.name}")+ out.outputStream().use { bmp.compress(android.graphics.Bitmap.CompressFormat.JPEG, 90, it) }+ out+ }.getOrDefault(f)+ }+ addImage(Uri.fromFile(upright))+ }+ return+ }if (!ok || !f.isFile || f.length() == 0L) {if (scanPages.isEmpty()) toolScreen = nullreturn@@ -1504,6 +1806,12 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {busy = "Cleaning up page $p of ${paths.size}…"runCatching { eng.tool("page_enhance_camera", mapOf("doc" to id, "page" to p, "mode" to filter.mode, "level" to filter.level)) }}+ // the scan's words become text, searchable and selectable, when text recognition is installed+ withContext(Dispatchers.IO) { runCatching { eng.prepareOcrModels(getApplication()) } }+ if (runCatching { eng.tool("ocr_status") }.getOrNull()?.optBoolean("available", false) == true) {+ busy = "Recognizing text…"+ runCatching { eng.tool("ocr_recognize", mapOf("doc" to id)) }+ }val out = tempFile("pdf")eng.tool("doc_save", mapOf("doc" to id, "path" to out.absolutePath, "full" to true))val target = insertScanAt@@ -1693,6 +2001,39 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {runCatching { if (u.scheme == "file") File(requireNotNull(u.path)) else files.workingCopy(u) }.getOrNull()}+ /** Files ticked in Home's lists (a long press starts it), keyed by where they are. */+ val selectedFiles = androidx.compose.runtime.mutableStateMapOf<String, io.github.artcraftandroid.pdfcraft.ui.home.FileRow>()++ fun toggleSelected(row: io.github.artcraftandroid.pdfcraft.ui.home.FileRow) {+ if (selectedFiles.remove(row.key) == null) selectedFiles[row.key] = row+ }++ /** Several PDFs to the share sheet at once. */+ fun shareFiles(rows: List<io.github.artcraftandroid.pdfcraft.ui.home.FileRow>) {+ viewModelScope.launch {+ val local = rows.mapNotNull { r -> localFileOf(r)?.let { it to r.name } }+ if (local.isEmpty()) return@launch tell("The files couldn't be read.")+ val uris = withContext(Dispatchers.IO) { files.shareableAll(local) }+ val send = if (uris.size == 1) Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uris.first())+ else Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris))+ intents.trySend(Intent.createChooser(send.setType("application/pdf").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), null))+ }+ }++ /** Combine the ticked files, in the order shown. */+ fun combineSelected(rows: List<io.github.artcraftandroid.pdfcraft.ui.home.FileRow>) {+ combineFiles.clear()+ rows.take(12).forEach { combineFiles.add(PickedFile(Uri.parse(it.key), it.name, it.size)) }+ toolScreen = ToolScreen.Combine(null)+ }++ fun removeRecents(rows: List<io.github.artcraftandroid.pdfcraft.ui.home.FileRow>) {+ viewModelScope.launch {+ withContext(Dispatchers.IO) { recents.remove(rows.map { it.key }.toSet()) }+ refreshRecents()+ }+ }+fun shareFile(row: io.github.artcraftandroid.pdfcraft.ui.home.FileRow) {viewModelScope.launch {val f = localFileOf(row) ?: return@launch tell("The file couldn't be read.")@@ -1730,6 +2071,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {require(f.renameTo(target)) { "The file couldn't be renamed." }recents.remove(setOf(row.key))recents.touch(RecentFile(Uri.fromFile(target).toString(), name, System.currentTimeMillis(), 0, target.length()))+ bookmarkStore.move(row.key, Uri.fromFile(target).toString())}// what the tools saved to Downloads: MediaStore entries keep their address when renamedu.authority == android.provider.MediaStore.AUTHORITY -> {@@ -1742,6 +2084,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {?: error("This file can't be renamed here.")recents.remove(setOf(row.key))recents.touch(RecentFile(renamed.toString(), name, System.currentTimeMillis(), 0, files.size(renamed) ?: 0))+ bookmarkStore.move(row.key, renamed.toString())}}}@@ -1869,6 +2212,11 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {runTool(doc, "comment_edit", commentArgs(c) + ("color" to color.hex())) { reselect(doc, c) }}+ /** Change a comment's opacity or line width (one undo step each). */+ fun styleComment(doc: OpenDocument, c: io.github.artcraftandroid.pdfcraft.core.CommentInfo, style: Map<String, Any?>) {+ runTool(doc, "comment_edit", commentArgs(c) + style) { reselect(doc, c) }+ }+fun editCommentText(doc: OpenDocument, c: io.github.artcraftandroid.pdfcraft.core.CommentInfo, text: String) {runTool(doc, "comment_edit", commentArgs(c) + ("contents" to text)) { reselect(doc, c) }}@@ -1877,6 +2225,24 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {runTool(doc, "comment_edit", commentArgs(c) + ("move" to listOf(dx.toDouble(), dy.toDouble()))) { reselect(doc, c) }}+ /** Put a comment in a new rectangle (points, top-left origin): a resize. */+ fun resizeComment(doc: OpenDocument, c: io.github.artcraftandroid.pdfcraft.core.CommentInfo, rect: List<Float>) {+ runTool(doc, "comment_edit", commentArgs(c) + ("rect" to rect.map { it.toDouble() })) { reselect(doc, c) }+ }++ /** Move or resize a Fill & Sign element, keeping it selected. */+ fun moveFill(doc: OpenDocument, c: io.github.artcraftandroid.pdfcraft.core.CommentInfo, dx: Float, dy: Float) {+ runTool(doc, "comment_edit", commentArgs(c) + ("move" to listOf(dx.toDouble(), dy.toDouble()))) {+ selectedFill = doc.comments.firstOrNull { it.page == c.page && it.index == c.index }+ }+ }++ fun resizeFill(doc: OpenDocument, c: io.github.artcraftandroid.pdfcraft.core.CommentInfo, rect: List<Float>) {+ runTool(doc, "comment_edit", commentArgs(c) + ("rect" to rect.map { it.toDouble() })) {+ selectedFill = doc.comments.firstOrNull { it.page == c.page && it.index == c.index }+ }+ }+/** After an edit the comment is read again (same page and position). */private fun reselect(doc: OpenDocument, c: io.github.artcraftandroid.pdfcraft.core.CommentInfo) {val again = doc.comments.firstOrNull { it.page == c.page && it.index == c.index }diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/FreeTextLayout.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/FreeTextLayout.ktnew file mode 100644index 0000000..1c27fce--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/FreeTextLayout.kt@@ -0,0 +1,63 @@+package io.github.artcraftandroid.pdfcraft.ui++/**+ * How typed text sits in a new text box, measured the way the engine draws the box (its Helvetica+ * width table, 2 pt inside the edge, lines 1.2 × the size apart), so the box the app asks for holds+ * exactly the lines the engine draws: nothing wraps again, nothing is cut off.+ */+internal object FreeTextLayout {+ /** Room between the box's edge and its text (the engine's, for a box with no border). */+ const val PAD = 2f++ /** The width of [s] at [size] points, as the engine measures Helvetica. */+ fun width(s: String, size: Float): Float = s.sumOf { c ->+ when (c) {+ ' ', 'i', 'j', 'l', '\'', '!', '|', '.', ',', ':', ';', 'I' -> 260+ 'f', 't', 'r', '(', ')', '[', ']', '/', '-', '"' -> 333+ 'm', 'M' -> 833+ 'w' -> 722+ 'W' -> 944+ 'J', 'c', 'k', 's', 'v', 'x', 'y', 'z' -> 500+ in '0'..'9', in 'a'..'z', '$', '#', '?', '_' -> 556+ in 'A'..'Z' -> 680+ '@' -> 1015+ else -> if (c.isWhitespace()) 260 else 584+ }.toInt()+ } * size / 1000f++ /** [text] broken into lines no wider than [maxWidth] (at spaces; a word too long, by letters). */+ fun wrap(text: String, size: Float, maxWidth: Float): List<String> {+ val lines = mutableListOf<String>()+ for (para in text.split('\n', '\r')) {+ var line = ""+ for (word in para.split(' ')) {+ val candidate = if (line.isEmpty()) word else "$line $word"+ if (width(candidate, size) <= maxWidth || line.isEmpty() && width(word, size) <= maxWidth) {+ line = candidate+ continue+ }+ if (line.isNotEmpty()) lines += line.also { line = "" }+ for (ch in word) {+ if (line.isNotEmpty() && width(line + ch, size) > maxWidth) lines += line.also { line = "" }+ line += ch+ }+ }+ lines += line+ }+ return lines+ }++ /**+ * The lines of [text] when the box may grow to [room] points wide, and the box's width and height:+ * as wide as the longest line, as tall as the lines (the engine's first baseline is 0.9 × the size+ * below the padding, and the descenders need about 0.3 × the size under the last one).+ */+ fun layout(text: String, size: Float, room: Float): Triple<List<String>, Float, Float> {+ val lines = wrap(text, size, (room - 2 * PAD).coerceAtLeast(size))+ val longest = lines.maxOfOrNull { width(it, size) } ?: 0f+ // a point to spare, so a line the full width doesn't break again on rounding+ val w = (longest + 2 * PAD + 1f).coerceAtLeast(size * 2)+ val h = 2 * PAD + size * 0.9f + (lines.size - 1).coerceAtLeast(0) * size * 1.2f + size * 0.3f+ return Triple(lines, w, h)+ }+}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/OpenDocument.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/OpenDocument.ktindex 63ad5ab..fe31871 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/OpenDocument.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/OpenDocument.kt@@ -61,8 +61,11 @@ class OpenDocument(/** What the active tool still holds (ink being drawn), to add when the tool is left. */var commitTool: (() -> Unit)? = null- /** Undo inside the active tool (the last stroke drawn); true when it took something back. */- var undoTool: (() -> Boolean)? = null+ /**+ * Undo and redo inside the active tool (strokes drawn but not yet added): while it is set the+ * top bar's undo and redo act on it and never reach the document, as the reference's do.+ */+ var localUndo by mutableStateOf<LocalUndo?>(null)/** The file name without its extension, as the reference titles documents. */val title: String get() = info.name.removeSuffix(".pdf").removeSuffix(".PDF")@@ -78,3 +81,6 @@ class OpenDocument(selection.clear()}}++/** A tool's own undo history (see [OpenDocument.localUndo]); the checks read Compose state. */+class LocalUndo(val canUndo: () -> Boolean, val canRedo: () -> Boolean, val undo: () -> Unit, val redo: () -> Unit)diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ToolScreens.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ToolScreens.ktindex 2801625..44da357 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ToolScreens.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ToolScreens.kt@@ -316,7 +316,8 @@ fun ProtectScreen(vm: AppViewModel, doc: OpenDocument) {fun ExportScreen(vm: AppViewModel, doc: OpenDocument) {val c = pdfColorsvar tab by remember { mutableStateOf(0) }- var format by remember(tab) { mutableStateOf(0) }+ // the image format used last time comes first chosen+ var format by remember(tab) { mutableStateOf(if (tab == 1 && vm.lastImageFormat == "png") 1 else 0) }val formats = if (tab == 0) {listOf("Word (docx)" to "docx", "Rich Text Format (rtf)" to "rtf", "Excel (xlsx)" to "xlsx", "PowerPoint (pptx)" to "pptx")} else {@@ -405,6 +406,7 @@ fun ToolScreenHost(vm: AppViewModel, screen: ToolScreen) {*/@Composablefun CombineScreen(vm: AppViewModel) {+ var naming by remember { mutableStateOf(false) }val c = pdfColorsval files = vm.combineFilesvar dragIndex by remember { mutableStateOf<Int?>(null) }@@ -472,9 +474,18 @@ fun CombineScreen(vm: AppViewModel) {}Box(Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 12.dp).height(42.dp).clip(RoundedCornerShape(21.dp))- .background(if (ok) c.button else c.pressed).clickable(enabled = ok) { vm.combine("Combine") },+ .background(if (ok) c.button else c.pressed).clickable(enabled = ok) { naming = true },contentAlignment = Alignment.Center,) { Text("Combine as PDF", color = if (ok) Color.White else c.textSecondary, fontSize = 17.sp, fontWeight = FontWeight.SemiBold) }+ if (naming) {+ var name by remember { mutableStateOf("Combine " + java.text.DateFormat.getDateInstance(java.text.DateFormat.LONG).format(java.util.Date())) }+ val focus = remember { androidx.compose.ui.focus.FocusRequester() }+ PdfDialog(+ onDismiss = { naming = false }, title = "Name the combined file", confirm = "Save",+ onConfirm = { naming = false; vm.combine(name.trim().ifEmpty { "Combine" }) },+ confirmEnabled = name.isNotBlank(),+ ) { PdfField(name, { name = it }, "File name", focus = focus) }+ }}}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/HomeScreen.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/HomeScreen.ktindex f33b39e..7c1bc50 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/HomeScreen.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/HomeScreen.kt@@ -43,6 +43,7 @@ import androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.foundation.combinedClickableimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.drawBehindimport androidx.compose.ui.geometry.Offset@@ -148,9 +149,21 @@ private fun HomeTabScreen(vm: AppViewModel, onBrowse: () -> Unit) {var fabMenu by remember { mutableStateOf(false) }var menu by remember { mutableStateOf(false) }var confirmClear by remember { mutableStateOf(false) }- LaunchedEffect(tab) { if (tab == 2) vm.scanLocal() }+ var confirmDeleteSelected by remember { mutableStateOf(false) }+ LaunchedEffect(tab) { if (tab == 2) vm.scanLocal(); vm.selectedFiles.clear() }+ androidx.activity.compose.BackHandler(enabled = vm.selectedFiles.isNotEmpty()) { vm.selectedFiles.clear() }+ if (confirmDeleteSelected) {+ val rows = vm.selectedFiles.values.toList()+ io.github.artcraftandroid.pdfcraft.ui.PdfDialog(+ onDismiss = { confirmDeleteSelected = false },+ title = if (rows.size == 1) "Delete 1 file?" else "Delete ${rows.size} files?",+ confirm = "Delete", destructive = true,+ onConfirm = { confirmDeleteSelected = false; rows.forEach(vm::deleteFile); vm.selectedFiles.clear() },+ ) { Text("They are removed from this phone.", color = c.text, fontSize = 14.sp) }+ }Box(Modifier.fillMaxSize()) {Column(Modifier.fillMaxSize().safeTopPadding()) {+ if (vm.selectedFiles.isNotEmpty()) SelectionBar(vm, recent = tab == 0, onDelete = { confirmDeleteSelected = true }) elseRow(Modifier.fillMaxWidth().height(56.dp).padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {Image(painterResource(R.drawable.ic_launcher_tile), null, modifier = Modifier.size(28.dp).clip(RoundedCornerShape(6.dp)))Spacer(Modifier.width(10.dp))@@ -330,9 +343,19 @@ fun FileThumb(vm: AppViewModel, path: String?, width: Int, height: Int) {}@Composable+@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)fun FileListRow(vm: AppViewModel, r: FileRow, recent: Boolean = false) {val c = pdfColors- Row(Modifier.fillMaxWidth().clickable(onClick = r.open).padding(start = 12.dp, end = 4.dp, top = 12.dp, bottom = 12.dp), verticalAlignment = Alignment.CenterVertically) {+ val selecting = vm.selectedFiles.isNotEmpty()+ val ticked = r.key in vm.selectedFiles+ // a long press ticks the file (several can then be shared, combined or deleted together)+ Row(+ Modifier.fillMaxWidth()+ .background(if (ticked) c.toolAccent.copy(alpha = 0.12f) else Color.Transparent)+ .combinedClickable(onClick = { if (selecting) vm.toggleSelected(r) else r.open() }, onLongClick = { vm.toggleSelected(r) })+ .padding(start = 12.dp, end = 4.dp, top = 12.dp, bottom = 12.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {Box(Modifier.width(48.dp), contentAlignment = Alignment.Center) { FileThumb(vm, r.thumbPath, 36, 42) }Spacer(Modifier.width(12.dp))Column(Modifier.weight(1f)) {@@ -351,7 +374,43 @@ fun FileListRow(vm: AppViewModel, r: FileRow, recent: Boolean = false) {Text(listOfNotNull("PDF", whenLabel(r.date), r.size.takeIf { it > 0 }?.let { formatSize(it) }).joinToString(" • "), color = c.textTertiary, fontSize = 13.sp, fontWeight = FontWeight.Medium, maxLines = 1)}}- BarIcon(LucideIcons.EllipsisVertical, "More options for ${r.name}", { vm.fileSheet = r to recent })+ if (selecting) {+ Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) { SelectBox(ticked) }+ } else {+ BarIcon(LucideIcons.EllipsisVertical, "More options for ${r.name}", { vm.fileSheet = r to recent })+ }+ }+}++/** A round tick for a ticked file, an empty ring for the others. */+@Composable+private fun SelectBox(ticked: Boolean) {+ val c = pdfColors+ Box(+ Modifier.size(22.dp).clip(CircleShape).background(if (ticked) c.toolAccent else Color.Transparent)+ .border(2.dp, if (ticked) c.toolAccent else c.textSecondary, CircleShape),+ contentAlignment = Alignment.Center,+ ) { if (ticked) Icon(LucideIcons.Check, null, tint = Color.White, modifier = Modifier.size(14.dp)) }+}++/** Home's bar while files are ticked: how many, Share, Combine, and the rest in a menu. */+@Composable+private fun SelectionBar(vm: AppViewModel, recent: Boolean, onDelete: () -> Unit) {+ val c = pdfColors+ val rows = vm.selectedFiles.values.toList()+ var menu by remember { mutableStateOf(false) }+ Row(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {+ BarIcon(LucideIcons.X, "Clear selection", { vm.selectedFiles.clear() })+ Text(if (rows.size == 1) "1 file selected" else "${rows.size} files selected", color = c.text, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f).padding(start = 8.dp))+ BarIcon(LucideIcons.Share2, "Share", { vm.shareFiles(rows); vm.selectedFiles.clear() })+ if (rows.size >= 2) BarIcon(LucideIcons.Combine, "Combine files", { vm.combineSelected(rows); vm.selectedFiles.clear() })+ Box {+ BarIcon(LucideIcons.EllipsisVertical, "More options", { menu = true })+ DropdownMenu(expanded = menu, onDismissRequest = { menu = false }, containerColor = c.surface) {+ if (recent) DropdownMenuItem(text = { Text("Remove from recent") }, onClick = { menu = false; vm.removeRecents(rows); vm.selectedFiles.clear() })+ DropdownMenuItem(text = { Text("Delete", color = c.red) }, onClick = { menu = false; onDelete() })+ }+ }}}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/Tabs.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/Tabs.ktindex 3781d11..045bc31 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/Tabs.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/Tabs.kt@@ -147,6 +147,12 @@ private fun OnThisDevice(vm: AppViewModel) {/** A tool of the Tools tab: its tile, name and one line about it. */private class HubTool(val icon: ImageVector, val name: String, val about: String, val hue: Color, val categories: Set<String>, val go: () -> Unit)+/** Where a category lists its tools in an order of its own (the rest keep the All order). */+private val CategoryOrder = mapOf(+ "Edit" to listOf("Edit PDF", "Crop pages", "Organize pages", "Combine files", "Set password"),+ "Convert" to listOf("Export PDF", "Compress PDF"),+)+/** Tools: every tool, by category (All, Read, Create, Edit, Convert), as outlined cards. */@Composablefun ToolsTab(vm: AppViewModel) {@@ -186,7 +192,7 @@ fun ToolsTab(vm: AppViewModel) {GridCells.Adaptive(140.dp), modifier = Modifier.weight(1f).padding(horizontal = 16.dp),horizontalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp),) {- items(tools.filter { cat == "All" || cat in it.categories }) { t ->+ items(tools.filter { cat == "All" || cat in it.categories }.sortedBy { t -> CategoryOrder[cat]?.indexOf(t.name)?.takeIf { it >= 0 } ?: Int.MAX_VALUE }) { t ->Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(c.surface).border(1.dp, c.divider, RoundedCornerShape(12.dp)).clickable(onClick = t.go).padding(16.dp).semantics { contentDescription = t.name },@@ -218,6 +224,8 @@ fun SearchTab(vm: AppViewModel) {Spacer(Modifier.width(10.dp))BasicTextField(value = query, onValueChange = { query = it }, singleLine = true,+ keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Search),+ keyboardActions = androidx.compose.foundation.text.KeyboardActions(onSearch = { vm.addRecentSearch(query) }),textStyle = TextStyle(fontFamily = Inter, fontSize = 16.sp, color = c.text), cursorBrush = SolidColor(c.accent),modifier = Modifier.weight(1f).semantics { contentDescription = "Search your files" },decorationBox = { inner -> Box { if (query.isEmpty()) Text("Search your files", color = c.textSecondary, fontSize = 16.sp); inner() } },@@ -225,9 +233,33 @@ fun SearchTab(vm: AppViewModel) {if (query.isNotEmpty()) BarIcon(LucideIcons.X, "Clear", { query = "" }, size = 32.dp)}if (query.isBlank()) {- EmptyState(LucideIcons.Search, "Search your files", "Find PDFs on this phone by name.")+ val recent = vm.recentSearches+ if (recent.isEmpty()) {+ EmptyState(LucideIcons.Search, "Search your files", "Find PDFs on this phone by name.")+ return@Column+ }+ // the last searches, to run again with a tap+ Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) {+ Text("Recent searches", color = c.text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f))+ Text("Clear", color = c.toolAccent, fontSize = 15.sp, modifier = Modifier.clickable { vm.clearRecentSearches() }.padding(12.dp))+ }+ LazyColumn(Modifier.weight(1f)) {+ items(recent, key = { it }) { q ->+ Row(Modifier.fillMaxWidth().height(52.dp).clickable { query = q }.padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) {+ Icon(LucideIcons.Clock, null, tint = c.icon, modifier = Modifier.size(22.dp))+ Spacer(Modifier.width(16.dp))+ Text(q, color = c.text, fontSize = 16.sp, maxLines = 1, modifier = Modifier.weight(1f))+ BarIcon(LucideIcons.X, "Remove $q", { vm.removeRecentSearch(q) }, size = 40.dp)+ }+ }+ }return@Column}+ // a search left in place for a moment counts as one made+ LaunchedEffect(query) {+ kotlinx.coroutines.delay(2000)+ if (vm.searchFiles(query).isNotEmpty()) vm.addRecentSearch(query)+ }val results = vm.searchFiles(query).let { list ->when (sort) {1 -> list.sortedBy { it.name.lowercase() }diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/CommentDrag.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/CommentDrag.ktnew file mode 100644index 0000000..16c7bd0--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/CommentDrag.kt@@ -0,0 +1,126 @@+package io.github.artcraftandroid.pdfcraft.ui.viewer++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import io.github.artcraftandroid.pdfcraft.core.CommentInfo+import io.github.artcraftandroid.pdfcraft.ui.OpenDocument+import kotlin.math.roundToInt++/** Comments whose rectangle can be resized (the engine re-draws these to a new rectangle). */+private val Resizable = setOf("Square", "Circle", "FreeText", "Stamp")++/**+ * Move and resize a selected comment, as the reference lets: drag inside its frame to move it, or+ * (for rectangles, ovals, text boxes and stamps) a corner handle to resize it. The frame follows+ * the finger; the comment is changed when the finger lifts, as one undo step. Marked text has no+ * frame and isn't handled here.+ */+@Composable+fun CommentDragOverlay(+ doc: OpenDocument,+ c: CommentInfo,+ onMove: (dx: Float, dy: Float) -> Unit,+ onResize: (rect: List<Float>) -> Unit,+) {+ if (c.rect.size < 4 || c.locked) return+ if (c.subtype in setOf("Highlight", "Underline", "StrikeOut", "Squiggly")) return+ val page = c.page.toInt()+ val density = LocalDensity.current+ val slop = with(density) { 14.dp.toPx() }+ val a = doc.viewer.pageToScreen(page, c.rect[0], c.rect[1])+ val b = doc.viewer.pageToScreen(page, c.rect[2], c.rect[3])+ val frame = Rect(a, b)+ // a note's icon is drawn at a fixed size around its point: give it a finger-sized area+ val area = if (c.subtype == "Text" || c.subtype == "Sound") Rect(frame.center, with(density) { 22.dp.toPx() }) else frame.inflate(slop)+ var shift by remember(c.page, c.index, c.rect) { mutableStateOf(Offset.Zero) }+ var resized by remember(c.page, c.index, c.rect) { mutableStateOf<Rect?>(null) }+ val ppp = doc.viewer.pixelsPerPoint(page).coerceAtLeast(0.01f)++ // the frame where the comment will go+ Canvas(Modifier.fillMaxSize()) {+ val r = resized ?: frame.translate(shift)+ if (shift != Offset.Zero || resized != null) {+ drawRect(Color(0xFF448AFF), r.topLeft, r.size, style = Stroke(2.dp.toPx(), pathEffect = androidx.compose.ui.graphics.PathEffect.dashPathEffect(floatArrayOf(8.dp.toPx(), 5.dp.toPx()))))+ }+ }+ // the body: drag to move+ Box(+ Modifier+ .offset { IntOffset(area.left.roundToInt(), area.top.roundToInt()) }+ .size(with(density) { area.width.toDp() }, with(density) { area.height.toDp() })+ .pointerInput(c.page, c.index, c.rect) { detectTapGestures { } }+ .pointerInput(c.page, c.index, c.rect) {+ detectDragGestures(+ onDrag = { change, d -> change.consume(); shift += d },+ onDragEnd = {+ val s = shift+ if (s.getDistance() > 2f) onMove(s.x / ppp, s.y / ppp) else shift = Offset.Zero+ },+ onDragCancel = { shift = Offset.Zero },+ )+ }+ .semantics { contentDescription = "Move comment" },+ )+ if (c.subtype !in Resizable) return+ // corner handles: drag to resize, the opposite corner staying put+ val handle = with(density) { 24.dp.toPx() }+ val corners = listOf(frame.topLeft, frame.topRight, frame.bottomLeft, frame.bottomRight)+ corners.forEachIndexed { i, corner ->+ Box(+ Modifier+ .offset { IntOffset((corner.x - handle / 2).roundToInt(), (corner.y - handle / 2).roundToInt()) }+ .size(24.dp)+ .pointerInput(c.page, c.index, c.rect, i) {+ var current = frame+ detectDragGestures(+ onDragStart = { current = frame },+ onDrag = { change, d ->+ change.consume()+ val minSide = 12.dp.toPx()+ current = when (i) {+ 0 -> Rect(minOf(current.left + d.x, current.right - minSide), minOf(current.top + d.y, current.bottom - minSide), current.right, current.bottom)+ 1 -> Rect(current.left, minOf(current.top + d.y, current.bottom - minSide), maxOf(current.right + d.x, current.left + minSide), current.bottom)+ 2 -> Rect(minOf(current.left + d.x, current.right - minSide), current.top, current.right, maxOf(current.bottom + d.y, current.top + minSide))+ else -> Rect(current.left, current.top, maxOf(current.right + d.x, current.left + minSide), maxOf(current.bottom + d.y, current.top + minSide))+ }+ resized = current+ },+ onDragEnd = {+ val r = resized ?: return@detectDragGestures+ val p0 = doc.viewer.screenToPage(r.topLeft, nearest = true)+ val p1 = doc.viewer.screenToPage(r.bottomRight, nearest = true)+ if (p0 != null && p1 != null && p0.page == page && p1.page == page) onResize(listOf(p0.x, p0.y, p1.x, p1.y)) else resized = null+ },+ onDragCancel = { resized = null },+ )+ }+ .semantics { contentDescription = "Resize comment" },+ ) {+ Canvas(Modifier.fillMaxSize()) {+ drawCircle(Color.White, size.minDimension / 2.6f)+ drawCircle(Color(0xFF448AFF), size.minDimension / 2.6f, style = Stroke(2.dp.toPx()))+ }+ }+ }+}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/CommentPanel.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/CommentPanel.ktindex 1f7bd35..eee462f 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/CommentPanel.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/CommentPanel.kt@@ -124,8 +124,25 @@ fun CommentPanel(vm: AppViewModel, doc: OpenDocument, c: CommentInfo) {}}if (palette) {+ // the comment's colour, and as the reference also offers there its opacity and,+ // for drawings and shapes, its line width+ val shown = c.color?.let { Color(0xFF000000 or it.toLong()) } ?: Color.TransparentSpacer(Modifier.height(8.dp))- ColorGrid(c.color?.let { Color(0xFF000000 or it.toLong()) } ?: Color.Transparent) { vm.recolorComment(doc, c, it); palette = false }+ ColorGrid(shown) { vm.recolorComment(doc, c, it) }+ if (c.subtype != "FreeText") {+ var opacity by remember(c.page, c.index) { mutableStateOf(c.opacity) }+ LaunchedEffect(opacity) {+ if (opacity == c.opacity) return@LaunchedEffect+ kotlinx.coroutines.delay(300)+ vm.styleComment(doc, c, mapOf("opacity" to opacity.toDouble()))+ }+ Text("Opacity", color = colors.text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 78.dp, top = 16.dp, bottom = 8.dp))+ OpacitySlider(shown, opacity) { opacity = it }+ }+ if (c.width != null && c.subtype in LineComments) {+ Text("Line thickness", color = colors.text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 20.dp, top = 16.dp, bottom = 8.dp))+ InkWidthRow(shown, InkWidths.minByOrNull { kotlin.math.abs(it - (c.width ?: 0f)) }) { vm.styleComment(doc, c, mapOf("width" to it.toDouble())) }+ }Spacer(Modifier.height(8.dp))}Column(Modifier.weight(1f).verticalScroll(scroll)) {@@ -214,3 +231,6 @@ fun CommentPanel(vm: AppViewModel, doc: OpenDocument, c: CommentInfo) {}}}++/** Comments drawn with a line whose width can be changed. */+private val LineComments = setOf("Ink", "Line", "Square", "Circle", "Polygon", "PolyLine")diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Edit.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Edit.ktindex b7af787..03584b2 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Edit.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Edit.kt@@ -37,6 +37,9 @@ import androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.foundation.layout.ime+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.foundation.layout.widthInimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.drawBehindimport androidx.compose.ui.draw.shadow@@ -103,7 +106,7 @@ private val EditColors = listOf()/** Which formatting panel is open over the bar. */-private enum class FormatPanel { None, Size, Font, Color, Align }+private enum class FormatPanel { None, Size, Font, Color, Align, List }/*** Edit PDF's bottom bar. With nothing selected: Organize pages, then Add text and Add image. With a@@ -132,7 +135,11 @@ private fun EditToolsBar(vm: AppViewModel, doc: OpenDocument) {vm.editMode = if (vm.editMode == EditMode.AddText) EditMode.Select else EditMode.AddTextif (vm.editMode == EditMode.AddText) vm.tell("Tap the page where the text should go")}- EditBarItem(LucideIcons.ImagePlus, "Add image", false, 78.dp) { vm.pickEditImage(doc) }+ // as Add text: a mode, then a tap places the picture there+ EditBarItem(LucideIcons.ImagePlus, "Add image", vm.editMode == EditMode.AddImage, 78.dp) {+ vm.editMode = if (vm.editMode == EditMode.AddImage) EditMode.Select else EditMode.AddImage+ if (vm.editMode == EditMode.AddImage) vm.tell("Tap the page where the picture should go")+ }}}@@ -174,6 +181,7 @@ private fun EditFormatBar(vm: AppViewModel, doc: OpenDocument, para: Paragraph)vm.editAlign[para.page to para.number] = avm.styleParagraph(doc, para, mapOf("align" to a))}+ FormatPanel.List -> ListPanel(ListStyle.of(vm.editDraft?.takeIf { vm.editing != null } ?: para.text)) { vm.listParagraph(doc, para, it) }FormatPanel.None -> Unit}Row(@@ -204,6 +212,8 @@ private fun EditFormatBar(vm: AppViewModel, doc: OpenDocument, para: Paragraph))}FormatButton(alignIcon(vm.editAlign[para.page to para.number] ?: "left"), "Align text", true, tintSelected = panel == FormatPanel.Align || true) { toggle(FormatPanel.Align) }+ // bulleted and numbered lists, as the reference's phone toolbar offers+ FormatButton(LucideIcons.List, "List", true, tintSelected = true) { toggle(FormatPanel.List) }}}}@@ -244,14 +254,14 @@ private fun FormatButton(icon: ImageVector, description: String, selected: Boole@Composableprivate fun SizePanel(para: Paragraph, onSize: (Float) -> Unit) {val c = pdfColors- var size by remember(para.page, para.number, para.size) { mutableFloatStateOf(para.size.coerceIn(6f, 72f)) }+ var size by remember(para.page, para.number, para.size) { mutableFloatStateOf(para.size.coerceIn(6f, 66f)) }Column(Modifier.fillMaxWidth().barTopLine().padding(top = 10.dp, bottom = 6.dp)) {Text("Text size: ${size.roundToInt()} pt", color = c.label, fontSize = 15.sp, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth())Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = 8.dp)) {Text("A", color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 10.dp))Slider(- value = size, onValueChange = { size = it.roundToInt().toFloat() }, onValueChangeFinished = { onSize(size) },- valueRange = 6f..72f, steps = 65,+ value = size, onValueChange = { size = ((it / 2f).roundToInt() * 2f).coerceIn(6f, 66f) }, onValueChangeFinished = { onSize(size) },+ valueRange = 6f..66f, steps = 29,colors = SliderDefaults.colors(thumbColor = Color.White, activeTrackColor = c.textSecondary, inactiveTrackColor = c.textSecondary, activeTickColor = c.textSecondary, inactiveTickColor = c.textSecondary),modifier = Modifier.weight(1f),)@@ -299,6 +309,20 @@ private fun ColorPanel(current: String?, onColor: (String) -> Unit) {}}+/** None, the bullets and the numberings, the paragraph's own one marked. */+@Composable+private fun ListPanel(current: ListStyle, onPick: (ListStyle) -> Unit) {+ val c = pdfColors+ Row(Modifier.fillMaxWidth().barTopLine().padding(vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally)) {+ for (style in ListStyle.entries) {+ Box(+ Modifier.height(40.dp).widthIn(min = 40.dp).clickable { onPick(style) }.padding(horizontal = 6.dp).semantics { contentDescription = "List ${style.name}" },+ contentAlignment = Alignment.Center,+ ) { Text(style.label, color = if (style == current) c.toolAccent else c.icon, fontSize = 17.sp, fontWeight = if (style == current) FontWeight.SemiBold else FontWeight.Normal) }+ }+ }+}+@Composableprivate fun AlignPanel(current: String, onAlign: (String) -> Unit) {val c = pdfColors@@ -471,7 +495,24 @@ private fun BoxScope.InlineEditor(vm: AppViewModel, doc: OpenDocument, para: ParmutableStateOf(TextFieldValue(para.text, if (vm.editSelectAll) TextRange(0, para.text.length) else TextRange(para.text.length)))}LaunchedEffect(para) { runCatching { focus.requestFocus() } }+ val ime = androidx.compose.foundation.layout.WindowInsets.ime.getBottom(density)+ LaunchedEffect(ime) {+ if (ime <= 0) return@LaunchedEffect+ val v = doc.viewer+ // the formatting bar (and a panel) sit on the keyboard: keep the box's bottom clear of them+ val clear = v.viewH - ime - with(density) { (BottomBarHeight + 64.dp).toPx() }+ if (b.y > clear) v.setScroll(v.scrollX, v.scrollY + (b.y - clear))+ }LaunchedEffect(value.text) { vm.editDraft = value.text }+ // 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) }+ var typos by remember(para) { mutableStateOf<List<Typo>>(emptyList()) }+ var layout by remember { mutableStateOf<androidx.compose.ui.text.TextLayoutResult?>(null) }+ LaunchedEffect(value.text) {+ kotlinx.coroutines.delay(600)+ typos = speller.check(value.text)+ }var paper by remember(para) { mutableStateOf<Color?>(null) }LaunchedEffect(para) { paper = vm.paperColor(doc, para) }val fontPx = para.size * ppp@@ -497,10 +538,60 @@ private fun BoxScope.InlineEditor(vm: AppViewModel, doc: OpenDocument, para: PartextDecoration = if (vm.editUnderline[para.page to para.number] == true) TextDecoration.Underline else null,),cursorBrush = SolidColor(SelectionBlue),- modifier = Modifier.fillMaxWidth().focusRequester(focus).semantics { contentDescription = "Paragraph text" },+ onTextLayout = { layout = it },+ modifier = Modifier.fillMaxWidth().focusRequester(focus).semantics { contentDescription = "Paragraph text" }+ .drawWithContent {+ drawContent()+ val l = layout ?: return@drawWithContent+ for (t in typos) {+ if (t.end > l.layoutInput.text.length) continue+ for (line in l.getLineForOffset(t.start)..l.getLineForOffset(t.end - 1)) {+ val x0 = if (line == l.getLineForOffset(t.start)) l.getHorizontalPosition(t.start, true) else l.getLineLeft(line)+ val x1 = if (line == l.getLineForOffset(t.end - 1)) l.getHorizontalPosition(t.end, true) else l.getLineRight(line)+ drawSquiggle(x0, x1, l.getLineBottom(line) - 1.dp.toPx())+ }+ }+ },)}+ // the word at the cursor, if misspelled: its suggestions above the box, a tap puts one in+ val at = value.selection.start+ val typo = typos.firstOrNull { value.selection.collapsed && at in it.start..it.end && it.suggestions.isNotEmpty() }+ if (typo != null) {+ Row(+ Modifier.offset { IntOffset(a.x.roundToInt(), (a.y - 48.dp.toPx()).roundToInt()) }+ .background(Color(0xFF2C2C2C), androidx.compose.foundation.shape.RoundedCornerShape(4.dp)).padding(horizontal = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ for (word in typo.suggestions) {+ Text(+ word, color = Color.White, fontSize = 15.sp,+ modifier = Modifier.clickable {+ val t = value.text.replaceRange(typo.start, typo.end, word)+ value = TextFieldValue(t, TextRange(typo.start + word.length))+ }.padding(horizontal = 12.dp, vertical = 10.dp),+ )+ }+ }+ }+ }+}++/** A red wavy line from [x0] to [x1] at [y], under a misspelled word. */+private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawSquiggle(x0: Float, x1: Float, y: Float) {+ val step = 2.dp.toPx()+ val path = androidx.compose.ui.graphics.Path().apply {+ moveTo(x0, y)+ var x = x0+ var up = true+ while (x < x1) {+ val nx = minOf(x + step, x1)+ lineTo(nx, if (up) y - step / 1.5f else y)+ x = nx+ up = !up+ }}+ drawPath(path, Color(0xFFE34850), style = Stroke(1.dp.toPx()))}@Composablediff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/EditLists.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/EditLists.ktnew file mode 100644index 0000000..1d57cd2--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/EditLists.kt@@ -0,0 +1,70 @@+package io.github.artcraftandroid.pdfcraft.ui.viewer++/**+ * Bulleted and numbered lists in Edit PDF: each line of a paragraph (its hard line breaks) becomes+ * an item with a marker in front. The markers are ones the standard PDF fonts carry (a bullet, an+ * en dash, numbers, letters and small roman numerals), so any paragraph can take them.+ */+enum class ListStyle(val label: String) {+ None("None"),+ Bullet("•"),+ Dash("–"),+ Number("1."),+ Lower("a."),+ Upper("A."),+ Roman("i.");++ /** The marker of item [n] (0-based). */+ fun marker(n: Int): String = when (this) {+ None -> ""+ Bullet -> "•"+ Dash -> "–"+ Number -> "${n + 1}."+ Lower -> "${letters(n, 'a')}."+ Upper -> "${letters(n, 'A')}."+ Roman -> "${roman(n + 1)}."+ }++ companion object {+ private val patterns = mapOf(+ Bullet to Regex("^•\\s+"),+ Dash to Regex("^–\\s+"),+ Number to Regex("^\\d{1,3}\\.\\s+"),+ Roman to Regex("^[ivxlcdm]{1,7}\\.\\s+"),+ Lower to Regex("^[a-z]{1,2}\\.\\s+"),+ Upper to Regex("^[A-Z]{1,2}\\.\\s+"),+ )++ /** The list style every line of [text] already has, or [None]. */+ fun of(text: String): ListStyle {+ val lines = text.split('\n').filter { it.isNotBlank() }+ if (lines.isEmpty()) return None+ // roman before letters: "i." is both, and a list of i., ii., iii. is roman+ for (style in listOf(Bullet, Dash, Number, Roman, Lower, Upper)) {+ val p = patterns.getValue(style)+ if (lines.all { p.containsMatchIn(it) } && lines.withIndex().all { (i, l) -> l.startsWith(style.marker(i) + " ") || style == Bullet || style == Dash }) return style+ }+ return None+ }++ /** [text] as a list of [style] (or a plain paragraph for [None]), replacing any list it was. */+ fun apply(text: String, style: ListStyle): String {+ val current = of(text)+ val lines = text.split('\n')+ val plain = if (current == None) lines else lines.map { l -> patterns.getValue(current).replaceFirst(l, "") }+ if (style == None) return plain.joinToString("\n")+ var n = 0+ return plain.joinToString("\n") { l -> if (l.isBlank()) l else "${style.marker(n++)} $l" }+ }++ private fun letters(n: Int, a: Char): String = if (n < 26) "${a + n}" else "${a + (n / 26 - 1)}${a + n % 26}"++ private fun roman(v: Int): String {+ val parts = listOf(1000 to "m", 900 to "cm", 500 to "d", 400 to "cd", 100 to "c", 90 to "xc", 50 to "l", 40 to "xl", 10 to "x", 9 to "ix", 5 to "v", 4 to "iv", 1 to "i")+ var rest = v+ val sb = StringBuilder()+ for ((k, s) in parts) while (rest >= k) { sb.append(s); rest -= k }+ return sb.toString()+ }+ }+}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/PageMenu.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/PageMenu.ktnew file mode 100644index 0000000..04358e8--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/PageMenu.kt@@ -0,0 +1,114 @@+package io.github.artcraftandroid.pdfcraft.ui.viewer++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+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.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.shadow+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.pdfcraft.ui.AppViewModel+import io.github.artcraftandroid.pdfcraft.ui.LucideIcons+import io.github.artcraftandroid.pdfcraft.ui.OpenDocument+import io.github.artcraftandroid.pdfcraft.ui.pdfColors+import kotlin.math.roundToInt++/** A long press on an empty part of a page: the menu of what can start there. */+class PageMenu(val doc: OpenDocument, val at: PagePoint, val screen: Offset, val pageHasText: Boolean)++/**+ * The reference's page menu: a row of the commenting tools that start at the pressed point+ * (comment, draw, text, sign), then a list of page tools. Tapping outside closes it.+ */+@Composable+fun PageMenuView(vm: AppViewModel, menu: PageMenu) {+ val c = pdfColors+ val doc = menu.doc+ val density = LocalDensity.current+ var size by remember { mutableStateOf(IntSize.Zero) }+ val close = { vm.pageMenu = null }+ val annotate = doc.info.allowsAnnotation+ val fill = doc.info.allowsFormFilling || annotate+ Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { close() } }) {+ val margin = with(density) { 8.dp.toPx() }+ val x = (menu.screen.x - size.width / 2f).coerceIn(margin, (doc.viewer.viewW - size.width - margin).coerceAtLeast(margin))+ // below the finger when it fits, else above it+ val below = menu.screen.y + with(density) { 24.dp.toPx() }+ val y = if (below + size.height < doc.viewer.viewH - doc.viewer.padBottom) below else (menu.screen.y - size.height - with(density) { 24.dp.toPx() }).coerceAtLeast(doc.viewer.padTop)+ Column(+ Modifier+ .offset { IntOffset(x.roundToInt(), y.roundToInt()) }+ .onSizeChanged { size = it }+ .width(209.dp)+ .shadow(6.dp, RoundedCornerShape(4.dp))+ .background(c.menu, RoundedCornerShape(4.dp))+ .pointerInput(Unit) { detectTapGestures { } },+ ) {+ Row(Modifier.fillMaxWidth().height(61.dp), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {+ PageMenuIcon(LucideIcons.MessageSquarePlus, "Add comment", annotate) { close(); vm.notePrompt = NotePrompt(doc, menu.at) }+ PageMenuIcon(LucideIcons.Pencil, "Draw", annotate) { close(); vm.enterTool(doc, ViewerTool.Draw) }+ PageMenuIcon(LucideIcons.Type, "Add text", annotate) { close(); vm.textPrompt = TextPrompt(doc, menu.at) }+ if (fill) PageMenuIcon(LucideIcons.Signature, "Sign", true) { close(); vm.enterTool(doc, ViewerTool.FillSign) }+ }+ Box(Modifier.fillMaxWidth().padding(horizontal = 4.dp).height(1.dp).background(c.divider))+ Spacer(Modifier.height(8.dp))+ if (!menu.pageHasText) PageMenuRow(LucideIcons.ScanText, "Recognize text") { close(); vm.recognizeText(doc) }+ PageMenuRow(LucideIcons.Crop, "Crop pages") { close(); vm.openCrop(doc) }+ PageMenuRow(LucideIcons.FilePenLine, "Edit PDF") { close(); vm.enterTool(doc, ViewerTool.Edit) }+ PageMenuRow(LucideIcons.ImagePlus, "Add image") { close(); vm.addImageAt(doc, menu.at) }+ Spacer(Modifier.height(8.dp))+ }+ }+}++@Composable+private fun PageMenuIcon(icon: ImageVector, label: String, enabled: Boolean, onClick: () -> Unit) {+ val c = pdfColors+ Box(+ Modifier.size(48.dp).clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = label },+ contentAlignment = Alignment.Center,+ ) {+ Icon(icon, null, tint = if (enabled) c.icon else c.icon.copy(alpha = 0.35f), modifier = Modifier.size(24.dp))+ }+}++@Composable+private fun PageMenuRow(icon: ImageVector, label: String, onClick: () -> Unit) {+ val c = pdfColors+ Row(Modifier.fillMaxWidth().height(41.dp).clickable(onClick = onClick).padding(horizontal = 14.dp), verticalAlignment = Alignment.CenterVertically) {+ Icon(icon, null, tint = c.icon, modifier = Modifier.size(22.dp))+ Spacer(Modifier.width(21.dp))+ Text(label, color = c.text, fontSize = 15.sp)+ }+}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/PagesScreen.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/PagesScreen.ktindex fb3f62c..fbc8952 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/PagesScreen.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/PagesScreen.kt@@ -85,14 +85,18 @@ fun PagesScreen(vm: AppViewModel, doc: OpenDocument, onClose: () -> Unit) {// dragging a page: its index and where it would dropvar dragFrom by remember { mutableStateOf<Int?>(null) }var dragTo by remember { mutableStateOf<Int?>(null) }+ val exporting = vm.imageExportfun close() {vm.organizing = false+ vm.imageExport = nullselected.clear()onClose()}// the tick leaves organizing for the grid of pages; back from the grid returns to the documentfun back() {- if (organizing) {+ if (exporting != null) {+ close()+ } else if (organizing) {vm.organizing = falseselected.clear()} else {@@ -128,8 +132,8 @@ fun PagesScreen(vm: AppViewModel, doc: OpenDocument, onClose: () -> Unit) {if (organizing && picked.isNotEmpty()) "Selected ${picked.size}" else if (organizing) "Select pages" else "Pages",color = c.label, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f),)- if (organizing) {- UndoMenuButton(doc.info.undo != null, doc.info.redo != null, { vm.undo(doc) }, { vm.redo(doc) })+ if (organizing && exporting == null) {+ UndoMenuButton(doc.info.undo != null, doc.info.redo != null, { vm.undo(doc) }, { vm.redo(doc) }, doc.info.undo, doc.info.redo)Spacer(Modifier.width(6.dp))}}@@ -247,7 +251,11 @@ fun PagesScreen(vm: AppViewModel, doc: OpenDocument, onClose: () -> Unit) {horizontalArrangement = Arrangement.spacedBy(if (organizing) 0.dp else 20.dp, Alignment.CenterHorizontally),verticalAlignment = Alignment.CenterVertically,) {- if (organizing) {+ if (exporting != null) {+ // picking the pages to export: save them to the phone's pictures, or share them+ OrganizeItem(LucideIcons.Save, "Save", enabled) { vm.writeImages(doc, exporting, picked, share = false) }+ OrganizeItem(LucideIcons.Share2, "Share", enabled) { vm.writeImages(doc, exporting, picked, share = true) }+ } else if (organizing) {OrganizeItem(LucideIcons.FilePlus, "Insert Page", true) { insertMenu = true }OrganizeItem(LucideIcons.FileOutput, "Extract", enabled) { vm.extractPages(doc, picked) }OrganizeItem(LucideIcons.Trash2, "Delete", enabled && picked.size < doc.pageCount) {@@ -269,9 +277,36 @@ fun PagesScreen(vm: AppViewModel, doc: OpenDocument, onClose: () -> Unit) {}}if (insertMenu) {- val at = (picked.lastOrNull() ?: (doc.pageCount - 1)) + 2+ // where the new pages go, as the reference asks: around the selection, or at either end+ var after by remember { mutableStateOf(true) }+ val first = picked.firstOrNull()+ val last = picked.lastOrNull()+ val at = when {+ first == null || last == null -> if (after) doc.pageCount + 1 else 1+ after -> last + 2+ else -> first + 1+ }PdfSheet(onDismiss = { insertMenu = false }, dim = true) {SheetTitle("Insert")+ val c = pdfColors+ for (option in listOf(false, true)) {+ val label = when {+ first == null || last == null -> if (option) "At the end" else "At the start"+ option -> "After page ${last + 1}"+ else -> "Before page ${first + 1}"+ }+ Row(+ Modifier.fillMaxWidth().clickable(role = Role.RadioButton) { after = option }.padding(horizontal = 12.dp, vertical = 2.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ androidx.compose.material3.RadioButton(+ selected = after == option, onClick = { after = option },+ colors = androidx.compose.material3.RadioButtonDefaults.colors(selectedColor = c.toolAccent, unselectedColor = c.icon),+ )+ Text(label, color = c.text, fontSize = 16.sp)+ }+ }+ io.github.artcraftandroid.pdfcraft.ui.SheetDivider()SheetRow(LucideIcons.File, "Blank page", { insertMenu = false; vm.runTool(doc, "page_insert_blank", mapOf("at" to at)) })SheetRow(LucideIcons.FileStack, "From another file", { insertMenu = false; vm.pickInsertFile(doc, at) })SheetRow(LucideIcons.Camera, "From a scan", { insertMenu = false; vm.insertScanAt = doc to at; vm.startScan() })diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ReadAloud.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ReadAloud.ktindex 0b8ce53..2ec7a50 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ReadAloud.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ReadAloud.kt@@ -93,9 +93,18 @@ class ReadAloud(private val scope: CoroutineScope,startPage: Int,private val onEnd: () -> Unit,+ /** Where this document's reading position is kept between sessions. */+ private val key: String = "",+ /** Start inside [startPage] at this glyph (the selection's first word), not its top. */+ private val startGlyph: UInt? = null,+ /** Pick up a stopped reading: paragraph and character within [startPage]. */+ private val resumeAt: Pair<Int, Int>? = null,) {var page by mutableIntStateOf(startPage)private set++ /** The document's title, for the reading notification. */+ val title: String get() = doc.titlevar playing by mutableStateOf(false)private setvar finished by mutableStateOf(false)@@ -105,6 +114,21 @@ class ReadAloud(var problem by mutableStateOf<String?>(null)private set+ /** The language the voice reads in. */+ var language by mutableStateOf<Locale>(Locale.getDefault())+ private set++ /** The languages the phone's voice can read, by name. */+ fun languages(): List<Locale> = runCatching { tts.availableLanguages.orEmpty().sortedBy { it.getDisplayName(Locale.getDefault()) } }.getOrDefault(emptyList())++ /** Read in [locale] from now on (remembered), going on from where the voice is. */+ fun chooseLanguage(locale: Locale) {+ language = locale+ tts.language = locale+ prefs(prefsCtx).edit().putString("lang", locale.toLanguageTag()).apply()+ if (playing) speakCurrent()+ }+/** The lines of the paragraph being read and of its current word (points, flattened x0, y0, x1, y1). */var blockRects by mutableStateOf<List<Float>>(emptyList())private set@@ -126,14 +150,26 @@ class ReadAloud(return@launch}ready = true- tts.language = Locale.getDefault()+ // the language chosen before (Voice), else the phone's+ tts.language = prefs(prefsCtx).getString("lang", null)?.let { Locale.forLanguageTag(it) } ?: Locale.getDefault()+ language = tts.language ?: Locale.getDefault()tts.setSpeechRate(speed)loadPage(page)+ placeStart()play()}}+ /** The document's words (CJK characters count one each), once counted; 250 a page until then. */+ private var totalWords by mutableIntStateOf(0)+init {+ // count the words of every page for the time estimate, as the reference does+ scope.launch {+ totalWords = withContext(Dispatchers.Default) {+ (0 until doc.pageCount).sumOf { p -> countWords(runCatching { engine.session.pagePlainText(doc.id, p.toUInt()) }.getOrDefault("")) }+ }+ }tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() {override fun onStart(utteranceId: String?) {}@@ -169,6 +205,25 @@ class ReadAloud(if (doc.viewer.currentPage != p) doc.viewer.goToPage(p)}+ /** Move to the selection's word, or to where a stopped reading was, within the loaded page. */+ private fun placeStart() {+ val g = startGlyph+ if (g != null) {+ val i = blocks.indexOfFirst { g >= it.range.start && g < it.range.end }+ if (i >= 0) {+ index = i+ offset = blocks[i].glyphOfChar.indexOfFirst { it >= g }.coerceAtLeast(0)+ }+ return+ }+ resumeAt?.let { (i, o) ->+ if (i in blocks.indices) {+ index = i+ offset = o.coerceIn(0, blocks[i].text.length)+ }+ }+ }+private suspend fun nextPage() {var p = page + 1while (p < doc.pageCount) {@@ -303,6 +358,12 @@ class ReadAloud(fun stop() {playing = false+ // keep the place for next time (the reference offers to resume); a finished reading starts over+ if (key.isNotEmpty()) {+ val e = prefs(prefsCtx).edit()+ if (finished) e.remove("pos:$key") else e.putString("pos:$key", "$page,$index,$offset")+ e.apply()+ }runCatching {tts.stop()tts.shutdown()@@ -320,14 +381,40 @@ class ReadAloud(return ((page + within) / doc.pageCount).coerceIn(0f, 1f)}- /** Reading time left and gone, estimated from the pages (at about 250 words a page). */- val estimatedTotalMs: Long get() = (doc.pageCount * 250L * 60_000L / (WORDS_PER_MINUTE * speed)).toLong()+ /** Reading time in all, estimated from the document's words (about 250 a page until they are counted). */+ val estimatedTotalMs: Long get() {+ val words = if (totalWords > 0) totalWords.toLong() else doc.pageCount * 250L+ return (words * 60_000L / (WORDS_PER_MINUTE * speed)).toLong()+ }companion object {val SPEEDS = listOf(0.5f, 0.75f, 1f, 1.25f, 1.5f, 1.75f, 2f)/** A voice's pace at 1.0x, for turning 15 seconds into words. */private const val WORDS_PER_MINUTE = 128fprivate fun prefs(c: Context) = c.getSharedPreferences("readAloud", Context.MODE_PRIVATE)++ /** Words in [text]: runs of letters or digits, with each CJK character a word of its own. */+ fun countWords(text: String): Int {+ var n = 0+ var inWord = false+ for (ch in text) {+ val cjk = Character.UnicodeScript.of(ch.code) in setOf(Character.UnicodeScript.HAN, Character.UnicodeScript.HIRAGANA, Character.UnicodeScript.KATAKANA, Character.UnicodeScript.HANGUL)+ when {+ cjk -> { n++; inWord = false }+ ch.isLetterOrDigit() -> { if (!inWord) n++; inWord = true }+ else -> inWord = false+ }+ }+ return n+ }++ /** Where reading of a document stopped: page, paragraph and character, if it did. */+ fun savedPosition(c: Context, key: String): Triple<Int, Int, Int>? {+ val v = prefs(c).getString("pos:$key", null)?.split(',')?.mapNotNull { it.toIntOrNull() } ?: return null+ return if (v.size == 3) Triple(v[0], v[1], v[2]) else null+ }++ fun forgetPosition(c: Context, key: String) = prefs(c).edit().remove("pos:$key").apply()}}@@ -458,12 +545,15 @@ private fun ReadAloudFull(vm: io.github.artcraftandroid.pdfcraft.ui.AppViewModelval context = LocalContext.currentvar thumb by remember(r.page) { mutableStateOf<ImageBitmap?>(null) }var speeds by remember { mutableStateOf(false) }+ var voices by remember { mutableStateOf(false) }LaunchedEffect(r.page) {val eng = vm.engine ?: return@LaunchedEffectval size = doc.info.pages.getOrNull(r.page) ?: return@LaunchedEffectval scale = 480f / maxOf(size.width, size.height).coerceAtLeast(1f)thumb = runCatching { withContext(eng.thumbnails) { eng.session.renderPage(doc.id, r.page.toUInt(), scale, null).toBitmap().asImageBitmap() } }.getOrNull()}+ // the language sheet sits over the player, not in its column (which the player fills)+ Box(Modifier.fillMaxSize()) {PdfSheet(onDismiss = onClose, maxHeightFraction = 1f, fill = true) {Column(Modifier.fillMaxSize().padding(horizontal = 20.dp), horizontalAlignment = Alignment.CenterHorizontally) {Box(Modifier.fillMaxWidth()) {@@ -499,9 +589,7 @@ private fun ReadAloudFull(vm: io.github.artcraftandroid.pdfcraft.ui.AppViewModelSpacer(Modifier.weight(1f))Row(Modifier.fillMaxWidth().padding(bottom = 16.dp), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically) {Column(- Modifier.clickable {- runCatching { context.startActivity(Intent("com.android.settings.TTS_SETTINGS").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }- }.padding(8.dp),+ Modifier.clickable { voices = true }.padding(8.dp),horizontalAlignment = Alignment.CenterHorizontally,) {Icon(LucideIcons.AudioLines, null, tint = c.icon, modifier = Modifier.size(24.dp))@@ -514,6 +602,44 @@ private fun ReadAloudFull(vm: io.github.artcraftandroid.pdfcraft.ui.AppViewModel}}}+ if (voices) LanguageSheet(r, onVoiceSettings = {+ voices = false+ runCatching { context.startActivity(Intent("com.android.settings.TTS_SETTINGS").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }+ }) { voices = false }+ }+}++/** Choose the language to read in: the ones the phone's voice has, then its voice settings. */+@Composable+private fun LanguageSheet(r: ReadAloud, onVoiceSettings: () -> Unit, onDismiss: () -> Unit) {+ val c = pdfColors+ val langs = remember { r.languages() }+ // opened at the language in use (a couple of rows above it showing)+ val current = remember(langs, r.language) { languageIndex(langs, r.language) }+ val list = androidx.compose.foundation.lazy.rememberLazyListState(initialFirstVisibleItemIndex = (current - 2).coerceAtLeast(0))+ io.github.artcraftandroid.pdfcraft.ui.PdfSheet(onDismiss = onDismiss, dim = true) {+ io.github.artcraftandroid.pdfcraft.ui.SheetTitle("Choose language")+ androidx.compose.foundation.lazy.LazyColumn(Modifier.heightIn(max = 420.dp), state = list) {+ items(langs.size) { i ->+ val l = langs[i]+ io.github.artcraftandroid.pdfcraft.ui.SheetRow(null, l.getDisplayName(Locale.getDefault()), { r.chooseLanguage(l); onDismiss() }, checked = i == current)+ }+ }+ io.github.artcraftandroid.pdfcraft.ui.SheetRow(LucideIcons.Settings, "Voice settings", onVoiceSettings)+ Spacer(Modifier.height(8.dp))+ }+}++/**+ * Where [current] is in [langs]: the same language and country, else the same language. Voices+ * often list their languages by three-letter codes ("eng", "USA"), so both are compared that way.+ * -1 when it isn't there.+ */+internal fun languageIndex(langs: List<Locale>, current: Locale): Int {+ fun Locale.lang() = runCatching { isO3Language }.getOrDefault(language).lowercase(Locale.ROOT)+ fun Locale.place() = runCatching { isO3Country }.getOrDefault(country).uppercase(Locale.ROOT)+ val exact = langs.indexOfFirst { it.lang() == current.lang() && it.place() == current.place() }+ return if (exact >= 0) exact else langs.indexOfFirst { it.lang() == current.lang() }}private fun readClock(ms: Long): String {diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/SpellCheck.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/SpellCheck.ktnew file mode 100644index 0000000..0cb94f2--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/SpellCheck.kt@@ -0,0 +1,64 @@+package io.github.artcraftandroid.pdfcraft.ui.viewer++import android.content.Context+import android.view.textservice.SentenceSuggestionsInfo+import android.view.textservice.SpellCheckerSession+import android.view.textservice.SuggestionsInfo+import android.view.textservice.TextInfo+import android.view.textservice.TextServicesManager+import java.util.Locale+import kotlin.coroutines.resume+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withTimeoutOrNull++/** A word the spell checker doesn't know: characters [start] until [end], and what it suggests. */+data class Typo(val start: Int, val end: Int, val suggestions: List<String>)++/**+ * Spell checking for Edit PDF's text, as the reference underlines misspelled words while editing:+ * the phone's own spell checker (the keyboard's), asked word by word (the request every checker+ * answers; some give nothing useful for whole sentences). Nothing is reported when the phone has+ * no spell checker or it doesn't answer.+ */+class SpellCheck(context: Context) {+ private val manager = context.getSystemService(TextServicesManager::class.java)++ suspend fun check(text: String): List<Typo> {+ if (text.isBlank()) return emptyList()+ val tsm = manager ?: return emptyList()+ // the words, with where each starts (letters and apostrophes; at most 200 of them)+ val words = Regex("[\\p{L}][\\p{L}'’]*").findAll(text).take(200).toList()+ if (words.isEmpty()) return emptyList()+ return withTimeoutOrNull(3000) {+ suspendCancellableCoroutine { cont ->+ var session: SpellCheckerSession? = null+ val listener = object : SpellCheckerSession.SpellCheckerSessionListener {+ override fun onGetSuggestions(results: Array<out SuggestionsInfo>?) {+ val typos = mutableListOf<Typo>()+ results.orEmpty().forEachIndexed { i, info ->+ val m = words.getOrNull(i) ?: return@forEachIndexed+ val attrs = info.suggestionsAttributes+ if (attrs and SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO == 0) return@forEachIndexed+ if (attrs and SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY != 0) return@forEachIndexed+ val suggestions = (0 until info.suggestionsCount.coerceAtLeast(0)).mapNotNull { info.getSuggestionAt(it) }.filter { it.isNotBlank() }+ if (suggestions.any { it.equals(m.value, ignoreCase = true) }) return@forEachIndexed+ typos += Typo(m.range.first, m.range.last + 1, suggestions.take(3))+ }+ session?.close()+ if (cont.isActive) cont.resume(typos)+ }++ override fun onGetSentenceSuggestions(results: Array<out SentenceSuggestionsInfo>?) {}+ }+ session = runCatching { tsm.newSpellCheckerSession(null, Locale.getDefault(), listener, true) }.getOrNull()+ if (session == null) {+ cont.resume(emptyList())+ } else {+ cont.invokeOnCancellation { session?.close() }+ @Suppress("DEPRECATION")+ session.getSuggestions(words.map { TextInfo(it.value) }.toTypedArray(), 3, true)+ }+ }+ } ?: emptyList()+ }+}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/TextSelection.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/TextSelection.ktindex 46a91e5..692d57a 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/TextSelection.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/TextSelection.kt@@ -23,6 +23,9 @@ class TextSelectionState(private val engine: Engine, private val doc: ULong, privar selection by mutableStateOf<Selection?>(null)private set+ /** Where a handle is being dragged (screen), for the magnifier over it; null when none is. */+ var magnifierAt by mutableStateOf<androidx.compose.ui.geometry.Offset?>(null)+/** The glyph the selection started from, which stays put while the other handle moves. */private var anchor = 0diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Tools.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Tools.ktindex e32a43e..ee35226 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Tools.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Tools.kt@@ -38,6 +38,7 @@ import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import io.github.artcraftandroid.pdfcraft.ui.LocalUndoimport androidx.compose.ui.draw.drawBehindimport androidx.compose.ui.graphics.drawscope.clipPathimport androidx.compose.foundation.gestures.detectHorizontalDragGestures@@ -169,6 +170,8 @@ private fun TapLayer(doc: OpenDocument, onTap: (PagePoint) -> Unit) {@Composableprivate fun DrawLayer(vm: AppViewModel, doc: OpenDocument) {val strokes = remember { mutableStateListOf<InkStroke>() }+ // strokes taken back, for redo; a new stroke clears them+ val undone = remember { mutableStateListOf<InkStroke>() }var current by remember { mutableStateOf<InkStroke?>(null) }val prefs = vm.toolPrefsval color = prefs.color(StyledTool.Ink)@@ -194,10 +197,16 @@ private fun DrawLayer(vm: AppViewModel, doc: OpenDocument) {)}strokes.clear()+ undone.clear()}- doc.undoTool = { if (strokes.isNotEmpty()) { strokes.removeAt(strokes.lastIndex); true } else false }+ doc.localUndo = LocalUndo(+ canUndo = { strokes.isNotEmpty() },+ canRedo = { undone.isNotEmpty() },+ undo = { if (strokes.isNotEmpty()) undone.add(strokes.removeAt(strokes.lastIndex)) },+ redo = { if (undone.isNotEmpty()) strokes.add(undone.removeAt(undone.lastIndex)) },+ )onDispose {- doc.undoTool = null+ doc.localUndo = null}}// press and hold: where the finger has been still since, and when it last moved further@@ -221,6 +230,7 @@ private fun DrawLayer(vm: AppViewModel, doc: OpenDocument) {stillAt = pmovedAt = System.currentTimeMillis()current = InkStroke(at.page).also { it.points.add(Offset(at.x, at.y)); strokes.add(it) }+ undone.clear()},onMove = { p ->val s = current ?: return@toolGestures@@ -436,21 +446,7 @@ fun PropertyPicker(vm: AppViewModel, tool: StyledTool, picker: Picker, markup: T}Picker.Width -> {Text("Line thickness", color = c.text, fontSize = 17.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, modifier = Modifier.padding(start = 20.dp, bottom = 12.dp))- Row(Modifier.fillMaxWidth().padding(bottom = 16.dp), horizontalArrangement = Arrangement.Center) {- val ink = prefs.color(StyledTool.Ink)- InkWidths.forEachIndexed { i, w ->- val selected = prefs.inkWidth == w- Box(- Modifier.size(48.dp)- .then(if (selected) Modifier.border(1.5.dp, c.accent, RoundedCornerShape(4.dp)) else Modifier)- .clickable(role = Role.RadioButton) { prefs.updateInkWidth(w) }- .semantics { contentDescription = "Stroke width ${i + 1}" },- contentAlignment = Alignment.Center,- ) {- Box(Modifier.width(28.dp).height((1 + i * 1.2f).dp).background(ink))- }- }- }+ InkWidthRow(prefs.color(StyledTool.Ink), prefs.inkWidth) { prefs.updateInkWidth(it) }}Picker.TextSize -> {Text("Text size", color = c.text, fontSize = 17.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, modifier = Modifier.padding(start = 20.dp, bottom = 4.dp))@@ -472,6 +468,25 @@ fun PropertyPicker(vm: AppViewModel, tool: StyledTool, picker: Picker, markup: T}}+/** The seven line widths as bars of growing thickness, the chosen one framed. */+@Composable+fun InkWidthRow(color: Color, selected: Float?, onPick: (Float) -> Unit) {+ val c = pdfColors+ Row(Modifier.fillMaxWidth().padding(bottom = 16.dp), horizontalArrangement = Arrangement.Center) {+ InkWidths.forEachIndexed { i, w ->+ Box(+ Modifier.size(48.dp)+ .then(if (selected == w) Modifier.border(1.5.dp, c.accent, RoundedCornerShape(4.dp)) else Modifier)+ .clickable(role = Role.RadioButton) { onPick(w) }+ .semantics { contentDescription = "Stroke width ${i + 1}" },+ contentAlignment = Alignment.Center,+ ) {+ Box(Modifier.width(28.dp).height((1 + i * 1.2f).dp).background(color))+ }+ }+ }+}+/** The 18 colour swatches: 32 dp rounded squares 18 dp apart, the chosen one ringed and checked. */@Composablefun ColorGrid(selected: Color, onPick: (Color) -> Unit) {diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerBars.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerBars.ktindex 83fb9a6..b29f52e 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerBars.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerBars.kt@@ -82,6 +82,9 @@ fun ViewerTopBar(moreOpen: Boolean,/** A tool with its own title (Edit PDF): Done, the title and Undo only. */title: String? = null,+ /** What Undo and Redo would take back or bring back, for their menu. */+ undoLabel: String? = null,+ redoLabel: String? = null,) {val c = pdfColorsRow(@@ -101,7 +104,7 @@ fun ViewerTopBar(if (title != null) {Spacer(Modifier.width(6.dp))Text(title, color = c.label, fontSize = 17.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, modifier = Modifier.weight(1f))- UndoMenuButton(canUndo, canRedo, onUndo, onRedo)+ UndoMenuButton(canUndo, canRedo, onUndo, onRedo, undoLabel, redoLabel)Spacer(Modifier.width(10.dp))return@Row}@@ -123,7 +126,7 @@ fun ViewerTopBar(BarIcon(LucideIcons.Redo2, "Redo", onRedo, enabled = canRedo)}} else if (canUndo) {- UndoMenuButton(canUndo, canRedo, onUndo, onRedo)+ UndoMenuButton(canUndo, canRedo, onUndo, onRedo, undoLabel, redoLabel)}if (onSearch != null) BarIcon(LucideIcons.Search, "Find in document", onSearch)BarIcon(LucideIcons.Share2, "Share", onShare)@@ -134,7 +137,7 @@ fun ViewerTopBar(/** Undo with a corner mark: a tap opens Undo and Redo. */@Composable-fun UndoMenuButton(canUndo: Boolean, canRedo: Boolean, onUndo: () -> Unit, onRedo: () -> Unit) {+fun UndoMenuButton(canUndo: Boolean, canRedo: Boolean, onUndo: () -> Unit, onRedo: () -> Unit, undoLabel: String? = null, redoLabel: String? = null) {val c = pdfColorsvar open by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(false) }Box {@@ -151,11 +154,11 @@ fun UndoMenuButton(canUndo: Boolean, canRedo: Boolean, onUndo: () -> Unit, onRed}androidx.compose.material3.DropdownMenu(expanded = open, onDismissRequest = { open = false }, containerColor = c.menu) {androidx.compose.material3.DropdownMenuItem(- text = { Text("Undo", color = c.text) }, enabled = canUndo,+ text = { Text(undoLabel?.let { "Undo $it" } ?: "Undo", color = c.text) }, enabled = canUndo,leadingIcon = { Icon(LucideIcons.Undo2, null, tint = c.icon) }, onClick = { open = false; onUndo() },)androidx.compose.material3.DropdownMenuItem(- text = { Text("Redo", color = c.text) }, enabled = canRedo,+ text = { Text(redoLabel?.let { "Redo $it" } ?: "Redo", color = c.text) }, enabled = canRedo,leadingIcon = { Icon(LucideIcons.Redo2, null, tint = c.icon) }, onClick = { open = false; onRedo() },)}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerOverlays.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerOverlays.ktindex b4217bd..3d78eb7 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerOverlays.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerOverlays.kt@@ -394,11 +394,15 @@ fun BoxScope.SelectionHandles(doc: OpenDocument, sel: Selection) {.offset { IntOffset((anchor.x - size / 2f).roundToInt(), anchor.y.roundToInt()) }.size(20.dp).pointerInput(sel.range.page, start) {- detectDragGestures(onDragEnd = { drag = Offset.Zero }, onDragCancel = { drag = Offset.Zero }) { change, d ->+ detectDragGestures(+ onDragEnd = { drag = Offset.Zero; doc.selection.magnifierAt = null },+ onDragCancel = { drag = Offset.Zero; doc.selection.magnifierAt = null },+ ) { change, d ->change.consume()drag += d// aim at the middle of the line the handle is underval target = Offset(anchor.x, anchor.y - lineHeight / 2f) + drag+ doc.selection.magnifierAt = targetdoc.viewer.screenToPage(target, nearest = true)?.let { doc.selection.dragHandle(start, it) }}}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.ktindex 0e3c85c..618dc9e 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt@@ -34,6 +34,7 @@ import androidx.compose.runtime.setValueimport androidx.compose.runtime.snapshotFlowimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.foundation.magnifierimport androidx.compose.ui.draw.clipimport androidx.compose.foundation.layout.imePaddingimport io.github.artcraftandroid.pdfcraft.ui.LucideIcons@@ -118,7 +119,12 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {// Reopen where the reader left off.LaunchedEffect(doc) {snapshotFlow { doc.viewer.viewW }.collect { w ->- if (w > 0f) vm.pendingPage?.let { p -> doc.viewer.goToPage(p); vm.pendingPage = null }+ if (w > 0f) vm.pendingPage?.let { p ->+ val spot = vm.pendingSpot+ if (spot != null) doc.viewer.showSpot(p, spot.first, spot.second, spot.third) else doc.viewer.goToPage(p)+ vm.pendingPage = null+ vm.pendingSpot = null+ }}}@@ -158,7 +164,16 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {}}- Box(Modifier.fillMaxSize().background(c.desk)) {+ // a magnifier over the text while a selection handle is dragged, as the reference shows one+ Box(+ Modifier.fillMaxSize().background(c.desk).magnifier(+ sourceCenter = { selection.magnifierAt ?: Offset.Unspecified },+ magnifierCenter = { selection.magnifierAt?.let { it - Offset(0f, with(density) { 56.dp.toPx() }) } ?: Offset.Unspecified },+ zoom = 1.25f,+ size = androidx.compose.ui.unit.DpSize(120.dp, 44.dp),+ cornerRadius = 22.dp,+ ),+ ) {val gesturesForTool = ctl.tool == ViewerTool.None || ctl.tool == ViewerTool.Editif (vm.readingMode) ReadingModeContent(vm, doc,@@ -189,10 +204,11 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {},// a double tap zooms with the bars out of the way, as the reference's doesonDoubleTap = { if (ctl.tool == ViewerTool.None && !ctl.searching) ctl.barsVisible = false },- onLongPress = { _, at ->+ onLongPress = { p, at ->if (at != null) scope.launch {val slop = 12f / doc.viewer.pixelsPerPoint(at.page).coerceAtLeast(0.1f) * density.density- selection.selectWordAt(at, slop)+ // no word there: a picture, or the page menu, as the reference's long press+ if (!selection.selectWordAt(at, slop) && ctl.tool == ViewerTool.None && !vm.readingMode) vm.longPressPage(doc, at, p)}},overlay = {@@ -213,6 +229,10 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {vm.fillTextPrompt?.takeIf { it.doc === doc }?.let { TextEntry(vm, it, onDone = vm::postFillText) }vm.addTextPrompt?.takeIf { it.doc === doc }?.let { TextEntry(vm, it, onDone = vm::postAddText) }vm.fieldEdit?.takeIf { it.doc === doc }?.let { FieldEditor(vm, it) }+ // a Fill & Sign element can be dragged and, for boxes, resized (a comment's: over its panel, below)+ if (ctl.tool == ViewerTool.FillSign) vm.selectedFill?.let { c ->+ CommentDragOverlay(doc, c, onMove = { dx, dy -> vm.moveFill(doc, c, dx, dy) }, onResize = { vm.resizeFill(doc, c, it) })+ }if (ctl.tool == ViewerTool.FillSign) vm.selectedFill?.let { FillElementMenu(vm, doc, it) }// Scrubber and page pill (continuous, three pages or more).@@ -296,8 +316,9 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {if (fa != null) FieldTopBar(fa) else ViewerTopBar(toolActive = ctl.tool != ViewerTool.None,doneIsCheck = ctl.tool != ViewerTool.Comment,- canUndo = doc.info.undo != null,- canRedo = doc.info.redo != null,+ // while drawing, the strokes not yet added have their own undo and redo+ canUndo = doc.localUndo?.canUndo?.invoke() ?: (doc.info.undo != null),+ canRedo = doc.localUndo?.canRedo?.invoke() ?: (doc.info.redo != null),onBack = { if (ctl.tool != ViewerTool.None) vm.leaveTool(doc) else vm.closeDocument() },onUndo = { vm.undo(doc) },onRedo = { vm.redo(doc) },@@ -313,6 +334,8 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {onMore = { ctl.sheet = if (ctl.sheet == ViewerSheet.More) ViewerSheet.None else ViewerSheet.More },moreOpen = ctl.sheet == ViewerSheet.More,title = if (ctl.tool == ViewerTool.Edit) "Edit PDF" else null,+ undoLabel = if (doc.localUndo != null) "Drawing" else doc.info.undo,+ redoLabel = if (doc.localUndo != null) "Drawing" else doc.info.redo,)}}@@ -349,7 +372,8 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {// Text selection's menu.selection.selection?.let { sel ->SelectionHandles(doc, sel)- SelectionMenu(vm, doc, sel)+ // out of the way while a handle is dragged; back where the selection ends+ if (selection.magnifierAt == null) SelectionMenu(vm, doc, sel)}// Sheets and dialogs.@@ -365,10 +389,25 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {}}if (ctl.sheet == ViewerSheet.Comments) CommentListScreen(vm, doc)+ vm.pageMenu?.takeIf { it.doc === doc }?.let { PageMenuView(vm, it) }+ if (vm.imageSource?.first === doc) {+ io.github.artcraftandroid.pdfcraft.ui.PdfSheet(onDismiss = { vm.imageSource = null }, dim = true) {+ io.github.artcraftandroid.pdfcraft.ui.SheetTitle("Add image")+ io.github.artcraftandroid.pdfcraft.ui.SheetRow(LucideIcons.Images, "From photos", { vm.addImageFrom(camera = false) })+ io.github.artcraftandroid.pdfcraft.ui.SheetRow(LucideIcons.Camera, "From camera", { vm.addImageFrom(camera = true) })+ Spacer(Modifier.height(12.dp))+ }+ }vm.notePrompt?.takeIf { it.doc === doc }?.let { NoteSheet(vm, it) }vm.voicePrompt?.takeIf { it.doc === doc }?.let { VoiceSheet(vm, it) }if (vm.micRationale) MicRationaleDialog(vm)vm.selectedComment?.takeIf { it.first === doc }?.let { (_, cm) -> CommentPanel(vm, doc, cm) }+ // over the panel's tap-to-close area, but only where the comment is: drag it to move, corners to resize+ if (ctl.tool == ViewerTool.None && doc.info.allowsAnnotation) {+ vm.selectedComment?.takeIf { it.first === doc }?.second?.let { c ->+ CommentDragOverlay(doc, c, onMove = { dx, dy -> vm.moveComment(doc, c, dx, dy) }, onResize = { vm.resizeComment(doc, c, it) })+ }+ }vm.replyPrompt?.takeIf { it.doc === doc }?.let { ReplySheet(vm, it) }vm.readAloud?.let { ReadAloudBar(vm, doc, it) }if (ctl.goToPage) GoToPageDialog(doc, onDismiss = { ctl.goToPage = false })diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerState.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerState.ktindex def4aee..cdc1412 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerState.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerState.kt@@ -156,6 +156,22 @@ class ViewerState(pages: List<PageSize>) {clamp()}+ /** Show the spot [x], [y] (points) of page [index] at the screen's top-left, at [level] zoom (continuous pages). */+ fun showSpot(index: Int, x: Float, y: Float, level: Float) {+ val l = layout+ if (mode != PageMode.Continuous || l.rects.isEmpty() || !x.isFinite() || !y.isFinite() || !level.isFinite()) {+ goToPage(index)+ return+ }+ val i = index.coerceIn(0, l.rects.lastIndex)+ val r = l.rects[i]+ val s = l.scaleOf(i)+ zoom = level.coerceIn(minZoom, maxZoom)+ scrollX = (r.left + x * s) * zoom+ scrollY = (r.top + y * s) * zoom - padTop+ clamp()+ }+/** Where single-page mode should rest after a swipe with velocity [vx] (pixels/s). */fun snapTarget(vx: Float): Float {val page = (scrollX / max(1f, viewW))diff --git a/apps/pdfcraft-android/android/app/src/main/res/drawable/ic_stat_read_aloud.xml b/apps/pdfcraft-android/android/app/src/main/res/drawable/ic_stat_read_aloud.xmlnew file mode 100644index 0000000..053bbd7--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/main/res/drawable/ic_stat_read_aloud.xml@@ -0,0 +1,21 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Read aloud's notification icon: a speaker with two sound waves (drawn for PdfCraft). -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M3,9 L7,9 L12,4.5 L12,19.5 L7,15 L3,15 Z" />+ <path+ android:strokeColor="#FFFFFFFF"+ android:strokeWidth="2"+ android:strokeLineCap="round"+ android:pathData="M15.5,8.5 A5,5 0 0,1 15.5,15.5" />+ <path+ android:strokeColor="#FFFFFFFF"+ android:strokeWidth="2"+ android:strokeLineCap="round"+ android:pathData="M18.5,5.5 A9,9 0 0,1 18.5,18.5" />+</vector>diff --git a/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/EditListsTest.kt b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/EditListsTest.ktnew file mode 100644index 0000000..f3c46f6--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/EditListsTest.kt@@ -0,0 +1,38 @@+package io.github.artcraftandroid.pdfcraft.ui++import io.github.artcraftandroid.pdfcraft.ui.viewer.ListStyle+import org.junit.Assert.assertEquals+import org.junit.Test++class EditListsTest {+ private val items = "Apples\nPears\nPlums"++ @Test+ fun eachLineGetsItsMarker() {+ assertEquals("• Apples\n• Pears\n• Plums", ListStyle.apply(items, ListStyle.Bullet))+ assertEquals("1. Apples\n2. Pears\n3. Plums", ListStyle.apply(items, ListStyle.Number))+ assertEquals("i. Apples\nii. Pears\niii. Plums", ListStyle.apply(items, ListStyle.Roman))+ assertEquals("A. Apples\nB. Pears\nC. Plums", ListStyle.apply(items, ListStyle.Upper))+ }++ @Test+ fun aListIsRecognisedAndCanBeChangedOrRemoved() {+ val numbered = ListStyle.apply(items, ListStyle.Number)+ assertEquals(ListStyle.Number, ListStyle.of(numbered))+ assertEquals("a. Apples\nb. Pears\nc. Plums", ListStyle.apply(numbered, ListStyle.Lower))+ assertEquals(items, ListStyle.apply(numbered, ListStyle.None))+ assertEquals(ListStyle.Roman, ListStyle.of(ListStyle.apply(items, ListStyle.Roman)))+ }++ @Test+ fun plainTextIsNotTakenForAList() {+ assertEquals(ListStyle.None, ListStyle.of("a. b. c. are letters\nnot a list"))+ assertEquals(ListStyle.None, ListStyle.of(items))+ assertEquals(items, ListStyle.apply(items, ListStyle.None))+ }++ @Test+ fun blankLinesKeepTheirPlaceAndAreNotCounted() {+ assertEquals("1. One\n\n2. Two", ListStyle.apply("One\n\nTwo", ListStyle.Number))+ }+}diff --git a/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/FreeTextLayoutTest.kt b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/FreeTextLayoutTest.ktnew file mode 100644index 0000000..feffb42--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/FreeTextLayoutTest.kt@@ -0,0 +1,38 @@+package io.github.artcraftandroid.pdfcraft.ui++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class FreeTextLayoutTest {+ @Test+ fun widthFollowsTheEngineTable() {+ // "Hi" = H 680 + i 260 units+ assertEquals(9.4f, FreeTextLayout.width("Hi", 10f), 0.001f)+ }++ @Test+ fun longTextWrapsAtSpacesWithinTheRoom() {+ val text = "Wrapping test for a long note that runs past the edge of the page"+ val (lines, w, h) = FreeTextLayout.layout(text, 16f, 200f)+ assertTrue(lines.size > 1)+ assertEquals(text, lines.joinToString(" "))+ assertTrue(w <= 200f)+ // each line fits the width the engine will wrap at, so it draws the same lines+ lines.forEach { assertTrue(FreeTextLayout.width(it, 16f) <= w - 2 * FreeTextLayout.PAD) }+ // and every line's baseline is inside the box+ assertTrue(h >= 2 * FreeTextLayout.PAD + 16f * 0.9f + (lines.size - 1) * 16f * 1.2f)+ }++ @Test+ fun typedLineBreaksAreKept() {+ assertEquals(listOf("one", "", "two"), FreeTextLayout.wrap("one\n\ntwo", 12f, 500f))+ }++ @Test+ fun aWordWiderThanTheRoomBreaksByLetters() {+ val lines = FreeTextLayout.wrap("mmmmmmmmmm", 10f, 30f)+ assertEquals("mmmmmmmmmm", lines.joinToString(""))+ lines.forEach { assertTrue(FreeTextLayout.width(it, 10f) <= 30f) }+ }+}diff --git a/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ReadAloudLanguageTest.kt b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ReadAloudLanguageTest.ktnew file mode 100644index 0000000..5442e41--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ReadAloudLanguageTest.kt@@ -0,0 +1,25 @@+package io.github.artcraftandroid.pdfcraft.ui++import io.github.artcraftandroid.pdfcraft.ui.viewer.languageIndex+import java.util.Locale+import org.junit.Assert.assertEquals+import org.junit.Test++class ReadAloudLanguageTest {+ private val langs = listOf(Locale("deu", "DEU"), Locale("eng", "GBR"), Locale("eng", "USA"), Locale("fra", "FRA"))++ @Test+ fun twoLetterLocaleFindsItsThreeLetterTwin() {+ assertEquals(2, languageIndex(langs, Locale.US))+ }++ @Test+ fun sameLanguageWhenTheCountryIsMissing() {+ assertEquals(1, languageIndex(langs, Locale("en", "AU")))+ }++ @Test+ fun missingLanguage() {+ assertEquals(-1, languageIndex(langs, Locale.JAPAN))+ }+}diff --git a/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ReadAloudWordsTest.kt b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ReadAloudWordsTest.ktnew file mode 100644index 0000000..243d32d--- /dev/null+++ b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ReadAloudWordsTest.kt@@ -0,0 +1,20 @@+package io.github.artcraftandroid.pdfcraft.ui++import io.github.artcraftandroid.pdfcraft.ui.viewer.ReadAloud+import org.junit.Assert.assertEquals+import org.junit.Test++class ReadAloudWordsTest {+ @Test+ fun wordsAreRunsOfLettersAndDigits() {+ assertEquals(0, ReadAloud.countWords(""))+ assertEquals(4, ReadAloud.countWords("A PDF reader, judged!"))+ assertEquals(3, ReadAloud.countWords("page 12 — done"))+ }++ @Test+ fun eachCjkCharacterIsAWord() {+ assertEquals(3, ReadAloud.countWords("縦書き"))+ assertEquals(6, ReadAloud.countWords("Hi 世界 and 한국"))+ }+}diff --git a/apps/pdfcraft-android/src/lib.rs b/apps/pdfcraft-android/src/lib.rsindex 659fe75..6536524 100644--- a/apps/pdfcraft-android/src/lib.rs+++ b/apps/pdfcraft-android/src/lib.rs@@ -243,6 +243,10 @@ pub struct CommentInfo {pub locked: bool,/// Placed with Fill & Sign rather than the comment tools.pub fill_sign: bool,+ /// Its opacity, 0 to 1.+ pub opacity: f32,+ /// Its line width in points, when it draws a line (ink, shapes, lines).+ pub width: Option<f32>,}/// A form field's widget on a page: what a tap there fills.@@ -625,6 +629,8 @@ impl MobileSession {state: a.state.clone(),locked: a.locked,fill_sign: a.fill_sign,+ opacity: a.opacity,+ width: a.width,}).collect()})diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rsindex 8ad9e7b..1755cd7 100644--- a/crates/annot/src/lib.rs+++ b/crates/annot/src/lib.rs@@ -2026,6 +2026,10 @@ pub struct Summary {pub intent: Option<String>,/// A Fill & Sign mark ([`is_fill_sign`]).pub fill_sign: bool,+ /// `/CA`, the opacity, 0 to 1 (1 when absent or not a number).+ pub opacity: f32,+ /// The line width in points: `/BS /W`, else the third number of `/Border`.+ pub width: Option<f32>,}fn text_value(doc: &Document, d: &Dict, key: &[u8]) -> Option<String> {@@ -2081,6 +2085,15 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {}let quads = nums(b"QuadPoints").as_chunks::<8>().0.to_vec();let in_reply_to = d.get(b"IRT").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).and_then(|p| text_value(doc, &p, b"NM"));+ // keep in step with `pdfcraft_render::inspect`+ let opacity = d.get(b"CA").and_then(|o| doc.resolve(o).as_f64()).filter(|v| v.is_finite()).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32);+ let width = d+ .get(b"BS")+ .map(|o| doc.resolve(o))+ .and_then(|o| o.as_dict().and_then(|bs| bs.get(b"W")).and_then(|w| doc.resolve(w).as_f64()))+ .or_else(|| nums(b"Border").get(2).map(|w| f64::from(*w)))+ .filter(|w| w.is_finite() && *w >= 0.0)+ .map(|w| w as f32);out.push(Summary {page,index,@@ -2099,6 +2112,8 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {locked: annotation_flags(doc, d) & FLAG_LOCKED != 0,intent: d.get(b"IT").and_then(|o| doc.resolve(o).as_name().map(|n| String::from_utf8_lossy(n).into_owned())),fill_sign: is_fill_sign(doc, d),+ opacity,+ width,});}}diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rsindex e94bc14..9c02d9e 100644--- a/crates/annot/src/tests.rs+++ b/crates/annot/src/tests.rs@@ -1268,3 +1268,19 @@ fn cached_appearances_are_reused_while_annotations_are_unchanged() {assert!(!a.is_empty());assert_eq!(a, b, "the reused appearance is byte-identical");}++/// The comment panel shows a comment's own opacity and line width: summaries read `/CA` and the+/// border width, and default to fully opaque with no width when they are missing or malformed.+#[test]+fn summaries_report_opacity_and_line_width() {+ let mut doc = fixture();+ let mut ink = new(0, Shape::Ink { strokes: vec![vec![[10.0, 10.0], [20.0, 20.0]]] });+ ink.style.opacity = 0.5;+ ink.style.width = 4.0;+ add_annotation(&mut doc, &ink, &meta("ink")).unwrap();+ let doc = reopen(&doc);+ let all = summaries(&doc);+ let s = all.iter().find(|s| s.subtype == "Ink").expect("the ink comment is listed");+ assert!((s.opacity - 0.5).abs() < 1e-6, "{}", s.opacity);+ assert_eq!(s.width, Some(4.0));+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex e9bb1fb..c9a0a45 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -2355,6 +2355,8 @@ fn comment_list(doc: &pdfcraft_cos::Document) -> Vec<pdfcraft_render::Annotationlocked: s.locked,intent: s.intent,fill_sign: s.fill_sign,+ opacity: s.opacity,+ width: s.width,}).collect()}diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rsindex 8e4414b..e9fa260 100644--- a/crates/render/src/inspect.rs+++ b/crates/render/src/inspect.rs@@ -281,6 +281,11 @@ pub struct Annotation {/// A Fill & Sign mark: typed text, a check, cross, dot or line, or a typed, drawn or picture/// signature or initials (the rules of `pdfcraft_annot::is_fill_sign`).pub fill_sign: bool,+ /// `/CA`, the opacity, 0 to 1 (1 when absent or not a number).+ pub opacity: f32,+ /// The line width in points: `/BS /W`, else the third number of `/Border`; none when neither+ /// is there.+ pub width: Option<f32>,}impl Annotation {@@ -954,6 +959,18 @@ impl<'a> Inspector<'a> {};let in_reply_to = d.get(b"IRT").ok().and_then(|o| self.dict(o)).and_then(|p| self.text(p, b"NM"));let fill_sign = self.is_fill_sign(d, &subtype);+ let opacity =+ d.get(b"CA").ok().and_then(|o| self.resolve(o).as_float().ok()).filter(|v| v.is_finite()).map_or(1.0, |v| v.clamp(0.0, 1.0));+ let width = d+ .get(b"BS")+ .ok()+ .and_then(|o| self.dict(o))+ .and_then(|bs| bs.get(b"W").ok().and_then(|w| self.resolve(w).as_float().ok()))+ .or_else(|| match d.get(b"Border").map(|o| self.resolve(o)) {+ Ok(Object::Array(b)) => b.get(2).and_then(|w| w.as_float().ok()),+ _ => None,+ })+ .filter(|w| w.is_finite() && *w >= 0.0);info.annotations.push(Annotation {page,subtype,@@ -973,6 +990,8 @@ impl<'a> Inspector<'a> {locked: d.get(b"F").ok().and_then(|f| self.resolve(f).as_i64().ok()).unwrap_or(0) & 128 != 0,intent: self.name(d, b"IT"),fill_sign,+ opacity,+ width,});}}