Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ class DocumentFiles(private val context: Context) {
/** Files handed to other apps (share, print), through the FileProvider. */
private val shareDir = File(context.cacheDir, "share").apply { mkdirs() }

/** The picture last copied to the clipboard, through the FileProvider. */
private val clipboardDir = File(context.cacheDir, "clipboard").apply { mkdirs() }

/** Files the app creates itself (combine, create, scans) before the user saves them somewhere. */
val createdDir = File(context.filesDir, "Created").apply { mkdirs() }

Expand Down Expand Up @@ -185,6 +188,20 @@ class DocumentFiles(private val context: Context) {
}
}

/**
* A new folder in the app's space for a picture copied to the clipboard. The folder the last
* copy used is cleared first: the clipboard holds one picture at a time.
*/
fun newClipboardFolder(): File {
clipboardDir.listFiles()?.forEach { it.deleteRecursively() }
val dir = File(clipboardDir, System.nanoTime().toString())
if (!dir.mkdirs()) throw IOException("can't make $dir")
return dir
}

/** [file]'s URI for the clipboard: the app pasting it may read it through the FileProvider. */
fun clipboardUri(file: File): Uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file)

/** 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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.roundToInt

/** A message for the snackbar, with an optional action. */
data class Message(val text: String, val actionLabel: String? = null, val action: (() -> Unit)? = null)
Expand Down Expand Up @@ -348,7 +349,28 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
fun onPause() {
val doc = document ?: return
if (doc.controller.tool == ViewerTool.Draw) doc.commitTool?.invoke()
viewModelScope.launch { save(doc) }
// keep the reading place too: leaving by Home or the recents screen never closes the document
val place = capturePlace(doc)
viewModelScope.launch {
withContext(Dispatchers.IO) { storePlace(doc, place) }
save(doc)
}
}

/** Where the reader is now: page, spot, zoom and Reading Mode (read on the main thread). */
private class Place(val page: Int, val x: Float, val y: Float, val zoom: Float, val reading: Boolean)

private fun capturePlace(doc: OpenDocument): Place {
val v = doc.viewer
val pending = pendingPage
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
return Place(pending ?: spot?.page ?: v.currentPage, spot?.x ?: -1f, spot?.y ?: -1f, if (spot != null) v.zoom else 1f, readingMode)
}

private fun storePlace(doc: OpenDocument, p: Place) {
doc.source?.let { src ->
recents.update(src.toString()) { it.copy(lastPage = p.page, reading = p.reading, lastX = p.x, lastY = p.y, lastZoom = p.zoom) }
}
}

/**
Expand Down Expand Up @@ -1755,7 +1777,12 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
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 io.github.artcraftandroid.pdfcraft.ui.viewer.EditImage(
at.page,
o.optInt("image"),
FloatArray(4) { k -> full.optDouble(k).toFloat() },
FloatArray(4) { k -> rect.optDouble(k).toFloat() },
)
}
}
return null
Expand All @@ -1765,21 +1792,72 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
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.
* A long press where no word is: the page menu at that point, whose Edit PDF starts editing.
* A picture never opens Edit PDF by itself, so a stray long press on a scanned page can't
* start moving it; when copying is allowed, the menu offers Copy image for it instead.
*/
fun longPressPage(doc: OpenDocument, at: PagePoint, screen: androidx.compose.ui.geometry.Offset) {
val eng = engine ?: return
viewModelScope.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 image = if (doc.info.allowsCopying) imageUnder(doc, at) else null
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)
pageMenu = io.github.artcraftandroid.pdfcraft.ui.viewer.PageMenu(doc, at, screen, pageHasText = glyphs > 0u, image = image)
}
}

/**
* Copy [img] to the clipboard. The engine writes the picture as it is stored (a JPEG
* unchanged, else a lossless PNG); grouped Form artwork, which has no file of its own, is
* drawn the way the page shows it and copied as a PNG.
*/
fun copyImage(doc: OpenDocument, img: io.github.artcraftandroid.pdfcraft.ui.viewer.EditImage) {
if (!doc.info.allowsCopying) {
tell(text(R.string.msg_copy_images_not_allowed))
return
}
val eng = engine ?: return
viewModelScope.launch {
try {
val file = withContext(Dispatchers.IO) {
val dir = files.newClipboardFolder()
val base = File(dir, "image")
val saved = runCatching {
eng.tool("image_save", mapOf("doc" to doc.id, "page" to img.page + 1, "image" to img.number, "path" to base.absolutePath))
}.getOrNull()?.optString("path")?.takeIf { it.isNotEmpty() }
if (saved != null) File(saved) else drawImage(eng, doc, img, File(dir, "image.png"))
}
val cm = getApplication<Application>().getSystemService(android.content.ClipboardManager::class.java)
val label = text(R.string.msg_clip_image)
cm?.setPrimaryClip(ClipData.newUri(getApplication<Application>().contentResolver, label, files.clipboardUri(file)))
if (android.os.Build.VERSION.SDK_INT < 33) tell(text(R.string.msg_copied))
} catch (e: Exception) {
tell(e.userMessage)
}
}
}

