Skip to content

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

PowerPoint 97-2003 opens; a glass page menu; steadier Word editing; sheets glide; a Photos-like picture editor

chethan616704cc8e49bcb
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 14ad8f4..e32c34b 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -65,6 +65,8 @@
<data android:mimeType="text/csv" />
<data android:mimeType="text/comma-separated-values" />
<data android:mimeType="text/plain" />
+ <data android:mimeType="application/vnd.ms-powerpoint" />
+ <data android:mimeType="application/vnd.ms-excel" />
<data android:mimeType="text/markdown" />
</intent-filter>
</activity>
@@ -112,6 +114,8 @@
<data android:mimeType="text/csv" />
<data android:mimeType="text/comma-separated-values" />
<data android:mimeType="text/plain" />
+ <data android:mimeType="application/vnd.ms-powerpoint" />
+ <data android:mimeType="application/vnd.ms-excel" />
<data android:mimeType="text/markdown" />
</intent-filter>
</activity>
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt
index e0136a6..3cbb238 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt
@@ -26,6 +26,8 @@ object DocumentTypes {
"application/vnd.openxmlformats-officedocument.presentationml.slideshow",
"application/vnd.openxmlformats-officedocument.presentationml.template",
"application/vnd.ms-powerpoint.presentation.macroEnabled.12",
+ // PowerPoint 97-2003: its slides' text (Artefact's own reader)
+ "application/vnd.ms-powerpoint",
)
/** Workbooks and tables. */
@@ -34,6 +36,7 @@ object DocumentTypes {
"application/vnd.openxmlformats-officedocument.spreadsheetml.template",
"application/vnd.ms-excel.sheet.macroEnabled.12",
"application/vnd.ms-excel.sheet.binary.macroEnabled.12",
+ "application/vnd.ms-excel",
"application/vnd.oasis.opendocument.spreadsheet",
"text/csv",
"text/comma-separated-values",
@@ -47,8 +50,8 @@ object DocumentTypes {
val OPENABLE = arrayOf(PDF) + WORD + SLIDES + SHEETS + TEXT
private val WORD_EXTENSIONS = setOf("docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "rtf")
- private val SLIDE_EXTENSIONS = setOf("pptx", "pptm", "ppsx", "ppsm", "potx", "potm")
- private val SHEET_EXTENSIONS = setOf("xlsx", "xlsm", "xltx", "xltm", "xlsb", "ods", "csv", "tsv")
+ private val SLIDE_EXTENSIONS = setOf("pptx", "pptm", "ppsx", "ppsm", "potx", "potm", "ppt", "pps", "pot")
+ private val SHEET_EXTENSIONS = setOf("xlsx", "xlsm", "xltx", "xltm", "xlsb", "xls", "xlt", "ods", "csv", "tsv")
private val TEXT_EXTENSIONS = setOf("txt", "md", "markdown")
/** The kinds a file list can be narrowed to (Files ▸ ⋯). */
@@ -96,6 +99,8 @@ object DocumentTypes {
"pptx", "pptm" -> SLIDES[0]
"ppsx", "ppsm" -> SLIDES[1]
"potx", "potm" -> SLIDES[2]
+ "ppt", "pps", "pot" -> "application/vnd.ms-powerpoint"
+ "xls", "xlt" -> "application/vnd.ms-excel"
"xlsx", "xltx" -> SHEETS[0]
"xlsm", "xltm" -> SHEETS[2]
"xlsb" -> SHEETS[3]
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt
index 985c632..bcf1248 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt
@@ -58,6 +58,10 @@ object LucideIcons {
val FilePlus2: ImageVector get() = Icons.AutoMirrored.Rounded.NoteAdd
val FileStack: ImageVector get() = Icons.Rounded.FileCopy
val FileText: ImageVector get() = Icons.Rounded.Description
+ val Contrast: ImageVector get() = Icons.Rounded.Contrast
+ val Highlights: ImageVector get() = Icons.Rounded.Flare
+ val Shadows: ImageVector get() = Icons.Rounded.DarkMode
+ val Droplet: ImageVector get() = Icons.Rounded.WaterDrop
val MoreHorizontal: ImageVector get() = Icons.Rounded.MoreHoriz
val PaintBucket: ImageVector get() = Icons.Rounded.FormatColorFill
val WrapText: ImageVector get() = Icons.AutoMirrored.Rounded.WrapText
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt
index 0a7db86..9e81f84 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt
@@ -229,6 +229,8 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
readingMode = recent?.reading == true && pendingTool == null
document = doc
if (doc.info.signed) announceSignatures(doc)
+ // a PowerPoint 97-2003 file shows its slides' text: say so, once, as it opens
+ if (doc.info.name.substringAfterLast('.').lowercase() in setOf("ppt", "pps", "pot")) tell(text(R.string.msg_ppt_text_only))
startPendingTool(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) }
@@ -2407,15 +2409,20 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
/** Where the caret (or the selection) is in [wordEditing]. */
var wordCaret by mutableStateOf<com.chethan616.clearpdf.core.WordCaret?>(null)
+ /** Bumped by each tap that places the caret: the keyboard comes up (again) for it. */
+ var wordKeyboard by mutableStateOf(0)
+
/** WordCraft's formatting at the caret (`bold`, `italic`, ... as `format.state` gives it). */
var wordFormat by mutableStateOf(org.json.JSONObject())
/** Start editing Word document [doc]: a tap places the caret, the keyboard types. */
fun startWordEdit(doc: OpenDocument) {
wordEditing = doc
+ wordCaret = null
doc.selection.clear()
doc.controller.barsVisible = true
- viewModelScope.launch { refreshWordCaret(doc) }
+ // the keyboard waits for a place to type: a tap on the page puts the caret there
+ tell(text(R.string.word_tap_to_type))
}
/** Leave editing; the changes are saved with the document (as on closing it). */
@@ -2438,8 +2445,26 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
}
/** A tap on [doc]'s page while editing: the caret goes there ([extend]: the selection grows to it). */
- fun wordTap(doc: OpenDocument, at: com.chethan616.clearpdf.ui.viewer.PagePoint, extend: Boolean = false) =
+ fun wordTap(doc: OpenDocument, at: com.chethan616.clearpdf.ui.viewer.PagePoint, extend: Boolean = false) {
wordRun(doc, "caret.set", mapOf("page" to at.page, "x" to at.x, "y" to at.y, "extend" to extend))
+ wordKeyboard++
+ }
+
+ /** A long press while editing: the word there is selected (to format or replace it). */
+ fun wordSelectWord(doc: OpenDocument, at: com.chethan616.clearpdf.ui.viewer.PagePoint) {
+ val eng = engine ?: return
+ viewModelScope.launch {
+ val place = Engine.toJson(mapOf("page" to at.page, "x" to at.x, "y" to at.y)).toString()
+ runCatching {
+ eng.command {
+ wordCommand(doc.id, "caret.set", place)
+ wordCommand(doc.id, "select.word", "")
+ }
+ }.onFailure { tell(it.userMessage) }
+ refreshWordCaret(doc)
+ wordKeyboard++
+ }
+ }
private suspend fun refreshWordCaret(doc: OpenDocument) {
val eng = engine ?: return
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt
index 631d889..8238761 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt
@@ -1,7 +1,10 @@
package com.chethan616.clearpdf.ui.notes
+import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
+import androidx.compose.foundation.gestures.detectHorizontalDragGestures
+import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -11,10 +14,12 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.foundation.rememberScrollState
@@ -32,11 +37,19 @@ import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.chethan616.clearpdf.R
@@ -44,12 +57,14 @@ import com.chethan616.clearpdf.core.PhotoEditor
import com.chethan616.clearpdf.engine.toBitmap
import com.chethan616.clearpdf.ui.AppViewModel
import com.chethan616.clearpdf.ui.LucideIcons
-import com.chethan616.clearpdf.ui.glass.GlassChip
+import com.chethan616.clearpdf.ui.glass.Feel
import com.chethan616.clearpdf.ui.glass.GlassCircle
import com.chethan616.clearpdf.ui.glass.GlassIcon
-import com.chethan616.clearpdf.ui.glass.GlassSlider
+import com.chethan616.clearpdf.ui.glass.GlassPill
import com.chethan616.clearpdf.ui.glass.LocalBackdrop
-import com.chethan616.clearpdf.ui.glass.glassBar
+import com.chethan616.clearpdf.ui.glass.LocalHaptics
+import com.chethan616.clearpdf.ui.glass.RoundedRectangle
+import com.chethan616.clearpdf.ui.glass.pressable
import com.chethan616.clearpdf.ui.theme.Candy
import com.chethan616.clearpdf.ui.theme.ClearType
import com.kyant.backdrop.backdrops.layerBackdrop
@@ -60,24 +75,34 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.File
+import kotlin.math.abs
-/** One adjustment of LightCraft's develop settings: its section, field, label and range. */
-private enum class Adjust(val section: String, val field: String, val label: Int, val min: Float, val max: Float) {
- Exposure("light", "exposure", R.string.photo_exposure, -3f, 3f),
- Contrast("light", "contrast", R.string.photo_contrast, -100f, 100f),
- Highlights("light", "highlights", R.string.photo_highlights, -100f, 100f),
- Shadows("light", "shadows", R.string.photo_shadows, -100f, 100f),
- Vibrance("color", "vibrance", R.string.photo_vibrance, -100f, 100f),
- Saturation("color", "saturation", R.string.photo_saturation, -100f, 100f),
+/** One adjustment of LightCraft's develop settings: where it lives, its name, glyph and range. */
+private enum class Adjust(val section: String, val field: String, val label: Int, val icon: ImageVector, val min: Float, val max: Float, val decimals: Int) {
+ Exposure("light", "exposure", R.string.photo_exposure, LucideIcons.Sun, -3f, 3f, 2),
+ Contrast("light", "contrast", R.string.photo_contrast, LucideIcons.Contrast, -100f, 100f, 0),
+ Highlights("light", "highlights", R.string.photo_highlights, LucideIcons.Highlights, -100f, 100f, 0),
+ Shadows("light", "shadows", R.string.photo_shadows, LucideIcons.Shadows, -100f, 100f, 0),
+ Vibrance("color", "vibrance", R.string.photo_vibrance, LucideIcons.Palette, -100f, 100f, 0),
+ Saturation("color", "saturation", R.string.photo_saturation, LucideIcons.Droplet, -100f, 100f, 0),
}
/** The quarter turns LightCraft's orientation names, clockwise from as shot. */
private val TURNS = listOf("Normal", "Rotate90", "Rotate180", "Rotate270")
+/** "+0.40", "−12", "0": signed, as Photos shows an adjustment. */
+private fun shown(a: Adjust, v: Float): String {
+ val zero = if (a.decimals > 0) 0.005f else 0.5f
+ if (abs(v) < zero) return "0"
+ val n = if (a.decimals > 0) "%.${a.decimals}f".format(abs(v)) else abs(v).toInt().toString()
+ return (if (v > 0) "+" else "−") + n
+}
+
/**
- * A note's picture developed with LightCraft: the picture large, glass chips to pick an adjustment
- * and a glass slider for it, a quarter turn, and Done, which saves the developed picture in place of
- * the note's (a new file, so the desk's thumbnails see the change).
+ * A picture developed with LightCraft, the way Photos edits one: the picture large (hold it to see
+ * the original), the chosen adjustment's name and value, a ruler to drag it along (it catches at
+ * zero), and the adjustments as a row of glass dials, each ringed by how far it has moved. Rotate
+ * and Reset at the top; Done saves the developed picture in place of the note's.
*/
@Composable
fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: () -> Unit) {
@@ -88,45 +113,81 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
var turn by remember { mutableStateOf(0) }
var chosen by remember { mutableStateOf(Adjust.Exposure) }
var shown by remember { mutableStateOf<ImageBitmap?>(null) }
+ var original by remember { mutableStateOf<ImageBitmap?>(null) }
+ var comparing by remember { mutableStateOf(false) }
var saving by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
+ val edited = values.values.any { it != 0f } || turn != 0
- fun settings(): String {
+ fun settings(withValues: Boolean = true): String {
val o = JSONObject()
- for ((a, v) in values) if (v != 0f) (o.optJSONObject(a.section) ?: JSONObject().also { o.put(a.section, it) }).put(a.field, v.toDouble())
+ if (withValues) for ((a, v) in values) if (v != 0f) (o.optJSONObject(a.section) ?: JSONObject().also { o.put(a.section, it) }).put(a.field, v.toDouble())
if (turn != 0) o.put("orientation", TURNS[turn])
return o.toString()
}
- // re-develop as the sliders move; a newer value cancels the render still running
+ // re-develop as the ruler moves; a newer value cancels the render still running
LaunchedEffect(Unit) {
snapshotFlow { values.toMap() to turn }.collectLatest {
val json = settings()
shown = withContext(Dispatchers.Default) { runCatching { editor.render(source.absolutePath, json, 1600u).toBitmap().asImageBitmap() }.getOrNull() } ?: shown
}
}
+ // the picture as shot (turned as the edit is), for holding to compare
+ LaunchedEffect(turn) {
+ val json = settings(withValues = false)
+ original = withContext(Dispatchers.Default) { runCatching { editor.render(source.absolutePath, json, 1600u).toBitmap().asImageBitmap() }.getOrNull() }
+ }
val backdrop = rememberLayerBackdrop()
- Box(Modifier.fillMaxSize().background(Color(0xFF0B0C10))) {
- Box(Modifier.fillMaxSize().layerBackdrop(backdrop), contentAlignment = Alignment.Center) {
- shown?.let { Image(it, null, Modifier.fillMaxSize().padding(vertical = 120.dp), contentScale = ContentScale.Fit) }
+ Box(Modifier.fillMaxSize().background(Color.Black)) {
+ Column(Modifier.fillMaxSize().layerBackdrop(backdrop)) {
+ Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars))
+ Spacer(Modifier.height(72.dp))
+ Box(
+ Modifier.weight(1f).fillMaxWidth().padding(horizontal = 16.dp).pointerInput(Unit) {
+ detectTapGestures(onPress = {
+ comparing = true
+ tryAwaitRelease()
+ comparing = false
+ })
+ },
+ contentAlignment = Alignment.Center,
+ ) {
+ (if (comparing) original ?: shown else shown)?.let {
+ Image(it, null, Modifier.clip(RoundedRectangle(14.dp)), contentScale = ContentScale.Fit)
+ }
+ if (comparing) Text(
+ stringResource(R.string.photo_original), style = ClearType.Label, color = Color.White,
+ modifier = Modifier.align(Alignment.TopCenter).padding(top = 10.dp).background(Color.Black.copy(alpha = 0.45f), RoundedRectangle(10.dp)).padding(horizontal = 10.dp, vertical = 4.dp),
+ )
+ }
+ Spacer(Modifier.height(250.dp))
}
+
CompositionLocalProvider(LocalBackdrop provides backdrop) {
+ // the top row: cancel, reset (once something changed), rotate, done
Column(Modifier.fillMaxWidth().align(Alignment.TopCenter)) {
Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars))
- Row(Modifier.fillMaxWidth().padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
+ Row(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) {
GlassCircle(onClick = onClose, label = stringResource(R.string.common_cancel), ink = Color.White) { GlassIcon(LucideIcons.X, null, Modifier.size(20.dp)) }
Spacer(Modifier.weight(1f))
+ if (edited) GlassPill(onClick = { values.clear(); turn = 0 }, height = 40.dp, horizontalPadding = 16.dp) {
+ Text(stringResource(R.string.photo_reset), style = ClearType.Label.copy(fontSize = 14.sp), color = Candy.Lemon)
+ }
+ Spacer(Modifier.width(10.dp))
GlassCircle(onClick = { turn = (turn + 1) % 4 }, label = stringResource(R.string.photo_rotate), ink = Color.White) { GlassIcon(LucideIcons.RotateCw, null, Modifier.size(20.dp)) }
- Spacer(Modifier.size(10.dp))
+ Spacer(Modifier.width(10.dp))
GlassCircle(
onClick = {
if (saving) return@GlassCircle
+ if (!edited) { onClose(); return@GlassCircle }
saving = true
scope.launch {
val out = File(source.parentFile, "edited-${System.currentTimeMillis()}.jpg")
val ok = withContext(Dispatchers.Default) { runCatching { editor.exportJpeg(source.absolutePath, settings(), out.absolutePath, 92u) }.isSuccess }
if (ok) vm.notes.get(noteId)?.let { n -> vm.notes.put(n.copy(images = n.images.map { if (it == name) out.name else it })) }
+ else vm.tell(com.chethan616.clearpdf.text(R.string.photo_not_saved))
saving = false
onClose()
}
@@ -135,29 +196,91 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
) { GlassIcon(LucideIcons.Check, null, Modifier.size(20.dp)) }
}
}
- Column(Modifier.fillMaxWidth().align(Alignment.BottomCenter).padding(horizontal = 12.dp)) {
- Column(Modifier.fillMaxWidth().glassBar(com.chethan616.clearpdf.ui.glass.RoundedRectangle(28.dp)).padding(16.dp)) {
- Text(
- stringResource(chosen.label) + " " + "%.2f".format(values[chosen] ?: 0f).trimEnd('0').trimEnd('.'),
- style = ClearType.Caption.copy(fontSize = 13.sp), color = Color.White.copy(alpha = 0.8f),
- )
- Spacer(Modifier.size(8.dp))
- GlassSlider(values[chosen] ?: 0f, { values[chosen] = it }, range = chosen.min..chosen.max, accent = Candy.Sky)
- Spacer(Modifier.size(12.dp))
- Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- for (a in Adjust.entries) {
- GlassChip(
- onClick = { chosen = a },
- fill = if (a == chosen) ({ Candy.Lemon }) else null,
- ink = if (a == chosen) Color(0xFF172033) else Color.White,
- onLongClick = { values.remove(a) },
- ) { Text(stringResource(a.label), style = ClearType.Body.copy(fontSize = 14.sp)) }
- }
- }
+
+ // the controls: the chosen adjustment's value, its ruler, the dials
+ Column(Modifier.fillMaxWidth().align(Alignment.BottomCenter), horizontalAlignment = Alignment.CenterHorizontally) {
+ val v = values[chosen] ?: 0f
+ Text(stringResource(chosen.label).uppercase(), style = ClearType.Label.copy(fontSize = 12.sp, letterSpacing = 1.4.sp), color = Color.White.copy(alpha = 0.6f))
+ Spacer(Modifier.height(4.dp))
+ Text(shown(chosen, v), style = ClearType.Title.copy(fontSize = 22.sp, fontWeight = FontWeight.SemiBold), color = if (v != 0f) Candy.Lemon else Color.White)
+ Spacer(Modifier.height(10.dp))
+ Ruler(chosen, v) { values[chosen] = it }
+ Spacer(Modifier.height(18.dp))
+ Row(
+ Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 20.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ ) {
+ for (a in Adjust.entries) Dial(a, values[a] ?: 0f, a == chosen) { chosen = a }
}
- Spacer(Modifier.size(8.dp))
+ Spacer(Modifier.height(18.dp))
Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars))
}
}
}
}
+
+/**
+ * An adjustment as a round glass button: its glyph, a ring that fills by how far it has moved (the
+ * chosen one lit in lemon), as Photos draws its adjustment dials.
+ */
+@Composable
+private fun Dial(a: Adjust, value: Float, chosen: Boolean, onClick: () -> Unit) {
+ val span = maxOf(abs(a.min), abs(a.max))
+ val part = (value / span).coerceIn(-1f, 1f)
+ Box(Modifier.size(60.dp).pressable(onClick), contentAlignment = Alignment.Center) {
+ Canvas(Modifier.size(58.dp)) {
+ val stroke = 2.6.dp.toPx()
+ val inset = stroke / 2
+ val box = Size(size.width - stroke, size.height - stroke)
+ drawCircle(Color.White.copy(alpha = if (chosen) 0.16f else 0.08f), radius = size.minDimension / 2)
+ drawArc(Color.White.copy(alpha = 0.22f), 0f, 360f, false, Offset(inset, inset), box, style = Stroke(stroke))
+ if (part != 0f) drawArc(if (chosen) Candy.Lemon else Color.White, -90f, 360f * part, false, Offset(inset, inset), box, style = Stroke(stroke, cap = StrokeCap.Round))
+ }
+ GlassIcon(a.icon, stringResource(a.label), Modifier.size(22.dp), tint = if (chosen) Candy.Lemon else Color.White)
+ }
+}
+
+/**
+ * The value's ruler: ticks across the whole range, the value under the fixed centre line; dragging
+ * moves the ruler, and it catches at zero with a tick of the haptics.
+ */
+@Composable
+private fun Ruler(a: Adjust, value: Float, onChange: (Float) -> Unit) {
+ val haptics = LocalHaptics.current
+ val range = a.max - a.min
+ var drag by remember(a) { mutableStateOf(value) }
+ LaunchedEffect(value) { drag = value }
+ Canvas(
+ Modifier.fillMaxWidth().height(44.dp).pointerInput(a) {
+ // the whole range spans three screen widths
+ val perPx = range / (size.width * 3f)
+ detectHorizontalDragGestures { change, dx ->
+ change.consume()
+ val before = drag
+ var next = (drag - dx * perPx).coerceIn(a.min, a.max)
+ // a catch at zero
+ if (abs(next) < range * 0.012f) next = 0f
+ if ((before != 0f && next == 0f)) haptics?.play(Feel.Tick)
+ drag = next
+ onChange(next)
+ }
+ },
+ ) {
+ val w = size.width * 3f
+ val mid = size.width / 2
+ val t = (drag - a.min) / range
+ val ticks = 60
+ for (i in 0..ticks) {
+ val x = mid + (i.toFloat() / ticks - t) * w
+ if (x < -4 || x > size.width + 4) continue
+ val major = i % 10 == 0
+ val h = if (major) size.height * 0.55f else size.height * 0.32f
+ val fade = (1f - abs(x - mid) / mid).coerceIn(0.15f, 1f)
+ drawLine(Color.White.copy(alpha = (if (major) 0.8f else 0.45f) * fade), Offset(x, (size.height - h) / 2), Offset(x, (size.height + h) / 2), 1.6.dp.toPx(), StrokeCap.Round)
+ }
+ // zero's mark, and the centre line the value sits under
+ val zx = mid + ((0f - a.min) / range - t) * w
+ if (zx in 0f..size.width) drawCircle(Candy.Lemon, 2.4.dp.toPx(), Offset(zx, size.height - 2.dp.toPx()))
+ drawLine(Candy.Lemon, Offset(mid, 0f), Offset(mid, size.height), 2.4.dp.toPx(), StrokeCap.Round)
+ }
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
index 58a3418..0cdeff3 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
@@ -71,6 +71,15 @@ import com.chethan616.clearpdf.ui.theme.clear
import com.kyant.backdrop.backdrops.layerBackdrop
import com.kyant.backdrop.backdrops.rememberLayerBackdrop
import kotlinx.coroutines.flow.distinctUntilChanged
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
+import androidx.compose.foundation.gestures.calculateCentroid
+import androidx.compose.foundation.gestures.calculatePan
+import androidx.compose.foundation.gestures.calculateZoom
+import androidx.compose.animation.core.VectorConverter
+import androidx.compose.ui.input.pointer.positionChanged
+import androidx.compose.ui.geometry.isSpecified
+import androidx.compose.animation.core.animateDecay
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
@@ -269,19 +278,7 @@ fun SheetGrid(
Canvas(
Modifier
.fillMaxSize()
- .pointerInput(l) {
- detectTransformGestures { centroid, move, zoom, _ ->
- val s = (state.scale * zoom).coerceIn(0.4f, 4f)
- val f = s / state.scale
- val k = px * s
- val maxX = (l.colX.last() * k - size.width / 2f).coerceAtLeast(0f)
- val maxY = (l.rowY.last() * k - size.height / 2f).coerceAtLeast(0f)
- // zoom about the fingers, then follow them
- val p = (state.pan - centroid) * f + centroid + move
- state.pan = Offset(p.x.coerceIn(-maxX, 0f), p.y.coerceIn(-maxY, 0f))
- state.scale = s
- }
- }
+ .panZoomFling(state, l, px)
.pointerInput(l, onCell, onDoubleTapCell) {
detectTapGestures(
onTap = { p -> onCell?.invoke(cellAt(p)) },
@@ -676,3 +673,54 @@ private fun DrawScope.drawSheet(
drawLine(lineC, Offset(0f, head.y), Offset(size.width, head.y), 1f)
drawLine(lineC, Offset(head.x, 0f), Offset(head.x, size.height), 1f)
}
+
+/**
+ * Pan and pinch-zoom the grid with a finger or two, and let it glide on when let go, slowing as a
+ * list does (the platform's spline decay), held within the sheet.
+ */
+private fun Modifier.panZoomFling(state: SheetGridState, l: SheetLayout, px: Float): Modifier = pointerInput(l) {
+ val decay = androidx.compose.animation.splineBasedDecay<Offset>(this)
+ fun clamp(p: Offset, s: Float): Offset {
+ val k = px * s
+ val maxX = (l.colX.last() * k - size.width / 2f).coerceAtLeast(0f)
+ val maxY = (l.rowY.last() * k - size.height / 2f).coerceAtLeast(0f)
+ return Offset(p.x.coerceIn(-maxX, 0f), p.y.coerceIn(-maxY, 0f))
+ }
+ kotlinx.coroutines.coroutineScope {
+ var glide: kotlinx.coroutines.Job? = null
+ awaitEachGesture {
+ awaitFirstDown(requireUnconsumed = false)
+ glide?.cancel()
+ val tracker = androidx.compose.ui.input.pointer.util.VelocityTracker()
+ var pinched = false
+ do {
+ val event = awaitPointerEvent()
+ val zoom = event.calculateZoom()
+ val move = event.calculatePan()
+ val centroid = event.calculateCentroid(useCurrent = true)
+ if (zoom != 1f) pinched = true
+ if (zoom != 1f || move != Offset.Zero) {
+ val s = (state.scale * zoom).coerceIn(0.4f, 4f)
+ val f = s / state.scale
+ // zoom about the fingers, then follow them
+ val origin = if (centroid.isSpecified) centroid else Offset.Zero
+ state.pan = clamp((state.pan - origin) * f + origin + move, s)
+ state.scale = s
+ event.changes.forEach { if (it.positionChanged()) it.consume() }
+ }
+ event.changes.firstOrNull()?.let { tracker.addPosition(it.uptimeMillis, it.position) }
+ } while (event.changes.any { it.pressed })
+ if (!pinched) {
+ val v = tracker.calculateVelocity()
+ glide = launch {
+ androidx.compose.animation.core.AnimationState(Offset.VectorConverter, state.pan, Offset(v.x, v.y))
+ .animateDecay(decay) {
+ val next = clamp(value, state.scale)
+ state.pan = next
+ if (next != value) cancelAnimation()
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageMenu.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageMenu.kt
index d7e8074..36f44be 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageMenu.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageMenu.kt
@@ -26,6 +26,8 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
+import com.kyant.backdrop.floatingLayer
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
@@ -68,49 +70,48 @@ fun PageMenuView(vm: AppViewModel, menu: PageMenu) {
// 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(
+ // the selection menu's frosted glass and unfold (ViewerOverlays), out of the finger
+ val appear = remember { androidx.compose.animation.core.Animatable(0f) }
+ LaunchedEffect(Unit) { appear.animateTo(1f, com.chethan616.clearpdf.ui.glass.GlassMotion.unfold()) }
+ val opensDown = y > menu.screen.y
+ com.chethan616.clearpdf.ui.glass.GlassCard(
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))
+ .width(236.dp)
+ .floatingLayer {
+ val p = appear.value
+ scaleX = 0.6f + 0.4f * p
+ scaleY = 0.4f + 0.6f * p
+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, if (opensDown) 0f else 1f)
+ alpha = (p * 1.6f).coerceIn(0f, 1f)
+ }
.pointerInput(Unit) { detectTapGestures { } },
+ shape = com.chethan616.clearpdf.ui.glass.RoundedRectangle(24.dp),
+ wash = com.chethan616.clearpdf.ui.theme.clear.frost,
+ blur = 16.dp,
) {
- Row(Modifier.fillMaxWidth().height(61.dp), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
- PageMenuIcon(LucideIcons.MessageSquarePlus, stringResource(R.string.page_menu_add_comment), annotate) { close(); vm.notePrompt = NotePrompt(doc, menu.at) }
- PageMenuIcon(LucideIcons.Pencil, stringResource(R.string.common_tool_draw), annotate) { close(); vm.enterTool(doc, ViewerTool.Draw) }
- PageMenuIcon(LucideIcons.Type, stringResource(R.string.page_menu_add_text), annotate) { close(); vm.textPrompt = TextPrompt(doc, menu.at) }
- if (fill) PageMenuIcon(LucideIcons.Signature, stringResource(R.string.common_sign), true) { close(); vm.enterTool(doc, ViewerTool.FillSign) }
+ Spacer(Modifier.height(6.dp))
+ if (doc.isOffice) {
+ // a Word document, slides or a sheet: its own tools, not the PDF ones
+ if (!doc.isSlides && !doc.isSheets) MenuRow(LucideIcons.FilePenLine, stringResource(R.string.word_edit)) { close(); vm.startWordEdit(doc) }
+ MenuRow(LucideIcons.Volume2, stringResource(R.string.common_tool_read_aloud)) { close(); vm.startReadAloud(doc) }
+ MenuRow(LucideIcons.FilePdf, stringResource(R.string.office_export_pdf)) { close(); vm.exportOffice(doc, "pdf") }
+ } else {
+ Row(Modifier.fillMaxWidth().height(56.dp), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
+ MenuIcon(LucideIcons.MessageSquarePlus, stringResource(R.string.page_menu_add_comment), annotate) { close(); vm.notePrompt = NotePrompt(doc, menu.at) }
+ MenuIcon(LucideIcons.Pencil, stringResource(R.string.common_tool_draw), annotate) { close(); vm.enterTool(doc, ViewerTool.Draw) }
+ MenuIcon(LucideIcons.Type, stringResource(R.string.page_menu_add_text), annotate) { close(); vm.textPrompt = TextPrompt(doc, menu.at) }
+ if (fill) MenuIcon(LucideIcons.Signature, stringResource(R.string.common_sign), true) { close(); vm.enterTool(doc, ViewerTool.FillSign) }
+ }
+ Box(Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(1.dp).background(com.chethan616.clearpdf.ui.theme.clear.ink.copy(alpha = 0.12f)))
+ Spacer(Modifier.height(4.dp))
+ if (!menu.pageHasText) MenuRow(LucideIcons.ScanText, stringResource(R.string.common_tool_recognize_text)) { close(); vm.recognizeText(doc) }
+ MenuRow(LucideIcons.Crop, stringResource(R.string.common_tool_crop)) { close(); vm.openCrop(doc) }
+ MenuRow(LucideIcons.FilePenLine, stringResource(R.string.common_tool_edit_pdf)) { close(); vm.enterTool(doc, ViewerTool.Edit) }
+ MenuRow(LucideIcons.ImagePlus, stringResource(R.string.page_menu_add_image)) { close(); vm.addImageAt(doc, menu.at) }
}
- Box(Modifier.fillMaxWidth().padding(horizontal = 4.dp).height(1.dp).background(c.divider))
- Spacer(Modifier.height(8.dp))
- 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) }
- PageMenuRow(LucideIcons.ImagePlus, stringResource(R.string.page_menu_add_image)) { close(); vm.addImageAt(doc, menu.at) }
- Spacer(Modifier.height(8.dp))
+ Spacer(Modifier.height(6.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/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt
index b0402aa..d79c231 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt
@@ -254,7 +254,7 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)
}
@Composable
-private fun MenuIcon(icon: ImageVector, label: String, enabled: Boolean, onClick: () -> Unit) {
+internal fun MenuIcon(icon: ImageVector, label: String, enabled: Boolean, onClick: () -> Unit) {
val ink = clear.ink
Box(
Modifier.size(48.dp).clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = label },
@@ -265,7 +265,7 @@ private fun MenuIcon(icon: ImageVector, label: String, enabled: Boolean, onClick
}
@Composable
-private fun MenuRow(icon: ImageVector, label: String, onClick: () -> Unit) {
+internal fun MenuRow(icon: ImageVector, label: String, onClick: () -> Unit) {
val c = clear
// as the desk menu's rows: the label, its glyph at the end
Row(Modifier.fillMaxWidth().pressable(onClick).padding(horizontal = 16.dp, vertical = 11.dp), verticalAlignment = Alignment.CenterVertically) {
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt
index 1554e2e..d1c4c96 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt
@@ -258,7 +258,8 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {
},
onWheelZoom = { if (desktop) zoomButtons.poke() },
onLongPress = { p, at ->
- if (at != null) scope.launch {
+ if (at != null && vm.wordEditing == doc) vm.wordSelectWord(doc, at)
+ else if (at != null) scope.launch {
val slop = 12f / doc.viewer.pixelsPerPoint(at.page).coerceAtLeast(0.1f) * density.density
// 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)
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt
index 4962c0e..999d6e1 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt
@@ -13,6 +13,7 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
@@ -97,10 +98,29 @@ fun WordEditLayer(vm: AppViewModel, doc: OpenDocument) {
val focus = remember { FocusRequester() }
val keyboard = LocalSoftwareKeyboardController.current
var field by remember { mutableStateOf(TextFieldValue(SENTINEL, TextRange(SENTINEL.length))) }
- LaunchedEffect(Unit) {
+ // every tap that places the caret brings the keyboard up, focused on the field
+ LaunchedEffect(vm.wordKeyboard) {
+ if (vm.wordKeyboard == 0) return@LaunchedEffect
focus.requestFocus()
keyboard?.show()
}
+ // the caret kept in sight above the keyboard (and below the top bar)
+ val ime = androidx.compose.foundation.layout.WindowInsets.ime
+ val dens = androidx.compose.ui.platform.LocalDensity.current
+ val imeBottom = ime.getBottom(dens)
+ LaunchedEffect(caret, imeBottom) {
+ val c = caret ?: return@LaunchedEffect
+ if (c.selection.isNotEmpty()) return@LaunchedEffect
+ val v = doc.viewer
+ val bottom = v.pageToScreen(c.page.toInt(), c.x, c.top + c.height).y
+ val top = v.pageToScreen(c.page.toInt(), c.x, c.top).y
+ val room = v.viewH - imeBottom - with(dens) { 96.dp.toPx() }
+ when {
+ // scrollBy takes a finger's move: the page goes up as a finger moving up takes it
+ bottom > room -> v.scrollBy(0f, -(bottom - room))
+ top < v.padTop -> v.scrollBy(0f, v.padTop - top)
+ }
+ }
DisposableEffect(Unit) { onDispose { keyboard?.hide() } }
BasicTextField(
value = field,
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 4cd6665..f2f390d 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -975,6 +975,8 @@
<string name="sheet_insert_column">Insert column</string>
<string name="sheet_clear">Clear contents</string>
<string name="word_undo">Undo</string>
+ <string name="word_edit">Edit document</string>
+ <string name="word_tap_to_type">Tap where you want to type. Long press a word to select it.</string>
<string name="word_redo">Redo</string>
<string name="word_bold">Bold</string>
<string name="word_italic">Italic</string>
@@ -1014,6 +1016,10 @@
<string name="photo_saturation">Saturation</string>
<string name="photo_rotate">Rotate</string>
<string name="photo_edit">Edit picture</string>
+ <string name="msg_ppt_text_only">This PowerPoint 97–2003 file shows its slides\' text. Saved as .pptx, it opens with its pictures and layout.</string>
+ <string name="photo_original">Original</string>
+ <string name="photo_reset">Reset</string>
+ <string name="photo_not_saved">The picture couldn\'t be saved.</string>
<!-- Draw tool: lines drawn are turned into neat shapes. -->
<string name="msg_snap_to_shape_on">Snap to shape on</string>
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 468928b..a9a7bdd 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -128,6 +128,7 @@ name = "artefact-mobile"
version = "0.14.0"
dependencies = [
"android_logger",
+ "cfb",
"deckcraft-model",
"deckcraft-pdf",
"deckcraft-pptx",
diff --git a/engine/mobile/Cargo.toml b/engine/mobile/Cargo.toml
index 7f7598b..e6d5a3f 100644
--- a/engine/mobile/Cargo.toml
+++ b/engine/mobile/Cargo.toml
@@ -27,6 +27,8 @@ deckcraft-model = { workspace = true }
deckcraft-pptx = { workspace = true }
deckcraft-render = { workspace = true }
deckcraft-pdf = { workspace = true }
+# PowerPoint 97-2003 (src/ppt.rs): the compound file holding its record stream (already in the tree)
+cfb = "0.15"
# Excel workbooks (src/sheets.rs): GridCraft's engine
gridcraft-engine = { workspace = true }
gridcraft-xlsx = { workspace = true }
diff --git a/engine/mobile/src/lib.rs b/engine/mobile/src/lib.rs
index c0e1df8..a55c245 100644
--- a/engine/mobile/src/lib.rs
+++ b/engine/mobile/src/lib.rs
@@ -27,6 +27,7 @@ uniffi::setup_scaffolding!();
mod office;
mod photo;
+mod ppt;
mod sheets;
mod slides;
diff --git a/engine/mobile/src/office.rs b/engine/mobile/src/office.rs
index 23c5a02..d4aaf50 100644
--- a/engine/mobile/src/office.rs
+++ b/engine/mobile/src/office.rs
@@ -66,7 +66,7 @@ pub(crate) enum OfficeFile {
Word(&'static str),
Slides,
Sheets(&'static str),
- /// A PowerPoint 97-2003 presentation (.ppt), which no engine reads yet.
+ /// A PowerPoint 97-2003 presentation (.ppt): its slides' text (see `ppt.rs`).
LegacySlides,
}
@@ -125,7 +125,7 @@ pub(crate) fn sniff(bytes: &[u8], path: &str) -> Option<OfficeFile> {
if contains(&utf16("Workbook")) || (contains(&utf16("Book")) && sheets_named.is_some()) {
return Some(OfficeFile::Sheets(if sheets_named == Some("xlt") { "xlt" } else { "xls" }));
}
- // PowerPoint 97-2003: no reader yet, told as such rather than as a damaged file
+ // PowerPoint 97-2003
if contains(&utf16("PowerPoint Document")) {
return Some(OfficeFile::LegacySlides);
}
@@ -194,11 +194,8 @@ pub(crate) fn open(
OfficeFile::Word(ext) => Arc::new(crate::word::WordDocument::open(path, ext, bytes, password, locale)?),
OfficeFile::Slides => Arc::new(crate::slides::SlideDeck::open(path, bytes)?),
OfficeFile::Sheets(ext) => Arc::new(crate::sheets::SheetBook::open(path, ext, bytes, password)?),
- OfficeFile::LegacySlides => {
- return Err(MobileError::Open(
- "This is a PowerPoint 97-2003 presentation (.ppt), which Artefact can't open yet. Saved as .pptx (PowerPoint, Keynote, Google Slides or LibreOffice can), it opens here.".into(),
- ));
- }
+ // its slides' text, read by Artefact's own .ppt reader (DeckCraft reads .pptx only)
+ OfficeFile::LegacySlides => Arc::new(crate::slides::SlideDeck::open_ppt(path, bytes)?),
})
}
diff --git a/engine/mobile/src/ppt.rs b/engine/mobile/src/ppt.rs
new file mode 100644
index 0000000..c5293f5
--- /dev/null
+++ b/engine/mobile/src/ppt.rs
@@ -0,0 +1,229 @@
+//! PowerPoint 97-2003 presentations (.ppt), which DeckCraft doesn't read: their slides' text, read
+//! from the binary file's outline ([MS-PPT] `SlideListWithText`), set in a DeckCraft presentation
+//! of the file's slide size with Title and Content slides, so they open, draw, search and export
+//! like any deck. Pictures, shapes and the original layout are not carried over.
+
+use std::io::Read;
+use std::sync::Arc;
+
+use deckcraft_model::text::TextBody;
+use deckcraft_model::{LayoutType, PhType, Presentation};
+
+/// The most records read and the deepest nesting followed (a hostile file can claim anything).
+const MAX_RECORDS: usize = 500_000;
+const MAX_DEPTH: usize = 16;
+/// The most slides made.
+const MAX_SLIDES: usize = 2_000;
+
+const DOCUMENT_ATOM: u16 = 0x03E9;
+const SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0;
+const SLIDE_PERSIST_ATOM: u16 = 0x03F3;
+const TEXT_HEADER_ATOM: u16 = 0x0F9F;
+const TEXT_CHARS_ATOM: u16 = 0x0FA0;
+const TEXT_BYTES_ATOM: u16 = 0x0FA8;
+
+/// One slide's text: its title, and the rest (body, subtitle, other text) in order.
+#[derive(Default, Debug, PartialEq)]
+struct SlideText {
+ title: String,
+ body: Vec<String>,
+}
+
+#[derive(Default)]
+struct Outline {
+ /// The slide size in master units (576 to the inch).
+ size: Option<(i32, i32)>,
+ slides: Vec<SlideText>,
+}
+
+/// One record's header: its type, whether it holds other records, and its body.
+struct Record<'a> {
+ kind: u16,
+ instance: u16,
+ container: bool,
+ body: &'a [u8],
+}
+
+fn records(data: &[u8]) -> impl Iterator<Item = Record<'_>> {
+ let mut at = 0usize;
+ std::iter::from_fn(move || {
+ let head = data.get(at..at.checked_add(8)?)?;
+ let ver_inst = u16::from_le_bytes([head[0], head[1]]);
+ let kind = u16::from_le_bytes([head[2], head[3]]);
+ let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
+ let start = at + 8;
+ let end = start.checked_add(len)?.min(data.len());
+ at = start.checked_add(len)?;
+ Some(Record { kind, instance: ver_inst >> 4, container: ver_inst & 0xF == 0xF, body: data.get(start..end)? })
+ })
+}
+
+/// The text of a slide list: a new slide at each persist atom, each text after the header saying
+/// what kind of text it is.
+fn read_slide_list(body: &[u8], out: &mut Outline, budget: &mut usize) {
+ let mut kind = 1u32;
+ for r in records(body) {
+ if *budget == 0 || out.slides.len() > MAX_SLIDES {
+ return;
+ }
+ *budget -= 1;
+ match r.kind {
+ SLIDE_PERSIST_ATOM => out.slides.push(SlideText::default()),
+ TEXT_HEADER_ATOM => kind = r.body.get(..4).map_or(1, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
+ TEXT_CHARS_ATOM | TEXT_BYTES_ATOM => {
+ let text = if r.kind == TEXT_CHARS_ATOM {
+ let units: Vec<u16> = r.body.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect();
+ String::from_utf16_lossy(&units)
+ } else {
+ // Windows-1252 for the common range; the rest as Latin-1
+ r.body.iter().map(|&b| char::from(b)).collect()
+ };
+ // paragraphs end in CR; a vertical tab is a line break inside one
+ let text = text.replace('\u{b}', "\n");
+ let Some(slide) = out.slides.last_mut() else { continue };
+ match kind {
+ // title, centred title
+ 0 | 6 => {
+ if !slide.title.is_empty() {
+ slide.title.push(' ');
+ }
+ slide.title.push_str(text.trim_end_matches('\r'));
+ }
+ // notes are not slide text
+ 2 => {}
+ _ => slide.body.extend(text.split('\r').map(str::to_string)),
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+fn walk(data: &[u8], depth: usize, out: &mut Outline, budget: &mut usize) {
+ for r in records(data) {
+ if *budget == 0 {
+ return;
+ }
+ *budget -= 1;
+ match r.kind {
+ DOCUMENT_ATOM if out.size.is_none() => {
+ if let Some(b) = r.body.get(..8) {
+ out.size = Some((i32::from_le_bytes([b[0], b[1], b[2], b[3]]), i32::from_le_bytes([b[4], b[5], b[6], b[7]])));
+ }
+ }
+ // instance 0: the slides (1 is the masters, 2 the notes)
+ SLIDE_LIST_WITH_TEXT if r.instance == 0 => read_slide_list(r.body, out, budget),
+ _ if r.container && depth < MAX_DEPTH => walk(r.body, depth + 1, out, budget),
+ _ => {}
+ }
+ }
+}
+
+/// The outline of the .ppt file `bytes`.
+fn outline(bytes: &[u8]) -> Result<Outline, String> {
+ let mut cfb = cfb::CompoundFile::open(std::io::Cursor::new(bytes)).map_err(|e| format!("not a PowerPoint 97-2003 file: {e}"))?;
+ let mut stream = cfb.open_stream("PowerPoint Document").map_err(|_| "the file has no PowerPoint Document stream".to_string())?;
+ let mut data = Vec::new();
+ // the stream is read in full but never past 512 MB
+ stream.by_ref().take(512 << 20).read_to_end(&mut data).map_err(|e| e.to_string())?;
+ let mut out = Outline::default();
+ let mut budget = MAX_RECORDS;
+ walk(&data, 0, &mut out, &mut budget);
+ Ok(out)
+}
+
+/// A DeckCraft presentation holding the slides' text of the .ppt file `bytes`.
+pub(crate) fn import(bytes: &[u8]) -> Result<Presentation, String> {
+ let o = outline(bytes)?;
+ // master units are 576 to the inch: points are an eighth of them
+ let (w, h) = o.size.filter(|(w, h)| *w > 0 && *h > 0).map_or((720.0, 540.0), |(w, h)| (f64::from(w) / 8.0, f64::from(h) / 8.0));
+ let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::Size::new(w, h), Default::default(), false);
+ let content = deckcraft_model::defaults::layout_of_kind(&p, LayoutType::TitleAndContent);
+ let title_only = deckcraft_model::defaults::layout_of_kind(&p, LayoutType::TitleOnly).or(content);
+ for s in o.slides.into_iter().take(MAX_SLIDES) {
+ let body: Vec<String> = s.body.into_iter().filter(|l| !l.trim().is_empty()).collect();
+ let Some(layout) = (if body.is_empty() { title_only } else { content }) else { break };
+ let Some(mut slide) = deckcraft_model::defaults::new_slide(&mut p, layout) else { break };
+ for shape in &mut slide.shapes {
+ let Some(ph) = &shape.ph else { continue };
+ match ph.kind {
+ PhType::Title | PhType::CtrTitle => shape.text = Some(TextBody::from_text(&s.title)),
+ PhType::Body | PhType::Obj | PhType::SubTitle => shape.text = Some(TextBody::from_text(&body.join("\n"))),
+ _ => {}
+ }
+ }
+ p.slides.push(Arc::new(slide));
+ }
+ if p.slides.is_empty() {
+ return Err("no slides were found in this PowerPoint 97-2003 file".into());
+ }
+ Ok(p)
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+
+ fn record(kind: u16, instance: u16, container: bool, body: &[u8]) -> Vec<u8> {
+ let ver = if container { 0xF } else { 0 };
+ let mut out = ((instance << 4) | ver).to_le_bytes().to_vec();
+ out.extend(kind.to_le_bytes());
+ out.extend((body.len() as u32).to_le_bytes());
+ out.extend(body);
+ out
+ }
+
+ /// A .ppt file of two slides: a title with a subtitle, and a title with two bullets.
+ pub(crate) fn sample_ppt() -> Vec<u8> {
+ let header = |t: u32| record(TEXT_HEADER_ATOM, 0, false, &t.to_le_bytes());
+ let chars = |s: &str| record(TEXT_CHARS_ATOM, 0, false, &s.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>());
+ let bytes = |s: &str| record(TEXT_BYTES_ATOM, 0, false, s.as_bytes());
+ let mut list = Vec::new();
+ list.extend(record(SLIDE_PERSIST_ATOM, 0, false, &[0; 20]));
+ list.extend(header(6));
+ list.extend(chars("Quarterly review"));
+ list.extend(header(5));
+ list.extend(bytes("Sales and plans"));
+ list.extend(record(SLIDE_PERSIST_ATOM, 0, false, &[0; 20]));
+ list.extend(header(0));
+ list.extend(chars("Highlights"));
+ list.extend(header(1));
+ list.extend(chars("Revenue up 36 %\rTwo new markets"));
+ let mut atom = 5760i32.to_le_bytes().to_vec();
+ atom.extend(4320i32.to_le_bytes());
+ atom.extend([0u8; 32]);
+ let mut doc = record(DOCUMENT_ATOM, 0, false, &atom);
+ doc.extend(record(SLIDE_LIST_WITH_TEXT, 0, true, &list));
+ let stream = record(0x03E8, 0, true, &doc);
+ let mut cfb = cfb::CompoundFile::create(std::io::Cursor::new(Vec::new())).unwrap();
+ {
+ use std::io::Write;
+ let mut s = cfb.create_stream("PowerPoint Document").unwrap();
+ s.write_all(&stream).unwrap();
+ }
+ cfb.into_inner().into_inner()
+ }
+
+ #[test]
+ fn reads_the_slides_text_and_size() {
+ let o = outline(&sample_ppt()).unwrap();
+ assert_eq!(o.size, Some((5760, 4320)));
+ assert_eq!(o.slides.len(), 2);
+ assert_eq!(o.slides[0].title, "Quarterly review");
+ assert_eq!(o.slides[0].body, ["Sales and plans"]);
+ assert_eq!(o.slides[1].body, ["Revenue up 36 %", "Two new markets"]);
+ let p = import(&sample_ppt()).unwrap();
+ assert_eq!(p.slides.len(), 2);
+ assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0));
+ }
+
+ #[test]
+ fn a_damaged_record_stream_ends_quietly() {
+ let mut o = Outline::default();
+ let mut budget = MAX_RECORDS;
+ // a container claiming more bytes than there are
+ walk(&[0x0F, 0, 0xE8, 0x03, 0xFF, 0xFF, 0xFF, 0x7F, 1, 2], 0, &mut o, &mut budget);
+ assert!(o.slides.is_empty());
+ assert!(import(b"not a compound file").is_err());
+ }
+}
diff --git a/engine/mobile/src/slides.rs b/engine/mobile/src/slides.rs
index 8dcb0bf..02d7e95 100644
--- a/engine/mobile/src/slides.rs
+++ b/engine/mobile/src/slides.rs
@@ -29,14 +29,24 @@ impl SlideDeck {
return Err(MobileError::Open("password-protected presentations can't be opened yet".into()));
}
let pres = deckcraft_pptx::import(bytes).map_err(|e| MobileError::Open(e.to_string()))?;
+ Ok(Self::of(path, pres, bytes.len()))
+ }
+
+ /// A PowerPoint 97-2003 presentation (.ppt): its slides' text in a deck of its size.
+ pub(crate) fn open_ppt(path: &str, bytes: &[u8]) -> Result<SlideDeck, MobileError> {
+ let pres = crate::ppt::import(bytes).map_err(MobileError::Open)?;
+ Ok(Self::of(path, pres, bytes.len()))
+ }
+
+ fn of(path: &str, pres: Presentation, size: usize) -> SlideDeck {
let n = pres.slides.len();
- Ok(SlideDeck {
+ SlideDeck {
pres: Arc::new(pres),
name: crate::office::file_name(path),
path: path.to_string(),
- file_size: bytes.len() as u64,
+ file_size: size as u64,
texts: Mutex::new(vec![None; n]),
- })
+ }
}
fn slide(&self, page: u32) -> Result<usize, MobileError> {
diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rs
index 19ab954..66f9a79 100644
--- a/engine/mobile/src/tests.rs
+++ b/engine/mobile/src/tests.rs
@@ -712,3 +712,15 @@ fn a_word_document_is_typed_in_formatted_undone_and_saved() {
assert_eq!(s.page_plain_text(again, 0).unwrap().trim(), "Hello world, again");
assert!(s.word_command(id, "no.such.command".into(), String::new()).is_err());
}
+
+#[test]
+fn a_powerpoint_97_2003_file_opens_with_its_slides_text() {
+ let s = MobileSession::new();
+ let path = scratch().join("Old.ppt");
+ std::fs::write(&path, crate::ppt::tests::sample_ppt()).unwrap();
+ let info = s.open(path.to_string_lossy().into_owned(), None).unwrap();
+ assert_eq!(info.kind, DocumentKind::Slides);
+ assert_eq!(info.pages.len(), 2);
+ assert_eq!(s.find_in_page(info.id, 1, "new markets".into(), false, false).unwrap().len(), 1);
+ assert!(s.render_page(info.id, 0, 0.5, None).is_ok());
+}