/** Draw [img]'s visible part as the page shows it into [file] (Form artwork, which has no file). */
private suspend fun drawImage(eng: Engine, doc: OpenDocument, img: io.github.artcraftandroid.pdfcraft.ui.viewer.EditImage, file: File): File {
val r = img.visible
val w = r[2] - r[0]
val h = r[3] - r[1]
require(w > 0f && h > 0f) { text(R.string.msg_copy_image_failed) }
val page = doc.info.pages.getOrNull(img.page)
// big enough to keep the detail of a phone screen, small enough to stay a picture
val scale = (1600f / maxOf(w, h)).coerceIn(2f, 6f)
val pageW = ((page?.width ?: w) * scale).roundToInt().coerceAtLeast(1)
val pageH = ((page?.height ?: h) * scale).roundToInt().coerceAtLeast(1)
val x = (r[0] * scale).roundToInt().coerceIn(0, pageW - 1)
val y = (r[1] * scale).roundToInt().coerceIn(0, pageH - 1)
val tw = (w * scale).roundToInt().coerceIn(1, pageW - x)
val th = (h * scale).roundToInt().coerceIn(1, pageH - y)
val bitmap = withContext(eng.renders) {
eng.session.renderPage(doc.id, img.page.toUInt(), scale, io.github.artcraftandroid.pdfcraft.core.TileRect(x.toUInt(), y.toUInt(), tw.toUInt(), th.toUInt())).toBitmap()
}
withContext(Dispatchers.IO) {
file.outputStream().use { out -> bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out) }
}
return file
}

/** Put [img] in [rect] (points): a move or a resize. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,11 @@ data class Paragraph(
val color: String?,
)

/** A picture Edit PDF has selected: its number on the page and where it sits (points). */
data class EditImage(val page: Int, val number: Int, val rect: FloatArray)
/**
* A picture Edit PDF has selected: its number on the page and where it sits (points). [visible]
* is the part on show after a crop, for copying the picture as the page draws it.
*/
data class EditImage(val page: Int, val number: Int, val rect: FloatArray, val visible: FloatArray = rect)

/** What Edit PDF is doing: picking a paragraph, or placing new text or an image. */
enum class EditMode { Select, AddText, AddImage }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,11 @@ 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)
/**
* A long press on a page: the menu of what can start there. [image] is the picture under the
* press, when the document allows copying it: the menu offers Copy image for it.
*/
class PageMenu(val doc: OpenDocument, val at: PagePoint, val screen: Offset, val pageHasText: Boolean, val image: EditImage? = null)

/**
* The reference's page menu: a row of the commenting tools that start at the pressed point
Expand Down Expand Up @@ -85,6 +88,9 @@ fun PageMenuView(vm: AppViewModel, menu: PageMenu) {
}
Box(Modifier.fillMaxWidth().padding(horizontal = 4.dp).height(1.dp).background(c.divider))
Spacer(Modifier.height(8.dp))
menu.image?.let { img ->
PageMenuRow(LucideIcons.Copy, stringResource(R.string.page_menu_copy_image)) { close(); vm.copyImage(doc, img) }
}
if (!menu.pageHasText) PageMenuRow(LucideIcons.ScanText, stringResource(R.string.common_tool_recognize_text)) { close(); vm.recognizeText(doc) }
PageMenuRow(LucideIcons.Crop, stringResource(R.string.common_tool_crop)) { close(); vm.openCrop(doc) }
PageMenuRow(LucideIcons.FilePenLine, stringResource(R.string.common_tool_edit_pdf)) { close(); vm.enterTool(doc, ViewerTool.Edit) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@
<string name="page_menu_add_comment">إضافة تعليق</string>
<string name="page_menu_add_text">إضافة نص</string>
<string name="page_menu_add_image">إضافة صورة</string>
<string name="page_menu_copy_image">نسخ الصورة</string>
<string name="toolbar_label_password">كلمة المرور</string>
<string name="toolbar_label_combine">دمج</string>
<string name="toolbar_label_compress">ضغط</string>
Expand Down Expand Up @@ -746,6 +747,9 @@
<string name="msg_clip_pdf_text">نص PDF</string>
<string name="msg_copied">تم النسخ</string>
<string name="msg_copy_not_allowed">لا يسمح هذا المستند بنسخ نصه.</string>
<string name="msg_copy_images_not_allowed">لا يسمح هذا المستند بنسخ صوره.</string>
<string name="msg_copy_image_failed">تعذّر نسخ الصورة.</string>
<string name="msg_clip_image">صورة</string>
<string name="msg_busy_preparing_ocr">جارٍ تجهيز التعرّف على النص…</string>
<string name="msg_ocr_not_installed">التعرّف على النص غير مثبّت في هذه النسخة.</string>
<string name="msg_busy_recognizing">جارٍ التعرّف على النص…</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,7 @@
<string name="page_menu_add_comment">Add comment</string>
<string name="page_menu_add_text">Add text</string>
<string name="page_menu_add_image">Add image</string>
<string name="page_menu_copy_image">Copy image</string>

<!-- ================================================================== -->
<!-- Editing tools: Edit PDF, Fill &amp; Sign, comment tools, the quick toolbar, forms -->
Expand Down Expand Up @@ -1079,6 +1080,10 @@
<string name="msg_clip_pdf_text">PDF text</string>
<string name="msg_copied">Copied</string>
<string name="msg_copy_not_allowed">This document doesn\'t allow copying its text.</string>
<string name="msg_copy_images_not_allowed">This document doesn\'t allow copying its images.</string>
<string name="msg_copy_image_failed">The image couldn\'t be copied.</string>
<!-- Label of a picture put on the clipboard (a noun). -->
<string name="msg_clip_image">Image</string>

<!-- Messages: Recognize text (OCR) -->
<string name="msg_busy_preparing_ocr">Preparing text recognition…</string>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Files of PdfCraft's that another app may reach through its FileProvider: a document being
shared, printed or opened in another app, and a photo the camera app takes for Scan -->
shared, printed or opened in another app, a photo the camera app takes for Scan, and a
picture copied to the clipboard -->
<paths>
<cache-path name="share" path="share/" />
<cache-path name="camera" path="camera/" />
<cache-path name="clipboard" path="clipboard/" />
</paths>