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.

Mind map notes, photo editor tools, sheet ranges and charts, pictures and OPML

chethan61651b02e551436
diff --git a/CODE.md b/CODE.md
new file mode 100644
index 0000000..5f7ae51
--- /dev/null
+++ b/CODE.md
@@ -0,0 +1,106 @@
+# Artefact code guide
+
+How the code is laid out and the rules it is written to. For how screens should look and move, see
+[DESIGN.md](DESIGN.md).
+
+## The two halves
+
+```
+android/ the app: Kotlin, Jetpack Compose
+ app/src/main/java/com/chethan616/clearpdf/
+ engine/ the bridge to the Rust engine, files, thumbnails, document types
+ notes/ the notes store (notes.json), voice notes, audio export
+ preview/ Quick Preview: the card other apps open files into
+ ui/ every screen
+ glass/ liquid glass components, motion, haptics, adaptive luminance
+ theme/ colours (Candy, CardTone) and type (ClearType)
+ home/ the desk and its cards
+ desk/ Tools, Files, Settings
+ viewer/ the PDF and document viewer and its tools
+ sheets/ the spreadsheet viewer
+ notes/ the note editor, photo editor, mind map
+ backdrop/ Kyant's backdrop library (vendored, Apache-2.0)
+engine/ the engine: Rust
+ crates/ pdfcraft (PDF: model, render, edit, sign, OCR …)
+ mobile/ artefact-mobile: the one library the app loads (UniFFI)
+ vendor/ patched copies of upstream crates (see engine/vendor/README.md)
+```
+
+The app never parses a document itself. It asks the engine through `MobileSession` (generated
+Kotlin bindings, built by Gradle from `engine/mobile`). Office files go through the storytold
+engines: WordCraft (Word, Markdown, text), DeckCraft (PowerPoint), GridCraft (spreadsheets) and
+LightCraft (photos). Legacy formats GridCraft or DeckCraft skip are read in `engine/mobile`
+(`ppt.rs` for .ppt drawings, `xls_art.rs` for .xls pictures and charts).
+
+## Hard rules
+
+These are checked by CI or by review, and a pull request that breaks one is not merged.
+
+1. **Offline.** The app has no internet permission and never will. CI fails if the built APK asks
+ for `INTERNET`. No analytics, no crash reporting, no fonts or images from the network.
+2. **No English in Kotlin.** Every word a person sees is a string resource. `UiTextTest` fails on
+ text in code. New strings go into `values/strings.xml` and every `values-xx` folder.
+3. **Engine code is clean.** `cargo fmt`, `cargo clippy` with no warnings, and
+ `cargo test -p artefact-mobile` pass. The engine crates deny `unwrap`, `expect` and `panic` in
+ library code: return a `MobileError` instead.
+4. **App code builds and tests.** `./gradlew :app:testDebugUnitTest` passes.
+5. **Credit.** Every library, font, icon set or sample file is listed in `ATTRIBUTION.toml`,
+ `ATTRIBUTION.md` and the app's licences page.
+
+## Writing Kotlin
+
+- Compose, state in `mutableStateOf`, one `AppViewModel` for app-wide state. Screens take the view
+ model and read what they need.
+- Long work runs on `Dispatchers.Default` or `IO` (the engine call wrappers `eng.command { }` do
+ this). Nothing heavy on the main thread; a frame is 8ms on a 120Hz phone.
+- Name things for what they are to a person: `finishTyping`, `pickShape`, `Placement`, not
+ `handleInput2` or `Manager`.
+- Comments say what a thing is or why it is done that way, in plain sentences, above the code.
+ A KDoc on every public or non-obvious function. No commented-out code.
+- Match the file you are in. If it uses fully qualified names for a one-off import, so can you.
+- Shared UI goes in `ui/glass/` only if two screens use it. Otherwise keep it private to its file.
+- Pointer input that reads state: read through `rememberUpdatedState` or a state delegate, never
+ a value captured at the first composition (that bug made the sheet tap the wrong cell).
+
+## Writing Rust
+
+- Follow the crate you are in. `engine/mobile` is the only crate with UniFFI types
+ (`#[derive(uniffi::Record)]`, `#[uniffi::export]`).
+- Read untrusted files defensively: bounds-checked reads (`u16_at`, `get(..)`), a budget on
+ records, depth and bytes, and no allocation sized by a number the file gave you.
+- Tests go in `engine/mobile/src/tests.rs` (or the crate's own `tests` module). A bug fix comes with
+ a test that failed before it. Small fixture files live in `engine/mobile/tests/data/`.
+- A patch to a vendored crate is marked `Artefact patch` and noted in `engine/vendor/README.md`.
+
+## Adding things
+
+- **A tool:** first check it is not already part of a tool (see DESIGN.md). Then a `ToolDef` in
+ `ui/desk/Common.kt`, its screen in `ui/ToolScreens.kt` following the tool page pattern, and the
+ work in `AppViewModel`.
+- **A file type:** `engine/DocumentTypes.kt` (types, extensions, kind), the intent filters in
+ `AndroidManifest.xml`, the engine's sniffing in `engine/mobile/src/office.rs`, a thumbnail in
+ `engine/LocalFiles.kt`, and Quick Preview.
+- **A setting:** `GlassSettings` / `MotionSettings` or the app preferences, a `SettingRow`, and a
+ string in every language.
+- **A note kind:** `NoteKind` in `notes/Notes.kt`, its card in `ui/home/Cards.kt`, its editor routed
+ from `NoteEditor`, and its entry in the create menu (`ui/home/CreateDock.kt`).
+
+## Building and releasing
+
+- Debug build for a phone: `./gradlew :app:assembleFast -Partefact.abis=arm64-v8a`. It installs as
+ `com.chethan616.clearpdf.debug`, beside the release.
+- Versions live in `android/gradle.properties` (`artefact.version`, `artefact.versionCode`). The
+ version code of an APK is the base times ten plus an ABI digit (armeabi-v7a 1, arm64-v8a 2,
+ x86_64 3, x86 4, universal 0).
+- A release is a tag `vX.Y.Z[-alpha.N]`; the release workflow builds and signs one APK per ABI.
+ Each needs a changelog in `fastlane/metadata/android/en-US/changelogs/<versionCode>.txt`
+ (500 characters at most).
+- F-Droid builds the same tag and checks its APKs are identical to ours (reproducible builds), so
+ the build must not depend on the machine: pinned Gradle, Rust toolchain, NDK and cargo-ndk.
+
+## Commits and pull requests
+
+- One change per pull request, described in plain words, with screenshots for anything visible.
+- Commit messages say what changed for a person using the app ("Spreadsheet charts are drawn"),
+ not which files moved.
+- Pull requests are reviewed by the code owner (`.github/CODEOWNERS`) and CI must be green.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f5ec6f4..e2c8dcb 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -11,10 +11,23 @@ Thanks for helping! Bug reports, ideas and focused pull requests are all welcome
See [Build from source](README.md#build-from-source). The app is in `android/` (Kotlin, Jetpack Compose); the engine is in `engine/` (Rust). Run `cargo test -p artefact-mobile` in `engine/` after engine changes, and fix every warning (`cargo clippy`).
-## Style
+## Design and code rules
+Read these two before you change anything people see or anything in the engine:
+
+- **[DESIGN.md](DESIGN.md)**: colour, typography, liquid glass, motion, haptics, layout and the screen patterns to reuse.
+- **[CODE.md](CODE.md)**: how the app and the engine are laid out, the hard rules, and how to add a tool, a file type, a setting or a note kind.
+
+The short version:
+
+- **Typography.** All interface text is Plus Jakarta Sans through `ClearType` (`Headline`, `Title`, `Body`, `Label`, `Caption` …). No raw `fontSize` on a `Text`, and no new typefaces.
+- **Colour.** Accents come from `Candy` (`Candy.Sky` is the action colour, `Candy.Tomato` is for deleting); surfaces use `clear.ink*` and the card tones. No hex colours in screens. Check light and dark themes.
+- **Liquid glass.** Floating chrome is built from the glass components in `ui/glass/` (`GlassCircle`, `GlassPill`, `glassBar()`, `GlassMenu`, `GlassDialog` …) over a `layerBackdrop`. They read the user's Settings ▸ Liquid glass & motion (frost, lens, tint, adaptive luminance), so never fake glass with a translucent colour or hard-code a `GlassStyle`.
+- **Motion and haptics.** Use the named springs (`GlassMotion`, `Fluid`) and `Feel`s, so the user's motion settings apply. Sliders tick; menus unfold beside their button.
+- **Words.** Every string is in `res/values/strings.xml` and in every `values-xx` translation. The `UiTextTest` unit test fails on English written in Kotlin.
+- **Offline.** No internet permission, ever. CI checks the built APK.
+- **No duplicate tools.** If an existing tool already does it (PDF to text is in Export, text to PDF in Create PDF), add it there instead of a new tile.
- Match the code around your change: naming, comment density and idiom.
-- UI uses the glass components in `android/app/src/main/java/com/chethan616/clearpdf/ui/glass/` and strings in `res/values/strings.xml`.
- Every third-party asset or library is credited in `ATTRIBUTION.toml` / `ATTRIBUTION.md` and the app's licences page.
## Licence
diff --git a/DESIGN.md b/DESIGN.md
new file mode 100644
index 0000000..f116a76
--- /dev/null
+++ b/DESIGN.md
@@ -0,0 +1,187 @@
+# Artefact design rules
+
+This is how Artefact looks, moves and feels, and the rules a change has to follow to fit in. If a
+screen you are building needs something this file does not cover, copy the closest existing screen
+and ask in the pull request.
+
+Everything named here lives in `android/app/src/main/java/com/chethan616/clearpdf/ui/`:
+`theme/` for colour and type, `glass/` for the liquid glass, motion and haptics.
+
+## The idea
+
+- The document, note or picture is the hero. Chrome floats over it as glass and gets out of the way.
+- One action per place. A screen has one obvious next step (the blue pill, the check mark).
+- Everything responds to the finger: a press scales, a toggle ticks, a menu unfolds from its button.
+- Nothing is hard coded twice. Colours, type, glass, springs and haptics come from the shared
+ objects below, so Settings can change them everywhere at once.
+
+## Colour
+
+Accents come from `Candy` (`theme/ClearTheme.kt`). They are the same in light and dark themes.
+
+| Name | Use |
+| --- | --- |
+| `Candy.Sky` | The primary action: the action pill, the done check, selected chips, sliders, links |
+| `Candy.Tomato` | Destructive actions (Delete), errors, "not found" |
+| `Candy.Lemon` | A value that differs from its default (an edited slider value, Reset) |
+| `Candy.Mint`, `Lime`, `Grape`, `Bubblegum`, `Tangerine` | Tool and branch identity colours |
+
+Surfaces do not use Candy. They use:
+
+- `clear.ink`, `clear.inkSoft`, `clear.inkFaint` for text on the app's ground (they flip with the theme);
+- `CardTone`s (`clear.tone(Tone.Paper)`, `Tone.Lavender`, `Tone.Sage` …) for desk cards: a soft
+ gradient, the ink to write on it and the card's own accent for its title;
+- `pdfColors` only on the tool pages that follow the PDF reference layout.
+
+Rules:
+
+- Never write `Color(0xFF…)` for an accent. If you need a new one, add it to `Candy` with a comment
+ saying what it is for.
+- Text on a filled Candy colour is white, except on `Candy.Lemon`, where it is near-black.
+- Check both themes. A screen is not done until it reads well on the light sky and the dark sky.
+
+## Type
+
+All interface text is Plus Jakarta Sans through `ClearType`. Use the style, not a font size:
+
+| Style | Where |
+| --- | --- |
+| `Hero`, `Display` | Onboarding and empty states |
+| `Headline` | A tool page's large title |
+| `Title` | A top bar's title, a sheet's title |
+| `BodyStrong` | Button labels, a row's main text |
+| `Body` | Reading text, text fields |
+| `Label` | Secondary labels, chip text, values |
+| `Caption` | Dates, sizes, hints under things |
+| `Eyebrow` | Small uppercase section labels |
+
+The display faces are reserved for the places that already use them: the desk titles (`DeskAll`,
+`DeskNotes` …, one per shelf, all the same size so switching shelves never moves the layout),
+`ToolsTitle` (Fraunces, only on the Tools screen), `ToolWord`, `SerifWord` and `DotTitle` on cards.
+Do not introduce a new face; if you draw text on a canvas (the mind map does), load Plus Jakarta Sans
+from `R.font.jakarta` so it matches.
+
+Rules:
+
+- No `fontSize = 14.sp` on a `Text`. Pick a `ClearType` style and `.copy()` it only for weight or a
+ small size step.
+- Words come from `res/values/strings.xml`, never from code (the `UiTextTest` unit test fails the
+ build on English in Kotlin). Add every new string to all the `values-xx` translations too.
+- Write labels the way a person would say them: "Remove password", not "Password removal".
+
+## Liquid glass
+
+The glass is Kyant's backdrop library (vendored in `android/backdrop`) wrapped in our own
+components. A glass element blurs, refracts and tints what is behind it, so it needs a backdrop:
+
+```kotlin
+val backdrop = rememberLayerBackdrop()
+Box(Modifier.fillMaxSize()) {
+ Box(Modifier.fillMaxSize().layerBackdrop(backdrop)) { /* the content glass sits on */ }
+ CompositionLocalProvider(LocalBackdrop provides backdrop) { /* the glass chrome */ }
+}
+```
+
+Use the components, not raw `drawBackdrop`:
+
+| Component | Use |
+| --- | --- |
+| `GlassCircle` | A round icon button (Back, More, Undo). Pass `tint = Candy.Sky` for the main action |
+| `GlassPill` | A capsule button with words. `tint` makes it the vivid candy button |
+| `GlassChip` | A small capsule (filters, choices) |
+| `Modifier.glassBar()` | A floating bar or panel (toolbars, the photo editor's controls) |
+| `GlassCard`, `washPanel()` | A larger frosted panel |
+| `GlassMenu`, `MenuCard` | The popover menu that unfolds beside its button |
+| `GlassDialog`, `GlassSheet` | Dialogs and bottom sheets |
+| `GlassTextField` | A text field on glass |
+| `GlassToast` | A short message |
+| `GlassBackButton` | The Back of every screen |
+
+Ink on glass: wrap content with `rememberGlassInk(...)` and use `ink.color` (or `LocalGlassInk`).
+The ink turns dark or light from what is behind the glass, so icons stay readable over any page.
+
+Customisation lives in Settings ▸ Liquid glass & motion and is read through `GlassSettings`
+(`glass/Style.kt`): the glass look (frost, lens depth and strength, tint, colour, brightness, rim
+light, depth, prism edge), adaptive luminance, and the wallpaper. Presets are `GlassStyle.Default`,
+`Frosted`, `Crystal`, `Lite` and the menu's `MenuFrost` / `MenuFrostDark`.
+
+Rules:
+
+- Never fake glass with a translucent colour. If it floats, it is a glass component.
+- Do not read `GlassStyle` values directly in a screen. Components read `GlassSettings`, so a user's
+ settings and adaptive luminance apply everywhere.
+- Glass over a dark editor (the photo editor) uses `rememberGlassInk(Color.White)`.
+
+## Motion
+
+Springs and curves come from `glass/Motion.kt`, scaled by the user's Settings ▸ Motion:
+
+| Spec | Use |
+| --- | --- |
+| `GlassMotion.unfold()` / `fold()` | A menu or popover opening and closing |
+| `GlassMotion.morph()` | A dialog popping in |
+| `GlassMotion.pop()` | A small bouncy reaction |
+| `GlassMotion.shape()` / `shapeBack()` | A shape changing (a pressed button, a thumb) |
+| `Fluid.quick()`, `Fluid.fade()`, `Fluid.dismiss()` | Fades and quick tweens |
+| `Fluid.Ease` | Screen pushes and sheets |
+
+Rules:
+
+- No `tween(300)` or `spring(0.8f, 400f)` in a screen. Use a named spec so Settings applies.
+- Leaving is faster than arriving, and never bounces.
+- Menus unfold beside the button that opened them. There is no morph from the button.
+- Animate state the user caused. A static page does not breathe or shimmer.
+
+## Haptics
+
+`rememberFeel()` gives a function that plays a `Feel` (`glass/Haptics.kt`). It honours the phone's
+touch-vibration setting.
+
+| Feel | When |
+| --- | --- |
+| `Tap` | A button press (glass buttons already play it) |
+| `Tick` | A detent: a slider notch, picking an item, snapping to a guide |
+| `ToggleOn` / `ToggleOff` | A switch, folding and unfolding |
+| `Rise` / `Fall` | Something added or removed |
+| `Press` | A long press or the start of a drag |
+| `Confirm` / `Reject` | A drop that worked, an action refused |
+| `Spin` | A quarter turn |
+
+Rules:
+
+- Every slider ticks as it moves and taps firmly through zero (see `FeltSlider` in the photo editor).
+- Do not play a feel on every frame of a drag; play it when something changes state.
+
+## Layout and touch
+
+- Touch targets are at least 44dp. Bars are 44 to 72dp tall.
+- Screen edges: 12 to 16dp gutters for chrome, 24dp for tool page content.
+- Top bars sit under the status bar (`statusBarsPadding()`); bottom bars over the navigation bar
+ (`navigationBarsPadding()`), and over the keyboard with `imePadding()` when they hold a text field.
+- Corners: capsules (`ChromeCapsule`) for controls, `RoundedRectangle(20 to 30dp)` for panels.
+- Use `Modifier.pressable(onClick, pressedScale = 0.9f)` for anything tappable that is not already a
+ glass component, so it scales under the finger.
+
+## Screen patterns
+
+Reuse these instead of designing a new layout:
+
+- **Tool page** (`ToolPage` in `ui/ToolScreens.kt`): Back, a `Headline` title, the file card
+ (`OutlinedFileCard`), the options (radio rows, or underlined tabs as in Export and Encryption),
+ and the blue `ActionPill` at the bottom right. Compress, Export and Encryption are the models.
+- **Editor over content** (photo editor, mind map): the content fills the screen; a glass top bar
+ (cancel or back, the title or mode switch, done); a glass control bar at the bottom.
+- **Desk card** (`ui/home/Cards.kt`): `cardPaint(tone)`, a `CardTitle`, a preview, the date in the
+ corner.
+- **Settings row**: `SettingRow` with a coloured icon tile.
+
+Do not add a new tile to the Tools grid for something an existing tool already does (PDF to text
+is an option of Export; text to PDF is a source in Create PDF; finding form fields is part of Fill
+& Sign). Put it inside that tool.
+
+## Before you open a pull request
+
+- [ ] Light and dark theme both checked on a phone.
+- [ ] Glass, colour, type, motion and haptics come from the shared objects above.
+- [ ] Strings are in `strings.xml` and every `values-xx` file.
+- [ ] Screenshots or a short screen recording are in the pull request.
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index d50c6e1..690a215 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -57,6 +57,10 @@
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/pdf" />
+ <data android:mimeType="image/jpeg" />
+ <data android:mimeType="image/png" />
+ <data android:mimeType="text/x-opml" />
+ <data android:mimeType="application/x-opml" />
<data android:mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
<data android:mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.template" />
<data android:mimeType="application/vnd.ms-word.document.macroEnabled.12" />
@@ -99,6 +103,21 @@
android:taskAffinity=""
android:theme="@style/Theme.Artefact.Preview"
android:windowSoftInputMode="adjustResize">
+ <!-- An .opml that a file manager hands over as a generic file (Android doesn't know the
+ type): matched by its name. -->
+ <intent-filter android:label="@string/app_name">
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <data android:scheme="content" />
+ <data android:scheme="file" />
+ <data android:host="*" />
+ <data android:mimeType="application/octet-stream" />
+ <data android:mimeType="text/xml" />
+ <data android:mimeType="application/xml" />
+ <data android:pathPattern=".*\.opml" />
+ <data android:pathPattern=".*\..*\.opml" />
+ <data android:pathPattern=".*\..*\..*\.opml" />
+ </intent-filter>
<intent-filter android:label="@string/app_name">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
@@ -106,6 +125,10 @@
<data android:scheme="content" />
<data android:scheme="file" />
<data android:mimeType="application/pdf" />
+ <data android:mimeType="image/jpeg" />
+ <data android:mimeType="image/png" />
+ <data android:mimeType="text/x-opml" />
+ <data android:mimeType="application/x-opml" />
<data android:mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
<data android:mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.template" />
<data android:mimeType="application/vnd.ms-word.document.macroEnabled.12" />
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt
index fee5805..44816cb 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt
@@ -92,7 +92,7 @@ class MainActivity : ComponentActivity() {
setContent {
ClearApp(
vm,
- onBrowse = { launchSafely { pickPdf.launch(DocumentTypes.OPENABLE) } },
+ onBrowse = { launchSafely { pickPdf.launch(DocumentTypes.PICKABLE) } },
onPickSignatureImage = { launchSafely { pickSignature.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } },
)
}
@@ -115,7 +115,7 @@ class MainActivity : ComponentActivity() {
FilePickKind.Combine -> pickMany.launch(arrayOf("application/pdf", "image/*", "text/plain") + OFFICE_TYPES)
FilePickKind.Create -> pickMany.launch(arrayOf("image/*", "text/plain", "application/pdf") + OFFICE_TYPES)
FilePickKind.Insert -> pickOne.launch(arrayOf(DocumentTypes.PDF))
- FilePickKind.Open -> pickOne.launch(DocumentTypes.OPENABLE)
+ FilePickKind.Open -> pickOne.launch(DocumentTypes.PICKABLE)
// .p12 / .pfx: providers type them as PKCS #12, or not at all
FilePickKind.DigitalId -> pickOne.launch(arrayOf("application/x-pkcs12", "application/pkcs12", "application/octet-stream"))
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentFiles.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentFiles.kt
index 4e93275..03c4ca1 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentFiles.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentFiles.kt
@@ -243,7 +243,7 @@ class DocumentFiles(private val context: Context) {
*/
fun safeName(name: String): String {
val clean = name.replace(Regex("[\\\\/:*?\"<>|\\p{Cntrl}]"), "_").trim().trimStart('.').ifEmpty { "Document" }
- return if (clean.lowercase().endsWith(".pdf") || DocumentTypes.isOfficeName(clean)) clean else "$clean.pdf"
+ return if (clean.lowercase().endsWith(".pdf") || DocumentTypes.keepsExtension(clean)) clean else "$clean.pdf"
}
private fun sha(s: String): String =
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 3cbb238..9b690e0 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
@@ -46,22 +46,39 @@ object DocumentTypes {
/** Plain text and Markdown, read by the Word engine. */
val TEXT = arrayOf("text/plain", "text/markdown", "text/x-markdown")
- /** Everything the viewer opens. */
- val OPENABLE = arrayOf(PDF) + WORD + SLIDES + SHEETS + TEXT
+ /** Pictures: they open in the photo editor. */
+ val IMAGES = arrayOf("image/jpeg", "image/png")
+
+ /** Mind maps saved as OPML outlines (by Artefact or a desktop outliner): they open as a map. */
+ val MIND_MAPS = arrayOf("text/x-opml", "application/x-opml")
+
+ /**
+ * What the Open picker offers: everything the app opens, and files typed only as generic
+ * binary or XML, the way Android stores an .opml it doesn't know (the app reads them by name
+ * and says so when one isn't something it opens).
+ */
+ val PICKABLE get() = OPENABLE + arrayOf("application/octet-stream", "text/xml", "application/xml")
+
+ /** Everything the app opens. */
+ val OPENABLE = arrayOf(PDF) + WORD + SLIDES + SHEETS + TEXT + IMAGES + MIND_MAPS
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", "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")
+ private val IMAGE_EXTENSIONS = setOf("jpg", "jpeg", "png")
+ private val MAP_EXTENSIONS = setOf("opml")
/** The kinds a file list can be narrowed to (Files ▸ ⋯). */
- enum class Kind(val label: Int, val icon: androidx.compose.ui.graphics.vector.ImageVector) {
+ enum class Kind(val label: Int, val icon: androidx.compose.ui.graphics.vector.ImageVector, val short: Int = label) {
All(com.chethan616.clearpdf.R.string.files_kind_all, com.chethan616.clearpdf.ui.LucideIcons.Files),
- Pdf(com.chethan616.clearpdf.R.string.files_kind_pdf, com.chethan616.clearpdf.ui.LucideIcons.FileText),
- Word(com.chethan616.clearpdf.R.string.files_kind_word, com.chethan616.clearpdf.ui.LucideIcons.FilePenLine),
- Slides(com.chethan616.clearpdf.R.string.files_kind_slides, com.chethan616.clearpdf.ui.LucideIcons.Presentation),
- Sheets(com.chethan616.clearpdf.R.string.files_kind_sheets, com.chethan616.clearpdf.ui.LucideIcons.Sheet),
- Text(com.chethan616.clearpdf.R.string.files_kind_text, com.chethan616.clearpdf.ui.LucideIcons.Type),
+ Pdf(com.chethan616.clearpdf.R.string.files_kind_pdf, com.chethan616.clearpdf.ui.LucideIcons.FileText, com.chethan616.clearpdf.R.string.kind_short_pdf),
+ Word(com.chethan616.clearpdf.R.string.files_kind_word, com.chethan616.clearpdf.ui.LucideIcons.FilePenLine, com.chethan616.clearpdf.R.string.kind_short_word),
+ Slides(com.chethan616.clearpdf.R.string.files_kind_slides, com.chethan616.clearpdf.ui.LucideIcons.Presentation, com.chethan616.clearpdf.R.string.kind_short_slides),
+ Sheets(com.chethan616.clearpdf.R.string.files_kind_sheets, com.chethan616.clearpdf.ui.LucideIcons.Sheet, com.chethan616.clearpdf.R.string.kind_short_sheets),
+ Text(com.chethan616.clearpdf.R.string.files_kind_text, com.chethan616.clearpdf.ui.LucideIcons.Type, com.chethan616.clearpdf.R.string.kind_short_text),
+ Images(com.chethan616.clearpdf.R.string.files_kind_images, com.chethan616.clearpdf.ui.LucideIcons.Images, com.chethan616.clearpdf.R.string.kind_short_images),
+ MindMaps(com.chethan616.clearpdf.R.string.files_kind_mindmaps, com.chethan616.clearpdf.ui.LucideIcons.Network, com.chethan616.clearpdf.R.string.kind_short_maps),
}
/** The kind a file named [name] is. */
@@ -70,6 +87,8 @@ object DocumentTypes {
in SLIDE_EXTENSIONS -> Kind.Slides
in SHEET_EXTENSIONS -> Kind.Sheets
in TEXT_EXTENSIONS -> Kind.Text
+ in IMAGE_EXTENSIONS -> Kind.Images
+ in MAP_EXTENSIONS -> Kind.MindMaps
else -> Kind.Pdf
}
@@ -77,16 +96,25 @@ object DocumentTypes {
fun isWordName(name: String) = extension(name) in WORD_EXTENSIONS
+ /** A picture's name (.jpg, .jpeg, .png): it opens in the photo editor. */
+ fun isImageName(name: String) = extension(name) in IMAGE_EXTENSIONS
+
+ /** A mind map's name (.opml). */
+ fun isMindMapName(name: String) = extension(name) in MAP_EXTENSIONS
+
+ /** A name that keeps its own extension: an office document's, a picture's or a mind map's (anything else is a PDF). */
+ fun keepsExtension(name: String) = isOfficeName(name) || isImageName(name) || isMindMapName(name)
+
/** An office document's name (Word, slides or a workbook): it keeps its own extension. */
fun isOfficeName(name: String) = extension(name).let { it in WORD_EXTENSIONS || it in SLIDE_EXTENSIONS || it in SHEET_EXTENSIONS || it in TEXT_EXTENSIONS }
/** Whether a file of type [mime] named [name] is one the viewer opens. */
fun isOpenable(mime: String?, name: String) =
- mime == PDF || mime in WORD || mime in SLIDES || mime in SHEETS || mime in TEXT || extension(name) == "pdf" || isOfficeName(name)
+ mime == PDF || mime in WORD || mime in SLIDES || mime in SHEETS || mime in TEXT || mime in IMAGES || mime in MIND_MAPS || extension(name) == "pdf" || keepsExtension(name)
/** A file name without its extension, as documents are titled (`Report.docx` → `Report`). */
fun title(name: String): String =
- if (isOfficeName(name)) name.substringBeforeLast('.') else name.removeSuffix(".pdf").removeSuffix(".PDF")
+ if (keepsExtension(name)) name.substringBeforeLast('.') else name.removeSuffix(".pdf").removeSuffix(".PDF")
/** The type to hand another app a file named [name] as. */
fun mimeOf(name: String): String = when (extension(name)) {
@@ -109,6 +137,9 @@ object DocumentTypes {
"tsv" -> "text/tab-separated-values"
"txt" -> "text/plain"
"md", "markdown" -> "text/markdown"
+ "jpg", "jpeg" -> "image/jpeg"
+ "png" -> "image/png"
+ "opml" -> MIND_MAPS[0]
else -> PDF
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/engine/LocalFiles.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/LocalFiles.kt
index 79306b2..e72e9d2 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/LocalFiles.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/LocalFiles.kt
@@ -152,7 +152,59 @@ class Thumbnails(private val context: Context) {
if (path.startsWith("content:")) return ofContent(Uri.parse(path), maxSide)
val f = File(path)
if (!f.isFile) return null
- return cached(sha("$path|${f.lastModified()}|${f.length()}|$maxSide")) { fileThumbnail(path, maxSide.toUInt()).toBitmap() }
+ return cached(sha("$path|${f.lastModified()}|${f.length()}|$maxSide")) {
+ when {
+ DocumentTypes.isImageName(path) -> pictureThumbnail(path, maxSide)
+ DocumentTypes.isMindMapName(path) -> mapThumbnail(path, maxSide)
+ else -> fileThumbnail(path, maxSide.toUInt()).toBitmap()
+ }
+ }
+ }
+
+ /** A mind map (.opml) drawn small on a page of paper, so it reads as a map in a list. */
+ private fun mapThumbnail(path: String, maxSide: Int): Bitmap {
+ val file = File(path)
+ require(file.length() < 8L shl 20) { "too large" }
+ val doc = com.chethan616.clearpdf.ui.notes.mindFromOpml(file.readText()) ?: error("not a mind map")
+ com.chethan616.clearpdf.ui.notes.MapType.load(context)
+ val layout = com.chethan616.clearpdf.ui.notes.layoutMind(
+ doc, 1.5f, context.getString(com.chethan616.clearpdf.R.string.mindmap_root_hint), context.getString(com.chethan616.clearpdf.R.string.mindmap_node_hint),
+ )
+ val h = maxSide * 2
+ val w = h * 3 / 4
+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ val canvas = android.graphics.Canvas(bmp)
+ canvas.drawColor(android.graphics.Color.rgb(248, 249, 252))
+ val b = layout.bounds
+ val pad = w * 0.08f
+ val k = minOf((w - 2 * pad) / b.width().coerceAtLeast(1f), (h - 2 * pad) / b.height().coerceAtLeast(1f), 1f)
+ canvas.translate(w / 2f - b.centerX() * k, h / 2f - b.centerY() * k)
+ canvas.scale(k, k)
+ com.chethan616.clearpdf.ui.notes.drawMind(canvas, layout, dark = false)
+ return bmp
+ }
+
+ /** A picture made small: decoded at a fraction of its size, turned as its camera recorded it. */
+ private fun pictureThumbnail(path: String, maxSide: Int): Bitmap {
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeFile(path, bounds)
+ var sample = 1
+ while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxSide * 2) sample *= 2
+ val bmp = BitmapFactory.decodeFile(path, BitmapFactory.Options().apply { inSampleSize = sample }) ?: error("not a picture")
+ val turn = runCatching {
+ when (androidx.exifinterface.media.ExifInterface(path).getAttributeInt(androidx.exifinterface.media.ExifInterface.TAG_ORIENTATION, 1)) {
+ 6 -> 90f
+ 3 -> 180f
+ 8 -> 270f
+ else -> 0f
+ }
+ }.getOrDefault(0f)
+ val k = maxSide.toFloat() * 2 / maxOf(bmp.width, bmp.height)
+ val m = android.graphics.Matrix().apply {
+ if (k < 1f) postScale(k, k)
+ if (turn != 0f) postRotate(turn)
+ }
+ return Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, m, true)
}
private fun ofContent(uri: Uri, maxSide: Int): Bitmap? {
@@ -179,13 +231,20 @@ class Thumbnails(private val context: Context) {
"text/tab-separated-values" -> "tsv"
"text/plain" -> "txt"
"text/markdown", "text/x-markdown" -> "md"
+ "image/jpeg" -> "jpg"
+ "image/png" -> "png"
+ "text/x-opml", "application/x-opml" -> "opml"
else -> "pdf"
}
return cached(sha("$uri|$modified|$size|$maxSide|$extension")) {
val tmp = File.createTempFile("thumb", ".$extension", context.cacheDir)
try {
resolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("unreadable")
- fileThumbnail(tmp.absolutePath, maxSide.toUInt()).toBitmap()
+ when {
+ DocumentTypes.isImageName(tmp.name) -> pictureThumbnail(tmp.absolutePath, maxSide)
+ DocumentTypes.isMindMapName(tmp.name) -> mapThumbnail(tmp.absolutePath, maxSide)
+ else -> fileThumbnail(tmp.absolutePath, maxSide.toUInt()).toBitmap()
+ }
} finally {
tmp.delete()
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/notes/Notes.kt b/android/app/src/main/java/com/chethan616/clearpdf/notes/Notes.kt
index 73305c5..2640dce 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/notes/Notes.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/notes/Notes.kt
@@ -17,8 +17,8 @@ import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
-/** What a note is: words, a checklist, or a voice memo. */
-enum class NoteKind { Text, List, Voice }
+/** What a note is: words, a checklist, a voice memo, or a mind map. */
+enum class NoteKind { Text, List, Voice, Map }
@Immutable
data class CheckItem(val id: String, val text: String, val done: Boolean)
@@ -44,6 +44,8 @@ data class Note(
val pinned: Boolean = false,
/** The epoch day this is the "Thought of the day" for, or 0 for an ordinary note. */
val thought: Long = 0,
+ /** A mind map's ideas (JSON, see ui/notes/MindMap.kt); its [title] is the centre, its [body] the outline. */
+ val map: String = "",
) {
val isEmpty: Boolean get() = title.isBlank() && body.isBlank() && items.none { it.text.isNotBlank() } && images.isEmpty() && audio == null
}
@@ -169,6 +171,7 @@ private fun Note.toJson() = JSONObject().apply {
put("updated", updated)
put("pinned", pinned)
if (thought != 0L) put("thought", thought)
+ if (map.isNotEmpty()) put("map", map)
}
private fun JSONObject.toNote(): Note {
@@ -191,6 +194,7 @@ private fun JSONObject.toNote(): Note {
updated = optLong("updated", System.currentTimeMillis()),
pinned = optBoolean("pinned"),
thought = optLong("thought"),
+ map = optString("map"),
)
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt b/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt
index c17cba2..4a7f86e 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt
@@ -1,5 +1,10 @@
package com.chethan616.clearpdf.preview
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.ui.graphics.nativeCanvas
+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.Animatable
@@ -229,6 +234,8 @@ private fun Preview(
) { s ->
when (s) {
is PreviewState.Ready -> Pages(s, paper)
+ is PreviewState.Picture -> PictureView(s)
+ is PreviewState.Map -> MapView(s)
is PreviewState.Loading -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { GlassLoader(size = 72.dp) }
is PreviewState.Password -> PasswordCard(s, onPassword)
is PreviewState.Failed -> FailedCard(s.message) { close() }
@@ -256,13 +263,18 @@ private fun Preview(
onClose = ::close, onShare = onShare, onOpenWith = onOpenWith,
onSaveCopy = { onSaveCopy { toast = it } },
)
- if (state is PreviewState.Ready) {
+ if (state is PreviewState.Ready || state is PreviewState.Picture || state is PreviewState.Map) {
+ val picture = state is PreviewState.Picture
GlassPill(
onClick = ::open, tint = Candy.Sky, height = 50.dp, horizontalPadding = 30.dp,
- label = stringResource(R.string.preview_expand),
+ label = stringResource(if (picture) R.string.preview_edit_picture else R.string.preview_expand),
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 18.dp),
) {
- Text(stringResource(R.string.preview_open), style = ClearType.BodyStrong, color = Color.White)
+ if (picture) {
+ Icon(LucideIcons.SlidersHorizontal, null, tint = Color.White, modifier = Modifier.size(18.dp))
+ androidx.compose.foundation.layout.Spacer(Modifier.size(8.dp))
+ }
+ Text(stringResource(if (picture) R.string.preview_edit else R.string.preview_open), style = ClearType.BodyStrong, color = Color.White)
}
}
toast?.let { t -> GlassToast(t, null, {}, Modifier.align(Alignment.BottomCenter).padding(start = 16.dp, end = 16.dp, bottom = 84.dp)) }
@@ -273,6 +285,89 @@ private fun Preview(
}
}
+/** A mind map, drawn fitted under the header on its dotted paper. Pinch to look closer; double tap to fit again. */
+@Composable
+private fun MapView(s: PreviewState.Map) {
+ val context = androidx.compose.ui.platform.LocalContext.current
+ val density = LocalDensity.current.density
+ val dark = clear.dark
+ val rootHint = stringResource(R.string.mindmap_root_hint)
+ val hint = stringResource(R.string.mindmap_node_hint)
+ remember(context) { com.chethan616.clearpdf.ui.notes.MapType.load(context) }
+ val layout = remember(s, density) { com.chethan616.clearpdf.ui.notes.layoutMind(s.doc, density, rootHint, hint) }
+ var zoom by remember(s) { mutableStateOf(1f) }
+ var pan by remember(s) { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
+ androidx.compose.foundation.Canvas(
+ Modifier.fillMaxSize().padding(top = HeaderHeight, bottom = 84.dp)
+ .pointerInput(s) {
+ detectTapGestures(onDoubleTap = {
+ zoom = 1f
+ pan = androidx.compose.ui.geometry.Offset.Zero
+ })
+ }
+ .pointerInput(s) {
+ detectTransformGestures { _, move, z, _ ->
+ zoom = (zoom * z).coerceIn(0.5f, 5f)
+ pan += move
+ }
+ },
+ ) {
+ val b = layout.bounds
+ val fit = minOf(size.width * 0.92f / b.width().coerceAtLeast(1f), size.height * 0.92f / b.height().coerceAtLeast(1f), 1.2f)
+ val k = fit * zoom
+ drawIntoCanvas { cv ->
+ val nc = cv.nativeCanvas
+ nc.save()
+ nc.translate(size.width / 2f - b.centerX() * k + pan.x, size.height / 2f - b.centerY() * k + pan.y)
+ nc.scale(k, k)
+ com.chethan616.clearpdf.ui.notes.drawMind(nc, layout, dark)
+ nc.restore()
+ }
+ }
+}
+
+/**
+ * A picture, fitted under the header with room for Edit below it, its corners rounded. Pinch to
+ * look closer (and drag about), double tap to zoom in or back out.
+ */
+@Composable
+private fun PictureView(s: PreviewState.Picture) {
+ var zoom by remember(s) { mutableStateOf(1f) }
+ var pan by remember(s) { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
+ val haptics = com.chethan616.clearpdf.ui.glass.LocalHaptics.current
+ Box(
+ Modifier.fillMaxSize().padding(top = HeaderHeight, bottom = 84.dp, start = 14.dp, end = 14.dp)
+ .pointerInput(s) {
+ detectTapGestures(onDoubleTap = {
+ haptics?.play(com.chethan616.clearpdf.ui.glass.Feel.Tap)
+ zoom = if (zoom > 1.05f) 1f else 2.5f
+ pan = androidx.compose.ui.geometry.Offset.Zero
+ })
+ }
+ .pointerInput(s) {
+ detectTransformGestures { _, move, z, _ ->
+ zoom = (zoom * z).coerceIn(1f, 6f)
+ pan = if (zoom <= 1.01f) androidx.compose.ui.geometry.Offset.Zero else pan + move
+ }
+ },
+ contentAlignment = Alignment.Center,
+ ) {
+ androidx.compose.foundation.Image(
+ s.image, null,
+ // the picture's own shape, so its corners are the ones rounded
+ modifier = Modifier.aspectRatio(s.width.toFloat() / s.height.coerceAtLeast(1))
+ .graphicsLayer {
+ scaleX = zoom
+ scaleY = zoom
+ translationX = pan.x
+ translationY = pan.y
+ }
+ .clip(com.chethan616.clearpdf.ui.glass.RoundedRectangle(22.dp)),
+ contentScale = androidx.compose.ui.layout.ContentScale.Fit,
+ )
+ }
+}
+
/** The header's height: the pages start below it and fade up into it as they scroll. */
private val HeaderHeight = 84.dp
@@ -283,7 +378,7 @@ private fun Pages(s: PreviewState.Ready, paper: Color) {
// a workbook shows as its grid, read-only, under the header (its cells readable at their size)
if (s.info.kind == com.chethan616.clearpdf.core.DocumentKind.SHEETS) {
val grid = com.chethan616.clearpdf.ui.sheets.rememberSheetGrid(s.engine, s.info.id)
- com.chethan616.clearpdf.ui.sheets.SheetGrid(grid, top = with(density) { HeaderHeight.toPx() }, onCell = { grid.selected = it })
+ com.chethan616.clearpdf.ui.sheets.SheetGrid(grid, top = with(density) { HeaderHeight.toPx() }, onCell = { grid.choose(it) })
return
}
LaunchedEffect(s) {
@@ -319,6 +414,8 @@ private fun Header(
var menu by remember { mutableStateOf(false) }
var anchor by remember { mutableStateOf(Rect.Zero) }
val ready = state as? PreviewState.Ready
+ val picture = state as? PreviewState.Picture
+ val map = state as? PreviewState.Map
Column(
modifier.fillMaxWidth()
.background(Brush.verticalGradient(0f to paper, 0.74f to paper, 1f to paper.copy(alpha = 0f)))
@@ -339,7 +436,7 @@ private fun Header(
) {
Column(Modifier.weight(1f)) {
Text(
- ready?.name?.let(com.chethan616.clearpdf.engine.DocumentTypes::title) ?: stringResource(R.string.preview_title),
+ (ready?.name ?: picture?.name ?: map?.name)?.let(com.chethan616.clearpdf.engine.DocumentTypes::title) ?: stringResource(R.string.preview_title),
style = ClearType.BodyStrong, color = c.ink, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
if (ready != null) {
@@ -348,8 +445,21 @@ private fun Header(
style = ClearType.Caption, color = c.inkSoft, maxLines = 1,
)
}
+ if (map != null) {
+ val ideas = remember(map) { map.doc.root.count() }
+ Text(
+ listOf(stringResource(R.string.mindmap_title), androidx.compose.ui.res.pluralStringResource(R.plurals.preview_ideas, ideas, ideas), formatSize(map.size)).joinToString(" · "),
+ style = ClearType.Caption, color = c.inkSoft, maxLines = 1,
+ )
+ }
+ if (picture != null) {
+ Text(
+ listOf(picture.name.substringAfterLast('.').uppercase(), "${picture.width} × ${picture.height}", formatSize(picture.size)).joinToString(" · "),
+ style = ClearType.Caption, color = c.inkSoft, maxLines = 1,
+ )
+ }
}
- if (ready != null) {
+ if (ready != null || picture != null || map != null) {
QuietButton(
{ menu = true }, stringResource(R.string.common_more_options),
Modifier.onGloballyPositioned { anchor = it.boundsInWindow() },
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreviewActivity.kt b/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreviewActivity.kt
index 22fc812..01b1d8d 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreviewActivity.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreviewActivity.kt
@@ -4,6 +4,7 @@ import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
+import androidx.compose.ui.graphics.asImageBitmap
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
@@ -97,6 +98,30 @@ class QuickPreviewActivity : ComponentActivity() {
load(null)
}
+ /** The picture at [u] (copied in as documents are), decoded no larger than the card needs and turned as shot. */
+ private fun picture(u: Uri, name: String): PreviewState.Picture {
+ val f = copy ?: files.workingCopy(u).also { copy = it }
+ val bounds = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ android.graphics.BitmapFactory.decodeFile(f.absolutePath, bounds)
+ var sample = 1
+ while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= 2048) sample *= 2
+ var bmp = android.graphics.BitmapFactory.decodeFile(f.absolutePath, android.graphics.BitmapFactory.Options().apply { inSampleSize = sample })
+ ?: error(getString(R.string.common_file_unreadable))
+ val exif = androidx.exifinterface.media.ExifInterface(f.absolutePath)
+ val turn = when (exif.getAttributeInt(androidx.exifinterface.media.ExifInterface.TAG_ORIENTATION, 1)) {
+ 6 -> 90f
+ 3 -> 180f
+ 8 -> 270f
+ else -> 0f
+ }
+ if (turn != 0f) bmp = android.graphics.Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, android.graphics.Matrix().apply { postRotate(turn) }, true)
+ val sideways = turn == 90f || turn == 270f
+ return PreviewState.Picture(
+ bmp.asImageBitmap(), name, files.size(u) ?: f.length(),
+ if (sideways) bounds.outHeight else bounds.outWidth, if (sideways) bounds.outWidth else bounds.outHeight,
+ )
+ }
+
/** The document's address from a View or a Send intent. */
private fun sourceOf(i: Intent?): Uri? = when (i?.action) {
Intent.ACTION_VIEW -> i.data
@@ -113,6 +138,24 @@ class QuickPreviewActivity : ComponentActivity() {
val u = uri ?: return
lifecycleScope.launch {
state = if (password == null) PreviewState.Loading else state
+ // a picture is shown as it is (no engine needed); Edit opens it in the photo editor
+ val pictureName = withContext(Dispatchers.IO) { runCatching { files.displayNameRaw(u) }.getOrNull() }
+ // a mind map (OPML) is drawn as a map
+ if (pictureName != null && (com.chethan616.clearpdf.engine.DocumentTypes.isMindMapName(pictureName) || mime in com.chethan616.clearpdf.engine.DocumentTypes.MIND_MAPS)) {
+ state = runCatching {
+ withContext(Dispatchers.IO) {
+ val f = copy ?: files.workingCopy(u).also { copy = it }
+ require(f.length() < 8L shl 20)
+ val doc = com.chethan616.clearpdf.ui.notes.mindFromOpml(f.readText()) ?: error(getString(R.string.msg_not_opml))
+ PreviewState.Map(doc, pictureName, files.size(u) ?: f.length())
+ }
+ }.getOrElse { PreviewState.Failed(getString(R.string.msg_not_opml)) }
+ return@launch
+ }
+ if (pictureName != null && (com.chethan616.clearpdf.engine.DocumentTypes.isImageName(pictureName) || mime in com.chethan616.clearpdf.engine.DocumentTypes.IMAGES)) {
+ state = runCatching { withContext(Dispatchers.IO) { picture(u, pictureName) } }.getOrElse { PreviewState.Failed(it.userMessage) }
+ return@launch
+ }
val eng = app.engine.await().getOrNull() ?: run {
state = PreviewState.Failed(getString(R.string.msg_engine_not_started))
return@launch
@@ -239,6 +282,12 @@ internal sealed interface PreviewState {
class Failed(val message: String) : PreviewState
+ /** A mind map (.opml): drawn as a map. */
+ class Map(val doc: com.chethan616.clearpdf.ui.notes.MindDoc, val name: String, val size: Long) : PreviewState
+
+ /** A picture (.jpg, .png): shown as it is, with its size in pixels. */
+ class Picture(val image: androidx.compose.ui.graphics.ImageBitmap, val name: String, val size: Long, val width: Int, val height: Int) : PreviewState
+
class Ready(val info: DocumentInfo, val images: PageImages, val view: ViewerState, val name: String, val size: Long, val engine: Engine) : PreviewState {
suspend fun close(eng: Engine) {
images.close()
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 868706a..49b5624 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
@@ -211,6 +211,27 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
}
private suspend fun openFile(eng: Engine, uri: Uri, file: File, password: String?) {
+ // a mind map (OPML) opens as a map to look at, and can be made into a mind-map note
+ if (com.chethan616.clearpdf.engine.DocumentTypes.isMindMapName(file.name)) {
+ val doc = withContext(Dispatchers.IO) {
+ runCatching { if (file.length() < 8L shl 20) com.chethan616.clearpdf.ui.notes.mindFromOpml(file.readText()) else null }.getOrNull()
+ } ?: return tell(text(R.string.msg_not_opml))
+ previewingMap = OpenedMap(uri, file.name, doc, otherAppUri == uri)
+ withContext(Dispatchers.IO) {
+ recents.touch(RecentFile(uri.toString(), file.name, System.currentTimeMillis(), 1, file.length(), 0))
+ }
+ refreshRecents()
+ return
+ }
+ // a picture opens in the photo editor (over whatever is open), and is kept in Recent
+ if (com.chethan616.clearpdf.engine.DocumentTypes.isImageName(file.name)) {
+ editingImage = OpenedImage(uri, file, otherAppUri == uri)
+ withContext(Dispatchers.IO) {
+ recents.touch(RecentFile(uri.toString(), file.name, System.currentTimeMillis(), 1, file.length(), 0))
+ }
+ refreshRecents()
+ return
+ }
try {
document?.let { saveAndClose(eng, it) }
val info = eng.command { open(file.absolutePath, password) }
@@ -2676,6 +2697,38 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
/** A note's picture being edited (note id, picture name), over everything. */
var editingPhoto by mutableStateOf<Pair<String, String>?>(null)
+ /** A mind map file (OPML) opened, shown as a map over everything. */
+ internal var previewingMap by mutableStateOf<OpenedMap?>(null)
+
+ /** The map preview closed: back to the app that opened the file, if one did. */
+ fun closeMap() {
+ val map = previewingMap ?: return
+ previewingMap = null
+ if (map.fromOtherApp) leave.trySend(Unit)
+ }
+
+ /** A picture file opened (from Files, Recent or another app), in the photo editor over everything. */
+ var editingImage by mutableStateOf<OpenedImage?>(null)
+
+ /** The photo editor closed on an opened picture: back to the app that opened it, if one did. */
+ fun closeImage() {
+ val image = editingImage ?: return
+ editingImage = null
+ if (image.fromOtherApp) leave.trySend(Unit)
+ }
+
+ /**
+ * The edited picture [file] of [image], saved to Downloads beside the original (which is left as
+ * it was) as "<name> edited.jpg".
+ */
+ suspend fun saveEditedImage(image: OpenedImage, file: File) {
+ runCatching {
+ val name = DocumentFiles.safeName("${image.file.name.substringBeforeLast('.')} edited.jpg")
+ withContext(Dispatchers.IO) { files.saveToDownloads(file, name, "image/jpeg") }
+ tell(text(R.string.msg_saved_downloads, name))
+ }.onFailure { tell(it.userMessage) }
+ }
+
/** The desk's dock is turning into the open note's toolbar: the toolbar waits, unseen, until it has. */
var noteBarHidden by mutableStateOf(false)
@@ -2730,10 +2783,19 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
/** A new note (or list) straight into the editor. */
fun newNote(kind: com.chethan616.clearpdf.notes.NoteKind) {
+ if (kind == com.chethan616.clearpdf.notes.NoteKind.Map) return newMindMap(null)
val items = if (kind == com.chethan616.clearpdf.notes.NoteKind.List) listOf(com.chethan616.clearpdf.notes.checkItem("")) else emptyList()
openNote = notes.create(kind, items = items).id
}
+ /** A new mind-map note (of [from], a note's outline seen as a map, or an empty centre) opened to work on. */
+ internal fun newMindMap(from: com.chethan616.clearpdf.ui.notes.MindDoc?) {
+ val doc = from ?: com.chethan616.clearpdf.ui.notes.MindDoc(com.chethan616.clearpdf.ui.notes.MindNode(""))
+ val note = doc.asNote()
+ notes.add(note)
+ openNote = note.id
+ }
+
fun closeNote() {
val id = openNote ?: return
openNote = null
@@ -3495,3 +3557,9 @@ private const val MAX_CREATE_FILES = 12
/** A green banner saying a job worked, with the way to undo it. */
class SuccessBanner(val text: String, val undo: (() -> Unit)?)
+
+/** A picture file opened in the photo editor: where it came from, its working copy, and whether another app handed it over. */
+data class OpenedImage(val uri: Uri, val file: File, val fromOtherApp: Boolean)
+
+/** A mind map file (OPML) opened to look at: where it came from, its name, the map, and whether another app handed it over. */
+internal data class OpenedMap(val uri: Uri, val name: String, val doc: com.chethan616.clearpdf.ui.notes.MindDoc, val fromOtherApp: Boolean)
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt
index da1bb5a..5d0cada 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt
@@ -226,6 +226,17 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:
vm.certSign?.let { CertSignScreen(vm, it) }
vm.presenting?.let { d -> com.chethan616.clearpdf.ui.viewer.PresentMode(vm, d) { vm.presenting = null } }
vm.editingPhoto?.let { (note, picture) -> com.chethan616.clearpdf.ui.notes.PhotoEditScreen(vm, note, picture) { vm.editingPhoto = null } }
+ vm.editingImage?.let { image -> com.chethan616.clearpdf.ui.notes.PhotoEditScreen(vm, image) { vm.closeImage() } }
+ vm.previewingMap?.let { m ->
+ com.chethan616.clearpdf.ui.notes.MindMapPreview(
+ vm, m.doc, m.name.substringBeforeLast('.'),
+ // made into a note: the note opens here, even for a file another app handed over
+ onMake = {
+ vm.previewingMap = null
+ vm.newMindMap(m.doc)
+ },
+ ) { vm.closeMap() }
+ }
if (vm.idCreate) CreateIdScreen(vm)
}
},
@@ -234,14 +245,16 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:
// on the desk, the note's toolbar becomes the dock again
val lastRoute = remember { arrayOf(route) }
if (lastRoute[0] != route) {
- val intoNote = lastRoute[0] == HomeTab.Home.name && route.startsWith("note:") && doc == null
- val fromNote = lastRoute[0].startsWith("note:") && route == HomeTab.Home.name && doc == null
+ // a mind map has its own bars: it opens and closes like Files or PDFs, without the dock turning into a toolbar
+ fun isMap(r: String) = r.startsWith("note:") && vm.notes.get(r.removePrefix("note:"))?.kind == com.chethan616.clearpdf.notes.NoteKind.Map
+ val intoNote = lastRoute[0] == HomeTab.Home.name && route.startsWith("note:") && doc == null && !isMap(route)
+ val fromNote = lastRoute[0].startsWith("note:") && route == HomeTab.Home.name && doc == null && !isMap(lastRoute[0])
if (intoNote != dockIntoNote) dockIntoNote = intoNote
if (fromNote != dockFromNote) dockFromNote = fromNote
if (vm.noteBarHidden != (intoNote || fromNote)) vm.noteBarHidden = intoNote || fromNote
lastRoute[0] = route
}
- if ((onDesk || dockIntoNote) && vm.editingPhoto == null && vm.presenting == null) {
+ if ((onDesk || dockIntoNote) && vm.editingPhoto == null && vm.editingImage == null && vm.previewingMap == null && vm.presenting == null) {
CreateDock(vm, desk, onBrowse, intoNote = !onDesk, fromNote = onDesk && dockFromNote) {
dockIntoNote = false
dockFromNote = false
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.kt
index c1f854a..d10af98 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.kt
@@ -1,5 +1,6 @@
package com.chethan616.clearpdf.ui
+import com.chethan616.clearpdf.ui.glass.pressable
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
@@ -286,38 +287,70 @@ fun CompressScreen(vm: AppViewModel, doc: OpenDocument) {
}
}
-/** A password field of Set password: its label above an outlined box, with the eye to show it. */
+/**
+ * A password field of Encryption: a frosted panel like the file card above it, a lock, the field
+ * (its name waiting inside it until something is typed), and the eye to show or hide what is typed.
+ * A blue ring while it is typed in; a red one when what it holds can't be used.
+ */
@Composable
private fun PasswordField(label: String, value: String, onValue: (String) -> Unit, visible: Boolean, onToggle: (() -> Unit)?, error: Boolean, focus: androidx.compose.ui.focus.FocusRequester? = null) {
- val c = pdfColors
+ val c = com.chethan616.clearpdf.ui.theme.clear
var focused by remember { mutableStateOf(false) }
- Text(label, color = c.label, fontSize = 16.sp, modifier = Modifier.padding(start = 24.dp, top = 20.dp, bottom = 8.dp))
+ val ring by androidx.compose.animation.animateColorAsState(
+ when {
+ error -> com.chethan616.clearpdf.ui.theme.Candy.Tomato
+ focused -> com.chethan616.clearpdf.ui.theme.Candy.Sky
+ else -> Color.Transparent
+ },
+ com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "passwordRing",
+ )
+ val shape = com.chethan616.clearpdf.ui.glass.RoundedRectangle(20.dp)
+ val name = label.trimEnd('*', ' ')
Row(
- Modifier.fillMaxWidth().padding(horizontal = 24.dp).height(44.dp).clip(RoundedCornerShape(4.dp)).background(c.menu)
- .border(if (focused) 2.dp else 1.dp, if (error) c.red else if (focused) c.toolAccent else c.divider, RoundedCornerShape(4.dp)).padding(start = 12.dp),
+ Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 6.dp).height(58.dp)
+ .then(com.chethan616.clearpdf.ui.glass.washPanel())
+ .border(2.dp, ring, shape)
+ .padding(start = 16.dp, end = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
- androidx.compose.foundation.text.BasicTextField(
- value = value, onValueChange = onValue, singleLine = true,
- textStyle = androidx.compose.ui.text.TextStyle(color = c.text, fontSize = 17.sp),
- cursorBrush = androidx.compose.ui.graphics.SolidColor(c.toolAccent),
- visualTransformation = if (visible) VisualTransformation.None else PasswordVisualTransformation(),
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
- modifier = Modifier.weight(1f).then(if (focus != null) Modifier.focusRequester(focus) else Modifier)
- .onFocusChanged { focused = it.isFocused }.semantics { contentDescription = label },
- )
- BarIcon(if (visible) LucideIcons.Eye else LucideIcons.EyeOff, stringResource(if (visible) R.string.ui_hide_password else R.string.ui_show_password), { onToggle?.invoke() }, size = 44.dp)
+ Icon(LucideIcons.Lock, null, tint = if (error) com.chethan616.clearpdf.ui.theme.Candy.Tomato else c.inkSoft, modifier = Modifier.size(18.dp))
+ Spacer(Modifier.width(12.dp))
+ Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
+ if (value.isEmpty()) Text(name, style = com.chethan616.clearpdf.ui.theme.ClearType.Body, color = c.inkSoft.copy(alpha = 0.8f), maxLines = 1)
+ androidx.compose.foundation.text.BasicTextField(
+ value = value, onValueChange = onValue, singleLine = true,
+ textStyle = com.chethan616.clearpdf.ui.theme.ClearType.Body.copy(color = c.ink, fontSize = 17.sp, letterSpacing = if (visible) 0.sp else 2.sp),
+ cursorBrush = androidx.compose.ui.graphics.SolidColor(com.chethan616.clearpdf.ui.theme.Candy.Sky),
+ visualTransformation = if (visible) VisualTransformation.None else PasswordVisualTransformation(),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
+ modifier = Modifier.fillMaxWidth().then(if (focus != null) Modifier.focusRequester(focus) else Modifier)
+ .onFocusChanged { focused = it.isFocused }.semantics { contentDescription = name },
+ )
+ }
+ Box(
+ Modifier.size(44.dp).clip(androidx.compose.foundation.shape.CircleShape).pressable({ onToggle?.invoke() }, pressedScale = 0.88f),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(
+ if (visible) LucideIcons.Eye else LucideIcons.EyeOff,
+ stringResource(if (visible) R.string.ui_hide_password else R.string.ui_show_password),
+ tint = if (visible) com.chethan616.clearpdf.ui.theme.Candy.Sky else c.inkSoft, modifier = Modifier.size(20.dp),
+ )
+ }
}
}
-/** Set password: a password twice (6 to 128 printable characters), then a protected copy in Downloads. */
+/**
+ * Encryption, laid out as the other tool pages are (Compress, Export): the title, the file, two
+ * tabs for its two jobs, and the blue pill. Set password asks for it twice (6 to 128 printable
+ * characters) and saves a protected copy; Remove password saves an open copy of a protected PDF.
+ * The tab that fits the file opens first: Remove for a protected one, Set for the rest.
+ */
@Composable
fun ProtectScreen(vm: AppViewModel, doc: OpenDocument) {
val c = pdfColors
- val ink = com.chethan616.clearpdf.ui.theme.clear
val locked = doc.info.encrypted
- // the way that makes sense for this file is open first: a protected one to remove, else to set
- var removing by remember { mutableStateOf(locked) }
+ var tab by remember { mutableStateOf(if (locked) 1 else 0) }
var pw by remember { mutableStateOf("") }
var confirm by remember { mutableStateOf("") }
var visible by remember { mutableStateOf(false) }
@@ -325,44 +358,52 @@ fun ProtectScreen(vm: AppViewModel, doc: OpenDocument) {
val bad = pw.isNotEmpty() && (pw.length !in 6..128 || pw.any { it < '!' || it > '~' })
val mismatch = confirm.isNotEmpty() && confirm != pw
val canSet = pw.isNotEmpty() && confirm.isNotEmpty() && !bad && !mismatch
- ToolScaffold(
+ ToolPage(
stringResource(R.string.tool_encryption), { vm.toolScreen = null },
- action = stringResource(if (removing) R.string.tools_unlock_action else R.string.common_tool_set_password),
- actionEnabled = if (removing) locked else canSet,
- onAction = { if (removing) vm.removePassword(doc) else vm.protect(doc, pw) },
+ action = stringResource(if (tab == 1) R.string.tools_unlock_action else R.string.common_tool_set_password),
+ actionEnabled = if (tab == 1) locked else canSet,
+ onAction = { if (tab == 1) vm.removePassword(doc) else vm.protect(doc, pw) },
trailing = {
com.chethan616.clearpdf.ui.glass.GlassCircle({ info = true }, label = stringResource(R.string.tools_about_passwords)) {
com.chethan616.clearpdf.ui.glass.GlassIcon(LucideIcons.Info, null, Modifier.size(20.dp))
}
},
) {
- Column(Modifier.verticalScroll(rememberScrollState()).padding(bottom = 12.dp)) {
+ Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) {
+ OutlinedFileCard(vm, doc)
// how the file stands now
- Row(Modifier.padding(start = 24.dp, end = 24.dp, top = 4.dp, bottom = 14.dp), verticalAlignment = Alignment.CenterVertically) {
- Icon(if (locked) LucideIcons.Lock else LucideIcons.LockOpen, null, tint = ink.inkSoft, modifier = Modifier.size(16.dp))
+ Row(Modifier.padding(start = 26.dp, end = 24.dp, top = 12.dp), verticalAlignment = Alignment.CenterVertically) {
+ Icon(if (locked) LucideIcons.Lock else LucideIcons.LockOpen, null, tint = if (locked) com.chethan616.clearpdf.ui.theme.Candy.Grape else c.text, modifier = Modifier.size(15.dp))
Spacer(Modifier.width(8.dp))
- Text(
- stringResource(if (locked) R.string.tools_unlock_title else R.string.msg_no_password_yet),
- style = com.chethan616.clearpdf.ui.theme.ClearType.Label, color = ink.inkSoft,
- )
+ Text(stringResource(if (locked) R.string.tools_unlock_title else R.string.msg_no_password_yet), color = c.text, fontSize = 13.sp)
}
- EncryptionChoice(
- LucideIcons.Lock, com.chethan616.clearpdf.ui.theme.Candy.Grape,
- stringResource(R.string.common_tool_set_password), stringResource(R.string.tools_set_password_body),
- chosen = !removing, enabled = true, onClick = { removing = false },
- ) {
+ Spacer(Modifier.height(16.dp))
+ // the tabs sit at the left, each underlined across its own label (as Export's)
+ Box(Modifier.fillMaxWidth().padding(horizontal = 8.dp)) {
+ Box(Modifier.align(Alignment.BottomStart).fillMaxWidth().height(1.dp).background(c.divider))
+ Row {
+ listOf(R.string.common_tool_set_password, R.string.tools_unlock_action).forEachIndexed { i, label ->
+ Column(Modifier.clickable { tab = i }.padding(horizontal = 8.dp).width(androidx.compose.foundation.layout.IntrinsicSize.Max)) {
+ Text(stringResource(label), color = if (tab == i) c.label else c.text, fontSize = 16.sp, modifier = Modifier.padding(vertical = 12.dp))
+ Box(Modifier.fillMaxWidth().height(2.dp).background(if (tab == i) c.label else Color.Transparent))
+ }
+ if (i == 0) Spacer(Modifier.width(14.dp))
+ }
+ }
+ }
+ if (tab == 0) {
+ Text(stringResource(R.string.tools_set_password_body), color = c.text, fontSize = 14.sp, modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 16.dp, bottom = 10.dp))
PasswordField(stringResource(R.string.tools_new_password), pw, { pw = it }, visible, { visible = !visible }, bad)
- if (bad) Text(stringResource(R.string.tools_password_rule), color = c.red, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp))
+ if (bad) Text(stringResource(R.string.tools_password_rule), style = com.chethan616.clearpdf.ui.theme.ClearType.Caption, color = com.chethan616.clearpdf.ui.theme.Candy.Tomato, modifier = Modifier.padding(horizontal = 30.dp, vertical = 2.dp))
PasswordField(stringResource(R.string.tools_repeat_password), confirm, { confirm = it }, visible, { visible = !visible }, mismatch)
- if (mismatch) Text(stringResource(R.string.tools_password_mismatch), color = c.red, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp))
- Spacer(Modifier.height(16.dp))
+ if (mismatch) Text(stringResource(R.string.tools_password_mismatch), style = com.chethan616.clearpdf.ui.theme.ClearType.Caption, color = com.chethan616.clearpdf.ui.theme.Candy.Tomato, modifier = Modifier.padding(horizontal = 30.dp, vertical = 2.dp))
+ } else {
+ Text(
+ stringResource(if (locked) R.string.tools_unlock_body else R.string.msg_no_password),
+ color = c.text, fontSize = 14.sp, modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 16.dp),
+ )
}
- Spacer(Modifier.height(12.dp))
- EncryptionChoice(
- LucideIcons.LockOpen, com.chethan616.clearpdf.ui.theme.Candy.Mint,
- stringResource(R.string.tools_unlock_action), stringResource(if (locked) R.string.tools_unlock_body else R.string.msg_no_password),
- chosen = removing, enabled = locked, onClick = { removing = true },
- ) {}
+ Spacer(Modifier.height(16.dp))
}
}
if (info) {
@@ -372,56 +413,6 @@ fun ProtectScreen(vm: AppViewModel, doc: OpenDocument) {
}
}
-/**
- * One of Encryption's two ways, as a card: its sign in its colour, what it is called and what it
- * does, a tick when it is the chosen one (the card is then ringed, and [more] opens under it). The
- * button at the foot of the screen does the chosen one. A way that can't apply (removing a password
- * from a file that has none) is shown faint and can't be chosen.
- */
-@Composable
-private fun EncryptionChoice(
- icon: androidx.compose.ui.graphics.vector.ImageVector,
- accent: Color,
- title: String,
- body: String,
- chosen: Boolean,
- enabled: Boolean,
- onClick: () -> Unit,
- more: @Composable ColumnScope.() -> Unit,
-) {
- val ink = com.chethan616.clearpdf.ui.theme.clear
- val shape = com.chethan616.clearpdf.ui.glass.RoundedRectangle(24.dp)
- Column(
- Modifier.padding(horizontal = 16.dp).fillMaxWidth()
- .alpha(if (enabled) 1f else 0.5f)
- .clip(shape)
- .background(ink.glass)
- .border(if (chosen && enabled) 2.dp else 1.dp, if (chosen && enabled) com.chethan616.clearpdf.ui.theme.Candy.Sky else ink.ink.copy(alpha = 0.10f), shape),
- ) {
- Row(
- Modifier.fillMaxWidth().clickable(enabled = enabled, onClick = onClick).padding(16.dp),
- verticalAlignment = Alignment.CenterVertically,
- ) {
- Box(Modifier.size(44.dp).clip(com.chethan616.clearpdf.ui.glass.RoundedRectangle(14.dp)).background(accent), contentAlignment = Alignment.Center) {
- Icon(icon, null, tint = Color.White, modifier = Modifier.size(23.dp))
- }
- Spacer(Modifier.width(14.dp))
- Column(Modifier.weight(1f)) {
- Text(title, style = com.chethan616.clearpdf.ui.theme.ClearType.BodyStrong, color = ink.ink)
- Text(body, style = com.chethan616.clearpdf.ui.theme.ClearType.Caption, color = ink.inkSoft, modifier = Modifier.padding(top = 2.dp))
- }
- Spacer(Modifier.width(10.dp))
- Box(
- Modifier.size(24.dp).clip(androidx.compose.foundation.shape.CircleShape)
- .background(if (chosen && enabled) com.chethan616.clearpdf.ui.theme.Candy.Sky else Color.Transparent)
- .border(2.dp, if (chosen && enabled) com.chethan616.clearpdf.ui.theme.Candy.Sky else ink.inkFaint, androidx.compose.foundation.shape.CircleShape),
- contentAlignment = Alignment.Center,
- ) { if (chosen && enabled) Icon(LucideIcons.Check, null, tint = Color.White, modifier = Modifier.size(14.dp)) }
- }
- androidx.compose.animation.AnimatedVisibility(chosen && enabled) { Column(content = more) }
- }
-}
-
/** Export PDF: Document (Word, RTF, Excel, PowerPoint) or Image (JPEG, PNG) of its pages. */
@Composable
fun ExportScreen(vm: AppViewModel, doc: OpenDocument) {
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt
index 4bc59ea..c902256 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt
@@ -104,7 +104,7 @@ object ToolCatalog {
// Text to PDF is a way of Create PDF, and finding a form's fields a part of Fill & Sign: neither
// is a tile of its own
- val All = listOf(Edit, FillSign, Scan, Combine, Comment, ReadAloud, Organize, Compress, Export, Crop, Protect, Create, PdfToText, EditPhoto)
+ val All = listOf(Edit, FillSign, Scan, Combine, Comment, ReadAloud, Organize, Compress, Export, Crop, Protect, Create, EditPhoto)
}
/**
@@ -153,6 +153,8 @@ internal fun kindBadge(name: String?): Pair<String, Color> {
com.chethan616.clearpdf.engine.DocumentTypes.Kind.Word -> ext to Color(0xFF2F6FED)
com.chethan616.clearpdf.engine.DocumentTypes.Kind.Slides -> ext to Color(0xFFE8672C)
com.chethan616.clearpdf.engine.DocumentTypes.Kind.Text -> ext to Color(0xFF6B7280)
+ com.chethan616.clearpdf.engine.DocumentTypes.Kind.Images -> ext to Candy.Grape
+ com.chethan616.clearpdf.engine.DocumentTypes.Kind.MindMaps -> ext to Candy.Bubblegum
else -> "PDF" to Candy.Tomato
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/Cards.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/Cards.kt
index 5ddf33d..24d75fc 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/Cards.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/Cards.kt
@@ -5,6 +5,8 @@ import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Canvas
+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -247,6 +249,53 @@ fun NoteCard(note: Note, onOpen: () -> Unit, onLong: () -> Unit, modifier: Modif
}
}
+/** A mind map: lavender paper, its centre idea as the title and the map itself drawn small under it. */
+@Composable
+fun MapCard(note: Note, onOpen: () -> Unit, onLong: () -> Unit, modifier: Modifier = Modifier) {
+ val tone = clear.tone(Tone.Lavender)
+ val dark = clear.dark
+ val d = androidx.compose.ui.platform.LocalDensity.current.density
+ val context = androidx.compose.ui.platform.LocalContext.current
+ remember(context) { com.chethan616.clearpdf.ui.notes.MapType.load(context) }
+ val rootHint = stringResource(R.string.mindmap_root_hint)
+ val hint = stringResource(R.string.mindmap_node_hint)
+ val layout = remember(note.map, d) {
+ val doc = com.chethan616.clearpdf.ui.notes.mindFromJson(note.map)
+ ?: com.chethan616.clearpdf.ui.notes.MindDoc(com.chethan616.clearpdf.ui.notes.parseOutline(note.title, note.body))
+ com.chethan616.clearpdf.ui.notes.layoutMind(doc, d, rootHint, hint)
+ }
+ Column(
+ modifier.heightIn(min = 156.dp).pressable(onOpen, onLong, pressedScale = 0.96f).cardPaint(tone, Offset(0.1f, 0.0f)).padding(18.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Icon(LucideIcons.Network, null, tint = tone.ink.copy(alpha = 0.75f), modifier = Modifier.size(14.dp))
+ Spacer(Modifier.width(6.dp))
+ Text(stringResource(R.string.mindmap_title), style = ClearType.Caption.copy(fontSize = 11.sp), color = tone.ink.copy(alpha = 0.75f))
+ }
+ Spacer(Modifier.height(6.dp))
+ WordFitText(note.title.ifBlank { stringResource(R.string.mindmap_title) }, ClearType.CardTitle.copy(color = tone.accent), maxLines = 3)
+ Spacer(Modifier.height(10.dp))
+ // the map itself, small: on a soft well so its colours read on the lavender
+ Canvas(
+ Modifier.fillMaxWidth().height(92.dp).clip(RoundedRectangle(16.dp))
+ .background(if (dark) Color(0xFF14152B).copy(alpha = 0.55f) else Color.White.copy(alpha = 0.55f)),
+ ) {
+ val b = layout.bounds
+ val k = minOf((size.width - 16f) / b.width().coerceAtLeast(1f), (size.height - 16f) / b.height().coerceAtLeast(1f), 0.6f)
+ drawIntoCanvas { cv ->
+ val nc = cv.nativeCanvas
+ nc.save()
+ nc.translate(size.width / 2f - b.centerX() * k, size.height / 2f - b.centerY() * k)
+ nc.scale(k, k)
+ com.chethan616.clearpdf.ui.notes.drawMind(nc, layout, dark)
+ nc.restore()
+ }
+ }
+ Spacer(Modifier.height(12.dp).weight(1f, fill = false))
+ Text(shortDate(note.updated), style = ClearType.Caption.copy(fontSize = 10.5.sp), color = tone.ink.copy(alpha = 0.55f), modifier = Modifier.align(Alignment.End))
+ }
+}
+
/** "Thought of the day": a note's frosted paper with only its title, in the note blue, and today's date in the corner. */
@Composable
fun ThoughtCard(onOpen: () -> Unit, modifier: Modifier = Modifier) {
@@ -512,9 +561,14 @@ fun StackCard(
*/
@Composable
fun PhotoChip(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, icon: ImageVector? = null) {
- GlassChip(onClick = onClick, modifier = modifier, height = 34.dp, contentPadding = PaddingValues(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), ink = Color.White) {
- if (icon != null) Icon(icon, null, tint = Color.White, modifier = Modifier.size(15.dp))
- Text(text, style = ClearType.Label, color = Color.White, maxLines = 1)
+ // white over a photo; with Adaptive luminance, dark wherever the glass turns light
+ val ink = com.chethan616.clearpdf.ui.glass.rememberGlassInk(Color.White)
+ GlassChip(
+ onClick = onClick, modifier = modifier.then(ink.modifier), height = 34.dp, contentPadding = PaddingValues(horizontal = 12.dp),
+ horizontalArrangement = Arrangement.spacedBy(6.dp), ink = ink.color,
+ ) {
+ if (icon != null) Icon(icon, null, tint = ink.color, modifier = Modifier.size(15.dp))
+ Text(text, style = ClearType.Label.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold), color = ink.color, maxLines = 1)
}
}
@@ -564,7 +618,9 @@ fun RecentCard(vm: AppViewModel, rows: List<FileRow>, onAll: () -> Unit, modifie
) {
Row(Modifier.align(Alignment.BottomStart).padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (rows.size > 1) PhotoChip("+${rows.size - 1}", onAll)
- PhotoChip(stringResource(R.string.desk_chip_pdfs), onAll, icon = LucideIcons.FileText)
+ // what the newest is: PDFs, Pictures, Spreadsheets, Mind maps …
+ val kind = com.chethan616.clearpdf.engine.DocumentTypes.kindOf(top.name)
+ PhotoChip(stringResource(kind.short), onAll, icon = kind.icon)
}
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/CreateDock.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/CreateDock.kt
index 77a55bb..ef4d412 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/CreateDock.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/CreateDock.kt
@@ -378,6 +378,7 @@ private fun BoxScope.Fan(vm: AppViewModel, desk: DeskState, open: Boolean, onBro
val items = listOf(
FanItem(LucideIcons.SquarePen, stringResource(R.string.create_note), Candy.Sky, go { vm.newNote(NoteKind.Text) }),
FanItem(LucideIcons.ListChecks, stringResource(R.string.create_list), Candy.Mint, go { vm.newNote(NoteKind.List) }),
+ FanItem(LucideIcons.Network, stringResource(R.string.create_mindmap), Candy.Grape, go { vm.newNote(NoteKind.Map) }),
FanItem(ToolCatalog.Scan.icon, stringResource(ToolCatalog.Scan.label), Candy.Tomato, go { ToolCatalog.Scan.go(vm) }),
FanItem(LucideIcons.FolderOpen, stringResource(R.string.home_open_file), Candy.Grape, go(onBrowse)),
FanItem(LucideIcons.Images, stringResource(R.string.desk_photos_to_pdf), Candy.Tangerine, go { vm.pickPhotosToPdf() }),
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt
index ddb6fe9..e44a6e7 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt
@@ -142,7 +142,7 @@ fun deskItems(filter: DeskFilter, notes: List<Note>, recents: List<FileRow>): Li
out.add(minOf(6, out.size), DeskItem.Pdfs(recents.size))
out
}
- DeskFilter.Notes -> sorted.filter { it.kind == NoteKind.Text }.map { DeskItem.Of(it) }
+ DeskFilter.Notes -> sorted.filter { it.kind == NoteKind.Text || it.kind == NoteKind.Map }.map { DeskItem.Of(it) }
DeskFilter.Todo -> sorted.filter { it.kind == NoteKind.List }.map { DeskItem.Of(it) }
DeskFilter.Audio -> sorted.filter { it.kind == NoteKind.Voice }.map { DeskItem.Of(it) }
DeskFilter.Images -> sorted.filter { it.images.isNotEmpty() }.map { DeskItem.Picture(it) }
@@ -231,6 +231,7 @@ fun HomeScreen(vm: AppViewModel, desk: DeskState) {
{ play(item.note) }, { actionsFor = item.note }, m,
)
NoteKind.Text -> NoteCard(item.note, { vm.openNote = item.note.id }, { actionsFor = item.note }, m)
+ NoteKind.Map -> MapCard(item.note, { vm.openNote = item.note.id }, { actionsFor = item.note }, m)
}
is DeskItem.Picture -> {
val n = item.note
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt
index c661e34..84c4e97 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt
@@ -6,81 +6,316 @@ import android.graphics.Path
import android.graphics.RectF
import android.graphics.Typeface
import android.graphics.pdf.PdfDocument
+import android.text.Layout
+import android.text.StaticLayout
import android.text.TextPaint
import android.text.TextUtils
import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.animate
+import androidx.compose.animation.core.spring
+import androidx.compose.animation.expandVertically
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+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.foundation.gestures.detectTransformGestures
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.heightIn
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.isImeVisible
+import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.input.pointer.positionChange
+import androidx.compose.ui.layout.boundsInWindow
+import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.TextRange
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.compose.ui.util.lerp
import com.chethan616.clearpdf.R
import com.chethan616.clearpdf.ui.AppViewModel
import com.chethan616.clearpdf.ui.LucideIcons
+import com.chethan616.clearpdf.ui.glass.Feel
import com.chethan616.clearpdf.ui.glass.GlassBackButton
import com.chethan616.clearpdf.ui.glass.GlassCircle
import com.chethan616.clearpdf.ui.glass.GlassIcon
+import com.chethan616.clearpdf.ui.glass.GlassMenu
+import com.chethan616.clearpdf.ui.glass.GlassMenuItem
+import com.chethan616.clearpdf.ui.glass.GlassPill
+import com.chethan616.clearpdf.ui.glass.LocalBackdrop
+import com.chethan616.clearpdf.ui.glass.LocalGlassInk
+import com.chethan616.clearpdf.ui.glass.glassBar
+import com.chethan616.clearpdf.ui.glass.pressable
+import com.chethan616.clearpdf.ui.glass.rememberFeel
+import com.chethan616.clearpdf.ui.glass.rememberGlassInk
import com.chethan616.clearpdf.ui.theme.Candy
import com.chethan616.clearpdf.ui.theme.ClearType
import com.chethan616.clearpdf.ui.theme.clear
+import com.kyant.backdrop.backdrops.layerBackdrop
+import com.kyant.backdrop.backdrops.rememberLayerBackdrop
import java.io.File
+import java.util.UUID
+import kotlin.math.ceil
+import kotlin.math.hypot
+import kotlin.math.max
+import kotlin.math.min
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+import org.json.JSONArray
+import org.json.JSONObject
-/** One idea of a mind map: its words, how deep it sits, and (once laid out) its box. */
-internal class MapNode(val text: String, val level: Int) {
- val children = ArrayList<MapNode>()
- var label: String = text
+// ---- the map ---------------------------------------------------------------------------------------
+
+/** The most ideas a map holds (a note is not a database). */
+private const val MAX_NODES = 400
+
+/** The branch colours, in the order a map's first ideas take them. */
+private val BranchColors = listOf(Candy.Sky, Candy.Bubblegum, Candy.Mint, Candy.Tangerine, Candy.Grape, Candy.Lemon, Candy.Tomato, Candy.Lime)
+
+internal fun branchColor(i: Int): Color = if (i < 0) Candy.Sky else BranchColors[i % BranchColors.size]
+
+/**
+ * One idea of a mind map: its words, the colour picked for it (-1: its branch's), whether its
+ * branch is folded away, and how far it was dragged from where the map would put it (dp). The rest
+ * is set by [layoutMind] each time the map changes.
+ */
+internal class MindNode(var text: String, val id: String = UUID.randomUUID().toString().take(12)) {
+ val children = ArrayList<MindNode>()
+ var color = -1
+ var collapsed = false
+ var dx = 0f
+ var dy = 0f
+
+ // set out by layoutMind, in pixels
+ var parent: MindNode? = null
+ var depth = 0
+ var tint = 0
+ var side = 1
var left = 0f
var top = 0f
var width = 0f
var height = 0f
- /** Which of the root's branches it belongs to (its colour). */
- var branch = 0
- val centerY: Float get() = top + height / 2f
+ var span = 0f
+ var hidden = 0
+ var words: StaticLayout? = null
+ var wordsKey = ""
+
+ val cx: Float get() = left + width / 2f
+ val cy: Float get() = top + height / 2f
+ val right: Float get() = left + width
+ val bottom: Float get() = top + height
+
+ fun find(id: String): MindNode? {
+ if (this.id == id) return this
+ for (c in children) c.find(id)?.let { return it }
+ return null
+ }
+
+ fun count(): Int = 1 + children.sumOf { it.count() }
+
+ /** Whether [n] is this idea or one under it. */
+ fun holds(n: MindNode): Boolean = this === n || children.any { it.holds(n) }
}
-/** The most ideas a map draws (a note is not a database). */
-private const val MAX_NODES = 400
+/** A mind map: its centre idea and whether its branches all go to the right. */
+internal class MindDoc(val root: MindNode, var oneSided: Boolean = false) {
+ /** A new mind-map note holding this map. */
+ fun asNote() = com.chethan616.clearpdf.notes.Note(
+ UUID.randomUUID().toString(), com.chethan616.clearpdf.notes.NoteKind.Map,
+ title = root.text.trim(), body = outline(), map = toJson(),
+ )
+}
+
+private fun MindNode.json(): JSONObject = JSONObject().apply {
+ put("id", id)
+ put("t", text)
+ if (color >= 0) put("c", color)
+ if (collapsed) put("f", true)
+ if (dx != 0f) put("dx", dx.toDouble())
+ if (dy != 0f) put("dy", dy.toDouble())
+ if (children.isNotEmpty()) put("k", JSONArray().apply { children.forEach { put(it.json()) } })
+}
+
+private fun JSONObject.node(budget: IntArray): MindNode = MindNode(optString("t"), optString("id").ifEmpty { UUID.randomUUID().toString().take(12) }).also { n ->
+ n.color = optInt("c", -1)
+ n.collapsed = optBoolean("f")
+ n.dx = optDouble("dx", 0.0).toFloat()
+ n.dy = optDouble("dy", 0.0).toFloat()
+ optJSONArray("k")?.let { a ->
+ for (i in 0 until a.length()) {
+ if (budget[0]-- <= 0) break
+ n.children.add(a.getJSONObject(i).node(budget))
+ }
+ }
+}
+
+/** The map as it is kept in its note. */
+internal fun MindDoc.toJson(): String =
+ JSONObject().put("v", 1).put("layout", if (oneSided) "right" else "both").put("root", root.json()).toString()
+
+internal fun mindFromJson(s: String): MindDoc? {
+ if (s.isBlank()) return null
+ return runCatching {
+ val o = JSONObject(s)
+ MindDoc(o.getJSONObject("root").node(intArrayOf(MAX_NODES)), o.optString("layout") == "right")
+ }.getOrNull()
+}
+
+/** The map's ideas as an indented outline (two spaces a level): the note's body, for search and sharing. */
+internal fun MindDoc.outline(): String = buildString {
+ fun walk(n: MindNode, depth: Int) {
+ for (c in n.children) {
+ if (c.text.isNotBlank()) {
+ repeat(depth) { append(" ") }
+ append(c.text.replace('\n', ' ').trim()).append('\n')
+ }
+ walk(c, depth + 1)
+ }
+ }
+ walk(root, 0)
+}.trimEnd()
+
+/** The map as OPML 2.0, which desktop outliners and mind-map apps open. */
+internal fun MindDoc.opml(): String = buildString {
+ fun esc(s: String) = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("\n", "&#10;")
+ append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<opml version=\"2.0\">\n <head><title>")
+ append(esc(root.text)).append("</title></head>\n <body>\n")
+ fun walk(n: MindNode, depth: Int) {
+ val indent = " ".repeat(depth + 2)
+ append(indent).append("<outline text=\"").append(esc(n.text)).append('"')
+ if (n.children.isEmpty()) {
+ append("/>\n")
+ } else {
+ append(">\n")
+ n.children.forEach { walk(it, depth + 1) }
+ append(indent).append("</outline>\n")
+ }
+ }
+ walk(root, 0)
+ append(" </body>\n</opml>\n")
+}
+
+/**
+ * An OPML outline (what desktop outliners and mind-map apps export) as a map: its `outline`
+ * elements nested as ideas, each named by its `text` (or `title`) attribute. One top outline is
+ * the centre; several hang from a centre named by the head's `title`. Null when it has no outline.
+ * Read with a small tokenizer rather than an XML parser, so a damaged file still gives what it can.
+ */
+internal fun mindFromOpml(xml: String): MindDoc? {
+ fun unescape(s: String): String = Regex("&(#x[0-9a-fA-F]+|#\\d+|amp|lt|gt|quot|apos);").replace(s) { m ->
+ val e = m.groupValues[1]
+ when {
+ e == "amp" -> "&"
+ e == "lt" -> "<"
+ e == "gt" -> ">"
+ e == "quot" -> "\""
+ e == "apos" -> "'"
+ e.startsWith("#x") -> e.drop(2).toIntOrNull(16)?.let { String(Character.toChars(it)) } ?: m.value
+ else -> e.drop(1).toIntOrNull()?.let { String(Character.toChars(it)) } ?: m.value
+ }
+ }
+ val attr = Regex("""([A-Za-z_:][-\w:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)')""")
+ fun attrs(s: String): Map<String, String> = attr.findAll(s).associate { it.groupValues[1].lowercase() to unescape(it.groupValues[2].ifEmpty { it.groupValues[3] }) }
+ val title = Regex("<title>(.*?)</title>", RegexOption.DOT_MATCHES_ALL).find(xml)?.groupValues?.get(1)?.let { unescape(it).trim() }.orEmpty()
+ val holder = MindNode(title)
+ val path = ArrayList<MindNode>().apply { add(holder) }
+ var count = 0
+ for (m in Regex("""<(/?)outline\b([^>]*?)(/?)>""", RegexOption.IGNORE_CASE).findAll(xml)) {
+ val closing = m.groupValues[1] == "/"
+ if (closing) {
+ if (path.size > 1) path.removeAt(path.lastIndex)
+ continue
+ }
+ if (++count > MAX_NODES) break
+ val a = attrs(m.groupValues[2])
+ val node = MindNode((a["text"] ?: a["title"] ?: "").replace('\n', ' ').trim())
+ path.last().children.add(node)
+ if (m.groupValues[3] != "/") path.add(node)
+ }
+ if (holder.children.isEmpty()) return null
+ // one top outline is the centre itself
+ return MindDoc(holder.children.singleOrNull() ?: holder)
+}
/**
* A note's outline as a tree. One idea a line: headings (`#`, `##`…) open branches, and under
* them, or with no headings at all, indentation (two spaces or a tab a step) and bullets (`-`,
* `*`, `•`, `1.`) nest ideas under the line above. [title] is the map's centre.
*/
-internal fun parseOutline(title: String, body: String): MapNode {
- val root = MapNode(title.trim(), -1)
- val path = ArrayList<MapNode>().apply { add(root) }
- // where plain lines start counting from: one deeper than the heading they are under
+internal fun parseOutline(title: String, body: String): MindNode {
+ val root = MindNode(title.trim())
+ // each open idea with how deep it sits (the centre at -1)
+ val path = ArrayList<Pair<MindNode, Int>>().apply { add(root to -1) }
var base = 0
var count = 0
for (raw in body.lines()) {
@@ -103,238 +338,1041 @@ internal fun parseOutline(title: String, body: String): MapNode {
s = s.replace("**", "").replace("__", "").trim()
if (s.isEmpty()) continue
if (++count > MAX_NODES) break
- // the line above that is less deep is its parent
- while (path.size > 1 && path.last().level >= level) path.removeAt(path.lastIndex)
- val node = MapNode(s, path.last().level + 1)
- path.last().children.add(node)
- path.add(node)
+ while (path.size > 1 && path.last().second >= level) path.removeAt(path.lastIndex)
+ val node = MindNode(s)
+ val (parent, depth) = path.last()
+ parent.children.add(node)
+ path.add(node to depth + 1)
}
return root
}
-/** A map set out: its tree with every box placed, and the room it takes (pixels at [density]). */
-internal class MapLayout(val root: MapNode, val width: Float, val height: Float, val density: Float)
+// ---- laid out --------------------------------------------------------------------------------------
+
+/** A map set out: every idea shown (in drawing order) with its box placed, and the room they take. */
+internal class MindLayout(val doc: MindDoc, val density: Float, val nodes: List<MindNode>, val bounds: RectF) {
+ /** The idea at ([x], [y]), the one drawn on top; [skip]'s branch is looked through (an idea being dragged). */
+ fun hit(x: Float, y: Float, slop: Float, skip: MindNode? = null): MindNode? =
+ nodes.lastOrNull { (skip == null || !skip.holds(it)) && x >= it.left - slop && x <= it.right + slop && y >= it.top - slop && y <= it.bottom + slop }
+
+ /** The folded idea whose count badge is at ([x], [y]). */
+ fun badgeAt(x: Float, y: Float): MindNode? =
+ nodes.firstOrNull { it.hidden > 0 && hypot(x - badgeX(it), y - it.cy) <= 17f * density }
+}
+
+private fun badgeX(n: MindNode) = if (n.side >= 0) n.right else n.left
+
+/** The app's own face (Plus Jakarta Sans) for the map's words, once a screen has loaded it. */
+internal object MapType {
+ @Volatile
+ private var base: Typeface? = null
+
+ val loaded: Boolean get() = base != null
+
+ fun load(context: android.content.Context) {
+ if (base == null) base = runCatching { androidx.core.content.res.ResourcesCompat.getFont(context, R.font.jakarta) }.getOrNull()
+ }
+
+ fun face(weight: Int): Typeface = Typeface.create(base ?: Typeface.DEFAULT, weight, false)
+}
+
+private fun wordsPaint(d: Float, depth: Int) = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = when (depth) {
+ 0 -> 19f
+ 1 -> 16f
+ else -> 15f
+ } * d
+ typeface = MapType.face(if (depth == 0) 800 else if (depth == 1) 700 else 500)
+}
/**
- * Sets the tree out left to right: the centre at the left, each generation a column further right,
- * leaves stacked down the page and every parent level with the middle of its children.
+ * Sets [doc] out the way mind maps are drawn: the centre in the middle, its ideas branching out to
+ * the right and the left in turn (or all to the right), each idea's own ideas stacked beside it and
+ * centred on it. A dragged idea keeps its offset, and its branch moves with it. Words wrap past a
+ * width and are measured once until they change.
*/
-internal fun layoutMap(root: MapNode, density: Float): MapLayout {
- val d = density
- val paint = mapTextPaint(d, bold = false)
- val bold = mapTextPaint(d, bold = true)
- val maxText = 230f * d
- val pad = 24f * d
- val columns = ArrayList<Float>()
- fun measure(n: MapNode, depth: Int) {
- val p = if (depth <= 1) bold else paint
- n.label = TextUtils.ellipsize(n.text.ifEmpty { " " }, p, maxText, TextUtils.TruncateAt.END).toString()
- n.width = p.measureText(n.label) + (if (depth == 0) 40f else 28f) * d
- n.height = (if (depth == 0) 48f else 36f) * d
- while (columns.size <= depth) columns.add(0f)
- columns[depth] = maxOf(columns[depth], n.width)
- n.children.forEach { measure(it, depth + 1) }
- }
- measure(root, 0)
- val x = FloatArray(columns.size)
- var at = pad
- for (i in columns.indices) {
- x[i] = at
- at += columns[i] + 46f * d
- }
- var cursor = pad
- fun place(n: MapNode, depth: Int, branch: Int) {
- n.left = x[depth]
- n.branch = branch
- if (n.children.isEmpty()) {
- n.top = cursor
- cursor += n.height + 12f * d
- } else {
- n.children.forEachIndexed { i, c -> place(c, depth + 1, if (depth == 0) i else branch) }
- n.top = (n.children.first().centerY + n.children.last().centerY) / 2f - n.height / 2f
+internal fun layoutMind(doc: MindDoc, d: Float, rootHint: String, hint: String): MindLayout {
+ val paints = Array(3) { wordsPaint(d, it) }
+ val shown = ArrayList<MindNode>()
+ fun measure(n: MindNode, parent: MindNode?, depth: Int, branch: Int) {
+ n.parent = parent
+ n.depth = depth
+ n.tint = when {
+ depth == 0 -> -1
+ n.color >= 0 -> n.color
+ depth == 1 -> branch
+ else -> parent!!.tint
+ }
+ val words = n.text.ifBlank { if (depth == 0) rootHint else hint }
+ val key = "$d|$depth|${MapType.loaded}|${n.text.isBlank()}|$words"
+ if (n.words == null || n.wordsKey != key) {
+ val p = paints[depth.coerceAtMost(2)]
+ val max = (if (depth == 0) 240f else 210f) * d
+ val w = ceil(min(Layout.getDesiredWidth(words, p), max)).toInt().coerceAtLeast(1)
+ n.words = StaticLayout.Builder.obtain(words, 0, words.length, p, w)
+ .setAlignment(Layout.Alignment.ALIGN_CENTER)
+ .setIncludePad(false)
+ .setMaxLines(6)
+ .setEllipsize(TextUtils.TruncateAt.END)
+ .build()
+ n.wordsKey = key
}
+ val padX = when (depth) {
+ 0 -> 26f
+ 1 -> 18f
+ else -> 14f
+ } * d
+ val padY = when (depth) {
+ 0 -> 16f
+ 1 -> 11f
+ else -> 9f
+ } * d
+ val words2 = n.words!!
+ n.width = max(words2.width + padX * 2f, (if (depth == 0) 96f else 56f) * d)
+ n.height = words2.height + padY * 2f
+ n.hidden = if (n.collapsed) n.count() - 1 else 0
+ shown.add(n)
+ if (!n.collapsed) n.children.forEachIndexed { i, c -> measure(c, n, depth + 1, if (depth == 0) i else branch) }
}
- place(root, 0, 0)
- return MapLayout(root, at - 46f * d + pad, cursor - 12f * d + pad, d)
-}
+ measure(doc.root, null, 0, 0)
+
+ val gapRoot = 24f * d
+ val gap = 12f * d
+ fun spans(n: MindNode): Float {
+ val kids = if (n.collapsed) emptyList() else n.children
+ val inner = kids.sumOf { spans(it).toDouble() }.toFloat() + (if (n.depth == 0) gapRoot else gap) * (kids.size - 1).coerceAtLeast(0)
+ n.span = max(n.height, inner)
+ return n.span
+ }
+ spans(doc.root)
-private fun mapTextPaint(density: Float, bold: Boolean) = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
- textSize = 15f * density
- typeface = if (bold) Typeface.create(Typeface.DEFAULT, Typeface.BOLD) else Typeface.DEFAULT
+ fun place(n: MindNode, side: Int, edge: Float, centreY: Float) {
+ n.side = side
+ val reach = (if (n.depth == 1) 64f else 40f) * d
+ n.left = if (side > 0) edge + reach else edge - reach - n.width
+ n.top = centreY - n.height / 2f
+ if (n.collapsed || n.children.isEmpty()) return
+ val total = n.children.sumOf { it.span.toDouble() }.toFloat() + gap * (n.children.size - 1)
+ var y = centreY - total / 2f
+ for (c in n.children) {
+ place(c, side, if (side > 0) n.right else n.left, y + c.span / 2f)
+ y += c.span + gap
+ }
+ }
+ val root = doc.root
+ root.side = 0
+ root.left = -root.width / 2f
+ root.top = -root.height / 2f
+ if (!root.collapsed) {
+ for (side in intArrayOf(1, -1)) {
+ val kids = root.children.filterIndexed { i, _ -> if (side > 0) doc.oneSided || i % 2 == 0 else !doc.oneSided && i % 2 == 1 }
+ if (kids.isEmpty()) continue
+ val total = kids.sumOf { it.span.toDouble() }.toFloat() + gapRoot * (kids.size - 1)
+ var y = -total / 2f
+ for (c in kids) {
+ place(c, side, if (side > 0) root.right else root.left, y + c.span / 2f)
+ y += c.span + gapRoot
+ }
+ }
+ }
+ // dragged ideas, with their branches
+ fun shift(n: MindNode, ox: Float, oy: Float) {
+ val x = ox + n.dx * d
+ val y = oy + n.dy * d
+ n.left += x
+ n.top += y
+ if (!n.collapsed) n.children.forEach { shift(it, x, y) }
+ }
+ shift(root, 0f, 0f)
+
+ val bounds = RectF(root.left, root.top, root.right, root.bottom)
+ for (n in shown) {
+ bounds.union(n.left, n.top, n.right, n.bottom)
+ if (n.hidden > 0) bounds.union(badgeX(n) - 12f * d, n.cy - 12f * d, badgeX(n) + 12f * d, n.cy + 12f * d)
+ }
+ return MindLayout(doc, d, shown, bounds)
}
-private val BranchColors = listOf(Candy.Sky, Candy.Bubblegum, Candy.Mint, Candy.Tangerine, Candy.Grape, Candy.Lemon, Candy.Tomato)
+// ---- drawn -----------------------------------------------------------------------------------------
+
+/** A branch from ([x0], [y0]) to ([x1], [y1]): a soft S-curve that thins from [w0] to [w1]. */
+private fun taper(path: Path, x0: Float, y0: Float, x1: Float, y1: Float, w0: Float, w1: Float) {
+ path.reset()
+ val steps = 22
+ val mx = (x0 + x1) / 2f
+ val xs = FloatArray(steps + 1)
+ val ys = FloatArray(steps + 1)
+ for (i in 0..steps) {
+ val t = i / steps.toFloat()
+ val u = 1f - t
+ xs[i] = u * u * u * x0 + 3f * u * u * t * mx + 3f * u * t * t * mx + t * t * t * x1
+ ys[i] = u * u * u * y0 + 3f * u * u * t * y0 + 3f * u * t * t * y1 + t * t * t * y1
+ }
+ val lx = FloatArray(steps + 1)
+ val ly = FloatArray(steps + 1)
+ val rx = FloatArray(steps + 1)
+ val ry = FloatArray(steps + 1)
+ for (i in 0..steps) {
+ val a = max(i - 1, 0)
+ val b = min(i + 1, steps)
+ var tx = xs[b] - xs[a]
+ var ty = ys[b] - ys[a]
+ val len = hypot(tx, ty).coerceAtLeast(0.001f)
+ tx /= len
+ ty /= len
+ val half = lerp(w0, w1, i / steps.toFloat()) / 2f
+ lx[i] = xs[i] - ty * half
+ ly[i] = ys[i] + tx * half
+ rx[i] = xs[i] + ty * half
+ ry[i] = ys[i] - tx * half
+ }
+ path.moveTo(lx[0], ly[0])
+ for (i in 1..steps) path.lineTo(lx[i], ly[i])
+ for (i in steps downTo 0) path.lineTo(rx[i], ry[i])
+ path.close()
+ path.addCircle(x1, y1, w1 / 2f, Path.Direction.CW)
+}
/**
- * Draws [layout] on [canvas] (the screen, a picture or a PDF page, all alike): soft curves from each
- * idea to its children in the branch's colour, the centre as a dark capsule, the first ideas as
- * capsules of colour, the rest as tinted ones.
+ * Draws [layout] on [canvas] (the screen, a picture or a PDF page alike): branches that thin as
+ * they go out, in their branch's colour; the centre as a dark capsule, its first ideas filled with
+ * their colour, the rest as cards edged with it. A folded idea carries the count of what it hides;
+ * [selected] wears a ring, and [target] (where a dragged idea would go) a green one.
*/
-internal fun drawMap(canvas: android.graphics.Canvas, layout: MapLayout, dark: Boolean) {
+internal fun drawMind(canvas: android.graphics.Canvas, layout: MindLayout, dark: Boolean, selected: String? = null, target: String? = null) {
val d = layout.density
- val ink = if (dark) Color.White else Color(0xFF15171C)
- val line = Paint(Paint.ANTI_ALIAS_FLAG).apply {
- style = Paint.Style.STROKE
- strokeWidth = 2.2f * d
- strokeCap = Paint.Cap.ROUND
- }
val fill = Paint(Paint.ANTI_ALIAS_FLAG)
- val plain = mapTextPaint(d, bold = false)
- val bold = mapTextPaint(d, bold = true)
- val box = RectF()
+ val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
+ val badge = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = 11f * d
+ typeface = MapType.face(800)
+ textAlign = Paint.Align.CENTER
+ color = android.graphics.Color.WHITE
+ }
val path = Path()
- fun color(n: MapNode) = BranchColors[n.branch % BranchColors.size]
- fun links(n: MapNode) {
- for (c in n.children) {
- val x0 = n.left + n.width
- val x1 = c.left
- val mid = (x0 + x1) / 2f
- path.reset()
- path.moveTo(x0, n.centerY)
- path.cubicTo(mid, n.centerY, mid, c.centerY, x1, c.centerY)
- line.color = color(c).copy(alpha = 0.75f).toArgb()
- canvas.drawPath(path, line)
- links(c)
- }
- }
- fun boxes(n: MapNode, depth: Int) {
- box.set(n.left, n.top, n.left + n.width, n.top + n.height)
- val text = if (depth <= 1) bold else plain
- when (depth) {
+ val box = RectF()
+ for (n in layout.nodes) {
+ val p = n.parent ?: continue
+ val toRight = n.cx >= p.cx
+ val x0 = if (p.depth == 0) p.cx + (if (toRight) 1f else -1f) * p.width * 0.3f else if (toRight) p.right else p.left
+ val x1 = if (toRight) n.left else n.right
+ val (w0, w1) = when (n.depth) {
+ 1 -> 8f to 3f
+ 2 -> 3.8f to 2f
+ else -> 2.6f to 1.5f
+ }
+ taper(path, x0, p.cy, x1, n.cy, w0 * d, w1 * d)
+ fill.color = branchColor(n.tint).copy(alpha = if (dark) 0.9f else 0.82f).toArgb()
+ canvas.drawPath(path, fill)
+ }
+ val ink = if (dark) Color(0xFFF1F3F9) else Color(0xFF181B26)
+ for (n in layout.nodes) {
+ val colour = branchColor(n.tint)
+ box.set(n.left, n.top, n.right, n.bottom)
+ val radius = min(n.height / 2f, (if (n.depth == 0) 26f else if (n.depth == 1) 18f else 13f) * d)
+ fill.color = Color.Black.copy(alpha = if (dark) 0.3f else 0.08f).toArgb()
+ box.offset(0f, 2.5f * d)
+ canvas.drawRoundRect(box, radius, radius, fill)
+ box.offset(0f, -2.5f * d)
+ val words: Color
+ when (n.depth) {
0 -> {
fill.color = (if (dark) Color(0xFFF2F4FA) else Color(0xFF1E2233)).toArgb()
- text.color = (if (dark) Color(0xFF15171C) else Color.White).toArgb()
+ words = if (dark) Color(0xFF14152B) else Color.White
}
1 -> {
- fill.color = color(n).toArgb()
- text.color = Color.White.toArgb()
+ fill.color = colour.toArgb()
+ words = if (colour.luminance() > 0.5f) Color(0xFF1B1B1F) else Color.White
}
else -> {
- fill.color = color(n).copy(alpha = if (dark) 0.26f else 0.16f).toArgb()
- text.color = ink.toArgb()
+ fill.color = (if (dark) Color(0xFF242842) else Color.White).toArgb()
+ words = ink
}
}
- canvas.drawRoundRect(box, n.height / 2f, n.height / 2f, fill)
- val inset = (if (depth == 0) 20f else 14f) * d
- canvas.drawText(n.label, n.left + inset, n.centerY - (text.descent() + text.ascent()) / 2f, text)
- n.children.forEach { boxes(it, depth + 1) }
+ canvas.drawRoundRect(box, radius, radius, fill)
+ if (n.depth >= 2) {
+ stroke.strokeWidth = 1.6f * d
+ stroke.color = colour.copy(alpha = 0.8f).toArgb()
+ canvas.drawRoundRect(box, radius, radius, stroke)
+ }
+ n.words?.let { w ->
+ w.paint.color = (if (n.text.isBlank()) words.copy(alpha = 0.5f) else words).toArgb()
+ canvas.save()
+ canvas.translate(n.cx - w.width / 2f, n.cy - w.height / 2f)
+ w.draw(canvas)
+ canvas.restore()
+ }
+ if (n.hidden > 0) {
+ val bx = badgeX(n)
+ fill.color = (if (n.depth == 0) Candy.Sky else colour).toArgb()
+ canvas.drawCircle(bx, n.cy, 11f * d, fill)
+ stroke.strokeWidth = 2f * d
+ stroke.color = (if (dark) Color(0xFF14152B) else Color.White).toArgb()
+ canvas.drawCircle(bx, n.cy, 11f * d, stroke)
+ val label = if (n.hidden > 99) "99+" else n.hidden.toString()
+ canvas.drawText(label, bx, n.cy - (badge.descent() + badge.ascent()) / 2f, badge)
+ }
+ if (n.id == selected || n.id == target) {
+ val ring = 5f * d
+ stroke.strokeWidth = 2.5f * d
+ stroke.color = (if (n.id == target) Candy.Mint else Candy.Sky).toArgb()
+ box.inset(-ring, -ring)
+ canvas.drawRoundRect(box, radius + ring, radius + ring, stroke)
+ }
}
- links(layout.root)
- boxes(layout.root, 0)
}
-/** [layout] as a picture file (PNG, at most 4096 pixels on its long side) or a one-page PDF. */
-private fun writeMap(layout: MapLayout, dark: Boolean, pdf: Boolean, out: File) {
- val ground = (if (dark) Color(0xFF14152B) else Color.White).toArgb()
- if (pdf) {
- // a page of the map's own size: a density-independent pixel to a point
- val w = (layout.width / layout.density).toInt().coerceAtLeast(1)
- val h = (layout.height / layout.density).toInt().coerceAtLeast(1)
- val doc = PdfDocument()
+/** [doc] as a picture (PNG, at most 4096 pixels on its long side), a one-page PDF, or OPML. */
+private fun writeMind(doc: MindDoc, d: Float, dark: Boolean, kind: String, out: File, rootHint: String, hint: String) {
+ if (kind == "opml") {
+ out.writeText(doc.opml())
+ return
+ }
+ val layout = layoutMind(doc, d, rootHint, hint)
+ val pad = 36f * d
+ val b = RectF(layout.bounds).apply { inset(-pad, -pad) }
+ if (kind == "pdf") {
+ // a page of the map's own size, a dp to a point, on white (it is for printing)
+ val doc2 = PdfDocument()
try {
- val page = doc.startPage(PdfDocument.PageInfo.Builder(w, h, 1).create())
- page.canvas.drawColor(ground)
- page.canvas.scale(1f / layout.density, 1f / layout.density)
- drawMap(page.canvas, layout, dark)
- doc.finishPage(page)
- out.outputStream().use { doc.writeTo(it) }
+ val page = doc2.startPage(PdfDocument.PageInfo.Builder((b.width() / d).toInt().coerceAtLeast(1), (b.height() / d).toInt().coerceAtLeast(1), 1).create())
+ page.canvas.drawColor(android.graphics.Color.WHITE)
+ page.canvas.scale(1f / d, 1f / d)
+ page.canvas.translate(-b.left, -b.top)
+ drawMind(page.canvas, layout, dark = false)
+ doc2.finishPage(page)
+ out.outputStream().use { doc2.writeTo(it) }
} finally {
- doc.close()
+ doc2.close()
}
} else {
- val k = minOf(1f, 4096f / maxOf(layout.width, layout.height))
- val bitmap = Bitmap.createBitmap((layout.width * k).toInt().coerceAtLeast(1), (layout.height * k).toInt().coerceAtLeast(1), Bitmap.Config.ARGB_8888)
+ val k = min(1f, 4096f / max(b.width(), b.height()))
+ val bitmap = Bitmap.createBitmap((b.width() * k).toInt().coerceAtLeast(1), (b.height() * k).toInt().coerceAtLeast(1), Bitmap.Config.ARGB_8888)
val canvas = android.graphics.Canvas(bitmap)
- canvas.drawColor(ground)
+ canvas.drawColor((if (dark) Color(0xFF14152B) else Color(0xFFF8F9FC)).toArgb())
canvas.scale(k, k)
- drawMap(canvas, layout, dark)
+ canvas.translate(-b.left, -b.top)
+ drawMind(canvas, layout, dark)
out.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
bitmap.recycle()
}
}
+private fun safeName(s: String, fallback: String) =
+ s.replace(Regex("""[\\/:*?"<>|\n\r]"""), " ").trim().take(60).ifEmpty { fallback }
+
+/** The faint dot grid a map lies on, moving and scaling with it. */
+private fun androidx.compose.ui.graphics.drawscope.DrawScope.dots(pan: Offset, scale: Float, d: Float, colour: Color) {
+ var step = 26f * d * scale
+ while (step < 14f * d) step *= 2f
+ val points = ArrayList<Offset>()
+ var x = ((pan.x % step) + step) % step
+ while (x < size.width) {
+ var y = ((pan.y % step) + step) % step
+ while (y < size.height) {
+ points.add(Offset(x, y))
+ y += step
+ }
+ x += step
+ }
+ drawPoints(points, androidx.compose.ui.graphics.PointMode.Points, colour, strokeWidth = 2.4f * d, cap = StrokeCap.Round)
+}
+
+// ---- the editor ------------------------------------------------------------------------------------
+
/**
- * A note seen as a mind map: its title in the middle, its outline branching out to the right. Drag
- * to move it, pinch to zoom; the two buttons save it to Downloads as a picture or a PDF. The map is
- * drawn from the note as it is written (one idea a line, indented under the idea it belongs to), so
- * it is edited by editing the note, and nothing leaves the phone.
+ * A mind-map note. Tap an idea to pick it and tap it again to type; the bar under it adds an idea
+ * under it or beside it, colours its branch, folds it away or deletes it. Drag an idea to move it
+ * (its branch comes along), or drop it on another idea to put it there. Drag the paper to look
+ * around and pinch to zoom. Every change is kept with the note as it is made, and can be undone.
*/
@Composable
-fun MindMapScreen(vm: AppViewModel, title: String, body: String, onClose: () -> Unit) {
+fun MindMapEditor(vm: AppViewModel, id: String) {
+ val note = vm.notes.get(id) ?: run {
+ LaunchedEffect(id) { vm.openNote = null }
+ return
+ }
val c = clear
- val density = LocalDensity.current.density
+ val d = LocalDensity.current.density
val context = LocalContext.current
+ remember(context) { MapType.load(context) }
val scope = rememberCoroutineScope()
+ val feel = rememberFeel()
+ val keyboard = LocalSoftwareKeyboardController.current
+ val rootHint = stringResource(R.string.mindmap_root_hint)
+ val hint = stringResource(R.string.mindmap_node_hint)
val fallback = stringResource(R.string.mindmap_title)
- val layout = remember(title, body, density) { layoutMap(parseOutline(title.ifBlank { fallback }, body), density) }
- var scale by remember { mutableStateOf(1f) }
+
+ var doc by remember(id) { mutableStateOf(mindFromJson(note.map) ?: MindDoc(parseOutline(note.title, note.body))) }
+ var version by remember { mutableIntStateOf(0) }
+ val undo = remember(id) { ArrayList<String>() }
+ val redo = remember(id) { ArrayList<String>() }
+ var history by remember { mutableIntStateOf(0) }
+ var selected by remember { mutableStateOf<String?>(null) }
+ var editing by remember { mutableStateOf<String?>(null) }
+ var fresh by remember { mutableStateOf(false) }
+ var field by remember { mutableStateOf(TextFieldValue()) }
+ var palette by remember { mutableStateOf(false) }
+ var target by remember { mutableStateOf<String?>(null) }
+ var menuAt by remember { mutableStateOf<Rect?>(null) }
+ var moreAnchor by remember { mutableStateOf(Rect.Zero) }
+ var scale by remember { mutableFloatStateOf(1f) }
var pan by remember { mutableStateOf(Offset.Zero) }
- var fitted by remember(layout) { mutableStateOf(false) }
- val empty = layout.root.children.isEmpty()
- BackHandler(onBack = onClose)
+ var view by remember { mutableStateOf(IntSize.Zero) }
+ var fitted by remember { mutableStateOf(false) }
+ val layout = remember(doc, version, d, rootHint, hint) { layoutMind(doc, d, rootHint, hint) }
+ val current by rememberUpdatedState(layout)
+ val focus = remember { FocusRequester() }
+ var glide by remember { mutableStateOf<Job?>(null) }
- fun save(pdf: Boolean) {
- val name = title.ifBlank { fallback }.replace(Regex("""[\\/:*?"<>|\n\r]"""), " ").trim().take(60).ifEmpty { fallback }
+ fun save() {
+ val n = vm.notes.get(id) ?: return
+ val json = doc.toJson()
+ if (n.map != json) vm.notes.put(n.copy(title = doc.root.text.trim(), body = doc.outline(), map = json))
+ }
+ fun changed() {
+ version++
+ save()
+ }
+ // the map as it was, kept before each change for Undo
+ fun keep() {
+ undo.add(doc.toJson())
+ if (undo.size > 80) undo.removeAt(0)
+ redo.clear()
+ history++
+ }
+ fun glideTo(s: Float, p: Offset) {
+ glide?.cancel()
+ val s0 = scale
+ val p0 = pan
+ glide = scope.launch {
+ animate(0f, 1f, animationSpec = spring(dampingRatio = 0.9f, stiffness = 240f)) { v, _ ->
+ scale = lerp(s0, s, v)
+ pan = androidx.compose.ui.geometry.lerp(p0, p, v)
+ }
+ }
+ }
+ fun fit(animated: Boolean = true) {
+ if (view.width == 0) return
+ val b = current.bounds
+ val top = 92f * d
+ val bottom = 130f * d
+ val w = view.width - 40f * d
+ val h = (view.height - top - bottom).coerceAtLeast(100f)
+ val s = min(w / b.width().coerceAtLeast(1f), h / b.height().coerceAtLeast(1f)).coerceIn(0.25f, 1.25f)
+ val p = Offset(view.width / 2f - b.centerX() * s, top + h / 2f - b.centerY() * s)
+ if (animated) glideTo(s, p) else {
+ scale = s
+ pan = p
+ }
+ }
+ fun show(n: MindNode) {
+ val s = scale.coerceIn(0.85f, 1.6f)
+ glideTo(s, Offset(view.width / 2f, view.height * 0.3f) - Offset(n.cx, n.cy) * s)
+ }
+ fun startEdit(n: MindNode, isNew: Boolean) {
+ if (!isNew) keep()
+ fresh = isNew
+ palette = false
+ selected = n.id
+ editing = n.id
+ field = TextFieldValue(n.text, TextRange(0, n.text.length))
+ }
+ fun finishEdit() {
+ val n = editing?.let { doc.root.find(it) }
+ editing = null
+ if (n != null) {
+ n.text = n.text.trim()
+ // an idea left without words goes again
+ if (n.text.isEmpty() && n !== doc.root) {
+ n.parent?.children?.remove(n)
+ selected = n.parent?.id
+ }
+ }
+ changed()
+ // nothing came of it: no step to undo
+ if (undo.isNotEmpty() && undo.last() == doc.toJson()) {
+ undo.removeAt(undo.lastIndex)
+ history++
+ }
+ }
+ fun addChild(p: MindNode) {
+ keep()
+ p.collapsed = false
+ val n = MindNode("")
+ p.children.add(n)
+ version++
+ startEdit(n, isNew = true)
+ feel(Feel.Rise)
+ }
+ fun addSibling(n: MindNode) {
+ val p = n.parent ?: return addChild(n)
+ keep()
+ val s = MindNode("")
+ p.children.add(p.children.indexOf(n) + 1, s)
+ version++
+ startEdit(s, isNew = true)
+ feel(Feel.Rise)
+ }
+ fun delete(n: MindNode) {
+ val p = n.parent ?: return
+ keep()
+ p.children.remove(n)
+ selected = p.id
+ changed()
+ feel(Feel.Fall)
+ }
+ fun fold(n: MindNode) {
+ if (n.children.isEmpty()) return
+ keep()
+ n.collapsed = !n.collapsed
+ changed()
+ feel(if (n.collapsed) Feel.ToggleOff else Feel.ToggleOn)
+ }
+ fun colour(n: MindNode, i: Int) {
+ if (n.color == i) return
+ keep()
+ n.color = i
+ changed()
+ feel(Feel.Tick)
+ }
+ fun step(from: ArrayList<String>, to: ArrayList<String>) {
+ if (editing != null) finishEdit()
+ val s = from.removeLastOrNull() ?: return
+ to.add(doc.toJson())
+ mindFromJson(s)?.let { doc = it }
+ if (selected?.let { doc.root.find(it) } == null) selected = null
+ history++
+ save()
+ feel(Feel.Tick)
+ }
+ fun export(kind: String) {
+ val copy = mindFromJson(doc.toJson()) ?: return
+ val name = safeName(doc.root.text, fallback)
+ val dark = c.dark
scope.launch {
val file = withContext(Dispatchers.Default) {
- runCatching {
- File(context.cacheDir, "map-${System.nanoTime()}.${if (pdf) "pdf" else "png"}").also { writeMap(layout, c.dark, pdf, it) }
- }.getOrNull()
+ runCatching { File(context.cacheDir, "map-${System.nanoTime()}.$kind").also { writeMind(copy, d, dark, kind, it, rootHint, hint) } }.getOrNull()
}
- if (file == null) vm.tell(context.getString(R.string.common_file_unreadable))
- else vm.deliverFile(file, "$name.${if (pdf) "pdf" else "png"}", if (pdf) "application/pdf" else "image/png")
+ val mime = when (kind) {
+ "pdf" -> "application/pdf"
+ "png" -> "image/png"
+ else -> "text/x-opml"
+ }
+ if (file == null) vm.tell(context.getString(R.string.common_file_unreadable)) else vm.deliverFile(file, "$name.$kind", mime)
}
}
- Box(
- Modifier.fillMaxSize().background(if (c.dark) Color(0xFF14152B) else Color(0xFFF6F7FB)).onSizeChanged { size: IntSize ->
- // the whole map in view to begin with, never larger than life
- if (!fitted && size.width > 0 && layout.width > 0f) {
- val s = minOf(1f, size.width / layout.width, size.height * 0.8f / layout.height).coerceAtLeast(0.3f)
- scale = s
- pan = Offset((size.width - layout.width * s) / 2f, (size.height - layout.height * s) / 2f)
- fitted = true
+ BackHandler {
+ when {
+ editing != null -> finishEdit()
+ selected != null -> {
+ selected = null
+ palette = false
}
- },
- ) {
- if (empty) {
- Text(
- stringResource(R.string.mindmap_empty), style = ClearType.Body, color = c.inkSoft, textAlign = TextAlign.Center,
- modifier = Modifier.align(Alignment.Center).padding(40.dp),
- )
- } else {
+ else -> vm.closeNote()
+ }
+ }
+ LaunchedEffect(view) {
+ if (!fitted && view.width > 0) {
+ fit(animated = false)
+ fitted = true
+ }
+ }
+ // a new map starts by naming its centre
+ LaunchedEffect(id) {
+ if (doc.root.text.isBlank() && doc.root.children.isEmpty()) startEdit(doc.root, isNew = true)
+ }
+ // the keyboard put away ends the typing, so no cursor is left blinking in the bar
+ @OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
+ val imeOpen = androidx.compose.foundation.layout.WindowInsets.isImeVisible
+ var imeWasOpen by remember { mutableStateOf(false) }
+ LaunchedEffect(imeOpen) {
+ if (imeOpen) imeWasOpen = true
+ else if (imeWasOpen) {
+ // a moment's grace: going on to the next idea hands the keyboard from one field to the next
+ delay(350)
+ imeWasOpen = false
+ if (editing != null) finishEdit()
+ }
+ }
+ LaunchedEffect(editing) {
+ val n = editing?.let { current.doc.root.find(it) } ?: return@LaunchedEffect
+ // the new idea's field takes the keyboard at once, then the map glides to it
+ runCatching { focus.requestFocus() }
+ keyboard?.show()
+ show(n)
+ }
+
+ val chosen = selected?.let { doc.root.find(it) }?.takeIf { s -> layout.nodes.any { it === s } }
+ val ground = if (c.dark) Color(0xFF14152B) else Color(0xFFF6F7FB)
+ val backdrop = rememberLayerBackdrop()
+ Box(Modifier.fillMaxSize().background(ground)) {
+ Box(Modifier.fillMaxSize().layerBackdrop(backdrop)) {
Canvas(
- Modifier.fillMaxSize().pointerInput(layout) {
- detectTransformGestures { centroid, move, zoom, _ ->
- val next = (scale * zoom).coerceIn(0.2f, 4f)
- pan = (pan - centroid) * (next / scale) + centroid + move
- scale = next
- }
- },
+ Modifier
+ .fillMaxSize()
+ .onSizeChanged { view = it }
+ .pointerInput(id) {
+ awaitEachGesture {
+ val down = awaitFirstDown(requireUnconsumed = false)
+ glide?.cancel()
+ val lay = current
+ val start = (down.position - pan) / scale
+ val badge = lay.badgeAt(start.x, start.y)
+ val hit = if (badge == null) lay.hit(start.x, start.y, 4f * d) else null
+ // the centre doesn't move: dragging it looks around, as the paper does
+ val moving = hit?.takeIf { it !== lay.doc.root }
+ var dragged = false
+ var pinched = false
+ var travel = 0f
+ do {
+ val event = awaitPointerEvent()
+ val pressed = event.changes.count { it.pressed }
+ if (pressed >= 2) {
+ pinched = true
+ if (target != null) target = null
+ val zoom = event.calculateZoom()
+ val move = event.calculatePan()
+ val centre = event.calculateCentroid()
+ val next = (scale * zoom).coerceIn(0.2f, 3f)
+ pan = (pan - centre) * (next / scale) + centre + move
+ scale = next
+ event.changes.forEach { it.consume() }
+ } else if (!pinched) {
+ val ch = event.changes.firstOrNull { it.id == down.id } ?: event.changes.first()
+ val delta = ch.positionChange()
+ travel += delta.getDistance()
+ if (!dragged && travel > viewConfiguration.touchSlop) {
+ dragged = true
+ if (moving != null) {
+ if (editing != null) finishEdit()
+ keep()
+ selected = moving.id
+ palette = false
+ feel(Feel.Press)
+ }
+ }
+ if (dragged) {
+ if (moving != null) {
+ moving.dx += delta.x / scale / d
+ moving.dy += delta.y / scale / d
+ version++
+ val at = (ch.position - pan) / scale
+ val over = current.hit(at.x, at.y, 0f, skip = moving)?.takeIf { it !== moving.parent }
+ if (over?.id != target) {
+ target = over?.id
+ if (over != null) feel(Feel.Tick)
+ }
+ } else {
+ pan += delta
+ }
+ ch.consume()
+ }
+ }
+ } while (event.changes.any { it.pressed })
+ when {
+ moving != null && dragged -> {
+ val into = target?.let { doc.root.find(it) }
+ if (into != null && !pinched) {
+ moving.parent?.children?.remove(moving)
+ moving.dx = 0f
+ moving.dy = 0f
+ into.collapsed = false
+ into.children.add(moving)
+ feel(Feel.Confirm)
+ }
+ target = null
+ changed()
+ }
+ dragged || pinched -> Unit
+ badge != null -> fold(badge)
+ hit != null -> {
+ palette = false
+ when {
+ editing == hit.id -> Unit
+ editing != null -> {
+ finishEdit()
+ selected = hit.id
+ }
+ // a second tap on the picked idea types in it
+ selected == hit.id -> startEdit(hit, isNew = false)
+ else -> {
+ selected = hit.id
+ feel(Feel.Tick)
+ }
+ }
+ }
+ else -> {
+ if (editing != null) finishEdit()
+ selected = null
+ palette = false
+ }
+ }
+ }
+ },
) {
+ dots(pan, scale, d, (if (c.dark) Color.White else Color(0xFF1E2233)).copy(alpha = if (c.dark) 0.07f else 0.09f))
drawIntoCanvas { cv ->
- val native = cv.nativeCanvas
- native.save()
- native.translate(pan.x, pan.y)
- native.scale(scale, scale)
- drawMap(native, layout, c.dark)
- native.restore()
+ val nc = cv.nativeCanvas
+ nc.save()
+ nc.translate(pan.x, pan.y)
+ nc.scale(scale, scale)
+ drawMind(nc, layout, c.dark, selected, target)
+ nc.restore()
+ }
+ }
+ }
+
+ CompositionLocalProvider(LocalBackdrop provides backdrop) {
+ val ink = rememberGlassInk(c.ink)
+ // ---- top: back, the map's name, undo, redo, more
+ Row(
+ Modifier.fillMaxWidth().statusBarsPadding().padding(horizontal = 14.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ GlassBackButton({
+ if (editing != null) finishEdit()
+ vm.closeNote()
+ }, immediate = true)
+ Row(Modifier.weight(1f).height(44.dp).then(ink.modifier).glassBar().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
+ Icon(LucideIcons.Network, null, tint = Candy.Grape, modifier = Modifier.size(17.dp))
+ Spacer(Modifier.width(8.dp))
+ Text(
+ doc.root.text.ifBlank { fallback }, style = ClearType.Title.copy(fontSize = 15.sp), color = ink.color,
+ maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
+ }
+ val canUndo = history >= 0 && undo.isNotEmpty()
+ val canRedo = history >= 0 && redo.isNotEmpty()
+ GlassCircle(onClick = { step(undo, redo) }, modifier = Modifier.alpha(if (canUndo) 1f else 0.4f), size = 44.dp, label = stringResource(R.string.common_undo)) {
+ GlassIcon(LucideIcons.Undo2, null, Modifier.size(19.dp))
+ }
+ GlassCircle(onClick = { step(redo, undo) }, modifier = Modifier.alpha(if (canRedo) 1f else 0.4f), size = 44.dp, label = stringResource(R.string.common_redo)) {
+ GlassIcon(LucideIcons.Redo2, null, Modifier.size(19.dp))
+ }
+ GlassCircle(
+ onClick = { menuAt = moreAnchor },
+ modifier = Modifier.onGloballyPositioned { moreAnchor = it.boundsInWindow() },
+ size = 44.dp,
+ label = stringResource(R.string.common_more_options),
+ ) {
+ GlassIcon(LucideIcons.Ellipsis, null, Modifier.size(19.dp))
}
}
+
+ // ---- bottom: what can be done with the picked idea, or typing in it
+ Column(
+ Modifier.align(Alignment.BottomCenter).fillMaxWidth().navigationBarsPadding().imePadding().padding(horizontal = 12.dp, vertical = 10.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ val typing = editing?.let { doc.root.find(it) }
+ when {
+ typing != null -> {
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = 58.dp).then(ink.modifier).glassBar(RoundedCornerShape29).padding(start = 18.dp, end = 7.dp, top = 7.dp, bottom = 7.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
+ // Each idea is typed into a field of its own, with its own text and its own
+ // keyboard session: going on to the next idea starts the keyboard afresh, so
+ // nothing typed into the last one carries over into this one.
+ androidx.compose.runtime.key(typing.id) {
+ val ideaId = typing.id
+ val words = remember {
+ androidx.compose.foundation.text.input.TextFieldState(typing.text, TextRange(0, typing.text.length))
+ }
+ LaunchedEffect(words) {
+ androidx.compose.runtime.snapshotFlow { words.text.toString() }.collect { t ->
+ val n = doc.root.find(ideaId) ?: return@collect
+ val clean = t.replace('\n', ' ')
+ if (n.text != clean) {
+ n.text = clean
+ version++
+ save()
+ }
+ }
+ }
+ if (words.text.isEmpty()) {
+ Text(if (typing === doc.root) rootHint else hint, style = ClearType.Body, color = ink.color.copy(alpha = 0.45f))
+ }
+ BasicTextField(
+ state = words,
+ modifier = Modifier.fillMaxWidth().focusRequester(focus),
+ textStyle = ClearType.Body.copy(color = ink.color),
+ cursorBrush = SolidColor(Candy.Sky),
+ lineLimits = androidx.compose.foundation.text.input.TextFieldLineLimits.MultiLine(maxHeightInLines = 3),
+ keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences, imeAction = ImeAction.Done),
+ onKeyboardAction = { finishEdit() },
+ )
+ }
+ }
+ // straight on to the next idea: under this one, or beside it
+ GlassCircle(onClick = {
+ val at = typing.id
+ finishEdit()
+ doc.root.find(at)?.let { addChild(it) }
+ }, size = 44.dp, label = stringResource(R.string.mindmap_child)) {
+ GlassIcon(LucideIcons.Plus, null, Modifier.size(19.dp))
+ }
+ if (typing !== doc.root) {
+ GlassCircle(onClick = {
+ val at = typing.id
+ finishEdit()
+ doc.root.find(at)?.let { addSibling(it) }
+ }, size = 44.dp, label = stringResource(R.string.mindmap_sibling)) {
+ GlassIcon(LucideIcons.RowsAdd, null, Modifier.size(19.dp))
+ }
+ }
+ GlassCircle(onClick = { finishEdit() }, size = 44.dp, tint = Candy.Sky, label = stringResource(R.string.common_done)) {
+ GlassIcon(LucideIcons.Check, null, Modifier.size(20.dp))
+ }
+ }
+ }
+ chosen != null -> {
+ AnimatedVisibility(palette && chosen !== doc.root, enter = fadeIn() + expandVertically(), exit = fadeOut() + shrinkVertically()) {
+ Row(
+ Modifier.then(ink.modifier).glassBar().padding(horizontal = 12.dp, vertical = 10.dp),
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Swatch(Brush.sweepGradient(BranchColors + BranchColors.first()), chosen.color < 0, ink.color, stringResource(R.string.mindmap_branch_colour)) { colour(chosen, -1) }
+ BranchColors.forEachIndexed { i, col ->
+ Swatch(SolidColor(col), chosen.color == i, ink.color, null) { colour(chosen, i) }
+ }
+ }
+ }
+ Row(
+ Modifier.then(ink.modifier).glassBar().padding(horizontal = 6.dp, vertical = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ CompositionLocalProvider(LocalGlassInk provides ink.color) {
+ MapTool(LucideIcons.Plus, stringResource(R.string.mindmap_child)) { addChild(chosen) }
+ if (chosen !== doc.root) MapTool(LucideIcons.RowsAdd, stringResource(R.string.mindmap_sibling)) { addSibling(chosen) }
+ MapTool(LucideIcons.Pencil, stringResource(R.string.mindmap_edit)) { startEdit(chosen, isNew = false) }
+ if (chosen !== doc.root) MapTool(LucideIcons.Palette, stringResource(R.string.mindmap_colour), lit = palette) { palette = !palette }
+ if (chosen.children.isNotEmpty()) {
+ MapTool(if (chosen.collapsed) LucideIcons.Eye else LucideIcons.EyeOff, stringResource(if (chosen.collapsed) R.string.mindmap_unfold else R.string.mindmap_fold)) { fold(chosen) }
+ }
+ if (chosen !== doc.root) MapTool(LucideIcons.Trash2, stringResource(R.string.common_delete), tint = Candy.Tomato) { delete(chosen) }
+ }
+ }
+ }
+ else -> {
+ Text(
+ stringResource(R.string.mindmap_hint), style = ClearType.Caption, color = c.inkSoft, textAlign = TextAlign.Center,
+ modifier = Modifier.padding(horizontal = 24.dp),
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
+ GlassPill(onClick = { addChild(doc.root) }, tint = Candy.Sky, height = 48.dp, label = stringResource(R.string.mindmap_add_idea)) {
+ Icon(LucideIcons.Plus, null, tint = Color.White, modifier = Modifier.size(18.dp))
+ Spacer(Modifier.width(8.dp))
+ Text(stringResource(R.string.mindmap_add_idea), style = ClearType.BodyStrong, color = Color.White)
+ }
+ GlassCircle(onClick = { fit() }, size = 48.dp, label = stringResource(R.string.mindmap_fit)) {
+ GlassIcon(LucideIcons.Maximize, null, Modifier.size(19.dp))
+ }
+ }
+ }
+ }
+ }
+ }
+
+ menuAt?.let { anchor ->
+ GlassMenu(
+ anchor = anchor,
+ onDismiss = { menuAt = null },
+ items = listOf(
+ GlassMenuItem(stringResource(R.string.mindmap_fit), LucideIcons.Maximize) { fit() },
+ GlassMenuItem(stringResource(if (doc.oneSided) R.string.mindmap_both_sides else R.string.mindmap_one_side), LucideIcons.Network) {
+ keep()
+ doc.oneSided = !doc.oneSided
+ changed()
+ scope.launch {
+ delay(30)
+ fit()
+ }
+ },
+ GlassMenuItem(stringResource(R.string.mindmap_save_image), LucideIcons.ImagePlus) { export("png") },
+ GlassMenuItem(stringResource(R.string.mindmap_save_pdf), LucideIcons.FilePdf) { export("pdf") },
+ GlassMenuItem(stringResource(R.string.mindmap_save_opml), LucideIcons.FileOutput) { export("opml") },
+ ),
+ )
}
- Row(
- Modifier.fillMaxWidth().statusBarsPadding().padding(horizontal = 16.dp, vertical = 10.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(10.dp),
+ }
+}
+
+private val RoundedCornerShape29 = androidx.compose.foundation.shape.RoundedCornerShape(29.dp)
+
+/** One of the picked idea's tools: an icon over its name. */
+@Composable
+private fun MapTool(icon: ImageVector, label: String, tint: Color = LocalGlassInk.current, lit: Boolean = false, onClick: () -> Unit) {
+ Column(
+ Modifier.width(58.dp).height(58.dp).pressable(onClick, pressedScale = 0.88f).padding(vertical = 5.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(3.dp),
+ ) {
+ Box(
+ Modifier.size(30.dp).clip(CircleShape).background(if (lit) Candy.Sky else Color.Transparent),
+ contentAlignment = Alignment.Center,
) {
- GlassBackButton(onClose, immediate = true)
- Text(stringResource(R.string.mindmap_title), style = ClearType.Title, color = c.ink, modifier = Modifier.weight(1f).padding(start = 6.dp))
- if (!empty) {
- GlassCircle(onClick = { save(pdf = false) }, label = stringResource(R.string.mindmap_save_image)) {
- GlassIcon(LucideIcons.ImagePlus, null, Modifier.size(20.dp))
+ Icon(icon, null, tint = if (lit) Color.White else tint, modifier = Modifier.size(19.dp))
+ }
+ Text(label, style = ClearType.Label.copy(fontSize = 10.sp, fontWeight = FontWeight.Medium), color = tint.copy(alpha = 0.8f), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+}
+
+/** A colour to pick: a disc, ringed when it is the one in use. */
+@Composable
+private fun Swatch(fill: Brush, on: Boolean, ink: Color, label: String?, onClick: () -> Unit) {
+ Box(
+ Modifier
+ .size(32.dp)
+ .border(if (on) 2.dp else 0.dp, if (on) ink else Color.Transparent, CircleShape)
+ .padding(4.dp)
+ .clip(CircleShape)
+ .background(fill)
+ .pressable(onClick, pressedScale = 0.85f)
+ .then(if (label != null) Modifier.semantics { contentDescription = label } else Modifier),
+ )
+}
+
+// ---- a written note, seen as a map -----------------------------------------------------------------
+
+/**
+ * A text note seen as a mind map: its title in the middle, its outline branching out. Drag to look
+ * around and pinch to zoom; save it as a picture or a PDF, or make it a mind-map note to work on.
+ */
+@Composable
+fun MindMapScreen(vm: AppViewModel, title: String, body: String, onClose: () -> Unit) {
+ val fallback = stringResource(R.string.mindmap_title)
+ val doc = remember(title, body) { MindDoc(parseOutline(title.ifBlank { fallback }, body)) }
+ MindMapPreview(vm, doc, title, onClose = onClose)
+}
+
+/**
+ * A mind map to look at: a note's outline drawn as a map, or an OPML file opened from Files or
+ * another app. Drag to look around and pinch to zoom; save it as a picture or a PDF, or make it a
+ * mind-map note to work on.
+ */
+@Composable
+internal fun MindMapPreview(
+ vm: AppViewModel,
+ doc: MindDoc,
+ title: String,
+ /** Make it a mind-map note; by default the preview closes and the new note opens. */
+ onMake: (() -> Unit)? = null,
+ onClose: () -> Unit,
+) {
+ val c = clear
+ val d = LocalDensity.current.density
+ val context = LocalContext.current
+ remember(context) { MapType.load(context) }
+ val scope = rememberCoroutineScope()
+ val fallback = stringResource(R.string.mindmap_title)
+ val rootHint = stringResource(R.string.mindmap_root_hint)
+ val hint = stringResource(R.string.mindmap_node_hint)
+ val layout = remember(doc, d) { layoutMind(doc, d, rootHint, hint) }
+ var scale by remember { mutableFloatStateOf(1f) }
+ var pan by remember { mutableStateOf(Offset.Zero) }
+ var fitted by remember(layout) { mutableStateOf(false) }
+ val empty = doc.root.children.isEmpty()
+ BackHandler(onBack = onClose)
+
+ fun save(kind: String) {
+ val copy = mindFromJson(doc.toJson()) ?: return
+ val name = safeName(title, fallback)
+ val dark = c.dark
+ scope.launch {
+ val file = withContext(Dispatchers.Default) {
+ runCatching { File(context.cacheDir, "map-${System.nanoTime()}.$kind").also { writeMind(copy, d, dark, kind, it, rootHint, hint) } }.getOrNull()
+ }
+ if (file == null) vm.tell(context.getString(R.string.common_file_unreadable))
+ else vm.deliverFile(file, "$name.$kind", if (kind == "pdf") "application/pdf" else "image/png")
+ }
+ }
+
+ val backdrop = rememberLayerBackdrop()
+ Box(Modifier.fillMaxSize().background(if (c.dark) Color(0xFF14152B) else Color(0xFFF6F7FB))) {
+ Box(
+ Modifier.fillMaxSize().layerBackdrop(backdrop).onSizeChanged { size ->
+ if (!fitted && size.width > 0) {
+ val b = layout.bounds
+ val s = min(size.width * 0.9f / b.width().coerceAtLeast(1f), size.height * 0.7f / b.height().coerceAtLeast(1f)).coerceIn(0.25f, 1.2f)
+ scale = s
+ pan = Offset(size.width / 2f - b.centerX() * s, size.height / 2f - b.centerY() * s)
+ fitted = true
+ }
+ },
+ ) {
+ if (empty) {
+ Text(
+ stringResource(R.string.mindmap_empty), style = ClearType.Body, color = c.inkSoft, textAlign = TextAlign.Center,
+ modifier = Modifier.align(Alignment.Center).padding(40.dp),
+ )
+ } else {
+ Canvas(
+ Modifier.fillMaxSize().pointerInput(layout) {
+ detectTransformGestures { centroid, move, zoom, _ ->
+ val next = (scale * zoom).coerceIn(0.2f, 3f)
+ pan = (pan - centroid) * (next / scale) + centroid + move
+ scale = next
+ }
+ },
+ ) {
+ dots(pan, scale, d, (if (c.dark) Color.White else Color(0xFF1E2233)).copy(alpha = if (c.dark) 0.07f else 0.09f))
+ drawIntoCanvas { cv ->
+ val nc = cv.nativeCanvas
+ nc.save()
+ nc.translate(pan.x, pan.y)
+ nc.scale(scale, scale)
+ drawMind(nc, layout, c.dark)
+ nc.restore()
+ }
+ }
+ }
+ }
+ CompositionLocalProvider(LocalBackdrop provides backdrop) {
+ Row(
+ Modifier.fillMaxWidth().statusBarsPadding().padding(horizontal = 16.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ GlassBackButton(onClose, immediate = true)
+ Text(
+ title.ifBlank { fallback }, style = ClearType.Title, color = c.ink, maxLines = 1, overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f).padding(start = 6.dp),
+ )
+ if (!empty) {
+ GlassCircle(onClick = { save("png") }, label = stringResource(R.string.mindmap_save_image)) {
+ GlassIcon(LucideIcons.ImagePlus, null, Modifier.size(20.dp))
+ }
+ GlassCircle(onClick = { save("pdf") }, label = stringResource(R.string.mindmap_save_pdf)) {
+ GlassIcon(LucideIcons.FilePdf, null, Modifier.size(20.dp))
+ }
}
- GlassCircle(onClick = { save(pdf = true) }, label = stringResource(R.string.mindmap_save_pdf)) {
- GlassIcon(LucideIcons.FilePdf, null, Modifier.size(20.dp))
+ }
+ if (!empty) {
+ GlassPill(
+ onClick = {
+ if (onMake != null) {
+ onMake()
+ } else {
+ onClose()
+ vm.newMindMap(doc)
+ }
+ },
+ modifier = Modifier.align(Alignment.BottomCenter).navigationBarsPadding().padding(bottom = 18.dp),
+ tint = Candy.Grape,
+ height = 50.dp,
+ label = stringResource(R.string.mindmap_make),
+ ) {
+ Icon(LucideIcons.Network, null, tint = Color.White, modifier = Modifier.size(18.dp))
+ Spacer(Modifier.width(8.dp))
+ Text(stringResource(R.string.mindmap_make), style = ClearType.BodyStrong, color = Color.White)
}
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/NoteEditor.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/NoteEditor.kt
index 7275177..8899fd7 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/NoteEditor.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/NoteEditor.kt
@@ -109,6 +109,10 @@ fun NoteEditor(vm: AppViewModel, id: String) {
LaunchedEffect(id) { vm.openNote = null }
return
}
+ if (note.kind == NoteKind.Map) {
+ MindMapEditor(vm, id)
+ return
+ }
BackHandler { vm.closeNote() }
val c = clear
var title by remember(id) { mutableStateOf(TextFieldValue(note.title)) }
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 d6548de..dd52b68 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,31 +1,64 @@
package com.chethan616.clearpdf.ui.notes
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.PointF
+import android.graphics.RectF
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.spring
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
-import androidx.compose.foundation.Image
+import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
+import androidx.compose.foundation.gestures.calculatePan
+import androidx.compose.foundation.gestures.calculateRotation
+import androidx.compose.foundation.gestures.calculateZoom
+import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.isImeVisible
import androidx.compose.foundation.layout.navigationBars
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.layout.windowInsetsTopHeight
-import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.BlurOn
+import androidx.compose.material.icons.rounded.Details
+import androidx.compose.material.icons.rounded.Flip
+import androidx.compose.material.icons.rounded.GridOn
+import androidx.compose.material.icons.rounded.Vignette
+import androidx.compose.material.icons.rounded.WbSunny
+import androidx.compose.material3.Icon
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
@@ -34,25 +67,54 @@ import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.rememberUpdatedState
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.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.RoundRect
+import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.PathFillType
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.drawscope.clipPath
+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.ui.graphics.drawscope.rotate
+import androidx.compose.ui.graphics.nativeCanvas
+import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
-import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.input.pointer.positionChange
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
+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 com.chethan616.clearpdf.R
@@ -60,35 +122,38 @@ 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 androidx.compose.material.icons.rounded.Details
-import androidx.compose.material.icons.rounded.Straighten
-import androidx.compose.material.icons.rounded.Vignette
-import androidx.compose.material.icons.rounded.WbSunny
import com.chethan616.clearpdf.ui.glass.ChromeCapsule
+import com.chethan616.clearpdf.ui.glass.Feel
import com.chethan616.clearpdf.ui.glass.Fluid
import com.chethan616.clearpdf.ui.glass.GlassCircle
import com.chethan616.clearpdf.ui.glass.GlassIcon
import com.chethan616.clearpdf.ui.glass.GlassPill
import com.chethan616.clearpdf.ui.glass.LocalBackdrop
import com.chethan616.clearpdf.ui.glass.LocalGlassInk
-import com.chethan616.clearpdf.ui.glass.RoundedRectangle
import com.chethan616.clearpdf.ui.glass.glassBar
import com.chethan616.clearpdf.ui.glass.pressable
import com.chethan616.clearpdf.ui.glass.rememberBeat
+import com.chethan616.clearpdf.ui.glass.rememberFeel
import com.chethan616.clearpdf.ui.glass.rememberGlassInk
import com.chethan616.clearpdf.ui.theme.Candy
import com.chethan616.clearpdf.ui.theme.ClearType
import com.kyant.backdrop.backdrops.layerBackdrop
import com.kyant.backdrop.backdrops.rememberLayerBackdrop
+import java.io.File
+import kotlin.math.abs
+import kotlin.math.floor
+import kotlin.math.hypot
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
-import java.io.File
-import kotlin.math.abs
/** One adjustment LightCraft can develop. */
private enum class Adjust(
@@ -104,23 +169,32 @@ private enum class Adjust(
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),
+ Whites("light", "whites", R.string.photo_whites, Icons.Rounded.WbSunny, -100f, 100f, 0),
+ Blacks("light", "blacks", R.string.photo_blacks, LucideIcons.Moon, -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),
- // LightCraft's geometry, tone, presence and detail (names as its settings spell them)
- Straighten("geometry", "rotate", R.string.photo_straighten, androidx.compose.material.icons.Icons.Rounded.Straighten, -10f, 10f, 1),
- Whites("light", "whites", R.string.photo_whites, androidx.compose.material.icons.Icons.Rounded.WbSunny, -100f, 100f, 0),
- Blacks("light", "blacks", R.string.photo_blacks, LucideIcons.Moon, -100f, 100f, 0),
Clarity("effects", "clarity", R.string.photo_clarity, LucideIcons.Sparkles, -100f, 100f, 0),
- Sharpen("detail", "sharpen_amount", R.string.photo_sharpen, androidx.compose.material.icons.Icons.Rounded.Details, 0f, 150f, 0),
- Vignette("vignette", "amount", R.string.photo_vignette, androidx.compose.material.icons.Icons.Rounded.Vignette, -100f, 100f, 0),
- // below zero it softens the picture (the nearest LightCraft has to a blur), above it brings detail out
+ Sharpen("detail", "sharpen_amount", R.string.photo_sharpen, Icons.Rounded.Details, 0f, 150f, 0),
+ Vignette("vignette", "amount", R.string.photo_vignette, Icons.Rounded.Vignette, -100f, 100f, 0),
+ // below zero it softens the picture, above it brings detail out
Texture("effects", "texture", R.string.photo_texture, LucideIcons.Droplet, -100f, 100f, 0),
}
-private val TURNS = listOf("Normal", "Rotate90", "Rotate180", "Rotate270")
+/** What the editor is doing: developing, framing, hiding, or writing on the picture. */
+private enum class Mode(val label: Int, val icon: ImageVector) {
+ Adjust(R.string.photo_adjust, LucideIcons.SlidersHorizontal),
+ Crop(R.string.photo_crop, LucideIcons.Crop),
+ Blur(R.string.photo_blur, Icons.Rounded.BlurOn),
+ Text(R.string.photo_text, LucideIcons.Type),
+}
+
+/** The crop shapes (width to height); 0: free, -1: the picture's own. */
+private val SHAPES = listOf(0f to 0f, -1f to -1f, 1f to 1f, 4f to 5f, 3f to 4f, 4f to 3f, 16f to 9f, 9f to 16f)
-/** The shapes Crop steps through (width to height), after "as it is". */
-private val CROPS = listOf(1f to 1f, 4f to 3f, 3f to 4f, 16f to 9f, 9f to 16f)
+/** The colours words can take. */
+private val INKS = listOf(
+ Color.White, Color(0xFF141414), Candy.Lemon, Candy.Tangerine, Candy.Tomato, Candy.Bubblegum, Candy.Grape, Candy.Sky, Candy.Mint, Candy.Lime,
+)
private fun shown(a: Adjust, value: Float): String {
val zero = if (a.decimals > 0) 0.005f else 0.5f
@@ -129,52 +203,245 @@ private fun shown(a: Adjust, value: Float): String {
return (if (value > 0f) "+" else "−") + number
}
+private fun degrees(a: Float): String {
+ if (abs(a) < 0.05f) return "0°"
+ return (if (a > 0f) "+" else "−") + "%.1f°".format(abs(a))
+}
+
+/** [w] × [h] fitted in [area] (less [margin] all round), centred. */
+private fun fit(area: IntSize, w: Float, h: Float, margin: Float = 0f): RectF? {
+ if (area.width <= 0 || area.height <= 0 || w <= 0f || h <= 0f) return null
+ val aw = area.width - margin * 2f
+ val ah = area.height - margin * 2f
+ val k = min(aw / w, ah / h)
+ val left = (area.width - w * k) / 2f
+ val top = (area.height - h * k) / 2f
+ return RectF(left, top, left + w * k, top + h * k)
+}
+
+private fun fontFamily(i: Int) = when (i) {
+ 1 -> FontFamily.Serif
+ 2 -> FontFamily.Monospace
+ 3 -> FontFamily.Cursive
+ else -> FontFamily.SansSerif
+}
+
+private fun decodeMutable(file: File): Bitmap {
+ val opts = BitmapFactory.Options().apply { inMutable = true }
+ return try {
+ BitmapFactory.decodeFile(file.absolutePath, opts) ?: error("not decoded")
+ } catch (_: OutOfMemoryError) {
+ BitmapFactory.decodeFile(file.absolutePath, BitmapFactory.Options().apply { inMutable = true; inSampleSize = 2 }) ?: error("not decoded")
+ }
+}
+
/**
- * A direct-touch editor: the picture remains the focus, while two compact glass cylinders own the
- * adjustment value and adjustment selection. The slider is immediate; rendering happens behind it.
+ * The picture editor. The picture stays the focus; a glass switch at the top picks what the bar
+ * under it does:
+ * - Adjust: LightCraft's light and colour, one slider at a time (hold the picture to see it as it was);
+ * - Crop: a frame with corner and edge handles to drag, a dial to straighten it (±45°), quarter
+ * turns, a mirror, and the usual shapes;
+ * - Blur: paint over what should not be seen, blurred or pixelated (an eraser takes it back);
+ * - Text: tap to write on it; drag words to move them, pinch to size and turn them.
+ * Developing is LightCraft's (its own crop model, so the frame shown is the frame saved); the
+ * brush strokes and words are laid on its output, the same way for the preview and for the save.
*/
-@OptIn(kotlinx.coroutines.FlowPreview::class)
@Composable
fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: () -> Unit) {
val source = remember(noteId, name) { vm.notes.file(name) }
+ PhotoEditScreen(vm, source, name, onSaved = { output ->
+ vm.notes.get(noteId)?.let { note ->
+ vm.notes.put(note.copy(images = note.images.map { if (it == name) output.name else it }))
+ }
+ // opened as a tool: the edited picture is also put in Downloads
+ vm.savePhotoCopy(output)
+ }, onClose = onClose)
+}
+
+/** A picture file opened from Files, Recent or another app: the edited copy goes to Downloads. */
+@Composable
+fun PhotoEditScreen(vm: AppViewModel, image: com.chethan616.clearpdf.ui.OpenedImage, onClose: () -> Unit) {
+ PhotoEditScreen(vm, image.file, image.uri.toString(), outputDir = vm.getApplication<android.app.Application>().cacheDir, onSaved = { output ->
+ vm.saveEditedImage(image, output)
+ output.delete()
+ }, onClose = onClose)
+}
+
+@OptIn(kotlinx.coroutines.FlowPreview::class)
+@Composable
+private fun PhotoEditScreen(
+ vm: AppViewModel,
+ source: File,
+ name: String,
+ outputDir: File = source.parentFile ?: source,
+ onSaved: suspend (File) -> Unit,
+ onClose: () -> Unit,
+) {
+ val context = LocalContext.current
+ val density = LocalDensity.current.density
val editor = remember(name) { PhotoEditor() }
DisposableEffect(editor) { onDispose { editor.release(); editor.close() } }
+ val feel = rememberFeel()
+ val scope = rememberCoroutineScope()
val values = remember(name) { mutableStateMapOf<Adjust, Float>() }
- var turn by remember(name) { mutableStateOf(0) }
var selected by remember(name) { mutableStateOf(Adjust.Exposure) }
- var preview by remember(name) { mutableStateOf<ImageBitmap?>(null) }
+ var mode by remember(name) { mutableStateOf(Mode.Adjust) }
+ // the picture as its camera meant it to stand (its EXIF orientation, which LightCraft leaves to us)
+ val upright = remember(source) { exifFrame(source) }
+ var frame by remember(name) { mutableStateOf(upright) }
+ // the crop as last set by hand: straightening shrinks it to stay on the picture, and gives it back
+ var baseCrop by remember(name) { mutableStateOf(CropBox()) }
+ var shape by remember(name) { mutableIntStateOf(0) }
+ var aspect by remember(name) { mutableStateOf<Float?>(null) }
+ val marks = remember(name) { mutableStateListOf<Mark>() }
+ var marksVersion by remember { mutableIntStateOf(0) }
+ var brush by remember { mutableFloatStateOf(0.06f) }
+ var smudgeKind by remember { mutableIntStateOf(SMUDGE_BLUR) }
+ var brushAt by remember { mutableStateOf<Offset?>(null) }
+ var chosen by remember { mutableStateOf<Label?>(null) }
+ var typing by remember { mutableStateOf<Label?>(null) }
+ var typingNew by remember { mutableStateOf(false) }
+ var typed by remember { mutableStateOf("") }
+ var guide by remember { mutableStateOf(false) }
+ var lastInk by remember { mutableIntStateOf(Color.White.toArgb()) }
+ var lastStyle by remember { mutableIntStateOf(0) }
+ var lastFont by remember { mutableIntStateOf(0) }
+ var cropping by remember { mutableStateOf(false) }
+
+ var preview by remember(name) { mutableStateOf<Bitmap?>(null) }
+ var previewImage by remember(name) { mutableStateOf<ImageBitmap?>(null) }
+ var fx by remember(name) { mutableStateOf<Fx?>(null) }
var original by remember(name) { mutableStateOf<ImageBitmap?>(null) }
+ var framePic by remember(name) { mutableStateOf<ImageBitmap?>(null) }
+ // the turned picture's own size (its shape is what crops and marks are measured against)
+ var frameSize by remember(name) { mutableStateOf<Size?>(null) }
var comparing by remember { mutableStateOf(false) }
var saving by remember { mutableStateOf(false) }
- val scope = rememberCoroutineScope()
- // 0: the whole picture; else the shape of CROPS[crop - 1], cut from the middle
- var crop by remember(name) { mutableStateOf(0) }
- val changed = values.values.any { it != 0f } || turn != 0 || crop != 0
+ var area by remember { mutableStateOf(IntSize.Zero) }
+
+ val changed = values.values.any { it != 0f } || frame != upright || marks.isNotEmpty()
- fun settings(includeAdjustments: Boolean = true): String {
+ fun settings(adjust: Boolean = true, crop: Boolean = true): String {
val root = JSONObject()
- if (includeAdjustments) values.forEach { (adjustment, value) ->
+ if (adjust) values.forEach { (adjustment, value) ->
if (value != 0f) {
val section = root.optJSONObject(adjustment.section) ?: JSONObject().also { root.put(adjustment.section, it) }
section.put(adjustment.field, value.toDouble())
}
}
- if (turn != 0) root.put("orientation", TURNS[turn])
- val whole = original
- if (includeAdjustments && crop != 0 && whole != null && whole.width > 0 && whole.height > 0) {
- // the largest box of the chosen shape, from the middle of the picture as it stands
- val (cw, ch) = CROPS[crop - 1]
- val shape = cw / ch
- val picture = whole.width.toFloat() / whole.height
- val w = minOf(1f, shape / picture).toDouble()
- val h = minOf(1f, picture / shape).toDouble()
- val rect = JSONObject().put("x0", (1 - w) / 2).put("y0", (1 - h) / 2).put("x1", (1 + w) / 2).put("y1", (1 + h) / 2)
- root.put("crop", JSONObject().put("geometry", JSONObject().put("rect", rect).put("angle", 0.0)))
+ if (frame.orientation != "Normal") root.put("orientation", frame.orientation)
+ if (crop && frame.hasCrop) {
+ val c = frame.crop
+ val rect = JSONObject().put("x0", c.x0.toDouble()).put("y0", c.y0.toDouble()).put("x1", c.x1.toDouble()).put("y1", c.y1.toDouble())
+ root.put("crop", JSONObject().put("geometry", JSONObject().put("rect", rect).put("angle", frame.angle.toDouble())))
}
return root.toString()
}
+ // ---- developing: a working preview, the frame to crop in, and the picture as it was
+ LaunchedEffect(source) {
+ snapshotFlow { settings() }
+ .distinctUntilChanged()
+ .debounce(70)
+ .collectLatest { json ->
+ val bmp = withContext(Dispatchers.Default) { runCatching { editor.render(source.absolutePath, json, 1280u).toBitmap() }.getOrNull() } ?: return@collectLatest
+ preview = bmp
+ previewImage = bmp.asImageBitmap()
+ fx = withContext(Dispatchers.Default) { runCatching { fxOf(bmp) }.getOrNull() }
+ }
+ }
+ LaunchedEffect(source) {
+ snapshotFlow { if (mode == Mode.Crop) settings(crop = false) else null }
+ .distinctUntilChanged()
+ .debounce(40)
+ .collectLatest { json ->
+ if (json == null) return@collectLatest
+ framePic = withContext(Dispatchers.Default) { runCatching { editor.render(source.absolutePath, json, 1280u).toBitmap().asImageBitmap() }.getOrNull() } ?: framePic
+ }
+ }
+ LaunchedEffect(source, frame.turns, frame.mirror) {
+ val json = settings(adjust = false, crop = false)
+ withContext(Dispatchers.Default) { runCatching { editor.render(source.absolutePath, json, 1536u).toBitmap() }.getOrNull() }?.let {
+ frameSize = Size(it.width.toFloat(), it.height.toFloat())
+ }
+ }
+ LaunchedEffect(source, frame) {
+ delay(120)
+ val json = settings(adjust = false)
+ original = withContext(Dispatchers.Default) { runCatching { editor.render(source.absolutePath, json, 1280u).toBitmap().asImageBitmap() }.getOrNull() } ?: original
+ }
+
+ // ---- framing
+ fun setAngle(a: Float) {
+ val fs = frameSize ?: return
+ frame = frame.copy(angle = a, crop = fitInside(baseCrop, a, fs.width, fs.height))
+ }
+ fun pickShape(i: Int) {
+ val fs = frameSize ?: return
+ shape = i
+ val (w, h) = SHAPES[i]
+ aspect = when {
+ w == 0f -> null
+ w < 0f -> fs.width / fs.height
+ else -> w / h
+ }
+ aspect?.let {
+ val c = largest(it, frame.crop, frame.angle, fs.width, fs.height)
+ frame = frame.copy(crop = c)
+ baseCrop = c
+ }
+ feel(Feel.Tick)
+ }
+ fun turn() {
+ frame = frame.copy(turns = (frame.turns + 1).mod(4), crop = frame.crop.turned())
+ baseCrop = baseCrop.turned()
+ aspect = aspect?.let { 1f / it }
+ frameSize = frameSize?.let { Size(it.height, it.width) }
+ marks.forEach { it.turn() }
+ marksVersion++
+ feel(Feel.Spin)
+ }
+ fun mirror() {
+ frame = frame.copy(turns = (4 - frame.turns).mod(4), mirror = !frame.mirror, angle = -frame.angle, crop = frame.crop.mirrored())
+ baseCrop = baseCrop.mirrored()
+ marks.forEach { it.mirror() }
+ marksVersion++
+ feel(Feel.Tap)
+ }
+ fun reset() {
+ val sideways = (frame.turns - upright.turns) % 2 != 0
+ values.clear()
+ frame = upright
+ frameSize = frameSize?.let { if (sideways) Size(it.height, it.width) else it }
+ baseCrop = CropBox()
+ shape = 0
+ aspect = null
+ marks.clear()
+ chosen = null
+ marksVersion++
+ feel(Feel.Fall)
+ }
+
+ // ---- words
+ fun startTyping(l: Label, isNew: Boolean) {
+ typing = l
+ typingNew = isNew
+ typed = l.text
+ }
+ fun finishTyping() {
+ val l = typing ?: return
+ typing = null
+ if (typed.isBlank()) {
+ marks.remove(l)
+ if (chosen === l) chosen = null
+ } else {
+ l.text = typed.trimEnd()
+ chosen = l
+ }
+ marksVersion++
+ }
+
val close = rememberBeat(onClose)
val done = rememberBeat(action = {
if (saving) return@rememberBeat
@@ -183,17 +450,34 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
return@rememberBeat
}
saving = true
+ val json = settings()
+ val laid = marks.toList()
+ val fs = frameSize
+ val geometry = frame
scope.launch {
- val output = File(source.parentFile, "edited-${System.currentTimeMillis()}.jpg")
+ val stamp = System.currentTimeMillis()
+ val output = File(outputDir, "edited-$stamp.jpg")
val saved = withContext(Dispatchers.Default) {
- runCatching { editor.exportJpeg(source.absolutePath, settings(), output.absolutePath, 92u) }.isSuccess
+ runCatching {
+ if (laid.isEmpty() || fs == null) {
+ editor.exportJpeg(source.absolutePath, json, output.absolutePath, 92u)
+ } else {
+ val developed = File(context.cacheDir, "developed-$stamp.jpg")
+ try {
+ editor.exportJpeg(source.absolutePath, json, developed.absolutePath, 100u)
+ val bmp = decodeMutable(developed)
+ val place = Placement(fs.width, fs.height, geometry.angle, geometry.crop, bmp.width.toFloat(), bmp.height.toFloat())
+ paintMarks(android.graphics.Canvas(bmp), place, laid, if (laid.any { it is Smudge }) fxOf(bmp) else null)
+ output.outputStream().use { bmp.compress(Bitmap.CompressFormat.JPEG, 92, it) }
+ bmp.recycle()
+ } finally {
+ developed.delete()
+ }
+ }
+ }.isSuccess
}
if (saved) {
- vm.notes.get(noteId)?.let { note ->
- vm.notes.put(note.copy(images = note.images.map { if (it == name) output.name else it }))
- }
- // opened as a tool: the edited picture is also put in Downloads
- vm.savePhotoCopy(output)
+ onSaved(output)
} else {
vm.tell(com.chethan616.clearpdf.text(R.string.photo_not_saved))
}
@@ -202,48 +486,293 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
}
})
- BackHandler(enabled = true) { close() }
-
- // A smaller working render prevents native image development from competing with slider input.
- LaunchedEffect(source) {
- snapshotFlow { settings() }
- .distinctUntilChanged()
- .debounce(80)
- .collectLatest { json ->
- preview = withContext(Dispatchers.Default) {
- runCatching { editor.render(source.absolutePath, json, 1280u).toBitmap().asImageBitmap() }.getOrNull()
- } ?: preview
- }
- }
- LaunchedEffect(source, turn) {
- original = withContext(Dispatchers.Default) {
- runCatching { editor.render(source.absolutePath, settings(includeAdjustments = false), 1280u).toBitmap().asImageBitmap() }.getOrNull()
+ BackHandler(enabled = true) {
+ when {
+ typing != null -> finishTyping()
+ chosen != null -> chosen = null
+ else -> close()
}
}
+ // ---- where things are on screen
+ val pic = preview
+ val shownRect = if (pic != null) fit(area, pic.width.toFloat(), pic.height.toFloat()) else null
+ val place = if (pic != null && frameSize != null) Placement(frameSize!!.width, frameSize!!.height, frame.angle, frame.crop, pic.width.toFloat(), pic.height.toFloat()) else null
+ val frameBox = frameSize?.let { fit(area, it.width, it.height, margin = 22f * density) }
+ val now by rememberUpdatedState(Triple(shownRect, place, frameBox))
+ val k = if (shownRect != null && pic != null) shownRect.width() / pic.width else 1f
+
val backdrop = rememberLayerBackdrop()
Box(Modifier.fillMaxSize().background(Color(0xFF090A0F))) {
Box(Modifier.fillMaxSize().layerBackdrop(backdrop)) {
Box(
Modifier
.fillMaxSize()
- .padding(top = 76.dp, bottom = 176.dp, start = 12.dp, end = 12.dp)
- .pointerInput(Unit) {
- detectTapGestures(onPress = {
- comparing = true
- tryAwaitRelease()
- comparing = false
- })
+ .statusBarsPadding()
+ .navigationBarsPadding()
+ .padding(top = 66.dp, bottom = 168.dp, start = 12.dp, end = 12.dp)
+ .onSizeChanged { area = it }
+ .pointerInput(mode) {
+ when (mode) {
+ Mode.Adjust -> detectTapGestures(onPress = {
+ comparing = true
+ tryAwaitRelease()
+ comparing = false
+ })
+ Mode.Crop -> awaitEachGesture {
+ val down = awaitFirstDown()
+ val box = now.third ?: return@awaitEachGesture
+ val fs = frameSize ?: return@awaitEachGesture
+ val r0 = frame.crop
+ val cr = RectF(box.left + r0.x0 * box.width(), box.top + r0.y0 * box.height(), box.left + r0.x1 * box.width(), box.top + r0.y1 * box.height())
+ val p = down.position
+ val reach = 30f * density
+ val corners = arrayOf(Offset(cr.left, cr.top), Offset(cr.right, cr.top), Offset(cr.right, cr.bottom), Offset(cr.left, cr.bottom))
+ var handle = corners.indexOfFirst { (it - p).getDistance() <= reach }
+ if (handle < 0 && aspect == null) {
+ val near = 22f * density
+ handle = when {
+ abs(p.x - cr.left) <= near && p.y in cr.top..cr.bottom -> 4
+ abs(p.y - cr.top) <= near && p.x in cr.left..cr.right -> 5
+ abs(p.x - cr.right) <= near && p.y in cr.top..cr.bottom -> 6
+ abs(p.y - cr.bottom) <= near && p.x in cr.left..cr.right -> 7
+ else -> -1
+ }
+ }
+ if (handle < 0 && cr.contains(p.x, p.y)) handle = 8
+ if (handle < 0) return@awaitEachGesture
+ cropping = true
+ val minW = 56f * density / box.width()
+ val minH = 56f * density / box.height()
+ var acc = Offset.Zero
+ var stopped = false
+ do {
+ val event = awaitPointerEvent()
+ val ch = event.changes.firstOrNull { it.id == down.id } ?: break
+ val delta = ch.positionChange()
+ acc += delta
+ val dx = acc.x / box.width()
+ val dy = acc.y / box.height()
+ val cur = frame.crop
+ val wanted = when (handle) {
+ // moved a step at a time, across then down, so it slides along an edge it meets
+ 8 -> {
+ val a = constrain(cur, cur.moved(delta.x / box.width(), 0f), frame.angle, fs.width, fs.height)
+ a.moved(0f, delta.y / box.height())
+ }
+ in 0..3 -> {
+ val ax = if (handle == 0 || handle == 3) r0.x1 else r0.x0
+ val ay = if (handle == 0 || handle == 1) r0.y1 else r0.y0
+ val mx = (if (handle == 0 || handle == 3) r0.x0 else r0.x1) + dx
+ val my = (if (handle == 0 || handle == 1) r0.y0 else r0.y1) + dy
+ var w = max(abs(mx - ax), minW)
+ var h = max(abs(my - ay), minH)
+ aspect?.let { a ->
+ if (w * fs.width / (h * fs.height) > a) w = h * fs.height * a / fs.width else h = w * fs.width / a / fs.height
+ }
+ val x0 = if (handle == 0 || handle == 3) ax - w else ax
+ val y0 = if (handle == 0 || handle == 1) ay - h else ay
+ CropBox(x0, y0, x0 + w, y0 + h)
+ }
+ 4 -> cur.copy(x0 = min(r0.x0 + dx, r0.x1 - minW))
+ 5 -> cur.copy(y0 = min(r0.y0 + dy, r0.y1 - minH))
+ 6 -> cur.copy(x1 = max(r0.x1 + dx, r0.x0 + minW))
+ else -> cur.copy(y1 = max(r0.y1 + dy, r0.y0 + minH))
+ }
+ val next = constrain(cur, wanted, frame.angle, fs.width, fs.height)
+ // a light tick the moment the frame meets the picture's edge
+ val blocked = handle != 8 && abs(next.w - wanted.w) + abs(next.h - wanted.h) + abs(next.x0 - wanted.x0) + abs(next.y0 - wanted.y0) > 1e-4f
+ if (blocked && !stopped) feel(Feel.Tick)
+ stopped = blocked
+ frame = frame.copy(crop = next)
+ baseCrop = next
+ ch.consume()
+ } while (event.changes.any { it.pressed })
+ cropping = false
+ }
+ Mode.Blur -> awaitEachGesture {
+ val down = awaitFirstDown()
+ val (rect, pl, _) = now
+ if (rect == null || pl == null || !rect.contains(down.position.x, down.position.y)) return@awaitEachGesture
+ val scaleK = rect.width() / pl.outW
+ fun at(o: Offset): PointF = pl.back((o.x - rect.left) / scaleK, (o.y - rect.top) / scaleK)
+ val sm = Smudge(smudgeKind, brush)
+ sm.points.add(at(down.position))
+ marks.add(sm)
+ chosen = null
+ marksVersion++
+ brushAt = down.position
+ var last = down.position
+ do {
+ val event = awaitPointerEvent()
+ val ch = event.changes.firstOrNull { it.id == down.id } ?: break
+ if ((ch.position - last).getDistance() > 2.5f * density) {
+ sm.points.add(at(ch.position))
+ last = ch.position
+ marksVersion++
+ }
+ brushAt = ch.position
+ ch.consume()
+ } while (event.changes.any { it.pressed })
+ brushAt = null
+ }
+ Mode.Text -> awaitEachGesture {
+ val down = awaitFirstDown()
+ val (rect, pl, _) = now
+ if (rect == null || pl == null) return@awaitEachGesture
+ val scaleK = rect.width() / pl.outW
+ fun out(o: Offset) = Offset((o.x - rect.left) / scaleK, (o.y - rect.top) / scaleK)
+ val o0 = out(down.position)
+ val hit = marks.filterIsInstance<Label>().lastOrNull { labelBox(it, pl).holds(o0.x, o0.y, 10f * density / scaleK) }
+ val wasChosen = hit != null && hit === chosen
+ if (hit != null && hit !== chosen) {
+ chosen = hit
+ feel(Feel.Tick)
+ }
+ val grab = hit?.let { val b = pl.back(o0.x, o0.y); PointF(it.x - b.x, it.y - b.y) }
+ var moved = false
+ var many = false
+ var travel = 0f
+ do {
+ val event = awaitPointerEvent()
+ val pressed = event.changes.count { it.pressed }
+ val l = chosen
+ if (pressed >= 2 && l != null) {
+ many = true
+ l.size = (l.size * event.calculateZoom()).coerceIn(0.015f, 0.45f)
+ l.rotation += event.calculateRotation()
+ val move = event.calculatePan()
+ val c0 = pl.out(l.x, l.y)
+ val b = pl.back(c0.x + move.x / scaleK, c0.y + move.y / scaleK)
+ l.x = b.x
+ l.y = b.y
+ marksVersion++
+ event.changes.forEach { it.consume() }
+ } else if (pressed == 1 && hit != null && !many) {
+ val ch = event.changes.firstOrNull { it.id == down.id } ?: event.changes.first()
+ travel += ch.positionChange().getDistance()
+ if (travel > viewConfiguration.touchSlop) moved = true
+ if (moved && grab != null) {
+ val o = out(ch.position)
+ val b = pl.back(o.x, o.y)
+ hit.x = b.x + grab.x
+ hit.y = b.y + grab.y
+ // held on the middle line while near it
+ val c = pl.out(hit.x, hit.y)
+ val snap = abs(c.x - pl.outW / 2f) < 9f * density / scaleK
+ if (snap) {
+ val s = pl.back(pl.outW / 2f, c.y)
+ hit.x = s.x
+ hit.y = s.y
+ }
+ if (snap && !guide) feel(Feel.Tick)
+ guide = snap
+ marksVersion++
+ ch.consume()
+ }
+ }
+ } while (event.changes.any { it.pressed })
+ guide = false
+ if (!moved && !many) {
+ when {
+ hit != null -> if (wasChosen) startTyping(hit, isNew = false)
+ chosen != null -> chosen = null
+ rect.contains(down.position.x, down.position.y) -> {
+ val b = pl.back(o0.x, o0.y)
+ val l = Label("", b.x, b.y, rotation = -frame.angle, color = lastInk, style = lastStyle, font = lastFont)
+ marks.add(l)
+ chosen = l
+ startTyping(l, isNew = true)
+ }
+ }
+ }
+ }
+ }
},
- contentAlignment = Alignment.Center,
) {
- (if (comparing) original ?: preview else preview)?.let { image ->
- Image(
- bitmap = image,
- contentDescription = null,
- modifier = Modifier.fillMaxSize().clip(RoundedRectangle(24.dp)),
- contentScale = ContentScale.Fit,
- )
+ val gridAlpha by animateFloatAsState(if (cropping) 1f else 0f, Fluid.quick(), label = "grid")
+ Canvas(Modifier.fillMaxSize()) {
+ marksVersion.let { }
+ if (mode == Mode.Crop) {
+ val box = frameBox
+ val img = framePic
+ if (box != null && img != null) {
+ rotate(frame.angle, pivot = Offset(box.centerX(), box.centerY())) {
+ drawImage(
+ img,
+ dstOffset = IntOffset(box.left.roundToInt(), box.top.roundToInt()),
+ dstSize = IntSize(box.width().roundToInt(), box.height().roundToInt()),
+ )
+ }
+ val r = frame.crop
+ val cr = Rect(box.left + r.x0 * box.width(), box.top + r.y0 * box.height(), box.left + r.x1 * box.width(), box.top + r.y1 * box.height())
+ val outside = Path().apply {
+ fillType = PathFillType.EvenOdd
+ addRect(Rect(0f, 0f, size.width, size.height))
+ addRect(cr)
+ }
+ drawPath(outside, Color(0xFF090A0F).copy(alpha = 0.72f))
+ if (gridAlpha > 0f) {
+ for (i in 1..2) {
+ val x = cr.left + cr.width * i / 3f
+ val y = cr.top + cr.height * i / 3f
+ drawLine(Color.White.copy(alpha = 0.55f * gridAlpha), Offset(x, cr.top), Offset(x, cr.bottom), 1f * density)
+ drawLine(Color.White.copy(alpha = 0.55f * gridAlpha), Offset(cr.left, y), Offset(cr.right, y), 1f * density)
+ }
+ }
+ drawRect(Color.White.copy(alpha = 0.9f), cr.topLeft, cr.size, style = Stroke(1.2f * density))
+ val arm = min(22f * density, min(cr.width, cr.height) / 3f)
+ val t = 3.5f * density
+ val o = t / 2f
+ for ((cx, cy, sx, sy) in listOf(
+ Corner(cr.left, cr.top, 1f, 1f), Corner(cr.right, cr.top, -1f, 1f),
+ Corner(cr.right, cr.bottom, -1f, -1f), Corner(cr.left, cr.bottom, 1f, -1f),
+ )) {
+ drawLine(Color.White, Offset(cx - sx * o, cy - sy * o), Offset(cx + sx * arm, cy - sy * o), t, StrokeCap.Round)
+ drawLine(Color.White, Offset(cx - sx * o, cy - sy * o), Offset(cx - sx * o, cy + sy * arm), t, StrokeCap.Round)
+ }
+ if (aspect == null) {
+ val half = min(13f * density, min(cr.width, cr.height) / 6f)
+ drawLine(Color.White, Offset(cr.left, cr.center.y - half), Offset(cr.left, cr.center.y + half), t, StrokeCap.Round)
+ drawLine(Color.White, Offset(cr.right, cr.center.y - half), Offset(cr.right, cr.center.y + half), t, StrokeCap.Round)
+ drawLine(Color.White, Offset(cr.center.x - half, cr.top), Offset(cr.center.x + half, cr.top), t, StrokeCap.Round)
+ drawLine(Color.White, Offset(cr.center.x - half, cr.bottom), Offset(cr.center.x + half, cr.bottom), t, StrokeCap.Round)
+ }
+ }
+ } else {
+ val rect = shownRect
+ val img = if (comparing) original ?: previewImage else previewImage
+ if (rect != null && img != null) {
+ val clip = Path().apply { addRoundRect(RoundRect(Rect(rect.left, rect.top, rect.right, rect.bottom), CornerRadius(20f * density))) }
+ clipPath(clip) {
+ drawImage(
+ img,
+ dstOffset = IntOffset(rect.left.roundToInt(), rect.top.roundToInt()),
+ dstSize = IntSize(rect.width().roundToInt(), rect.height().roundToInt()),
+ )
+ val pl = place
+ if (!comparing && pl != null && marks.isNotEmpty()) {
+ drawIntoCanvas { cv ->
+ val nc = cv.nativeCanvas
+ nc.save()
+ nc.translate(rect.left, rect.top)
+ nc.scale(k, k)
+ paintMarks(nc, pl, if (typing != null) marks.filter { it !== typing } else marks, fx, if (mode == Mode.Text && typing == null) chosen else null)
+ nc.restore()
+ }
+ }
+ }
+ if (guide) {
+ drawLine(Candy.Lemon.copy(alpha = 0.9f), Offset(rect.centerX(), rect.top), Offset(rect.centerX(), rect.bottom), 1.5f * density)
+ }
+ brushAt?.let { at ->
+ val pl = place ?: return@let
+ val radius = brush * pl.long * k / 2f
+ drawCircle(Color.White.copy(alpha = 0.9f), radius, at, style = Stroke(1.5f * density))
+ drawCircle(Color.Black.copy(alpha = 0.25f), radius + 1.5f * density, at, style = Stroke(1f * density))
+ }
+ }
+ }
}
AnimatedVisibility(
visible = comparing,
@@ -251,9 +780,7 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
exit = fadeOut(Fluid.fade()),
modifier = Modifier.align(Alignment.TopCenter),
) {
- Box(
- Modifier.padding(top = 12.dp).background(Color.Black.copy(alpha = 0.58f), ChromeCapsule).padding(horizontal = 14.dp, vertical = 7.dp),
- ) {
+ Box(Modifier.padding(top = 12.dp).background(Color.Black.copy(alpha = 0.58f), ChromeCapsule).padding(horizontal = 14.dp, vertical = 7.dp)) {
Text(stringResource(R.string.photo_original), style = ClearType.Label, color = Color.White)
}
}
@@ -261,161 +788,439 @@ fun PhotoEditScreen(vm: AppViewModel, noteId: String, name: String, onClose: ()
}
CompositionLocalProvider(LocalBackdrop provides backdrop) {
+ val ink = rememberGlassInk(Color.White)
Box(Modifier.fillMaxSize()) {
- PhotoHeader(
- changed = changed,
- onClose = close,
- onDone = done,
- onReset = { values.clear(); turn = 0; crop = 0 },
- onRotate = { turn = (turn + 1) % 4 },
- cropLabel = if (crop == 0) null else CROPS[crop - 1].let { "${it.first.toInt()}:${it.second.toInt()}" },
- onCrop = { crop = (crop + 1) % (CROPS.size + 1) },
- )
- Box(Modifier.align(Alignment.BottomCenter)) {
- PhotoControls(
- selected = selected,
- value = values[selected] ?: 0f,
- onSelect = { selected = it },
- onValueChange = { next ->
- val caught = if (abs(next) < (selected.max - selected.min) * 0.012f) 0f else next
- values[selected] = caught
+ Column(Modifier.fillMaxWidth()) {
+ Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars))
+ Row(
+ Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ GlassCircle(onClick = close, size = 44.dp, ink = Color.White, label = stringResource(R.string.common_cancel)) {
+ GlassIcon(LucideIcons.X, null, Modifier.size(19.dp))
+ }
+ ModeSwitch(mode, Modifier.weight(1f)) {
+ if (typing != null) finishTyping()
+ if (it != mode) feel(Feel.Tick)
+ mode = it
+ if (it != Mode.Text) chosen = null
+ }
+ GlassCircle(
+ onClick = done,
+ size = 44.dp,
+ tint = if (changed) Candy.Sky else Color.Unspecified,
+ ink = Color.White,
+ label = stringResource(R.string.common_done),
+ ) {
+ GlassIcon(LucideIcons.Check, null, Modifier.size(20.dp))
+ }
+ }
+ AnimatedVisibility(
+ visible = changed,
+ enter = fadeIn(Fluid.quick()),
+ exit = fadeOut(Fluid.quick()),
+ modifier = Modifier.align(Alignment.End).padding(end = 14.dp),
+ ) {
+ GlassPill(onClick = { reset() }, height = 32.dp, horizontalPadding = 12.dp, label = stringResource(R.string.photo_reset)) {
+ Text(stringResource(R.string.photo_reset), style = ClearType.Label.copy(fontSize = 12.sp), color = Candy.Lemon)
+ }
+ }
+ }
+
+ Column(
+ Modifier.align(Alignment.BottomCenter).fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ CompositionLocalProvider(LocalGlassInk provides ink.color) {
+ // each bar its own glass (and its own press light), so only the one touched moves
+ fun bar() = Modifier.fillMaxWidth().then(ink.modifier)
+ when (mode) {
+ Mode.Adjust -> {
+ Row(bar().height(72.dp).glassBar().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ val value = values[selected] ?: 0f
+ ValueReadout(stringResource(selected.label), shown(selected, value), value != 0f, ink.color)
+ FeltSlider(value, selected.min..selected.max, ink.color, Modifier.weight(1f), key = selected) { next ->
+ values[selected] = if (abs(next) < (selected.max - selected.min) * 0.012f) 0f else next
+ }
+ }
+ LazyRow(
+ modifier = bar().height(70.dp).glassBar(),
+ contentPadding = PaddingValues(horizontal = 8.dp),
+ horizontalArrangement = Arrangement.spacedBy(2.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ items(Adjust.entries, key = { it.name }) { adjustment ->
+ ToolTab(adjustment.icon, stringResource(adjustment.label), adjustment == selected, dot = (values[adjustment] ?: 0f) != 0f) { selected = adjustment }
+ }
+ }
+ }
+ Mode.Crop -> {
+ Row(bar().height(72.dp).glassBar().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ ValueReadout(stringResource(R.string.photo_straighten), degrees(frame.angle), frame.angle != 0f, ink.color)
+ StraightenDial(frame.angle, ink.color, Modifier.weight(1f)) { setAngle(it) }
+ }
+ Row(bar().height(62.dp).glassBar().padding(horizontal = 6.dp), verticalAlignment = Alignment.CenterVertically) {
+ RoundTool(LucideIcons.RotateCw, stringResource(R.string.photo_rotate)) { turn() }
+ RoundTool(Icons.Rounded.Flip, stringResource(R.string.photo_mirror)) { mirror() }
+ Box(Modifier.padding(horizontal = 4.dp).width(1.dp).height(28.dp).background(ink.color.copy(alpha = 0.2f)))
+ LazyRow(
+ Modifier.weight(1f),
+ contentPadding = PaddingValues(horizontal = 4.dp),
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ itemsIndexed(SHAPES) { i, (w, h) ->
+ val label = when {
+ w == 0f -> stringResource(R.string.photo_free)
+ w < 0f -> stringResource(R.string.photo_shape_original)
+ else -> "${w.toInt()}:${h.toInt()}"
+ }
+ Chip(label, on = shape == i) { pickShape(i) }
+ }
+ }
+ }
+ }
+ Mode.Blur -> {
+ Row(bar().height(72.dp).glassBar().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ ValueReadout(stringResource(R.string.photo_brush), "${(brush * 100).roundToInt()}", false, ink.color)
+ FeltSlider(brush, 0.02f..0.16f, ink.color, Modifier.weight(1f), key = "brush") { brush = it }
+ Box(Modifier.size(34.dp), contentAlignment = Alignment.Center) {
+ val dot by animateDpAsState((10f + (brush - 0.02f) / 0.14f * 24f).dp, Fluid.quick(), label = "brushDot")
+ Box(Modifier.size(dot).clip(CircleShape).background(ink.color.copy(alpha = 0.85f)))
+ }
+ }
+ Row(bar().height(62.dp).glassBar().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Chip(stringResource(R.string.photo_blur), smudgeKind == SMUDGE_BLUR, Icons.Rounded.BlurOn) { smudgeKind = SMUDGE_BLUR }
+ Chip(stringResource(R.string.photo_pixelate), smudgeKind == SMUDGE_PIXELS, Icons.Rounded.GridOn) { smudgeKind = SMUDGE_PIXELS }
+ Chip(stringResource(R.string.photo_erase), smudgeKind == SMUDGE_ERASE, LucideIcons.BrushCleaning) { smudgeKind = SMUDGE_ERASE }
+ Spacer(Modifier.weight(1f))
+ val strokes = marksVersion >= 0 && marks.any { it is Smudge }
+ RoundTool(LucideIcons.Undo2, stringResource(R.string.common_undo), enabled = strokes) {
+ marks.lastOrNull { it is Smudge }?.let { marks.remove(it) }
+ marksVersion++
+ feel(Feel.Tick)
+ }
+ }
+ }
+ Mode.Text -> {
+ val l = chosen
+ Row(bar().height(72.dp).glassBar().padding(horizontal = 10.dp), verticalAlignment = Alignment.CenterVertically) {
+ if (l == null) {
+ Text(
+ stringResource(R.string.photo_text_help), style = ClearType.Label, color = ink.color.copy(alpha = 0.72f),
+ textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),
+ )
+ } else {
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
+ items(INKS) { col ->
+ val on = marksVersion >= 0 && l.color == col.toArgb()
+ Box(
+ Modifier.size(34.dp).border(if (on) 2.dp else 1.dp, if (on) Color.White else Color.White.copy(alpha = 0.25f), CircleShape)
+ .padding(4.dp).clip(CircleShape).background(col)
+ .pressable({
+ l.color = col.toArgb()
+ lastInk = l.color
+ marksVersion++
+ feel(Feel.Tick)
+ }, pressedScale = 0.85f),
+ )
+ }
+ }
+ }
+ }
+ Row(bar().height(62.dp).glassBar().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ GlassPill(
+ onClick = add@{
+ val pl = place ?: return@add
+ val b = pl.back(pl.outW / 2f, pl.outH / 2f)
+ val n = Label("", b.x, b.y, rotation = -frame.angle, color = lastInk, style = lastStyle, font = lastFont)
+ marks.add(n)
+ chosen = n
+ startTyping(n, isNew = true)
+ },
+ tint = Candy.Sky,
+ height = 42.dp,
+ horizontalPadding = 14.dp,
+ label = stringResource(R.string.photo_add_text),
+ ) {
+ Icon(LucideIcons.Plus, null, tint = Color.White, modifier = Modifier.size(16.dp))
+ Spacer(Modifier.width(6.dp))
+ Text(stringResource(R.string.photo_add_text), style = ClearType.Label, color = Color.White)
+ }
+ if (l != null) {
+ Spacer(Modifier.weight(1f))
+ // the font, shown in itself
+ Box(
+ Modifier.size(42.dp).clip(CircleShape).pressable({
+ l.font = (l.font + 1) % LABEL_FONTS
+ lastFont = l.font
+ marksVersion++
+ feel(Feel.Tick)
+ }, pressedScale = 0.88f),
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(stringResource(R.string.photo_font_sample), style = TextStyle(fontFamily = fontFamily(if (marksVersion >= 0) l.font else 0), fontWeight = FontWeight.Bold, fontSize = 17.sp), color = ink.color)
+ }
+ // plain, on a tag, outlined
+ Box(
+ Modifier.size(42.dp).clip(CircleShape).pressable({
+ l.style = (l.style + 1) % LABEL_STYLES
+ lastStyle = l.style
+ marksVersion++
+ feel(Feel.Tick)
+ }, pressedScale = 0.88f),
+ contentAlignment = Alignment.Center,
+ ) {
+ StyleGlyph(if (marksVersion >= 0) l.style else 0, ink.color)
+ }
+ RoundTool(LucideIcons.Pencil, stringResource(R.string.mindmap_edit)) { startTyping(l, isNew = false) }
+ RoundTool(LucideIcons.Trash2, stringResource(R.string.common_delete), tint = Candy.Tomato) {
+ marks.remove(l)
+ chosen = null
+ marksVersion++
+ feel(Feel.Fall)
+ }
+ }
+ }
+ }
+ }
+ }
+ Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars))
+ }
+ }
+
+ // ---- writing: the words big over the dimmed picture, the keyboard up
+ typing?.let { l ->
+ val focus = remember { FocusRequester() }
+ val keyboard = LocalSoftwareKeyboardController.current
+ // the keyboard put away ends the typing, so no cursor is left blinking over the picture
+ @OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
+ val imeOpen = WindowInsets.isImeVisible
+ var imeWasOpen by remember { mutableStateOf(false) }
+ LaunchedEffect(imeOpen) {
+ if (imeOpen) imeWasOpen = true
+ else if (imeWasOpen) {
+ imeWasOpen = false
+ finishTyping()
+ }
+ }
+ LaunchedEffect(l) {
+ delay(60)
+ runCatching { focus.requestFocus() }
+ keyboard?.show()
+ }
+ Box(
+ Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.64f)).pointerInput(l) { detectTapGestures { finishTyping() } }.navigationBarsPadding().imePadding(),
+ ) {
+ Row(Modifier.fillMaxWidth().statusBarsPadding().padding(horizontal = 14.dp, vertical = 8.dp), horizontalArrangement = Arrangement.End) {
+ GlassPill(onClick = { finishTyping() }, tint = Candy.Sky, height = 42.dp, label = stringResource(R.string.common_done)) {
+ Text(stringResource(R.string.common_done), style = ClearType.BodyStrong, color = Color.White)
+ }
+ }
+ BasicTextField(
+ value = typed,
+ onValueChange = { typed = it },
+ modifier = Modifier.align(Alignment.Center).fillMaxWidth().padding(horizontal = 28.dp).focusRequester(focus),
+ textStyle = TextStyle(
+ color = Color(if (marksVersion >= 0) l.color else 0),
+ fontSize = 30.sp,
+ lineHeight = 36.sp,
+ fontFamily = fontFamily(l.font),
+ fontWeight = FontWeight.Bold,
+ textAlign = TextAlign.Center,
+ ),
+ cursorBrush = SolidColor(Candy.Sky),
+ decorationBox = { inner ->
+ Box(contentAlignment = Alignment.Center) {
+ if (typed.isEmpty()) {
+ Text(
+ stringResource(R.string.photo_text_hint),
+ style = TextStyle(color = Color.White.copy(alpha = 0.45f), fontSize = 30.sp, fontFamily = fontFamily(l.font), fontWeight = FontWeight.Bold, textAlign = TextAlign.Center),
+ )
+ }
+ inner()
+ }
},
)
+ LazyRow(
+ Modifier.align(Alignment.BottomCenter).fillMaxWidth().padding(bottom = 14.dp),
+ horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.CenterHorizontally),
+ contentPadding = PaddingValues(horizontal = 16.dp),
+ ) {
+ items(INKS) { col ->
+ val on = l.color == col.toArgb()
+ Box(
+ Modifier.size(32.dp).border(if (on) 2.5.dp else 1.5.dp, if (on) Color.White else Color.White.copy(alpha = 0.4f), CircleShape)
+ .padding(3.dp).clip(CircleShape).background(col)
+ .pressable({
+ l.color = col.toArgb()
+ lastInk = l.color
+ marksVersion++
+ }, pressedScale = 0.85f),
+ )
+ }
+ }
}
}
}
}
}
+private data class Corner(val x: Float, val y: Float, val sx: Float, val sy: Float)
+
+/** The frame a picture starts in: turned and mirrored as its EXIF orientation says (1 to 8). */
+private fun exifFrame(file: File): PhotoFrame {
+ val o = runCatching {
+ androidx.exifinterface.media.ExifInterface(file.absolutePath).getAttributeInt(androidx.exifinterface.media.ExifInterface.TAG_ORIENTATION, 1)
+ }.getOrDefault(1)
+ // EXIF's eight orientations as (mirrored, quarter turns clockwise), LightCraft's `to_parts`
+ val (mirror, turns) = when (o) {
+ 2 -> true to 0
+ 3 -> false to 2
+ 4 -> true to 2
+ 5 -> true to 3
+ 6 -> false to 1
+ 7 -> true to 1
+ 8 -> false to 3
+ else -> false to 0
+ }
+ return PhotoFrame(turns = turns, mirror = mirror)
+}
+
+/** The switch between Adjust, Crop, Blur and Text: a lit capsule slides to the one in use. */
@Composable
-private fun PhotoHeader(
- changed: Boolean,
- onClose: () -> Unit,
- onDone: () -> Unit,
- onReset: () -> Unit,
- onRotate: () -> Unit,
- cropLabel: String?,
- onCrop: () -> Unit,
-) {
+private fun ModeSwitch(mode: Mode, modifier: Modifier, onPick: (Mode) -> Unit) {
val ink = rememberGlassInk(Color.White)
- Column(Modifier.fillMaxWidth()) {
- Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars))
- Row(
- Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(8.dp),
- ) {
- GlassCircle(onClick = onClose, size = 42.dp, ink = Color.White, label = stringResource(R.string.common_cancel)) {
- GlassIcon(LucideIcons.X, null, Modifier.size(19.dp))
- }
- Row(Modifier.weight(1f).height(42.dp).then(ink.modifier).glassBar().padding(horizontal = 15.dp), verticalAlignment = Alignment.CenterVertically) {
- Text(stringResource(R.string.photo_edit), style = ClearType.Title.copy(fontSize = 15.sp), color = ink.color)
- }
- AnimatedVisibility(visible = changed, enter = fadeIn(Fluid.quick()), exit = fadeOut(Fluid.quick())) {
- GlassPill(onClick = onReset, height = 42.dp, horizontalPadding = 13.dp, label = stringResource(R.string.photo_reset)) {
- Text(stringResource(R.string.photo_reset), style = ClearType.Label, color = Candy.Lemon)
+ BoxWithConstraints(modifier.height(48.dp).then(ink.modifier).glassBar().padding(4.dp)) {
+ val each = maxWidth / Mode.entries.size
+ val x by animateDpAsState(each * mode.ordinal, spring(dampingRatio = 0.78f, stiffness = 520f), label = "modeLight")
+ Box(Modifier.offset(x = x).width(each).fillMaxHeight().clip(ChromeCapsule).background(Candy.Sky))
+ Row(Modifier.fillMaxSize()) {
+ Mode.entries.forEach { m ->
+ val on = m == mode
+ Column(
+ Modifier.weight(1f).fillMaxHeight().clip(ChromeCapsule).pressable({ onPick(m) }, pressedScale = 0.92f),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.Center,
+ ) {
+ Icon(m.icon, null, tint = if (on) Color.White else ink.color.copy(alpha = 0.8f), modifier = Modifier.size(15.dp))
+ Text(
+ stringResource(m.label), style = ClearType.Label.copy(fontSize = 9.5.sp, fontWeight = if (on) FontWeight.SemiBold else FontWeight.Medium),
+ color = if (on) Color.White else ink.color.copy(alpha = 0.8f), maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
}
}
- // Crop steps through the shapes (1:1, 4:3, 3:4, 16:9, 9:16) and back to the whole picture
- GlassCircle(onClick = onCrop, size = 42.dp, ink = Color.White, label = stringResource(R.string.photo_crop)) {
- if (cropLabel == null) GlassIcon(LucideIcons.Crop, null, Modifier.size(19.dp))
- else Text(cropLabel, style = ClearType.Label.copy(fontSize = 11.sp), color = Candy.Lemon, maxLines = 1)
- }
- GlassCircle(onClick = onRotate, size = 42.dp, ink = Color.White, label = stringResource(R.string.photo_rotate)) {
- GlassIcon(LucideIcons.RotateCw, null, Modifier.size(19.dp))
- }
- GlassCircle(
- onClick = onDone,
- size = 42.dp,
- tint = if (changed) Candy.Sky else Color.Unspecified,
- ink = Color.White,
- label = stringResource(R.string.common_done),
- ) {
- GlassIcon(LucideIcons.Check, null, Modifier.size(20.dp))
- }
}
}
}
@Composable
-private fun PhotoControls(
- selected: Adjust,
- value: Float,
- onSelect: (Adjust) -> Unit,
- onValueChange: (Float) -> Unit,
-) {
- val ink = rememberGlassInk(Color.White)
- Column(
- Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
- horizontalAlignment = Alignment.CenterHorizontally,
- ) {
- Row(
- Modifier.fillMaxWidth().height(72.dp).then(ink.modifier).glassBar().padding(horizontal = 16.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(12.dp),
- ) {
- Column(Modifier.width(72.dp)) {
- Text(stringResource(selected.label), style = ClearType.Label, color = ink.color.copy(alpha = 0.66f), maxLines = 1, overflow = TextOverflow.Ellipsis)
- Text(shown(selected, value), style = ClearType.Title.copy(fontSize = 22.sp), color = if (value == 0f) ink.color else Candy.Lemon)
+private fun ValueReadout(label: String, value: String, lit: Boolean, ink: Color) {
+ Column(Modifier.width(76.dp)) {
+ Text(label, style = ClearType.Label, color = ink.copy(alpha = 0.66f), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(value, style = ClearType.Title.copy(fontSize = 21.sp), color = if (lit) Candy.Lemon else ink, maxLines = 1)
+ }
+}
+
+/** A slider felt under the thumb: a light tick every fortieth of the way, a firm one through zero. */
+@Composable
+private fun FeltSlider(value: Float, range: ClosedFloatingPointRange<Float>, ink: Color, modifier: Modifier, key: Any, onChange: (Float) -> Unit) {
+ val feel = rememberFeel()
+ val notch = remember(key) { intArrayOf(Int.MIN_VALUE) }
+ Slider(
+ value = value,
+ onValueChange = { v ->
+ val at = Math.round((v - range.start) / (range.endInclusive - range.start).coerceAtLeast(0.0001f) * 40f)
+ if (at != notch[0]) {
+ if (notch[0] != Int.MIN_VALUE) {
+ val throughZero = range.start < 0f && ((value < 0f) != (v < 0f) || v == 0f)
+ feel(if (throughZero) Feel.Tap else Feel.Tick)
+ }
+ notch[0] = at
}
- // felt under the thumb: a light tick every fortieth of the way, a firm one through zero
- val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()
- val notch = remember(selected) { intArrayOf(Int.MIN_VALUE) }
- Slider(
- value = value,
- onValueChange = { v ->
- val at = Math.round((v - selected.min) / (selected.max - selected.min).coerceAtLeast(0.0001f) * 40f)
- if (at != notch[0]) {
- if (notch[0] != Int.MIN_VALUE) {
- val throughZero = selected.min < 0f && ((value < 0f) != (v < 0f) || v == 0f)
- feel(if (throughZero) com.chethan616.clearpdf.ui.glass.Feel.Tap else com.chethan616.clearpdf.ui.glass.Feel.Tick)
+ onChange(v)
+ },
+ valueRange = range,
+ modifier = modifier,
+ colors = SliderDefaults.colors(thumbColor = Candy.Sky, activeTrackColor = Candy.Sky, inactiveTrackColor = ink.copy(alpha = 0.22f)),
+ )
+}
+
+/**
+ * The straighten dial: a ruler of degrees that slides under a fixed blue needle. A tick is felt at
+ * every degree and a firmer one at level; a double tap levels it again.
+ */
+@Composable
+private fun StraightenDial(angle: Float, ink: Color, modifier: Modifier, onChange: (Float) -> Unit) {
+ val feel = rememberFeel()
+ val density = LocalDensity.current.density
+ val perDegree = 9f * density
+ val current by rememberUpdatedState(angle)
+ Box(
+ modifier
+ .fillMaxHeight()
+ .pointerInput(Unit) {
+ detectTapGestures(onDoubleTap = {
+ if (current != 0f) feel(Feel.Tap)
+ onChange(0f)
+ })
+ }
+ .pointerInput(Unit) {
+ var raw = 0f
+ detectHorizontalDragGestures(
+ onDragStart = { raw = current },
+ onHorizontalDrag = { change, dx ->
+ change.consume()
+ raw = (raw - dx / perDegree).coerceIn(-45f, 45f)
+ val next = if (abs(raw) < 0.6f) 0f else (raw * 10f).roundToInt() / 10f
+ val before = current
+ if (next != before) {
+ if (floor(next) != floor(before)) feel(if (next == 0f || before == 0f) Feel.Tap else Feel.Tick)
+ onChange(next)
}
- notch[0] = at
- }
- onValueChange(v)
- },
- valueRange = selected.min..selected.max,
- modifier = Modifier.weight(1f),
- colors = SliderDefaults.colors(
- thumbColor = Candy.Sky,
- activeTrackColor = Candy.Sky,
- inactiveTrackColor = ink.color.copy(alpha = 0.22f),
- ),
- )
- }
- Spacer(Modifier.height(8.dp))
- LazyRow(
- modifier = Modifier.fillMaxWidth().height(70.dp).then(ink.modifier).glassBar(),
- contentPadding = PaddingValues(horizontal = 8.dp),
- horizontalArrangement = Arrangement.spacedBy(2.dp),
- verticalAlignment = Alignment.CenterVertically,
- ) {
- items(Adjust.entries, key = { it.name }) { adjustment ->
- CompositionLocalProvider(LocalGlassInk provides ink.color) {
- AdjustmentTab(adjustment, adjustment == selected, onClick = { onSelect(adjustment) })
- }
+ },
+ )
+ },
+ ) {
+ Canvas(Modifier.fillMaxSize()) {
+ val cx = size.width / 2f
+ val mid = size.height / 2f
+ for (deg in -45..45) {
+ val x = cx + (deg - angle) * perDegree
+ if (x < 0f || x > size.width) continue
+ val fade = (1f - abs(x - cx) / cx).coerceIn(0f, 1f)
+ val major = deg % 5 == 0
+ val h = (if (deg == 0) 22f else if (major) 15f else 8f) * density
+ drawLine(
+ (if (deg == 0) Candy.Lemon else ink).copy(alpha = (if (major) 0.85f else 0.45f) * fade),
+ Offset(x, mid - h / 2f), Offset(x, mid + h / 2f), (if (major) 1.6f else 1.1f) * density, StrokeCap.Round,
+ )
}
+ drawLine(Candy.Sky, Offset(cx, mid - 15f * density), Offset(cx, mid + 15f * density), 3f * density, StrokeCap.Round)
+ drawCircle(Candy.Sky, 3f * density, Offset(cx, mid - 18f * density))
}
- Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars))
}
}
+/** An icon over its name, lit when in use; a dot when it changes the picture. */
@Composable
-private fun AdjustmentTab(adjustment: Adjust, selected: Boolean, onClick: () -> Unit) {
+private fun ToolTab(icon: ImageVector, label: String, selected: Boolean, dot: Boolean = false, onClick: () -> Unit) {
val ink = LocalGlassInk.current
Column(
Modifier.width(68.dp).height(62.dp).pressable(onClick, pressedScale = 0.9f).padding(vertical = 4.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
- Box(
- Modifier.size(34.dp).clip(ChromeCapsule).background(if (selected) Candy.Sky else Color.Transparent),
- contentAlignment = Alignment.Center,
- ) {
- GlassIcon(adjustment.icon, null, Modifier.size(19.dp), tint = if (selected) Color.White else ink)
+ Box(Modifier.size(34.dp), contentAlignment = Alignment.Center) {
+ Box(Modifier.size(34.dp).clip(ChromeCapsule).background(if (selected) Candy.Sky else Color.Transparent), contentAlignment = Alignment.Center) {
+ GlassIcon(icon, null, Modifier.size(19.dp), tint = if (selected) Color.White else ink)
+ }
+ if (dot && !selected) Box(Modifier.align(Alignment.TopEnd).size(7.dp).clip(CircleShape).background(Candy.Lemon))
}
Text(
- stringResource(adjustment.label),
+ label,
style = ClearType.Label.copy(fontSize = 10.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal),
color = if (selected) ink else ink.copy(alpha = 0.62f),
maxLines = 1,
@@ -424,3 +1229,45 @@ private fun AdjustmentTab(adjustment: Adjust, selected: Boolean, onClick: () ->
)
}
}
+
+/** A capsule to pick, lit when picked. */
+@Composable
+private fun Chip(label: String, on: Boolean, icon: ImageVector? = null, onClick: () -> Unit) {
+ val ink = LocalGlassInk.current
+ Row(
+ Modifier.height(38.dp).clip(ChromeCapsule).background(if (on) Candy.Sky else ink.copy(alpha = 0.08f))
+ .pressable(onClick, pressedScale = 0.92f).padding(horizontal = 13.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ if (icon != null) {
+ Icon(icon, null, tint = if (on) Color.White else ink, modifier = Modifier.size(16.dp))
+ Spacer(Modifier.width(6.dp))
+ }
+ Text(label, style = ClearType.Label.copy(fontSize = 12.sp, fontWeight = if (on) FontWeight.SemiBold else FontWeight.Medium), color = if (on) Color.White else ink, maxLines = 1)
+ }
+}
+
+/** A round icon button inside a bar. */
+@Composable
+private fun RowScope.RoundTool(icon: ImageVector, label: String, tint: Color = LocalGlassInk.current, enabled: Boolean = true, onClick: () -> Unit) {
+ Box(
+ Modifier.size(42.dp).clip(CircleShape).pressable({ if (enabled) onClick() }, pressedScale = 0.88f),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(icon, label, tint = tint.copy(alpha = if (enabled) 1f else 0.35f), modifier = Modifier.size(19.dp))
+ }
+}
+
+/** How words sit: plain, on a filled tag, or outlined. */
+@Composable
+private fun StyleGlyph(style: Int, ink: Color) {
+ when (style) {
+ 1 -> Box(Modifier.size(24.dp, 20.dp).clip(androidx.compose.foundation.shape.RoundedCornerShape(6.dp)).background(ink), contentAlignment = Alignment.Center) {
+ Text("A", style = TextStyle(fontWeight = FontWeight.Black, fontSize = 13.sp), color = Color(0xFF141414))
+ }
+ 2 -> Box(Modifier.size(24.dp, 20.dp).border(1.5.dp, ink, androidx.compose.foundation.shape.RoundedCornerShape(6.dp)), contentAlignment = Alignment.Center) {
+ Text("A", style = TextStyle(fontWeight = FontWeight.Black, fontSize = 13.sp), color = ink)
+ }
+ else -> Text("A", style = TextStyle(fontWeight = FontWeight.Black, fontSize = 18.sp), color = ink)
+ }
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoMarks.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoMarks.kt
new file mode 100644
index 0000000..d0142f6
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoMarks.kt
@@ -0,0 +1,450 @@
+package com.chethan616.clearpdf.ui.notes
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.DashPathEffect
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.PointF
+import android.graphics.PorterDuff
+import android.graphics.PorterDuffXfermode
+import android.graphics.RectF
+import android.graphics.Typeface
+import android.text.Layout
+import android.text.StaticLayout
+import android.text.TextPaint
+import kotlin.math.abs
+import kotlin.math.ceil
+import kotlin.math.cos
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.roundToInt
+import kotlin.math.sin
+
+// ---- the frame: turns, mirror, straighten and crop -------------------------------------------------
+
+/**
+ * A crop, as LightCraft keeps it: a rectangle normalized to the turned picture (x / width,
+ * y / height), axis-aligned in the frame the straighten angle turns the picture in.
+ */
+internal data class CropBox(val x0: Float = 0f, val y0: Float = 0f, val x1: Float = 1f, val y1: Float = 1f) {
+ val w: Float get() = x1 - x0
+ val h: Float get() = y1 - y0
+ val cx: Float get() = (x0 + x1) / 2f
+ val cy: Float get() = (y0 + y1) / 2f
+ val isWhole: Boolean get() = x0 <= 1e-4f && y0 <= 1e-4f && x1 >= 1f - 1e-4f && y1 >= 1f - 1e-4f
+
+ fun moved(dx: Float, dy: Float) = CropBox(x0 + dx, y0 + dy, x1 + dx, y1 + dy)
+
+ /** This crop on the picture turned a quarter clockwise: (x, y) goes to (1 - y, x). */
+ fun turned() = CropBox(1f - y1, x0, 1f - y0, x1)
+
+ /** This crop on the picture mirrored left to right. */
+ fun mirrored() = CropBox(1f - x1, y0, 1f - x0, y1)
+}
+
+private fun mix(a: Float, b: Float, t: Float) = a + (b - a) * t
+
+private fun mix(a: CropBox, b: CropBox, t: Float) = CropBox(mix(a.x0, b.x0, t), mix(a.y0, b.y0, t), mix(a.x1, b.x1, t), mix(a.y1, b.y1, t))
+
+/**
+ * How the picture is framed: [turns] quarter turns clockwise after an optional [mirror], then
+ * straightened by [angle] degrees (clockwise) and cropped to [crop].
+ */
+internal data class PhotoFrame(val turns: Int = 0, val mirror: Boolean = false, val angle: Float = 0f, val crop: CropBox = CropBox()) {
+ /** LightCraft's orientation for the turns and the mirror (its `Orientation::from_parts`). */
+ val orientation: String
+ get() = when (turns.mod(4)) {
+ 0 -> if (mirror) "FlipH" else "Normal"
+ 1 -> if (mirror) "Transverse" else "Rotate90"
+ 2 -> if (mirror) "FlipV" else "Rotate180"
+ else -> if (mirror) "Transpose" else "Rotate270"
+ }
+ val isPlain: Boolean get() = turns.mod(4) == 0 && !mirror && angle == 0f && crop.isWhole
+ val hasCrop: Boolean get() = angle != 0f || !crop.isWhole
+}
+
+/** Whether every corner of [r] lies on the picture ([w] × [h]) once it is straightened by [angle]. */
+internal fun fits(r: CropBox, angle: Float, w: Float, h: Float): Boolean {
+ if (r.x0 > r.x1 || r.y0 > r.y1) return false
+ val a = Math.toRadians(-angle.toDouble())
+ val c = cos(a).toFloat()
+ val s = sin(a).toFloat()
+ val eps = 1e-3f
+ for ((nx, ny) in arrayOf(r.x0 to r.y0, r.x1 to r.y0, r.x1 to r.y1, r.x0 to r.y1)) {
+ val dx = nx * w - w / 2f
+ val dy = ny * h - h / 2f
+ val qx = (w / 2f + dx * c - dy * s) / w
+ val qy = (h / 2f + dx * s + dy * c) / h
+ if (qx < -eps || qy < -eps || qx > 1f + eps || qy > 1f + eps) return false
+ }
+ return true
+}
+
+/** As far from [from] towards [to] as the crop can go and stay on the picture. */
+internal fun constrain(from: CropBox, to: CropBox, angle: Float, w: Float, h: Float): CropBox {
+ if (fits(to, angle, w, h)) return to
+ if (!fits(from, angle, w, h)) return fitInside(from, angle, w, h)
+ var lo = 0f
+ var hi = 1f
+ repeat(18) {
+ val m = (lo + hi) / 2f
+ if (fits(mix(from, to, m), angle, w, h)) lo = m else hi = m
+ }
+ return mix(from, to, lo)
+}
+
+/** [r], shrunk (and drawn towards the middle) until it lies on the picture straightened by [angle]. */
+internal fun fitInside(r: CropBox, angle: Float, w: Float, h: Float): CropBox {
+ if (fits(r, angle, w, h)) return r
+ fun at(t: Float): CropBox {
+ val cx = mix(0.5f, r.cx, t)
+ val cy = mix(0.5f, r.cy, t)
+ return CropBox(cx - r.w * t / 2f, cy - r.h * t / 2f, cx + r.w * t / 2f, cy + r.h * t / 2f)
+ }
+ var lo = 0f
+ var hi = 1f
+ repeat(20) {
+ val m = (lo + hi) / 2f
+ if (fits(at(m), angle, w, h)) lo = m else hi = m
+ }
+ return at(lo)
+}
+
+/** The largest crop of [aspect] (width over height, in pixels) about the middle of [around]. */
+internal fun largest(aspect: Float, around: CropBox, angle: Float, w: Float, h: Float): CropBox {
+ val pic = w / h
+ val nw = min(1f, aspect / pic)
+ val nh = min(1f, pic / aspect)
+ val whole = CropBox(around.cx - nw / 2f, around.cy - nh / 2f, around.cx + nw / 2f, around.cy + nh / 2f)
+ // kept on the picture's own square first, then on the straightened picture
+ val dx = when {
+ whole.x0 < 0f -> -whole.x0
+ whole.x1 > 1f -> 1f - whole.x1
+ else -> 0f
+ }
+ val dy = when {
+ whole.y0 < 0f -> -whole.y0
+ whole.y1 > 1f -> 1f - whole.y1
+ else -> 0f
+ }
+ return fitInside(whole.moved(dx, dy), angle, w, h)
+}
+
+// ---- what is drawn on the picture ------------------------------------------------------------------
+
+internal const val SMUDGE_BLUR = 0
+internal const val SMUDGE_PIXELS = 1
+internal const val SMUDGE_ERASE = 2
+
+/** Something laid on the picture, placed in the turned (not yet straightened or cropped) picture. */
+internal sealed class Mark
+
+/** A brush stroke that blurs or pixelates what is under it, or takes that back ([SMUDGE_ERASE]). */
+internal class Smudge(val kind: Int, val width: Float) : Mark() {
+ /** Normalized to the turned picture; [width] is a share of its long side. */
+ val points = ArrayList<PointF>()
+}
+
+/**
+ * Words on the picture: centred at ([x], [y]) of the turned picture, [size] a share of its long
+ * side, turned [rotation] degrees, in [color] and one of the fonts and styles ([style]: 0 plain
+ * with a soft shadow, 1 on a filled tag, 2 outlined).
+ */
+internal class Label(
+ var text: String,
+ var x: Float,
+ var y: Float,
+ var size: Float = 0.06f,
+ var rotation: Float = 0f,
+ var color: Int = android.graphics.Color.WHITE,
+ var style: Int = 0,
+ var font: Int = 0,
+) : Mark()
+
+internal const val LABEL_FONTS = 4
+internal const val LABEL_STYLES = 3
+
+/** The marks follow the picture as it turns a quarter clockwise. */
+internal fun Mark.turn() {
+ when (this) {
+ is Smudge -> points.forEach { val x = it.x; it.x = 1f - it.y; it.y = x }
+ is Label -> {
+ val x0 = x
+ x = 1f - y
+ y = x0
+ rotation += 90f
+ }
+ }
+}
+
+/** The marks follow the picture as it is mirrored. */
+internal fun Mark.mirror() {
+ when (this) {
+ is Smudge -> points.forEach { it.x = 1f - it.x }
+ is Label -> {
+ x = 1f - x
+ rotation = -rotation
+ }
+ }
+}
+
+/**
+ * Where the turned picture ([w] × [h], any unit) lands in a developed output of [outW] × [outH]
+ * pixels: straightened by [angle] about its middle, then cropped to [crop] (LightCraft's
+ * `output_to_source`, the other way round).
+ */
+internal class Placement(val w: Float, val h: Float, val angle: Float, val crop: CropBox, val outW: Float, val outH: Float) {
+ private val c = cos(Math.toRadians(angle.toDouble())).toFloat()
+ private val s = sin(Math.toRadians(angle.toDouble())).toFloat()
+
+ /** Output pixels to a unit of the turned picture. */
+ val scale = outW / (crop.w * w).coerceAtLeast(1e-6f)
+
+ /** The turned picture's long side, in output pixels: what mark sizes are shares of. */
+ val long = max(w, h) * scale
+
+ fun out(nx: Float, ny: Float, into: PointF = PointF()): PointF {
+ val dx = nx * w - w / 2f
+ val dy = ny * h - h / 2f
+ val rx = w / 2f + dx * c - dy * s
+ val ry = h / 2f + dx * s + dy * c
+ into.set((rx - crop.x0 * w) * scale, (ry - crop.y0 * h) * scale)
+ return into
+ }
+
+ fun back(ox: Float, oy: Float): PointF {
+ val rx = ox / scale + crop.x0 * w
+ val ry = oy / scale + crop.y0 * h
+ val dx = rx - w / 2f
+ val dy = ry - h / 2f
+ return PointF((w / 2f + dx * c + dy * s) / w, (h / 2f - dx * s + dy * c) / h)
+ }
+}
+
+/** The picture blurred and pixelated, small: drawn stretched under the brush strokes. */
+internal class Fx(val blur: Bitmap, val pixels: Bitmap)
+
+/**
+ * [picture] blurred and pixelated. Both are made at a fixed share of the picture's long side, so
+ * the small preview and the full-size save look the same.
+ */
+internal fun fxOf(picture: Bitmap): Fx {
+ val long = max(picture.width, picture.height).toFloat()
+ val k = 320f / long
+ val small = Bitmap.createScaledBitmap(picture, max(1, (picture.width * k).roundToInt()), max(1, (picture.height * k).roundToInt()), true)
+ val px = IntArray(small.width * small.height)
+ small.getPixels(px, 0, small.width, 0, 0, small.width, small.height)
+ boxBlur(px, small.width, small.height, 7)
+ val blur = Bitmap.createBitmap(px, small.width, small.height, Bitmap.Config.ARGB_8888)
+ if (small !== picture) small.recycle()
+ val q = 44f / long
+ val pixels = Bitmap.createScaledBitmap(picture, max(1, (picture.width * q).roundToInt()), max(1, (picture.height * q).roundToInt()), true)
+ return Fx(blur, pixels)
+}
+
+/** Three box blurs across and down: close to a Gaussian of about [r] pixels. */
+private fun boxBlur(px: IntArray, w: Int, h: Int, r: Int) {
+ val tmp = IntArray(px.size)
+ repeat(3) {
+ boxPass(px, tmp, w, h, r, across = true)
+ boxPass(tmp, px, w, h, r, across = false)
+ }
+}
+
+private fun boxPass(src: IntArray, dst: IntArray, w: Int, h: Int, r: Int, across: Boolean) {
+ val lines = if (across) h else w
+ val len = if (across) w else h
+ val div = 2 * r + 1
+ for (line in 0 until lines) {
+ val base = if (across) line * w else line
+ val stride = if (across) 1 else w
+ var a = 0
+ var rr = 0
+ var g = 0
+ var b = 0
+ for (i in -r..r) {
+ val c = src[base + i.coerceIn(0, len - 1) * stride]
+ a += c ushr 24
+ rr += (c shr 16) and 255
+ g += (c shr 8) and 255
+ b += c and 255
+ }
+ for (i in 0 until len) {
+ dst[base + i * stride] = ((a / div) shl 24) or ((rr / div) shl 16) or ((g / div) shl 8) or (b / div)
+ val add = src[base + (i + r + 1).coerceAtMost(len - 1) * stride]
+ val rem = src[base + (i - r).coerceAtLeast(0) * stride]
+ a += (add ushr 24) - (rem ushr 24)
+ rr += ((add shr 16) and 255) - ((rem shr 16) and 255)
+ g += ((add shr 8) and 255) - ((rem shr 8) and 255)
+ b += (add and 255) - (rem and 255)
+ }
+ }
+}
+
+internal fun labelFont(i: Int): Typeface = when (i) {
+ 1 -> Typeface.create(Typeface.SERIF, Typeface.BOLD)
+ 2 -> Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
+ 3 -> Typeface.create("cursive", Typeface.BOLD)
+ else -> Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
+}
+
+private fun light(color: Int): Boolean {
+ val r = android.graphics.Color.red(color)
+ val g = android.graphics.Color.green(color)
+ val b = android.graphics.Color.blue(color)
+ return 0.299 * r + 0.587 * g + 0.114 * b > 165
+}
+
+private fun labelLayout(l: Label, size: Float): StaticLayout {
+ val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = size.coerceAtLeast(1f)
+ typeface = labelFont(l.font)
+ }
+ val text = l.text.ifEmpty { " " }
+ val width = ceil(text.lines().maxOf { Layout.getDesiredWidth(it, paint) }).toInt().coerceAtLeast(1)
+ return StaticLayout.Builder.obtain(text, 0, text.length, paint, width)
+ .setAlignment(Layout.Alignment.ALIGN_CENTER)
+ .setIncludePad(false)
+ .build()
+}
+
+/** A label's box: its middle in output pixels, half its width and height, and how far it is turned. */
+internal class LabelBox(val cx: Float, val cy: Float, val halfW: Float, val halfH: Float, val degrees: Float) {
+ fun holds(x: Float, y: Float, slop: Float): Boolean {
+ val a = Math.toRadians(-degrees.toDouble())
+ val dx = x - cx
+ val dy = y - cy
+ val lx = dx * cos(a) - dy * sin(a)
+ val ly = dx * sin(a) + dy * cos(a)
+ return abs(lx) <= halfW + slop && abs(ly) <= halfH + slop
+ }
+}
+
+internal fun labelBox(l: Label, place: Placement): LabelBox {
+ val p = place.out(l.x, l.y)
+ val size = l.size * place.long
+ val layout = labelLayout(l, size)
+ val pad = size * 0.34f
+ return LabelBox(p.x, p.y, layout.width / 2f + pad, layout.height / 2f + pad * 0.6f, l.rotation + place.angle)
+}
+
+private fun drawLabel(canvas: Canvas, place: Placement, l: Label, chosen: Boolean) {
+ val p = place.out(l.x, l.y)
+ val size = l.size * place.long
+ if (size < 1f) return
+ val layout = labelLayout(l, size)
+ val paint = layout.paint
+ val pad = size * 0.34f
+ val box = RectF(-pad, -pad * 0.6f, layout.width + pad, layout.height + pad * 0.6f)
+ canvas.save()
+ canvas.translate(p.x, p.y)
+ canvas.rotate(l.rotation + place.angle)
+ canvas.translate(-layout.width / 2f, -layout.height / 2f)
+ val onLight = light(l.color)
+ when (l.style) {
+ 1 -> {
+ val tag = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = l.color }
+ canvas.drawRoundRect(box, size * 0.36f, size * 0.36f, tag)
+ paint.color = if (onLight) 0xFF141414.toInt() else android.graphics.Color.WHITE
+ layout.draw(canvas)
+ }
+ 2 -> {
+ paint.style = Paint.Style.STROKE
+ paint.strokeWidth = size * 0.14f
+ paint.strokeJoin = Paint.Join.ROUND
+ paint.color = if (onLight) 0xFF141414.toInt() else android.graphics.Color.WHITE
+ layout.draw(canvas)
+ paint.style = Paint.Style.FILL
+ paint.color = l.color
+ layout.draw(canvas)
+ }
+ else -> {
+ paint.color = l.color
+ paint.setShadowLayer(size * 0.12f, 0f, size * 0.04f, if (onLight) 0x80000000.toInt() else 0x59FFFFFF)
+ layout.draw(canvas)
+ }
+ }
+ if (chosen) {
+ val frame = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = (place.long * 0.003f).coerceAtLeast(1.5f)
+ color = android.graphics.Color.WHITE
+ pathEffect = DashPathEffect(floatArrayOf(place.long * 0.012f, place.long * 0.008f), 0f)
+ setShadowLayer(place.long * 0.004f, 0f, 0f, 0x99000000.toInt())
+ }
+ box.inset(-pad * 0.4f, -pad * 0.4f)
+ canvas.drawRoundRect(box, size * 0.4f, size * 0.4f, frame)
+ }
+ canvas.restore()
+}
+
+/**
+ * Lays [marks] on a developed picture drawn at (0, 0) to ([Placement.outW], [Placement.outH]) on
+ * [canvas]: the brush strokes, in order, as masks over the blurred and pixelated picture in [fx]
+ * (an eraser stroke takes back what the strokes before it laid), then the words. The same for the
+ * editor's preview and for the picture saved.
+ */
+internal fun paintMarks(canvas: Canvas, place: Placement, marks: List<Mark>, fx: Fx?, chosen: Label? = null) {
+ val smudges = marks.filterIsInstance<Smudge>()
+ if (fx != null && smudges.isNotEmpty()) {
+ val brush = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeCap = Paint.Cap.ROUND
+ strokeJoin = Paint.Join.ROUND
+ color = android.graphics.Color.BLACK
+ }
+ val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = android.graphics.Color.BLACK }
+ val clear = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
+ val path = Path()
+ val pt = PointF()
+ // the layer covers only where strokes are, so a full-size save doesn't need a second picture
+ val reach = RectF()
+ var first = true
+ for (sm in smudges) {
+ val half = sm.width * place.long / 2f + 2f
+ for (p in sm.points) {
+ place.out(p.x, p.y, pt)
+ if (first) {
+ reach.set(pt.x - half, pt.y - half, pt.x + half, pt.y + half)
+ first = false
+ } else {
+ reach.union(pt.x - half, pt.y - half, pt.x + half, pt.y + half)
+ }
+ }
+ }
+ val whole = RectF(0f, 0f, place.outW, place.outH)
+ if (!first && reach.intersect(whole)) {
+ for (kind in intArrayOf(SMUDGE_BLUR, SMUDGE_PIXELS)) {
+ if (smudges.none { it.kind == kind }) continue
+ val layer = canvas.saveLayer(reach, null)
+ for (sm in smudges) {
+ if (sm.kind != kind && sm.kind != SMUDGE_ERASE) continue
+ val width = sm.width * place.long
+ val mode = if (sm.kind == SMUDGE_ERASE) clear else null
+ brush.xfermode = mode
+ dot.xfermode = mode
+ brush.strokeWidth = width
+ if (sm.points.size == 1) {
+ place.out(sm.points[0].x, sm.points[0].y, pt)
+ canvas.drawCircle(pt.x, pt.y, width / 2f, dot)
+ continue
+ }
+ path.reset()
+ sm.points.forEachIndexed { i, p ->
+ place.out(p.x, p.y, pt)
+ if (i == 0) path.moveTo(pt.x, pt.y) else path.lineTo(pt.x, pt.y)
+ }
+ canvas.drawPath(path, brush)
+ }
+ val over = Paint().apply {
+ xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
+ isFilterBitmap = kind == SMUDGE_BLUR
+ }
+ canvas.drawBitmap(if (kind == SMUDGE_BLUR) fx.blur else fx.pixels, null, whole, over)
+ canvas.restoreToCount(layer)
+ }
+ }
+ }
+ for (l in marks) if (l is Label) drawLabel(canvas, place, l, l === chosen)
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetCharts.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetCharts.kt
new file mode 100644
index 0000000..e201bbf
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetCharts.kt
@@ -0,0 +1,164 @@
+package com.chethan616.clearpdf.ui.sheets
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.DashPathEffect
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.RectF
+import android.graphics.Typeface
+import org.json.JSONArray
+import org.json.JSONObject
+import kotlin.math.max
+import kotlin.math.min
+
+/**
+ * A chart of a sheet as a picture: GridCraft lays the chart out (bars, lines, wedges, axes and
+ * every label) as drawing steps in points, and they are painted here with the phone's own text,
+ * at [scale] pixels a point (at most [maxPx] on the long side), so it reads as sharply as the cells.
+ */
+internal fun paintChart(prims: String, width: Float, height: Float, scale: Float, maxPx: Int = 2400): Bitmap? {
+ if (width <= 0f || height <= 0f) return null
+ val k = min(scale, maxPx / max(width, height))
+ val bitmap = Bitmap.createBitmap(max(1, (width * k).toInt()), max(1, (height * k).toInt()), Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(bitmap)
+ canvas.scale(k, k)
+ val steps = runCatching { JSONArray(prims) }.getOrNull() ?: return null
+ val fill = Paint(Paint.ANTI_ALIAS_FLAG)
+ val line = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeJoin = Paint.Join.ROUND
+ strokeCap = Paint.Cap.ROUND
+ }
+ val text = Paint(Paint.ANTI_ALIAS_FLAG)
+ val regular = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL)
+ val bold = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
+ val path = Path()
+ val box = RectF()
+
+ fun color(a: JSONArray?): Int? {
+ if (a == null || a.length() < 4) return null
+ return android.graphics.Color.argb(a.optInt(3), a.optInt(0), a.optInt(1), a.optInt(2))
+ }
+ fun stroke(o: JSONObject): Boolean {
+ val s = o.optJSONArray("stroke") ?: return false
+ line.color = color(s.optJSONArray(0)) ?: return false
+ line.strokeWidth = s.optDouble(1, 1.0).toFloat().coerceAtLeast(0.5f)
+ line.pathEffect = null
+ return true
+ }
+ fun points(a: JSONArray?, close: Boolean): Boolean {
+ path.reset()
+ if (a == null || a.length() == 0) return false
+ for (i in 0 until a.length()) {
+ val p = a.optJSONArray(i) ?: continue
+ val x = p.optDouble(0).toFloat()
+ val y = p.optDouble(1).toFloat()
+ if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
+ }
+ if (close) path.close()
+ return true
+ }
+
+ for (i in 0 until steps.length()) {
+ val step = steps.optJSONObject(i) ?: continue
+ val kind = step.keys().asSequence().firstOrNull() ?: continue
+ val o = step.optJSONObject(kind) ?: continue
+ when (kind) {
+ "Rect" -> {
+ val x = o.optDouble("x").toFloat()
+ val y = o.optDouble("y").toFloat()
+ box.set(x, y, x + o.optDouble("w").toFloat(), y + o.optDouble("h").toFloat())
+ val r = o.optDouble("radius").toFloat()
+ color(o.optJSONArray("fill"))?.let {
+ fill.color = it
+ canvas.drawRoundRect(box, r, r, fill)
+ }
+ if (stroke(o)) canvas.drawRoundRect(box, r, r, line)
+ }
+ "Line" -> {
+ if (!points(o.optJSONArray("pts"), close = false)) continue
+ line.color = color(o.optJSONArray("color")) ?: continue
+ val w = o.optDouble("width", 1.0).toFloat().coerceAtLeast(0.5f)
+ line.strokeWidth = w
+ line.pathEffect = if (o.optBoolean("dash")) DashPathEffect(floatArrayOf(w * 4f, w * 3f), 0f) else null
+ canvas.drawPath(path, line)
+ }
+ "Polygon" -> {
+ if (!points(o.optJSONArray("pts"), close = true)) continue
+ color(o.optJSONArray("fill"))?.let {
+ fill.color = it
+ canvas.drawPath(path, fill)
+ }
+ if (stroke(o)) canvas.drawPath(path, line)
+ }
+ "Wedge" -> {
+ // angles from 12 o'clock, clockwise, in radians; Android's arcs start at 3 o'clock
+ val cx = o.optDouble("cx").toFloat()
+ val cy = o.optDouble("cy").toFloat()
+ val ro = o.optDouble("r_outer").toFloat()
+ val ri = o.optDouble("r_inner").toFloat()
+ val a0 = Math.toDegrees(o.optDouble("a0")).toFloat() - 90f
+ val sweep = Math.toDegrees(o.optDouble("a1") - o.optDouble("a0")).toFloat()
+ path.reset()
+ if (sweep >= 359.99f) {
+ path.addCircle(cx, cy, ro, Path.Direction.CW)
+ if (ri > 0f) path.addCircle(cx, cy, ri, Path.Direction.CCW)
+ } else {
+ box.set(cx - ro, cy - ro, cx + ro, cy + ro)
+ path.arcTo(box, a0, sweep, true)
+ if (ri > 0f) {
+ box.set(cx - ri, cy - ri, cx + ri, cy + ri)
+ path.arcTo(box, a0 + sweep, -sweep)
+ } else {
+ path.lineTo(cx, cy)
+ }
+ path.close()
+ }
+ fill.color = color(o.optJSONArray("fill")) ?: continue
+ canvas.drawPath(path, fill)
+ if (stroke(o)) canvas.drawPath(path, line)
+ }
+ "Circle" -> {
+ val cx = o.optDouble("cx").toFloat()
+ val cy = o.optDouble("cy").toFloat()
+ val r = o.optDouble("r").toFloat()
+ color(o.optJSONArray("fill"))?.let {
+ fill.color = it
+ canvas.drawCircle(cx, cy, r, fill)
+ }
+ if (stroke(o)) canvas.drawCircle(cx, cy, r, line)
+ }
+ "Text" -> {
+ val words = o.optString("text")
+ if (words.isEmpty()) continue
+ text.color = color(o.optJSONArray("color")) ?: android.graphics.Color.BLACK
+ text.textSize = o.optDouble("size", 10.0).toFloat()
+ text.typeface = if (o.optBoolean("bold")) bold else regular
+ text.textAlign = when (o.optString("align")) {
+ "Center" -> Paint.Align.CENTER
+ "Right" -> Paint.Align.RIGHT
+ else -> Paint.Align.LEFT
+ }
+ val x = o.optDouble("x").toFloat()
+ val y = o.optDouble("y").toFloat()
+ val fm = text.fontMetrics
+ val baseline = when (o.optString("valign")) {
+ "Middle" -> y - (fm.ascent + fm.descent) / 2f
+ "Bottom" -> y - fm.descent
+ else -> y - fm.ascent
+ }
+ val turn = Math.toDegrees(o.optDouble("rotation")).toFloat()
+ if (turn != 0f) {
+ canvas.save()
+ canvas.rotate(turn, x, y)
+ canvas.drawText(words, x, baseline, text)
+ canvas.restore()
+ } else {
+ canvas.drawText(words, x, baseline, text)
+ }
+ }
+ }
+ }
+ return bitmap
+}
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 8e1a13e..ccb0767 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
@@ -1,5 +1,6 @@
package com.chethan616.clearpdf.ui.sheets
+import androidx.compose.foundation.layout.isImeVisible
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
@@ -229,8 +230,19 @@ class SheetGridState internal constructor(private val eng: Engine, private val d
internal var pictures by mutableStateOf<List<SheetImage>>(emptyList())
var scale by mutableStateOf(1f)
var pan by mutableStateOf(Offset.Zero)
- /** The chosen cell, if one is. */
+ /** What is chosen: a cell, or a range of cells. */
var selected by mutableStateOf<CellSpan?>(null)
+ /** The cell the choice began from (the one the formula bar shows and typing goes into), inside [selected]. */
+ var active by mutableStateOf<CellSpan?>(null)
+
+ /** Choose [cell] alone (null: nothing). */
+ fun choose(cell: CellSpan?) {
+ selected = cell
+ active = cell
+ }
+
+ /** Whether more than one cell is chosen. */
+ val isRange: Boolean get() = selected != null && selected != active
var hits by mutableStateOf<List<CellSpan>>(emptyList())
var hit by mutableIntStateOf(0)
/** Bumped when the workbook changed: the layout and cells are fetched again. */
@@ -245,7 +257,7 @@ class SheetGridState internal constructor(private val eng: Engine, private val d
fun show(index: Int) {
if (index == current) return
layout = null
- selected = null
+ choose(null)
hits = emptyList()
pan = Offset.Zero
pictures = emptyList()
@@ -281,6 +293,9 @@ class SheetGridState internal constructor(private val eng: Engine, private val d
while (maxOf(bounds.outWidth, bounds.outHeight) / sample > 1600) sample *= 2
val bitmap = android.graphics.BitmapFactory.decodeByteArray(p.data, 0, p.data.size, android.graphics.BitmapFactory.Options().apply { inSampleSize = sample })
bitmap?.let { SheetImage(p.x, p.y, p.width, p.height, it.asImageBitmap()) }
+ } + sheetCharts(docId, sheet.toUInt()).mapNotNull { c ->
+ // charts are painted from GridCraft's layout, sharp enough to zoom into
+ paintChart(c.prims, c.chartWidth, c.chartHeight, scale = 3f)?.let { SheetImage(c.x, c.y, c.width, c.height, it.asImageBitmap()) }
}
}
}.getOrDefault(emptyList()).takeIf { sheet == current }.orEmpty()
@@ -418,6 +433,8 @@ fun SheetGrid(
modifier: Modifier = Modifier,
top: Float = 0f,
onCell: ((CellSpan?) -> Unit)? = null,
+ /** A range was chosen or changed (a drag, a long press, a column or row heading). */
+ onRange: (() -> Unit)? = null,
) {
val c = pdfColors
val sheetSurface = if (c.dark) Color(0xFF18192F) else Color.White
@@ -455,7 +472,7 @@ fun SheetGrid(
val x = if (col < fc) state.pan.x else -(l.colX[col] - l.colX[minOf(fc, l.cols)]) * k + 24 * px
val y = if (r < fr) state.pan.y else -(l.rowY[r] - l.rowY[minOf(fr, l.rows)]) * k + 24 * px
state.pan = Offset(x.coerceAtMost(0f), y.coerceAtMost(0f))
- state.selected = h
+ state.choose(h)
}
// The bars over the grid grow and shrink (the formula bar comes with a chosen cell, the search
// field with Find), moving where the grid starts. The gestures below live as long as the
@@ -463,6 +480,8 @@ fun SheetGrid(
// to be measured against the old room, and chose a cell a few rows off the one touched.
val room = androidx.compose.runtime.rememberUpdatedState(top)
val tapped = androidx.compose.runtime.rememberUpdatedState(onCell)
+ val ranged = androidx.compose.runtime.rememberUpdatedState(onRange)
+ val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()
// ... and the cells stay where they were on the screen while the bars change over them
val lastTop = remember(l) { floatArrayOf(top) }
androidx.compose.runtime.SideEffect {
@@ -472,6 +491,20 @@ fun SheetGrid(
state.pan = Offset(state.pan.x, (state.pan.y - d).coerceAtMost(0f))
}
}
+ // the cell typed into stays in sight: the bars that come with a choice can cover it, so the
+ // sheet moves just enough to show it under them (a moment after, once they have settled)
+ LaunchedEffect(state.active, l) {
+ val a = state.active ?: return@LaunchedEffect
+ kotlinx.coroutines.delay(60)
+ val k = px * state.scale
+ val headH = HEAD_H * k.coerceAtMost(px * 1.5f)
+ val fr = minOf(l.info.frozenRows.toInt(), l.rows)
+ val r = a.row0.toInt()
+ if (r < fr || r >= l.rows) return@LaunchedEffect
+ val y = headH + l.rowY[r] * k + state.pan.y
+ val clear = headH + l.rowY[fr] * k
+ if (y < clear) state.pan = Offset(state.pan.x, (state.pan.y + clear - y + 6f * px).coerceAtMost(0f))
+ }
// the cell under a point of the canvas (null: a heading strip)
fun cellAt(p: Offset): CellSpan? {
val k = px * state.scale
@@ -486,6 +519,28 @@ fun SheetGrid(
val row = if (gy < l.rowY[fr] * k) l.indexAt(l.rowY, gy / k) else l.indexAt(l.rowY, (gy - state.pan.y) / k)
return l.spanAt(row, col) ?: CellSpan(row.toUInt(), col.toUInt(), row.toUInt(), col.toUInt())
}
+ // a column's letter or a row's number: the whole column or row
+ fun headingAt(p: Offset): CellSpan? {
+ val k = px * state.scale
+ val head = Offset(HEAD_W * k.coerceAtMost(px * 1.5f), HEAD_H * k.coerceAtMost(px * 1.5f))
+ val y = p.y - room.value
+ val fr = minOf(l.info.frozenRows.toInt(), l.rows)
+ val fc = minOf(l.info.frozenCols.toInt(), l.cols)
+ return when {
+ y < 0f -> null
+ y < head.y && p.x >= head.x -> {
+ val gx = p.x - head.x
+ val col = if (gx < l.colX[fc] * k) l.indexAt(l.colX, gx / k) else l.indexAt(l.colX, (gx - state.pan.x) / k)
+ CellSpan(0u, col.toUInt(), (l.rows - 1).toUInt(), col.toUInt())
+ }
+ p.x < head.x && y >= head.y -> {
+ val gy = y - head.y
+ val row = if (gy < l.rowY[fr] * k) l.indexAt(l.rowY, gy / k) else l.indexAt(l.rowY, (gy - state.pan.y) / k)
+ CellSpan(row.toUInt(), 0u, row.toUInt(), (l.cols - 1).toUInt())
+ }
+ else -> null
+ }
+ }
val flinger = remember { arrayOfNulls<kotlinx.coroutines.Job>(1) }
Canvas(
Modifier
@@ -496,8 +551,109 @@ fun SheetGrid(
// cell edits it), where waiting made every tap land a third of a second late
detectTapGestures(
onPress = { flinger[0]?.cancel() },
- onTap = { p -> tapped.value?.invoke(cellAt(p)) },
+ onTap = { p ->
+ val whole = headingAt(p)
+ if (whole != null) {
+ state.selected = whole
+ state.active = CellSpan(whole.row0, whole.col0, whole.row0, whole.col0)
+ feel(com.chethan616.clearpdf.ui.glass.Feel.Tick)
+ ranged.value?.invoke()
+ } else {
+ tapped.value?.invoke(cellAt(p))
+ }
+ },
)
+ }
+ .pointerInput(l) {
+ // A range, as Sheets and Excel take one on a phone: drag a handle of the choice to
+ // stretch it (the opposite corner stays), or hold a cell and drag from it. The sheet
+ // scrolls when the finger reaches its edge. These touches are taken from the pan.
+ val slop = viewConfiguration.touchSlop
+ val hold = viewConfiguration.longPressTimeoutMillis
+ awaitEachGesture {
+ val down = awaitFirstDown(requireUnconsumed = false)
+ val k = px * state.scale
+ val sel = state.selected
+ var anchor: Pair<Int, Int>? = null
+ if (sel != null) {
+ val a = sheetCorner(l, state, k, px, sel.row0.toInt(), sel.col0.toInt()) + Offset(0f, room.value)
+ val b = sheetCorner(l, state, k, px, sel.row1.toInt() + 1, sel.col1.toInt() + 1) + Offset(0f, room.value)
+ val reach = 26f * px
+ anchor = when {
+ (down.position - b).getDistance() <= reach -> sel.row0.toInt() to sel.col0.toInt()
+ (down.position - a).getDistance() <= reach -> sel.row1.toInt() to sel.col1.toInt()
+ else -> null
+ }
+ }
+ if (anchor != null) {
+ down.consume()
+ feel(com.chethan616.clearpdf.ui.glass.Feel.Press)
+ } else {
+ // held still long enough: a long press (lifted, moved or pinched first: not one)
+ val ended = withTimeoutOrNull(hold) {
+ while (true) {
+ val e = awaitPointerEvent()
+ val ch = e.changes.firstOrNull { it.id == down.id }
+ if (ch == null || !ch.pressed || e.changes.count { it.pressed } > 1 || (ch.position - down.position).getDistance() > slop) break
+ }
+ true
+ }
+ if (ended != null) return@awaitEachGesture
+ val cell = cellAt(down.position) ?: return@awaitEachGesture
+ anchor = cell.row0.toInt() to cell.col0.toInt()
+ state.choose(cell)
+ feel(com.chethan616.clearpdf.ui.glass.Feel.Press)
+ ranged.value?.invoke()
+ }
+ val (ar, ac) = anchor
+ val edge = 28f * px
+ var travelled = false
+ while (true) {
+ val e = awaitPointerEvent()
+ val ch = e.changes.firstOrNull { it.id == down.id } ?: break
+ e.changes.forEach { it.consume() }
+ if (!ch.pressed) break
+ // the sheet scrolls only once the finger has set off, not from where it landed
+ if (!travelled && (ch.position - down.position).getDistance() > slop) travelled = true
+ val kk = px * state.scale
+ val head = Offset(HEAD_W * kk.coerceAtMost(px * 1.5f), HEAD_H * kk.coerceAtMost(px * 1.5f))
+ val top0 = room.value + head.y
+ // at an edge the sheet moves under the finger
+ val dx = when {
+ !travelled -> 0f
+ ch.position.x > size.width - edge -> -16f * px
+ ch.position.x < head.x + edge && state.pan.x < 0f -> 16f * px
+ else -> 0f
+ }
+ val dy = when {
+ !travelled -> 0f
+ ch.position.y > size.height - edge -> -16f * px
+ ch.position.y < top0 + edge && state.pan.y < 0f -> 16f * px
+ else -> 0f
+ }
+ if (dx != 0f || dy != 0f) {
+ val maxX = (l.colX.last() * kk - size.width + 120 * px).coerceAtLeast(0f)
+ val maxY = (l.rowY.last() * kk - size.height + 160 * px).coerceAtLeast(0f)
+ state.pan = Offset((state.pan.x + dx).coerceIn(-maxX, 0f), (state.pan.y + dy).coerceIn(-maxY, 0f))
+ }
+ val p = Offset(ch.position.x.coerceIn(head.x + 1f, size.width - 1f), ch.position.y.coerceIn(top0 + 1f, size.height - 1f))
+ val at = cellAt(p) ?: continue
+ val span = CellSpan(
+ minOf(ar, at.row0.toInt()).toUInt(), minOf(ac, at.col0.toInt()).toUInt(),
+ maxOf(ar, at.row1.toInt()).toUInt(), maxOf(ac, at.col1.toInt()).toUInt(),
+ )
+ if (span != state.selected) {
+ state.selected = span
+ // the cell typed into stays inside the choice: the corner held still, if it left
+ val act = state.active
+ if (act == null || act.row0 !in span.row0..span.row1 || act.col0 !in span.col0..span.col1) {
+ state.active = CellSpan(ar.toUInt(), ac.toUInt(), ar.toUInt(), ac.toUInt())
+ }
+ feel(com.chethan616.clearpdf.ui.glass.Feel.Tick)
+ ranged.value?.invoke()
+ }
+ }
+ }
},
) {
translate(top = top) {
@@ -533,10 +689,19 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
with(density) { ((if (searching) 56.dp else 0.dp) + (if (grid.selected != null) 56.dp else 0.dp)).toPx() }
// the chosen cell's contents, for the formula bar
- LaunchedEffect(grid.selected, grid.version) {
- val s = grid.selected ?: return@LaunchedEffect
+ LaunchedEffect(grid.active, grid.version) {
+ val s = grid.active ?: return@LaunchedEffect
input = runCatching { eng.command { sheetInput(doc.id, grid.current.toUInt(), s.row0, s.col0) } }.getOrDefault("")
}
+ // a range's sum, average and count, as a spreadsheet's status bar gives them (a moment after it settles)
+ var stats by remember { mutableStateOf<com.chethan616.clearpdf.core.SheetStats?>(null) }
+ LaunchedEffect(grid.selected, grid.version, grid.current) {
+ stats = null
+ val s = grid.selected ?: return@LaunchedEffect
+ if (!grid.isRange) return@LaunchedEffect
+ delay(120)
+ stats = runCatching { eng.command { sheetStats(doc.id, grid.current.toUInt(), s) } }.getOrNull()
+ }
// live debounced search across the active sheet
LaunchedEffect(query, grid.current, searching) {
if (!searching || query.isBlank()) {
@@ -564,7 +729,7 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
}
}
fun commit() {
- val s = grid.selected ?: return
+ val s = grid.active ?: grid.selected ?: return
editing = false
scope.launch {
runCatching { eng.command { sheetSetCell(doc.id, grid.current.toUInt(), s.row0, s.col0, input) } }
@@ -574,19 +739,26 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
}
val backdrop = rememberLayerBackdrop()
+ val gridFocus = androidx.compose.ui.platform.LocalFocusManager.current
Box(Modifier.fillMaxSize()) {
Box(Modifier.fillMaxSize().layerBackdrop(backdrop)) {
SheetGrid(
grid, top = topPx,
onCell = { cell ->
+ // a tap on the sheet takes the focus from the search field (and its cursor)
+ if (searching) gridFocus.clearFocus()
// a tap chooses the cell; a tap on the chosen cell opens it for typing
- if (cell != null && cell == grid.selected) editing = true
+ if (cell != null && cell == grid.selected && !grid.isRange) editing = true
else {
if (cell != null) feel(com.chethan616.clearpdf.ui.glass.Feel.Tick)
- grid.selected = cell
+ grid.choose(cell)
editing = false
}
},
+ onRange = {
+ if (searching) gridFocus.clearFocus()
+ editing = false
+ },
)
}
CompositionLocalProvider(LocalBackdrop provides backdrop, LocalGlassInk provides chrome.color) {
@@ -622,7 +794,19 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
}
if (searching) {
val searchFocus = remember { FocusRequester() }
+ val focusManager = androidx.compose.ui.platform.LocalFocusManager.current
LaunchedEffect(Unit) { searchFocus.requestFocus() }
+ // the field lets go once the keyboard is put away, so no cursor is left blinking over the sheet
+ @OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
+ val imeOpen = WindowInsets.isImeVisible
+ var imeWasOpen by remember { mutableStateOf(false) }
+ LaunchedEffect(imeOpen) {
+ if (imeOpen) imeWasOpen = true
+ else if (imeWasOpen) {
+ imeWasOpen = false
+ focusManager.clearFocus()
+ }
+ }
val findLabel = stringResource(R.string.viewer_find_in_document)
val clearLabel = stringResource(R.string.common_clear)
val qTrim = query.trim()
@@ -661,6 +845,7 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
cursorBrush = SolidColor(if (notFound) Candy.Tomato else Candy.Sky),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = {
+ focusManager.clearFocus()
val q = query.trim()
scope.launch {
grid.hits = if (q.isEmpty()) emptyList() else runCatching {
@@ -753,11 +938,26 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
.padding(horizontal = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
+ val range = grid.isRange
Box(Modifier.padding(4.dp).glassBar(surface = Candy.Sky.copy(alpha = 0.22f)).padding(horizontal = 10.dp, vertical = 6.dp)) {
- Text(columnName(cell.col0.toInt()) + (cell.row0.toInt() + 1), style = ClearType.Label, color = LocalGlassInk.current)
+ Text(rangeName(cell, grid.layout, range), style = ClearType.Label, color = LocalGlassInk.current, maxLines = 1)
+ }
+ if (range) {
+ // what the range holds: its numbers added up and averaged, and its filled cells counted
+ val st = stats
+ val nf = remember { java.text.NumberFormat.getNumberInstance().apply { maximumFractionDigits = 2 } }
+ Text(
+ when {
+ st == null -> ""
+ st.numbers > 0u -> stringResource(R.string.sheet_stats, nf.format(st.sum), nf.format(st.sum / st.numbers.toDouble()), st.filled.toInt())
+ else -> stringResource(R.string.sheet_stats_count, st.filled.toInt())
+ },
+ style = ClearType.Label, color = LocalGlassInk.current, maxLines = 1, overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f).padding(horizontal = 8.dp),
+ )
}
// the cell's hyperlink, one tap away (a place in the workbook, or a web or mail address)
- val link = if (editing) null else grid.linkAt(cell.row0.toInt(), cell.col0.toInt())
+ val link = if (editing || range) null else grid.linkAt(cell.row0.toInt(), cell.col0.toInt())
if (link != null) {
Box(
Modifier.padding(end = 4.dp).height(36.dp).clip(Capsule).background(Candy.Sky)
@@ -771,7 +971,9 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
}
}
}
- if (editing) {
+ if (range) {
+ Unit
+ } else if (editing) {
val focus = remember { androidx.compose.ui.focus.FocusRequester() }
LaunchedEffect(Unit) { focus.requestFocus() }
GlassTextField(
@@ -1027,7 +1229,23 @@ private fun DrawScope.drawSheet(
val cEnd = minOf(f.col1.toInt(), l.cols - 1)
if (rEnd >= r0 && r < r1 && cEnd >= c0 && col < c1) {
val box = Rect(x(col), y(r), x(cEnd + 1), y(rEnd + 1))
- drawRect(accent.copy(alpha = 0.08f), box.topLeft, box.size)
+ val act = state.active
+ if (act != null && act != f) {
+ // a range: tinted, the cell it began from left clear and ringed, as a spreadsheet shows one
+ val hole = Rect(
+ x(act.col0.toInt()), y(act.row0.toInt()),
+ x(minOf(act.col1.toInt(), l.cols - 1) + 1), y(minOf(act.row1.toInt(), l.rows - 1) + 1),
+ )
+ val tint = androidx.compose.ui.graphics.Path().apply {
+ fillType = androidx.compose.ui.graphics.PathFillType.EvenOdd
+ addRect(box)
+ addRect(hole)
+ }
+ drawPath(tint, accent.copy(alpha = 0.13f))
+ drawRect(accent, hole.topLeft, hole.size, style = androidx.compose.ui.graphics.drawscope.Stroke(width = 1.5f * density))
+ } else {
+ drawRect(accent.copy(alpha = 0.08f), box.topLeft, box.size)
+ }
drawRect(accent, box.topLeft, box.size, style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.5f * density))
}
}
@@ -1141,6 +1359,18 @@ private fun DrawScope.drawSheet(
region(Rect(head.x + frozenW, head.y, size.width, head.y + frozenH), head, 0, fr, fc, l.cols, scrollX = true, scrollY = false)
region(Rect(head.x, head.y + frozenH, head.x + frozenW, size.height), head, fr, l.rows, 0, fc, scrollX = false, scrollY = true)
region(Rect(head.x, head.y, head.x + frozenW, head.y + frozenH), head, 0, fr, 0, fc, scrollX = false, scrollY = false)
+ // the choice's two handles, to drag it bigger or smaller (as on Sheets and Excel for phones)
+ selected?.let { f ->
+ val a = sheetCorner(l, state, k, density, f.row0.toInt(), f.col0.toInt())
+ val b = sheetCorner(l, state, k, density, f.row1.toInt() + 1, f.col1.toInt() + 1)
+ clipRect(head.x, head.y, size.width, size.height) {
+ for (p in listOf(a, b)) {
+ drawCircle(Color.Black.copy(alpha = 0.12f), 9f * density, p + Offset(0f, 1.5f * density))
+ drawCircle(Color.White, 8f * density, p)
+ drawCircle(accent, 8f * density, p, style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.5f * density))
+ }
+ }
+ }
val frozenDivider = if (dark) Color(0xFF777D9A) else Color(0xFF9AA3B2)
if (fr > 0) drawLine(frozenDivider, Offset(head.x, head.y + frozenH), Offset(size.width, head.y + frozenH), density)
if (fc > 0) drawLine(frozenDivider, Offset(head.x + frozenW, head.y), Offset(head.x + frozenW, size.height), density)
@@ -1234,6 +1464,8 @@ private fun Modifier.panZoomFling(
val event = awaitPointerEvent()
val pressed = event.changes.filter { it.pressed }
if (pressed.isEmpty()) break
+ // taken by a range being chosen (a handle dragged, a cell held): the sheet stays put
+ if (!started && event.changes.any { it.isConsumed }) break
val zoomChange = event.calculateZoom()
val pan = event.calculatePan()
@@ -1295,3 +1527,30 @@ private fun Modifier.panZoomFling(
}
}
}
+
+/**
+ * Where the corner before row [row] and column [col] is on the grid (pixels; the grid's top is 0):
+ * the frozen rows and columns stay put, the rest move with the sheet.
+ */
+internal fun sheetCorner(l: SheetLayout, state: SheetGridState, k: Float, density: Float, row: Int, col: Int): Offset {
+ val head = Offset(HEAD_W * k.coerceAtMost(density * 1.5f), HEAD_H * k.coerceAtMost(density * 1.5f))
+ val fr = minOf(l.info.frozenRows.toInt(), l.rows)
+ val fc = minOf(l.info.frozenCols.toInt(), l.cols)
+ val c = col.coerceIn(0, l.colX.size - 1)
+ val r = row.coerceIn(0, l.rowY.size - 1)
+ val x = head.x + l.colX[c] * k + (if (c >= fc) state.pan.x else 0f)
+ val y = head.y + l.rowY[r] * k + (if (r >= fr) state.pan.y else 0f)
+ return Offset(x, y)
+}
+
+/**
+ * A choice's name, as a spreadsheet writes it: `B4` for a cell, `B4:D9` for a range, `B:D` for whole
+ * columns and `4:9` for whole rows.
+ */
+internal fun rangeName(s: CellSpan, l: SheetLayout?, range: Boolean): String {
+ val (r0, c0, r1, c1) = listOf(s.row0.toInt(), s.col0.toInt(), s.row1.toInt(), s.col1.toInt())
+ if (!range) return columnName(c0) + (r0 + 1)
+ if (l != null && r0 == 0 && r1 >= l.rows - 1) return columnName(c0) + ":" + columnName(c1)
+ if (l != null && c0 == 0 && c1 >= l.cols - 1) return "${r0 + 1}:${r1 + 1}"
+ return columnName(c0) + (r0 + 1) + ":" + columnName(c1) + (r1 + 1)
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ReadAloud.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ReadAloud.kt
index f5db90c..87e43f3 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ReadAloud.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ReadAloud.kt
@@ -106,6 +106,9 @@ import com.chethan616.clearpdf.ui.glass.LocalGlassInk
import com.chethan616.clearpdf.ui.glass.LocalGlassOverlayHost
import com.chethan616.clearpdf.ui.glass.LocalScreenInk
import com.chethan616.clearpdf.ui.glass.RoundedRectangle
+import com.chethan616.clearpdf.ui.theme.ClearType
+import com.chethan616.clearpdf.ui.theme.Candy
+import com.chethan616.clearpdf.ui.glass.glassBar
import com.chethan616.clearpdf.ui.glass.glass
import com.chethan616.clearpdf.ui.glass.rememberGlassInk
import com.chethan616.clearpdf.ui.theme.clear
@@ -476,7 +479,11 @@ fun DrawScope.drawReadAloud(doc: OpenDocument, r: ReadAloud) {
mark(r.wordRects, Color(0xFFF8D904), 1.5f * density)
}
-/** The minimized read-aloud player: document, speed, live wave, skip, play/pause, and stop. */
+/**
+ * The read-aloud player, docked over the page: the app's glass bar (as the viewer's toolbar), the
+ * voice's sign in the accent beside the document's name and where it has got to, the speed, the
+ * live wave of progress, and the transport (back 15, play or pause, forward 15, stop).
+ */
@Composable
fun BoxScope.ReadAloudBar(doc: OpenDocument, r: ReadAloud) {
var speeds by remember { mutableStateOf(false) }
@@ -488,46 +495,55 @@ fun BoxScope.ReadAloudBar(doc: OpenDocument, r: ReadAloud) {
.navigationBarsPadding()
.padding(horizontal = 12.dp, vertical = 8.dp)
.then(ink.modifier)
- .glass(RoundedRectangle(28.dp), wash = Color.White.copy(alpha = 0.12f), blur = 18.dp)
- .padding(horizontal = 10.dp, vertical = 9.dp),
+ .glassBar(RoundedRectangle(30.dp))
+ .padding(start = 14.dp, end = 12.dp, top = 12.dp, bottom = 10.dp),
) {
CompositionLocalProvider(LocalGlassInk provides ink.color) {
Column(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
+ Box(Modifier.size(36.dp).clip(CircleShape).background(Candy.Sky), contentAlignment = Alignment.Center) {
+ Icon(LucideIcons.AudioLines, null, tint = Color.White, modifier = Modifier.size(18.dp))
+ }
+ Spacer(Modifier.width(10.dp))
Column(Modifier.weight(1f)) {
- Text(doc.title, color = LocalGlassInk.current, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
- Text(stringResource(R.string.common_tool_read_aloud), color = LocalGlassInk.current.copy(alpha = 0.62f), fontSize = 11.sp, maxLines = 1)
+ Text(doc.title, style = ClearType.BodyStrong, color = LocalGlassInk.current, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(
+ stringResource(R.string.common_tool_read_aloud) + " · " + stringResource(R.string.viewer_page_of, r.page + 1, doc.info.pages.size),
+ style = ClearType.Caption, color = LocalGlassInk.current.copy(alpha = 0.62f), maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
}
- }
- Spacer(Modifier.height(7.dp))
- WavyProgressTrack(r.progress, Modifier.fillMaxWidth().height(9.dp))
- Spacer(Modifier.height(7.dp))
- Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally)) {
+ Spacer(Modifier.width(8.dp))
Box {
GlassPill(
onClick = { speeds = true },
modifier = Modifier.onGloballyPositioned { speedAnchor = it.boundsInWindow() },
- height = 42.dp,
- horizontalPadding = 10.dp,
+ height = 36.dp,
+ horizontalPadding = 12.dp,
label = stringResource(R.string.read_aloud_speed),
) {
- Text(speedLabel(r.speed), color = LocalGlassInk.current, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
+ Text(speedLabel(r.speed), style = ClearType.Label.copy(fontWeight = FontWeight.SemiBold), color = LocalGlassInk.current)
}
if (speeds) SpeedMenu(speedAnchor, r) { speeds = false }
}
- SkipButton(back = true, size = 44.dp) { r.skip(false) }
+ }
+ Spacer(Modifier.height(10.dp))
+ WavyProgressTrack(r.progress, Modifier.fillMaxWidth().padding(horizontal = 4.dp).height(9.dp))
+ Spacer(Modifier.height(8.dp))
+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp, Alignment.CenterHorizontally)) {
+ SkipButton(back = true, size = 46.dp) { r.skip(false) }
GlassCircle(
onClick = { if (r.playing) r.pause() else r.play() },
- size = 52.dp,
- tint = Color(0xFF1683FF),
+ size = 56.dp,
+ tint = Candy.Sky,
label = stringResource(if (r.playing) R.string.common_pause else if (r.finished) R.string.read_aloud_read_again else R.string.common_play),
) { GlassIcon(if (r.playing) LucideIcons.Pause else LucideIcons.Play, null, Modifier.size(25.dp), tint = Color.White) }
- SkipButton(back = false, size = 44.dp) { r.skip(true) }
- GlassCircle(onClick = r::stop, size = 38.dp, label = stringResource(R.string.read_aloud_stop_reading)) {
- GlassIcon(LucideIcons.Square, null, Modifier.size(16.dp))
- }
+ SkipButton(back = false, size = 46.dp) { r.skip(true) }
}
- r.problem?.let { Text(it, color = Color(0xFFFF625D), fontSize = 12.sp, modifier = Modifier.padding(top = 5.dp)) }
+ r.problem?.let { Text(it, style = ClearType.Caption, color = Candy.Tomato, modifier = Modifier.padding(top = 6.dp)) }
+ }
+ // stop sits in the corner, away from play
+ GlassCircle(onClick = r::stop, size = 34.dp, label = stringResource(R.string.read_aloud_stop_reading), modifier = Modifier.align(Alignment.BottomEnd)) {
+ GlassIcon(LucideIcons.Square, null, Modifier.size(13.dp))
}
}
}
@@ -536,7 +552,7 @@ fun BoxScope.ReadAloudBar(doc: OpenDocument, r: ReadAloud) {
/** Material 3 Expressive's animated wave, tinted to the player rather than the app theme. */
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
-private fun WavyProgressTrack(progress: Float, modifier: Modifier, accent: Color = Color(0xFF1683FF)) {
+private fun WavyProgressTrack(progress: Float, modifier: Modifier, accent: Color = Candy.Sky) {
val animatedProgress by animateFloatAsState(progress.coerceIn(0f, 1f), animationSpec = tween(360), label = "readAloudProgress")
LinearWavyProgressIndicator(
progress = { animatedProgress },
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 d728b8b..e939c24 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
@@ -1,5 +1,6 @@
package com.chethan616.clearpdf.ui.viewer
+import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
@@ -458,92 +459,81 @@ fun BoxScope.SelectionHandles(doc: OpenDocument, sel: Selection) {
}
/**
- * Single page mode's page bar, along the bottom over the pages: a glass capsule holding the page
- * number (a tap opens Go to page) and a track. A tap anywhere on the track goes to that page and a
- * drag runs through the pages under the finger, a light tick at each. The track reads the page from
- * the viewer itself on every touch: the old pill kept the place it had when it was first drawn, so
- * each drag began again from page 1.
+ * Single page mode's scrubber: a liquid glass pill with the page number, riding a hairline along the
+ * bottom. Drag it through the pages (a light tick at each), tap it for Go to page. On every drag the
+ * pill starts from where it is now: it used to start from where it was when it was first drawn, so
+ * each drag jumped back to page 1.
*/
@Composable
fun BoxScope.HorizontalScrubber(doc: OpenDocument, visible: Boolean, bottom: Dp, onDrag: () -> Unit, onTap: () -> Unit) {
+ val c = pdfColors
val v = doc.viewer
- var dragging by remember { mutableStateOf(false) }
+ val density = LocalDensity.current
val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()
- val latestDrag by androidx.compose.runtime.rememberUpdatedState(onDrag)
- val count = doc.pageCount
- val page = v.currentPage
- val pageOf = stringResource(R.string.viewer_page_of, page + 1, count)
- AnimatedVisibility(visible || dragging, modifier = Modifier.align(Alignment.BottomCenter), enter = fadeIn(tween(150)), exit = fadeOut(tween(300))) {
- val ink = com.chethan616.clearpdf.ui.glass.rememberGlassInk(clear.ink)
- Row(
- Modifier
- .padding(start = 16.dp, end = 16.dp, bottom = bottom + 10.dp)
- .widthIn(max = 560.dp)
- .fillMaxWidth()
- .height(44.dp)
- .then(ink.modifier)
- .glassBar()
- .padding(start = 6.dp, end = 16.dp),
- verticalAlignment = Alignment.CenterVertically,
- ) {
- // the page number; a tap opens Go to page
+ var dragging by remember { mutableStateOf(false) }
+ var dragX by remember { mutableFloatStateOf(0f) }
+ // the pill swells a little under the finger, as the glass buttons do
+ val lift by androidx.compose.animation.core.animateFloatAsState(
+ if (dragging) 1.12f else 1f, com.chethan616.clearpdf.ui.glass.GlassMotion.pop(), label = "scrubLift",
+ )
+ AnimatedVisibility(
+ visible || dragging, modifier = Modifier.align(Alignment.BottomCenter),
+ enter = fadeIn(com.chethan616.clearpdf.ui.glass.Fluid.quick()), exit = fadeOut(com.chethan616.clearpdf.ui.glass.Fluid.fade()),
+ ) {
+ BoxWithConstraints(Modifier.fillMaxWidth().padding(start = 24.dp, end = 24.dp, bottom = bottom + 12.dp).height(36.dp)) {
+ val track = with(density) { maxWidth.toPx() }
+ val pillW = with(density) { 52.dp.toPx() }
+ val n = (doc.pageCount - 1).coerceAtLeast(1)
+ val x = if (dragging) dragX else v.currentPage.toFloat() / n * (track - pillW)
+ // read on every drag, not kept from the first composition
+ val now by androidx.compose.runtime.rememberUpdatedState(x)
+ val span by androidx.compose.runtime.rememberUpdatedState((track - pillW).coerceAtLeast(1f))
+ val pageOf = stringResource(R.string.viewer_page_of, v.currentPage + 1, doc.pageCount)
+ val ink = com.chethan616.clearpdf.ui.glass.rememberGlassInk(c.text)
Box(
- Modifier.height(36.dp).widthIn(min = 64.dp).clip(RoundedCornerShape(18.dp)).pressable(onTap).padding(horizontal = 10.dp)
- .semantics { contentDescription = pageOf },
- contentAlignment = Alignment.Center,
- ) {
- Text("${page + 1} / $count", color = ink.color, fontSize = 14.sp, maxLines = 1)
- }
- Spacer(Modifier.width(6.dp))
- val fraction = if (count > 1) page.toFloat() / (count - 1) else 0f
- val anim by androidx.compose.animation.core.animateFloatAsState(fraction, com.chethan616.clearpdf.ui.glass.GlassMotion.settle(), label = "pageBar")
+ Modifier.align(Alignment.CenterStart).fillMaxWidth().height(2.dp)
+ .clip(com.chethan616.clearpdf.ui.glass.ChromeCapsule).background(ink.color.copy(alpha = 0.22f)),
+ )
Box(
Modifier
- .weight(1f)
- .fillMaxHeight()
- .pointerInput(doc, count) {
- // the page at a point of the track: the track's own width, read on each touch
- fun pageAt(x: Float): Int {
- val r = 11.dp.toPx()
- val f = ((x - r) / (size.width - 2 * r).coerceAtLeast(1f)).coerceIn(0f, 1f)
- return (f * (count - 1)).roundToInt()
- }
- fun show(p: Int) {
- if (p != v.currentPage) {
- v.goToPage(p)
+ .align(Alignment.CenterStart)
+ .offset { IntOffset(x.roundToInt(), 0) }
+ .graphicsLayer {
+ scaleX = lift
+ scaleY = lift
+ }
+ .size(52.dp, 32.dp)
+ .then(ink.modifier)
+ .glassBar(com.chethan616.clearpdf.ui.glass.ChromeCapsule)
+ .pointerInput(doc) { detectTapGestures(onTap = { onTap() }) }
+ .pointerInput(doc) {
+ detectDragGestures(
+ onDragStart = {
+ dragX = now
+ dragging = true
+ feel(com.chethan616.clearpdf.ui.glass.Feel.Press)
+ },
+ onDragEnd = { dragging = false },
+ onDragCancel = { dragging = false },
+ ) { change, d ->
+ change.consume()
+ dragX = (dragX + d.x).coerceIn(0f, span)
+ val page = (dragX / span * (doc.pageCount - 1).coerceAtLeast(1)).roundToInt()
+ if (page != v.currentPage) {
+ v.goToPage(page)
feel(com.chethan616.clearpdf.ui.glass.Feel.Tick)
}
- latestDrag()
- }
- awaitEachGesture {
- val down = awaitFirstDown()
- dragging = true
- down.consume()
- show(pageAt(down.position.x))
- while (true) {
- val e = awaitPointerEvent()
- val ch = e.changes.firstOrNull { it.id == down.id } ?: break
- if (!ch.pressed) break
- ch.consume()
- show(pageAt(ch.position.x))
- }
- dragging = false
+ onDrag()
}
- },
- contentAlignment = Alignment.CenterStart,
+ }
+ .semantics { contentDescription = pageOf },
+ contentAlignment = Alignment.Center,
) {
- androidx.compose.foundation.Canvas(Modifier.fillMaxWidth().height(22.dp)) {
- val r = size.height / 2f
- val y = size.height / 2f
- val x = r + anim * (size.width - 2 * r)
- val thick = 4.dp.toPx()
- // the track, the part read in the accent, the thumb
- drawLine(ink.color.copy(alpha = 0.18f), Offset(r, y), Offset(size.width - r, y), thick, cap = androidx.compose.ui.graphics.StrokeCap.Round)
- drawLine(com.chethan616.clearpdf.ui.theme.Candy.Sky, Offset(r, y), Offset(x, y), thick, cap = androidx.compose.ui.graphics.StrokeCap.Round)
- drawCircle(Color.Black.copy(alpha = 0.18f), r, Offset(x, y + 1.dp.toPx()))
- drawCircle(Color.White, r - 1.dp.toPx(), Offset(x, y))
- drawCircle(com.chethan616.clearpdf.ui.theme.Candy.Sky, r * 0.38f, Offset(x, y))
- }
+ Text(
+ "${v.currentPage + 1}",
+ style = com.chethan616.clearpdf.ui.theme.ClearType.Label.copy(fontWeight = FontWeight.SemiBold),
+ color = ink.color,
+ )
}
}
}
diff --git a/android/app/src/main/res/values-ar/strings.xml b/android/app/src/main/res/values-ar/strings.xml
index 53aee0a..d9a077f 100644
--- a/android/app/src/main/res/values-ar/strings.xml
+++ b/android/app/src/main/res/values-ar/strings.xml
@@ -979,4 +979,268 @@
<item>لا تستطيع التحكم في كل موجة، لكنك تستطيع **اختيار كيف تواجهها**. النفَس الهادئ **معدٍ**.</item>
<item>جملة، رسمة، رفّ مرتّب. **الإبداع** يذكّرك بأنك تستطيع **تغيير العالم من حولك**، ولو قليلًا.</item>
</string-array>
+ <string name="tool_encryption">التشفير</string>
+ <string name="home_about_encryption">عيّن كلمة مرور لملف PDF أو أزلها نهائيًا</string>
+ <string name="tools_set_password_body">حفظ نسخة تطلب كلمة مرور قبل فتحها</string>
+ <string name="msg_no_password_yet">لا توجد كلمة مرور لملف PDF هذا</string>
+ <string name="tool_edit_photo">تعديل الصورة</string>
+ <string name="home_about_edit_photo">اقتصاص صورة وتقويمها وضبطها</string>
+ <string name="photo_texture">تنعيم / ملمس</string>
+ <string name="tool_text_to_pdf">نص إلى PDF</string>
+ <string name="home_about_text_to_pdf">اكتب نصًا أو الصقه واحفظه بصيغة PDF</string>
+ <string name="tool_pdf_to_text">PDF إلى نص</string>
+ <string name="home_about_pdf_to_text">حفظ نص ملف PDF كملف نصي عادي</string>
+ <string name="home_about_find_fields">تحويل الفراغات في نموذج مرسوم إلى حقول للتعبئة</string>
+ <string name="home_about_unlock">حفظ نسخة من ملف PDF محمي تُفتح دون كلمة مرور</string>
+ <string name="msg_no_password">لا توجد كلمة مرور لإزالتها من ملف PDF هذا</string>
+ <string name="tools_unlock_title">ملف PDF هذا محمي بكلمة مرور</string>
+ <string name="tools_unlock_body">حفظ نسخة تُفتح دون كلمة مرور، نهائيًا. وتُرفع أيضًا قيود الطباعة والنسخ والتعديل.</string>
+ <string name="tools_unlock_action">إزالة كلمة المرور</string>
+ <string name="tools_format_text">نص عادي (txt)</string>
+ <string name="msg_no_text_to_export">لا يحتوي ملف PDF هذا على نص للتصدير. تعرّف على نصه أولًا.</string>
+ <string name="tools_create_from_text">اكتب نصًا أو الصقه</string>
+ <string name="tools_create_action">إنشاء PDF</string>
+ <string name="tools_text_name">الاسم (اختياري)</string>
+ <string name="tools_text_hint">اكتب النص هنا أو الصقه</string>
+ <string name="root_licence_wordcraft">WordCraft (محرك Word)</string>
+ <string name="root_licence_deckcraft">DeckCraft (محرك الشرائح)</string>
+ <string name="root_licence_gridcraft">GridCraft (محرك جداول البيانات)</string>
+ <string name="root_licence_lightcraft">LightCraft (محرك الصور)</string>
+ <string name="root_licence_wordcraft_terms">MIT أو Apache-2.0، من storytold والمساهمين</string>
+ <string name="viewer_translate">ترجمة</string>
+ <string name="sheet_open_link">فتح الرابط</string>
+ <string name="msg_link_not_followed">يؤدي هذا الرابط إلى ملف لا يستطيع Artefact فتحه من هنا</string>
+ <string name="read_aloud_stop_reading">إيقاف القراءة</string>
+ <string name="read_aloud_system_default">الافتراضي في النظام (%1$s)</string>
+ <string name="read_aloud_language_selected">محددة</string>
+ <string name="read_aloud_languages_loading">جارٍ تحميل اللغات المتاحة…</string>
+ <string name="settings_read_aloud_language">لغة القراءة بصوت عالٍ</string>
+ <string name="settings_read_aloud_language_body">اختر اللغة المستخدمة لقراءة المستندات بصوت عالٍ.</string>
+ <string name="viewer_night_mode_on">الوضع الليلي مفعّل</string>
+ <string name="viewer_night_mode_off">الوضع الليلي متوقف</string>
+ <string name="read_aloud_speed">سرعة التشغيل</string>
+ <string name="sheet_not_found">غير موجود</string>
+ <string name="sheet_two_pages">صفحتان</string>
+ <string name="toolbar_label_find_fields">البحث عن الحقول</string>
+ <string name="tool_find_fields">البحث عن حقول النموذج</string>
+ <string name="msg_busy_finding_fields">جارٍ البحث عن أماكن للتعبئة…</string>
+ <string name="msg_no_fields_found">لم يُعثر على أماكن للتعبئة في هذا المستند</string>
+ <plurals name="msg_fields_found">
+ <item quantity="zero">لم يُعثر على حقول (%1$d).</item>
+ <item quantity="one">عُثر على حقل واحد (%1$d). انقر عليه لتعبئته.</item>
+ <item quantity="two">عُثر على حقلين (%1$d). انقر على أحدهما لتعبئته.</item>
+ <item quantity="few">عُثر على %1$d حقول. انقر على أحدها لتعبئته.</item>
+ <item quantity="many">عُثر على %1$d حقلًا. انقر على أحدها لتعبئته.</item>
+ <item quantity="other">عُثر على %1$d حقل. انقر على أحدها لتعبئته.</item>
+ </plurals>
+ <string name="msg_word_reading_only">تُفتح مستندات Word والعروض التقديمية للقراءة فقط حاليًا. التعديل قادم قريبًا.</string>
+ <string name="sheet_kind_word">Word</string>
+ <string name="sheet_kind_slides">الشرائح</string>
+ <string name="office_present">عرض تقديمي</string>
+ <string name="office_save_as_format">حفظ بصيغة %1$s</string>
+ <string name="sheet_edited">مُعدّل</string>
+ <string name="sheet_of">%1$d من %2$d</string>
+ <string name="sheet_tap_to_type">انقر لكتابة قيمة أو =صيغة</string>
+ <string name="sheet_fill">لون التعبئة</string>
+ <string name="sheet_fill_yellow">أصفر</string>
+ <string name="sheet_fill_green">أخضر</string>
+ <string name="sheet_fill_blue">أزرق</string>
+ <string name="sheet_fill_pink">وردي</string>
+ <string name="sheet_fill_none">بلا تعبئة</string>
+ <string name="sheet_wrap">التفاف النص</string>
+ <string name="sheet_percent">نسبة مئوية</string>
+ <string name="sheet_comma">فاصل الآلاف</string>
+ <string name="sheet_insert_row">إدراج صف</string>
+ <string name="sheet_insert_column">إدراج عمود</string>
+ <string name="sheet_clear">مسح المحتوى</string>
+ <string name="word_undo">تراجع</string>
+ <string name="word_edit">تعديل المستند</string>
+ <string name="word_tap_to_type">انقر على فقرة لتعديلها كما في ملف PDF. يطبّق «تم» التغييرات.</string>
+ <string name="word_redo">إعادة</string>
+ <string name="word_bold">غامق</string>
+ <string name="word_italic">مائل</string>
+ <string name="word_bullets">تعداد نقطي</string>
+ <string name="word_numbering">ترقيم</string>
+ <string name="word_align_left">محاذاة لليسار</string>
+ <string name="word_align_center">توسيط</string>
+ <string name="word_align_right">محاذاة لليمين</string>
+ <string name="word_heading">عنوان</string>
+ <string name="word_body_text">نص أساسي</string>
+ <string name="office_export_pdf">تصدير بصيغة PDF</string>
+ <string name="office_save_as">حفظ باسم</string>
+ <string name="office_format">%1$s (.%2$s)</string>
+ <string name="office_slide_of">%1$d من %2$d</string>
+ <string name="format_pdf">PDF</string>
+ <string name="format_docx">مستند Word</string>
+ <string name="format_odt">نص OpenDocument</string>
+ <string name="format_rtf">نص منسّق</string>
+ <string name="format_html">صفحة ويب</string>
+ <string name="format_md">Markdown</string>
+ <string name="format_txt">نص عادي</string>
+ <string name="format_pptx">عرض PowerPoint تقديمي</string>
+ <string name="format_xlsx">مصنف Excel</string>
+ <string name="format_csv">قيم مفصولة بفواصل</string>
+ <string name="format_other">أخرى</string>
+ <string name="files_kind_all">كل الملفات</string>
+ <string name="files_kind_pdf">ملفات PDF</string>
+ <string name="files_kind_word">مستندات Word</string>
+ <string name="files_kind_slides">العروض التقديمية</string>
+ <string name="files_kind_sheets">جداول البيانات</string>
+ <string name="files_kind_text">الملفات النصية</string>
+ <string name="files_kind_images">الصور</string>
+ <string name="photo_exposure">التعريض</string>
+ <string name="photo_contrast">التباين</string>
+ <string name="photo_highlights">الإضاءات</string>
+ <string name="photo_shadows">الظلال</string>
+ <string name="photo_vibrance">الحيوية</string>
+ <string name="photo_saturation">التشبع</string>
+ <string name="photo_straighten">تقويم</string>
+ <string name="photo_crop">اقتصاص</string>
+ <string name="photo_whites">الأبيض</string>
+ <string name="photo_blacks">الأسود</string>
+ <string name="photo_clarity">الوضوح</string>
+ <string name="photo_sharpen">الحدّة</string>
+ <string name="photo_vignette">تظليل الحواف</string>
+ <string name="photo_rotate">تدوير</string>
+ <string name="photo_edit">تعديل الصورة</string>
+ <string name="msg_ppt_text_only">يعرض ملف PowerPoint 97–2003 هذا نص شرائحه. عند حفظه بصيغة .pptx يُفتح بصوره وتخطيطه.</string>
+ <string name="photo_original">الأصل</string>
+ <string name="photo_reset">إعادة تعيين</string>
+ <string name="photo_adjust">ضبط</string>
+ <string name="photo_blur">تمويه</string>
+ <string name="photo_text">نص</string>
+ <string name="photo_pixelate">بكسلة</string>
+ <string name="photo_erase">مسح</string>
+ <string name="photo_brush">فرشاة</string>
+ <string name="photo_add_text">إضافة نص</string>
+ <string name="photo_text_hint">اكتب هنا</string>
+ <string name="photo_text_help">انقر على الصورة للكتابة عليها. اسحب الكلمات لتحريكها، وقرّب إصبعيك أو باعدهما لتغيير حجمها وتدويرها.</string>
+ <string name="photo_free">حر</string>
+ <string name="photo_shape_original">الأصل</string>
+ <string name="photo_mirror">عكس</string>
+ <string name="photo_font_sample">Aa</string>
+ <string name="photo_not_saved">تعذّر حفظ الصورة.</string>
+ <string name="msg_busy_removing_password">جارٍ إزالة كلمة المرور…</string>
+ <string name="msg_unlock_failed">لا يمكن إزالة حماية هذا الملف</string>
+ <string name="settings_custom">مخصص</string>
+ <string name="settings_general">عام</string>
+ <string name="settings_wallpaper">الخلفية</string>
+ <string name="settings_wallpaper_liquid">سائل</string>
+ <string name="settings_wallpaper_aurora">شفق</string>
+ <string name="settings_wallpaper_custom">المعرض</string>
+ <string name="settings_wallpaper_failed">تعذّر استخدام تلك الصورة</string>
+ <string name="settings_personalization">التخصيص</string>
+ <string name="gm_fine_tune">ضبط دقيق</string>
+ <string name="settings_glass_motion">الزجاج السائل &amp; الحركة</string>
+ <string name="gm_preview_body">تتحرك هذه الأزرار كما تضبطها في الأسفل. اضغط عليها مطولًا.</string>
+ <string name="gm_press_me">اضغطني</string>
+ <string name="gm_chip">شريحة</string>
+ <string name="gm_glass_look">الزجاج</string>
+ <string name="gm_blur">الصقيع</string>
+ <string name="gm_lens_height">عمق العدسة</string>
+ <string name="gm_lens_amount">قوة العدسة</string>
+ <string name="gm_tint">الصبغة</string>
+ <string name="gm_saturation">اللون</string>
+ <string name="gm_brightness">السطوع</string>
+ <string name="gm_highlight">إضاءة الحافة</string>
+ <string name="gm_depth">العمق</string>
+ <string name="gm_chromatic">حافة المنشور</string>
+ <string name="gm_adaptive">السطوع التكيّفي</string>
+ <string name="gm_adaptive_body">يصبح الزجاج فاتحًا أو داكنًا حسب ما خلفه. تتوقف الإعدادات المسبقة أعلاه ما دام مفعّلًا</string>
+ <string name="gm_spring">نابض الزجاج</string>
+ <string name="gm_spring_body">كيف ينتفخ الزجاج ويتجاوز ثم يستقر. انقر على الرسم لإيقافه مؤقتًا.</string>
+ <string name="gm_spring_stats">التخميد %1$s · الصلابة %2$s · يستقر خلال %3$s ث</string>
+ <string name="gm_bounce">الارتداد</string>
+ <string name="gm_speed">السرعة</string>
+ <string name="gm_press">الضغط</string>
+ <string name="gm_wobble">التمايل</string>
+ <string name="gm_stretch">التمدد</string>
+ <string name="gm_bloom">التفتّح</string>
+ <string name="gm_transitions">انتقالات الشاشة</string>
+ <string name="gm_curve_body">اسحب المقبضين لرسم المنحنى الذي تسير عليه الشاشات واللوحات والتلاشي. انقر على الرسم لإيقافه مؤقتًا.</string>
+ <string name="gm_duration">المدة</string>
+ <string name="gm_curve_drawer">الدرج</string>
+ <string name="gm_curve_standard">قياسي</string>
+ <string name="gm_curve_emphasized">مؤكد</string>
+ <string name="gm_curve_ease">دخول وخروج سلس</string>
+ <string name="gm_curve_linear">خطي</string>
+ <string name="gm_reset">إعادة الضبط الافتراضي</string>
+ <string name="licences_row">مبني بالمصادر المفتوحة</string>
+ <string name="licences_intro">يقوم Artefact على هذه الأعمال مفتوحة المصدر. انقر على أحدها لترى ترخيصه؛ يفتح السهم شيفرته المصدرية.</string>
+ <string name="licences_engines">محركات المستندات</string>
+ <string name="licences_interface">الواجهة</string>
+ <string name="licences_type">الخطوط</string>
+ <string name="licences_art">الأيقونات والرسوم</string>
+ <string name="licences_data">البيانات</string>
+ <string name="licences_platform">المنصة</string>
+ <string name="licences_source">مصدر %1$s</string>
+ <string name="licences_text_at_source">النص الكامل للترخيص موجود مع شيفرته المصدرية.</string>
+ <string name="licences_role_pdf">يقرأ ملفات PDF ويرسمها ويعدّلها ويوقّعها ويحفظها</string>
+ <string name="licences_role_word">مستندات Word وMarkdown والنصوص</string>
+ <string name="licences_role_slides">العروض التقديمية وعرض الشرائح</string>
+ <string name="licences_role_sheets">جداول البيانات وصيغها</string>
+ <string name="licences_role_photos">يعالج صورك ويعدّلها</string>
+ <string name="licences_role_ocr">يتعرّف على النص في المستندات الممسوحة</string>
+ <string name="licences_role_app">تطبيق Android الذي نشأ منه Artefact</string>
+ <string name="licences_role_glass">الزجاج السائل</string>
+ <string name="licences_role_tracker">انضغاط وتمدد مقابض الزجاج</string>
+ <string name="licences_role_toolkit">مجموعة أدوات الواجهة</string>
+ <string name="licences_role_bridge">يربط التطبيق بمحركاته</string>
+ <string name="licences_role_ui_font">خط الواجهة</string>
+ <string name="licences_role_titles">العناوين على المكتب</string>
+ <string name="licences_role_lists">عناوين القوائم</string>
+ <string name="licences_role_signatures">التوقيعات المكتوبة</string>
+ <string name="licences_role_doc_fonts">المستندات بخطوط غير موجودة في الهاتف</string>
+ <string name="licences_role_slide_font">الخط الاحتياطي للشرائح</string>
+ <string name="licences_role_icons">الأيقونات</string>
+ <string name="licences_role_mascots">التمائم</string>
+ <string name="licences_role_pdf_fonts">خطوط لملفات PDF التي لا تضمّن خطوطها</string>
+ <string name="licences_role_cmaps">النص الصيني والياباني والكوري في ملفات PDF</string>
+ <string name="licences_role_rust">لغة المحركات ومكتباتها</string>
+ <string name="voice_import">استيراد صوت</string>
+ <string name="mindmap_title">خريطة ذهنية</string>
+ <string name="mindmap_empty">اكتب الملاحظة كمخطط: فكرة في كل سطر، بإزاحة تحت الفكرة التي تتبعها. تُرسم هنا كخريطة.</string>
+ <string name="mindmap_save_image">حفظ كصورة</string>
+ <string name="mindmap_save_pdf">حفظ بصيغة PDF</string>
+ <string name="mindmap_save_opml">تصدير بصيغة OPML</string>
+ <string name="mindmap_root_hint">الفكرة المركزية</string>
+ <string name="mindmap_node_hint">فكرة جديدة</string>
+ <string name="mindmap_child">فرعية</string>
+ <string name="mindmap_sibling">مجاورة</string>
+ <string name="mindmap_edit">تعديل</string>
+ <string name="mindmap_colour">اللون</string>
+ <string name="mindmap_branch_colour">لون الفرع</string>
+ <string name="mindmap_fold">طي</string>
+ <string name="mindmap_unfold">توسيع</string>
+ <string name="mindmap_add_idea">إضافة فكرة</string>
+ <string name="mindmap_fit">ملاءمة الشاشة</string>
+ <string name="mindmap_one_side">الفروع إلى اليمين</string>
+ <string name="mindmap_both_sides">الفروع على الجانبين</string>
+ <string name="mindmap_make">تحويلها إلى خريطة ذهنية</string>
+ <string name="mindmap_hint">انقر على فكرة لاختيارها ثم مرة أخرى للكتابة. اسحبها لتحريكها أو أفلتها على فكرة أخرى.</string>
+ <string name="create_mindmap">خريطة ذهنية</string>
+ <string name="voice_imported">أُضيف الصوت إلى مكتبك</string>
+ <string name="voice_export">حفظ في التنزيلات</string>
+ <string name="voice_export_name">ملاحظة صوتية</string>
+ <string name="preview_edit">تعديل</string>
+ <string name="preview_edit_picture">تعديل الصورة</string>
+ <string name="files_kind_mindmaps">الخرائط الذهنية</string>
+ <string name="msg_not_opml">هذا الملف ليس مخطط خريطة ذهنية (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="zero">%d فكرة</item>
+ <item quantity="one">%d فكرة</item>
+ <item quantity="two">%d فكرتان</item>
+ <item quantity="few">%d أفكار</item>
+ <item quantity="many">%d فكرة</item>
+ <item quantity="other">%d فكرة</item>
+ </plurals>
+ <string name="sheet_stats">المجموع %1$s · المتوسط %2$s · العدد %3$d</string>
+ <string name="sheet_stats_count">العدد %1$d</string>
+ <string name="kind_short_pdf">PDF</string>
+ <string name="kind_short_word">مستندات</string>
+ <string name="kind_short_slides">شرائح</string>
+ <string name="kind_short_sheets">جداول</string>
+ <string name="kind_short_text">نص</string>
+ <string name="kind_short_images">صور</string>
+ <string name="kind_short_maps">خرائط</string>
</resources>
diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml
index 51ef78f..0928e0d 100644
--- a/android/app/src/main/res/values-de/strings.xml
+++ b/android/app/src/main/res/values-de/strings.xml
@@ -1333,4 +1333,260 @@
<item>Du kannst nicht jede Welle kontrollieren, aber du kannst **wählen, wie du ihr begegnest**. Ein ruhiger Atem ist **ansteckend**.</item>
<item>Ein Satz, eine Skizze, ein aufgeräumtes Regal. **Erschaffen** erinnert dich daran, dass du **die Welt um dich** verändern kannst, auch nur ein wenig.</item>
</string-array>
+ <string name="tool_encryption">Verschlüsselung</string>
+ <string name="home_about_encryption">Passwort für ein PDF festlegen oder dauerhaft entfernen</string>
+ <string name="tools_set_password_body">Eine Kopie speichern, die vor dem Öffnen nach einem Passwort fragt</string>
+ <string name="msg_no_password_yet">Dieses PDF hat kein Passwort</string>
+ <string name="tool_edit_photo">Foto bearbeiten</string>
+ <string name="home_about_edit_photo">Ein Bild zuschneiden, gerade ausrichten und anpassen</string>
+ <string name="photo_texture">Weichzeichnen / Struktur</string>
+ <string name="tool_text_to_pdf">Text zu PDF</string>
+ <string name="home_about_text_to_pdf">Text eingeben oder einfügen und als PDF speichern</string>
+ <string name="tool_pdf_to_text">PDF zu Text</string>
+ <string name="home_about_pdf_to_text">Den Text eines PDFs als reine Textdatei speichern</string>
+ <string name="home_about_find_fields">Die Lücken eines gezeichneten Formulars zu ausfüllbaren Feldern machen</string>
+ <string name="home_about_unlock">Eine Kopie eines geschützten PDFs speichern, die sich ohne Passwort öffnet</string>
+ <string name="msg_no_password">Dieses PDF hat kein Passwort zum Entfernen</string>
+ <string name="tools_unlock_title">Dieses PDF ist passwortgeschützt</string>
+ <string name="tools_unlock_body">Eine Kopie speichern, die sich dauerhaft ohne Passwort öffnet. Auch die Einschränkungen für Drucken, Kopieren und Bearbeiten werden aufgehoben.</string>
+ <string name="tools_unlock_action">Passwort entfernen</string>
+ <string name="tools_format_text">Reiner Text (txt)</string>
+ <string name="msg_no_text_to_export">Dieses PDF enthält keinen Text zum Exportieren. Lass zuerst seinen Text erkennen.</string>
+ <string name="tools_create_from_text">Text eingeben oder einfügen</string>
+ <string name="tools_create_action">PDF erstellen</string>
+ <string name="tools_text_name">Name (optional)</string>
+ <string name="tools_text_hint">Text hier schreiben oder einfügen</string>
+ <string name="root_licence_wordcraft">WordCraft (Word-Engine)</string>
+ <string name="root_licence_deckcraft">DeckCraft (Folien-Engine)</string>
+ <string name="root_licence_gridcraft">GridCraft (Tabellen-Engine)</string>
+ <string name="root_licence_lightcraft">LightCraft (Foto-Engine)</string>
+ <string name="root_licence_wordcraft_terms">MIT ODER Apache-2.0, von storytold und Mitwirkenden</string>
+ <string name="viewer_translate">Übersetzen</string>
+ <string name="sheet_open_link">Link öffnen</string>
+ <string name="msg_link_not_followed">Dieser Link führt zu einer Datei, die Artefact von hier aus nicht öffnen kann</string>
+ <string name="read_aloud_stop_reading">Vorlesen beenden</string>
+ <string name="read_aloud_system_default">Systemstandard (%1$s)</string>
+ <string name="read_aloud_language_selected">Ausgewählt</string>
+ <string name="read_aloud_languages_loading">Verfügbare Sprachen werden geladen…</string>
+ <string name="settings_read_aloud_language">Sprache zum Vorlesen</string>
+ <string name="settings_read_aloud_language_body">Wähle die Sprache, in der Dokumente vorgelesen werden.</string>
+ <string name="viewer_night_mode_on">Nachtmodus an</string>
+ <string name="viewer_night_mode_off">Nachtmodus aus</string>
+ <string name="read_aloud_speed">Wiedergabegeschwindigkeit</string>
+ <string name="sheet_not_found">Nicht gefunden</string>
+ <string name="sheet_two_pages">Zwei Seiten</string>
+ <string name="toolbar_label_find_fields">Felder finden</string>
+ <string name="tool_find_fields">Formularfelder finden</string>
+ <string name="msg_busy_finding_fields">Stellen zum Ausfüllen werden gesucht…</string>
+ <string name="msg_no_fields_found">In diesem Dokument wurden keine Stellen zum Ausfüllen gefunden</string>
+ <plurals name="msg_fields_found">
+ <item quantity="one">%1$d Feld gefunden. Tippe darauf, um es auszufüllen.</item>
+ <item quantity="other">%1$d Felder gefunden. Tippe auf eines, um es auszufüllen.</item>
+ </plurals>
+ <string name="msg_word_reading_only">Word-Dokumente und Präsentationen öffnen sich vorerst nur zum Lesen. Bearbeiten kommt bald.</string>
+ <string name="sheet_kind_word">Word</string>
+ <string name="sheet_kind_slides">Folien</string>
+ <string name="office_present">Präsentieren</string>
+ <string name="office_save_as_format">Als %1$s speichern</string>
+ <string name="sheet_edited">bearbeitet</string>
+ <string name="sheet_of">%1$d von %2$d</string>
+ <string name="sheet_tap_to_type">Tippe, um einen Wert oder =Formel einzugeben</string>
+ <string name="sheet_fill">Füllfarbe</string>
+ <string name="sheet_fill_yellow">Gelb</string>
+ <string name="sheet_fill_green">Grün</string>
+ <string name="sheet_fill_blue">Blau</string>
+ <string name="sheet_fill_pink">Rosa</string>
+ <string name="sheet_fill_none">Keine Füllung</string>
+ <string name="sheet_wrap">Text umbrechen</string>
+ <string name="sheet_percent">Prozent</string>
+ <string name="sheet_comma">Tausendertrennzeichen</string>
+ <string name="sheet_insert_row">Zeile einfügen</string>
+ <string name="sheet_insert_column">Spalte einfügen</string>
+ <string name="sheet_clear">Inhalt löschen</string>
+ <string name="word_undo">Rückgängig</string>
+ <string name="word_edit">Dokument bearbeiten</string>
+ <string name="word_tap_to_type">Tippe auf einen Absatz, um ihn wie in einem PDF zu bearbeiten. Fertig übernimmt die Änderungen.</string>
+ <string name="word_redo">Wiederholen</string>
+ <string name="word_bold">Fett</string>
+ <string name="word_italic">Kursiv</string>
+ <string name="word_bullets">Aufzählung</string>
+ <string name="word_numbering">Nummerierung</string>
+ <string name="word_align_left">Linksbündig</string>
+ <string name="word_align_center">Zentriert</string>
+ <string name="word_align_right">Rechtsbündig</string>
+ <string name="word_heading">Überschrift</string>
+ <string name="word_body_text">Fließtext</string>
+ <string name="office_export_pdf">Als PDF exportieren</string>
+ <string name="office_save_as">Speichern unter</string>
+ <string name="office_format">%1$s (.%2$s)</string>
+ <string name="office_slide_of">%1$d von %2$d</string>
+ <string name="format_pdf">PDF</string>
+ <string name="format_docx">Word-Dokument</string>
+ <string name="format_odt">OpenDocument-Text</string>
+ <string name="format_rtf">Rich Text</string>
+ <string name="format_html">Webseite</string>
+ <string name="format_md">Markdown</string>
+ <string name="format_txt">Reiner Text</string>
+ <string name="format_pptx">PowerPoint-Präsentation</string>
+ <string name="format_xlsx">Excel-Arbeitsmappe</string>
+ <string name="format_csv">Kommagetrennte Werte</string>
+ <string name="format_other">Andere</string>
+ <string name="files_kind_all">Alle Dateien</string>
+ <string name="files_kind_pdf">PDFs</string>
+ <string name="files_kind_word">Word-Dokumente</string>
+ <string name="files_kind_slides">Präsentationen</string>
+ <string name="files_kind_sheets">Tabellen</string>
+ <string name="files_kind_text">Textdateien</string>
+ <string name="files_kind_images">Bilder</string>
+ <string name="photo_exposure">Belichtung</string>
+ <string name="photo_contrast">Kontrast</string>
+ <string name="photo_highlights">Lichter</string>
+ <string name="photo_shadows">Tiefen</string>
+ <string name="photo_vibrance">Dynamik</string>
+ <string name="photo_saturation">Sättigung</string>
+ <string name="photo_straighten">Gerade ausrichten</string>
+ <string name="photo_crop">Zuschneiden</string>
+ <string name="photo_whites">Weiß</string>
+ <string name="photo_blacks">Schwarz</string>
+ <string name="photo_clarity">Klarheit</string>
+ <string name="photo_sharpen">Schärfen</string>
+ <string name="photo_vignette">Vignette</string>
+ <string name="photo_rotate">Drehen</string>
+ <string name="photo_edit">Bild bearbeiten</string>
+ <string name="msg_ppt_text_only">Diese PowerPoint-97–2003-Datei zeigt den Text ihrer Folien. Als .pptx gespeichert öffnet sie sich mit Bildern und Layout.</string>
+ <string name="photo_original">Original</string>
+ <string name="photo_reset">Zurücksetzen</string>
+ <string name="photo_adjust">Anpassen</string>
+ <string name="photo_blur">Weichzeichnen</string>
+ <string name="photo_text">Text</string>
+ <string name="photo_pixelate">Verpixeln</string>
+ <string name="photo_erase">Radieren</string>
+ <string name="photo_brush">Pinsel</string>
+ <string name="photo_add_text">Text hinzufügen</string>
+ <string name="photo_text_hint">Hier tippen</string>
+ <string name="photo_text_help">Tippe auf das Bild, um darauf zu schreiben. Ziehe Wörter, um sie zu verschieben, und zieh sie mit zwei Fingern auf, um sie zu skalieren und zu drehen.</string>
+ <string name="photo_free">Frei</string>
+ <string name="photo_shape_original">Original</string>
+ <string name="photo_mirror">Spiegeln</string>
+ <string name="photo_font_sample">Aa</string>
+ <string name="photo_not_saved">Das Bild konnte nicht gespeichert werden.</string>
+ <string name="msg_busy_removing_password">Passwort wird entfernt…</string>
+ <string name="msg_unlock_failed">Der Schutz dieser Datei kann nicht entfernt werden</string>
+ <string name="settings_custom">Eigene</string>
+ <string name="settings_general">Allgemein</string>
+ <string name="settings_wallpaper">Hintergrund</string>
+ <string name="settings_wallpaper_liquid">Flüssig</string>
+ <string name="settings_wallpaper_aurora">Aurora</string>
+ <string name="settings_wallpaper_custom">Galerie</string>
+ <string name="settings_wallpaper_failed">Dieses Bild konnte nicht verwendet werden</string>
+ <string name="settings_personalization">Personalisierung</string>
+ <string name="gm_fine_tune">Feinabstimmung</string>
+ <string name="settings_glass_motion">Flüssigglas &amp; Bewegung</string>
+ <string name="gm_preview_body">Diese Tasten bewegen sich so, wie du es unten einstellst. Halte sie gedrückt.</string>
+ <string name="gm_press_me">Drück mich</string>
+ <string name="gm_chip">Chip</string>
+ <string name="gm_glass_look">Glas</string>
+ <string name="gm_blur">Frost</string>
+ <string name="gm_lens_height">Linsentiefe</string>
+ <string name="gm_lens_amount">Linsenstärke</string>
+ <string name="gm_tint">Tönung</string>
+ <string name="gm_saturation">Farbe</string>
+ <string name="gm_brightness">Helligkeit</string>
+ <string name="gm_highlight">Randlicht</string>
+ <string name="gm_depth">Tiefe</string>
+ <string name="gm_chromatic">Prismenkante</string>
+ <string name="gm_adaptive">Adaptive Helligkeit</string>
+ <string name="gm_adaptive_body">Das Glas wird hell oder dunkel, passend zu dem, was dahinter liegt. Die Voreinstellungen oben ruhen, solange es an ist</string>
+ <string name="gm_spring">Glasfeder</string>
+ <string name="gm_spring_body">Wie Glas anschwillt, überschwingt und zur Ruhe kommt. Tippe auf die Grafik, um sie anzuhalten.</string>
+ <string name="gm_spring_stats">Dämpfung %1$s · Steifigkeit %2$s · ruht nach %3$s s</string>
+ <string name="gm_bounce">Federn</string>
+ <string name="gm_speed">Geschwindigkeit</string>
+ <string name="gm_press">Drücken</string>
+ <string name="gm_wobble">Wackeln</string>
+ <string name="gm_stretch">Dehnen</string>
+ <string name="gm_bloom">Aufblühen</string>
+ <string name="gm_transitions">Bildschirmübergänge</string>
+ <string name="gm_curve_body">Ziehe die beiden Griffe, um die Kurve zu zeichnen, auf der Bildschirme, Blätter und Überblendungen laufen. Tippe auf die Grafik, um sie anzuhalten.</string>
+ <string name="gm_duration">Dauer</string>
+ <string name="gm_curve_drawer">Schublade</string>
+ <string name="gm_curve_standard">Standard</string>
+ <string name="gm_curve_emphasized">Betont</string>
+ <string name="gm_curve_ease">Weich ein und aus</string>
+ <string name="gm_curve_linear">Linear</string>
+ <string name="gm_reset">Auf Standard zurücksetzen</string>
+ <string name="licences_row">Mit Open Source gebaut</string>
+ <string name="licences_intro">Artefact steht auf diesen Open-Source-Werken. Tippe auf eines für seine Lizenz; der Pfeil öffnet seinen Quellcode.</string>
+ <string name="licences_engines">Dokument-Engines</string>
+ <string name="licences_interface">Oberfläche</string>
+ <string name="licences_type">Schriften</string>
+ <string name="licences_art">Symbole und Grafik</string>
+ <string name="licences_data">Daten</string>
+ <string name="licences_platform">Plattform</string>
+ <string name="licences_source">Quellcode von %1$s</string>
+ <string name="licences_text_at_source">Der vollständige Lizenztext liegt beim Quellcode.</string>
+ <string name="licences_role_pdf">Liest, zeichnet, bearbeitet, signiert und speichert PDFs</string>
+ <string name="licences_role_word">Word-Dokumente, Markdown und Text</string>
+ <string name="licences_role_slides">Präsentationen und die Bildschirmpräsentation</string>
+ <string name="licences_role_sheets">Tabellen und ihre Formeln</string>
+ <string name="licences_role_photos">Entwickelt und bearbeitet deine Bilder</string>
+ <string name="licences_role_ocr">Erkennt Text in Scans</string>
+ <string name="licences_role_app">Die Android-App, aus der Artefact entstand</string>
+ <string name="licences_role_glass">Das Flüssigglas</string>
+ <string name="licences_role_tracker">Das Stauchen und Strecken der Glas-Regler</string>
+ <string name="licences_role_toolkit">Das Oberflächen-Toolkit</string>
+ <string name="licences_role_bridge">Verbindet die App mit ihren Engines</string>
+ <string name="licences_role_ui_font">Die Schrift der Oberfläche</string>
+ <string name="licences_role_titles">Titel auf dem Schreibtisch</string>
+ <string name="licences_role_lists">Listentitel</string>
+ <string name="licences_role_signatures">Getippte Unterschriften</string>
+ <string name="licences_role_doc_fonts">Dokumente in Schriften, die das Telefon nicht hat</string>
+ <string name="licences_role_slide_font">Die Ersatzschrift der Folien</string>
+ <string name="licences_role_icons">Symbole</string>
+ <string name="licences_role_mascots">Die Maskottchen</string>
+ <string name="licences_role_pdf_fonts">Schriften für PDFs, die ihre eigenen nicht einbetten</string>
+ <string name="licences_role_cmaps">Chinesischer, japanischer und koreanischer Text in PDFs</string>
+ <string name="licences_role_rust">Die Sprache und Bibliotheken der Engines</string>
+ <string name="voice_import">Audio importieren</string>
+ <string name="mindmap_title">Mindmap</string>
+ <string name="mindmap_empty">Schreib die Notiz als Gliederung: eine Idee pro Zeile, eingerückt unter der Idee, zu der sie gehört. Hier wird sie als Karte gezeichnet.</string>
+ <string name="mindmap_save_image">Als Bild speichern</string>
+ <string name="mindmap_save_pdf">Als PDF speichern</string>
+ <string name="mindmap_save_opml">Als OPML exportieren</string>
+ <string name="mindmap_root_hint">Zentrale Idee</string>
+ <string name="mindmap_node_hint">Neue Idee</string>
+ <string name="mindmap_child">Unteridee</string>
+ <string name="mindmap_sibling">Nebenidee</string>
+ <string name="mindmap_edit">Bearbeiten</string>
+ <string name="mindmap_colour">Farbe</string>
+ <string name="mindmap_branch_colour">Zweigfarbe</string>
+ <string name="mindmap_fold">Einklappen</string>
+ <string name="mindmap_unfold">Ausklappen</string>
+ <string name="mindmap_add_idea">Idee hinzufügen</string>
+ <string name="mindmap_fit">An Bildschirm anpassen</string>
+ <string name="mindmap_one_side">Zweige nach rechts</string>
+ <string name="mindmap_both_sides">Zweige auf beiden Seiten</string>
+ <string name="mindmap_make">Als Mindmap anlegen</string>
+ <string name="mindmap_hint">Tippe auf eine Idee, um sie auszuwählen, und noch einmal, um zu schreiben. Zieh sie, um sie zu verschieben, oder leg sie auf einer anderen Idee ab.</string>
+ <string name="create_mindmap">Mindmap</string>
+ <string name="voice_imported">Audio zu deinem Schreibtisch hinzugefügt</string>
+ <string name="voice_export">In Downloads speichern</string>
+ <string name="voice_export_name">Sprachnotiz</string>
+ <string name="preview_edit">Bearbeiten</string>
+ <string name="preview_edit_picture">Bild bearbeiten</string>
+ <string name="files_kind_mindmaps">Mindmaps</string>
+ <string name="msg_not_opml">Diese Datei ist keine Mindmap-Gliederung (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="one">%d Idee</item>
+ <item quantity="other">%d Ideen</item>
+ </plurals>
+ <string name="sheet_stats">Summe %1$s · Mittelwert %2$s · Anzahl %3$d</string>
+ <string name="sheet_stats_count">Anzahl %1$d</string>
+ <string name="kind_short_pdf">PDFs</string>
+ <string name="kind_short_word">Dokumente</string>
+ <string name="kind_short_slides">Folien</string>
+ <string name="kind_short_sheets">Tabellen</string>
+ <string name="kind_short_text">Text</string>
+ <string name="kind_short_images">Bilder</string>
+ <string name="kind_short_maps">Mindmaps</string>
</resources>
diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml
index 590a8d9..493e1be 100644
--- a/android/app/src/main/res/values-es/strings.xml
+++ b/android/app/src/main/res/values-es/strings.xml
@@ -1341,4 +1341,260 @@
<item>No puedes controlar cada ola, pero sí **elegir cómo recibirla**. Una respiración serena es **contagiosa**.</item>
<item>Una frase, un boceto, una estantería ordenada. **Crear** te recuerda que puedes **cambiar el mundo a tu alrededor**, aunque sea un poco.</item>
</string-array>
+ <string name="tool_encryption">Cifrado</string>
+ <string name="home_about_encryption">Pon una contraseña a un PDF o quítala para siempre</string>
+ <string name="tools_set_password_body">Guardar una copia que pida contraseña antes de abrirse</string>
+ <string name="msg_no_password_yet">Este PDF no tiene contraseña</string>
+ <string name="tool_edit_photo">Editar foto</string>
+ <string name="home_about_edit_photo">Recorta, endereza y ajusta una imagen</string>
+ <string name="photo_texture">Suavizar / Textura</string>
+ <string name="tool_text_to_pdf">Texto a PDF</string>
+ <string name="home_about_text_to_pdf">Escribe o pega texto y guárdalo como PDF</string>
+ <string name="tool_pdf_to_text">PDF a texto</string>
+ <string name="home_about_pdf_to_text">Guarda el texto de un PDF como archivo de texto plano</string>
+ <string name="home_about_find_fields">Convierte los espacios en blanco de un formulario dibujado en campos para rellenar</string>
+ <string name="home_about_unlock">Guarda una copia de un PDF protegido que se abra sin contraseña</string>
+ <string name="msg_no_password">Este PDF no tiene contraseña que quitar</string>
+ <string name="tools_unlock_title">Este PDF está protegido con contraseña</string>
+ <string name="tools_unlock_body">Guardar una copia que se abra sin contraseña, para siempre. También se quitan sus restricciones de impresión, copia y edición.</string>
+ <string name="tools_unlock_action">Quitar contraseña</string>
+ <string name="tools_format_text">Texto plano (txt)</string>
+ <string name="msg_no_text_to_export">Este PDF no tiene texto que exportar. Reconoce su texto primero.</string>
+ <string name="tools_create_from_text">Escribir o pegar texto</string>
+ <string name="tools_create_action">Crear PDF</string>
+ <string name="tools_text_name">Nombre (opcional)</string>
+ <string name="tools_text_hint">Escribe o pega el texto aquí</string>
+ <string name="root_licence_wordcraft">WordCraft (motor de Word)</string>
+ <string name="root_licence_deckcraft">DeckCraft (motor de diapositivas)</string>
+ <string name="root_licence_gridcraft">GridCraft (motor de hojas de cálculo)</string>
+ <string name="root_licence_lightcraft">LightCraft (motor de fotos)</string>
+ <string name="root_licence_wordcraft_terms">MIT O Apache-2.0, de storytold y colaboradores</string>
+ <string name="viewer_translate">Traducir</string>
+ <string name="sheet_open_link">Abrir enlace</string>
+ <string name="msg_link_not_followed">Este enlace lleva a un archivo que Artefact no puede abrir desde aquí</string>
+ <string name="read_aloud_stop_reading">Dejar de leer</string>
+ <string name="read_aloud_system_default">Predeterminado del sistema (%1$s)</string>
+ <string name="read_aloud_language_selected">Seleccionado</string>
+ <string name="read_aloud_languages_loading">Cargando idiomas disponibles…</string>
+ <string name="settings_read_aloud_language">Idioma de lectura en voz alta</string>
+ <string name="settings_read_aloud_language_body">Elige el idioma con el que se leen los documentos en voz alta.</string>
+ <string name="viewer_night_mode_on">Modo noche activado</string>
+ <string name="viewer_night_mode_off">Modo noche desactivado</string>
+ <string name="read_aloud_speed">Velocidad de reproducción</string>
+ <string name="sheet_not_found">No encontrado</string>
+ <string name="sheet_two_pages">Dos páginas</string>
+ <string name="toolbar_label_find_fields">Buscar campos</string>
+ <string name="tool_find_fields">Buscar campos del formulario</string>
+ <string name="msg_busy_finding_fields">Buscando sitios que rellenar…</string>
+ <string name="msg_no_fields_found">No se encontraron sitios que rellenar en este documento</string>
+ <plurals name="msg_fields_found">
+ <item quantity="one">%1$d campo encontrado. Tócalo para rellenarlo.</item>
+ <item quantity="other">%1$d campos encontrados. Toca uno para rellenarlo.</item>
+ </plurals>
+ <string name="msg_word_reading_only">Los documentos de Word y las presentaciones se abren solo para leer por ahora. La edición llegará pronto.</string>
+ <string name="sheet_kind_word">Word</string>
+ <string name="sheet_kind_slides">Diapositivas</string>
+ <string name="office_present">Presentar</string>
+ <string name="office_save_as_format">Guardar como %1$s</string>
+ <string name="sheet_edited">editado</string>
+ <string name="sheet_of">%1$d de %2$d</string>
+ <string name="sheet_tap_to_type">Toca para escribir un valor o una =fórmula</string>
+ <string name="sheet_fill">Color de relleno</string>
+ <string name="sheet_fill_yellow">Amarillo</string>
+ <string name="sheet_fill_green">Verde</string>
+ <string name="sheet_fill_blue">Azul</string>
+ <string name="sheet_fill_pink">Rosa</string>
+ <string name="sheet_fill_none">Sin relleno</string>
+ <string name="sheet_wrap">Ajustar texto</string>
+ <string name="sheet_percent">Porcentaje</string>
+ <string name="sheet_comma">Separador de miles</string>
+ <string name="sheet_insert_row">Insertar fila</string>
+ <string name="sheet_insert_column">Insertar columna</string>
+ <string name="sheet_clear">Borrar contenido</string>
+ <string name="word_undo">Deshacer</string>
+ <string name="word_edit">Editar documento</string>
+ <string name="word_tap_to_type">Toca un párrafo para editarlo, como en un PDF. Listo aplica los cambios.</string>
+ <string name="word_redo">Rehacer</string>
+ <string name="word_bold">Negrita</string>
+ <string name="word_italic">Cursiva</string>
+ <string name="word_bullets">Viñetas</string>
+ <string name="word_numbering">Numeración</string>
+ <string name="word_align_left">Alinear a la izquierda</string>
+ <string name="word_align_center">Centrar</string>
+ <string name="word_align_right">Alinear a la derecha</string>
+ <string name="word_heading">Título</string>
+ <string name="word_body_text">Texto normal</string>
+ <string name="office_export_pdf">Exportar como PDF</string>
+ <string name="office_save_as">Guardar como</string>
+ <string name="office_format">%1$s (.%2$s)</string>
+ <string name="office_slide_of">%1$d de %2$d</string>
+ <string name="format_pdf">PDF</string>
+ <string name="format_docx">Documento de Word</string>
+ <string name="format_odt">Texto OpenDocument</string>
+ <string name="format_rtf">Texto enriquecido</string>
+ <string name="format_html">Página web</string>
+ <string name="format_md">Markdown</string>
+ <string name="format_txt">Texto plano</string>
+ <string name="format_pptx">Presentación de PowerPoint</string>
+ <string name="format_xlsx">Libro de Excel</string>
+ <string name="format_csv">Valores separados por comas</string>
+ <string name="format_other">Otro</string>
+ <string name="files_kind_all">Todos los archivos</string>
+ <string name="files_kind_pdf">PDF</string>
+ <string name="files_kind_word">Documentos de Word</string>
+ <string name="files_kind_slides">Presentaciones</string>
+ <string name="files_kind_sheets">Hojas de cálculo</string>
+ <string name="files_kind_text">Archivos de texto</string>
+ <string name="files_kind_images">Imágenes</string>
+ <string name="photo_exposure">Exposición</string>
+ <string name="photo_contrast">Contraste</string>
+ <string name="photo_highlights">Luces</string>
+ <string name="photo_shadows">Sombras</string>
+ <string name="photo_vibrance">Intensidad</string>
+ <string name="photo_saturation">Saturación</string>
+ <string name="photo_straighten">Enderezar</string>
+ <string name="photo_crop">Recortar</string>
+ <string name="photo_whites">Blancos</string>
+ <string name="photo_blacks">Negros</string>
+ <string name="photo_clarity">Claridad</string>
+ <string name="photo_sharpen">Nitidez</string>
+ <string name="photo_vignette">Viñeta</string>
+ <string name="photo_rotate">Girar</string>
+ <string name="photo_edit">Editar imagen</string>
+ <string name="msg_ppt_text_only">Este archivo de PowerPoint 97–2003 muestra el texto de sus diapositivas. Guardado como .pptx, se abre con sus imágenes y su diseño.</string>
+ <string name="photo_original">Original</string>
+ <string name="photo_reset">Restablecer</string>
+ <string name="photo_adjust">Ajustar</string>
+ <string name="photo_blur">Desenfocar</string>
+ <string name="photo_text">Texto</string>
+ <string name="photo_pixelate">Pixelar</string>
+ <string name="photo_erase">Borrar</string>
+ <string name="photo_brush">Pincel</string>
+ <string name="photo_add_text">Añadir texto</string>
+ <string name="photo_text_hint">Escribe aquí</string>
+ <string name="photo_text_help">Toca la imagen para escribir en ella. Arrastra las palabras para moverlas y pellizca para cambiar su tamaño y girarlas.</string>
+ <string name="photo_free">Libre</string>
+ <string name="photo_shape_original">Original</string>
+ <string name="photo_mirror">Espejo</string>
+ <string name="photo_font_sample">Aa</string>
+ <string name="photo_not_saved">No se pudo guardar la imagen.</string>
+ <string name="msg_busy_removing_password">Quitando la contraseña…</string>
+ <string name="msg_unlock_failed">No se puede quitar la protección de este archivo</string>
+ <string name="settings_custom">Personalizado</string>
+ <string name="settings_general">General</string>
+ <string name="settings_wallpaper">Fondo de pantalla</string>
+ <string name="settings_wallpaper_liquid">Líquido</string>
+ <string name="settings_wallpaper_aurora">Aurora</string>
+ <string name="settings_wallpaper_custom">Galería</string>
+ <string name="settings_wallpaper_failed">No se pudo usar esa imagen</string>
+ <string name="settings_personalization">Personalización</string>
+ <string name="gm_fine_tune">Ajuste fino</string>
+ <string name="settings_glass_motion">Cristal líquido &amp; movimiento</string>
+ <string name="gm_preview_body">Estos botones se mueven como los ajustes de abajo. Mantenlos pulsados.</string>
+ <string name="gm_press_me">Púlsame</string>
+ <string name="gm_chip">Chip</string>
+ <string name="gm_glass_look">Cristal</string>
+ <string name="gm_blur">Escarcha</string>
+ <string name="gm_lens_height">Profundidad de la lente</string>
+ <string name="gm_lens_amount">Fuerza de la lente</string>
+ <string name="gm_tint">Tinte</string>
+ <string name="gm_saturation">Color</string>
+ <string name="gm_brightness">Brillo</string>
+ <string name="gm_highlight">Luz de borde</string>
+ <string name="gm_depth">Profundidad</string>
+ <string name="gm_chromatic">Borde prismático</string>
+ <string name="gm_adaptive">Luminancia adaptable</string>
+ <string name="gm_adaptive_body">El cristal se vuelve claro u oscuro según lo que tiene detrás. Los ajustes de arriba quedan en pausa mientras está activada</string>
+ <string name="gm_spring">Muelle del cristal</string>
+ <string name="gm_spring_body">Cómo el cristal se hincha, se pasa y se asienta. Toca el gráfico para pausarlo.</string>
+ <string name="gm_spring_stats">Amortiguación %1$s · rigidez %2$s · se asienta en %3$s s</string>
+ <string name="gm_bounce">Rebote</string>
+ <string name="gm_speed">Velocidad</string>
+ <string name="gm_press">Pulsación</string>
+ <string name="gm_wobble">Vaivén</string>
+ <string name="gm_stretch">Estirar</string>
+ <string name="gm_bloom">Florecer</string>
+ <string name="gm_transitions">Transiciones de pantalla</string>
+ <string name="gm_curve_body">Arrastra los dos tiradores para dibujar la curva que siguen las pantallas, las hojas y los fundidos. Toca el gráfico para pausarlo.</string>
+ <string name="gm_duration">Duración</string>
+ <string name="gm_curve_drawer">Cajón</string>
+ <string name="gm_curve_standard">Estándar</string>
+ <string name="gm_curve_emphasized">Enfatizada</string>
+ <string name="gm_curve_ease">Entrada y salida suaves</string>
+ <string name="gm_curve_linear">Lineal</string>
+ <string name="gm_reset">Restablecer valores predeterminados</string>
+ <string name="licences_row">Hecho con código abierto</string>
+ <string name="licences_intro">Artefact se apoya en estas obras de código abierto. Toca una para ver su licencia; la flecha abre su código fuente.</string>
+ <string name="licences_engines">Motores de documentos</string>
+ <string name="licences_interface">Interfaz</string>
+ <string name="licences_type">Tipografías</string>
+ <string name="licences_art">Iconos e ilustraciones</string>
+ <string name="licences_data">Datos</string>
+ <string name="licences_platform">Plataforma</string>
+ <string name="licences_source">Código fuente de %1$s</string>
+ <string name="licences_text_at_source">El texto completo de la licencia está con su código fuente.</string>
+ <string name="licences_role_pdf">Lee, dibuja, edita, firma y guarda PDF</string>
+ <string name="licences_role_word">Documentos de Word, Markdown y texto</string>
+ <string name="licences_role_slides">Las presentaciones y la proyección</string>
+ <string name="licences_role_sheets">Las hojas de cálculo y sus fórmulas</string>
+ <string name="licences_role_photos">Revela y edita tus imágenes</string>
+ <string name="licences_role_ocr">Reconoce el texto de los escaneos</string>
+ <string name="licences_role_app">La app de Android de la que nació Artefact</string>
+ <string name="licences_role_glass">El cristal líquido</string>
+ <string name="licences_role_tracker">El aplastar y estirar de los controles de cristal</string>
+ <string name="licences_role_toolkit">El kit de interfaz</string>
+ <string name="licences_role_bridge">Une la app con sus motores</string>
+ <string name="licences_role_ui_font">La tipografía de la interfaz</string>
+ <string name="licences_role_titles">Los títulos del escritorio</string>
+ <string name="licences_role_lists">Los títulos de listas</string>
+ <string name="licences_role_signatures">Las firmas escritas</string>
+ <string name="licences_role_doc_fonts">Documentos en fuentes que el teléfono no tiene</string>
+ <string name="licences_role_slide_font">La fuente de reserva de las diapositivas</string>
+ <string name="licences_role_icons">Iconos</string>
+ <string name="licences_role_mascots">Las mascotas</string>
+ <string name="licences_role_pdf_fonts">Fuentes para PDF que no incluyen las suyas</string>
+ <string name="licences_role_cmaps">Texto chino, japonés y coreano en PDF</string>
+ <string name="licences_role_rust">El lenguaje y las bibliotecas de los motores</string>
+ <string name="voice_import">Importar audio</string>
+ <string name="mindmap_title">Mapa mental</string>
+ <string name="mindmap_empty">Escribe la nota como un esquema: una idea por línea, con sangría bajo la idea a la que pertenece. Aquí se dibuja como un mapa.</string>
+ <string name="mindmap_save_image">Guardar como imagen</string>
+ <string name="mindmap_save_pdf">Guardar como PDF</string>
+ <string name="mindmap_save_opml">Exportar como OPML</string>
+ <string name="mindmap_root_hint">Idea central</string>
+ <string name="mindmap_node_hint">Nueva idea</string>
+ <string name="mindmap_child">Hija</string>
+ <string name="mindmap_sibling">Hermana</string>
+ <string name="mindmap_edit">Editar</string>
+ <string name="mindmap_colour">Color</string>
+ <string name="mindmap_branch_colour">Color de la rama</string>
+ <string name="mindmap_fold">Plegar</string>
+ <string name="mindmap_unfold">Desplegar</string>
+ <string name="mindmap_add_idea">Añadir idea</string>
+ <string name="mindmap_fit">Ajustar a la pantalla</string>
+ <string name="mindmap_one_side">Ramas a la derecha</string>
+ <string name="mindmap_both_sides">Ramas a ambos lados</string>
+ <string name="mindmap_make">Convertir en mapa mental</string>
+ <string name="mindmap_hint">Toca una idea para elegirla y otra vez para escribir. Arrástrala para moverla o suéltala sobre otra idea.</string>
+ <string name="create_mindmap">Mapa mental</string>
+ <string name="voice_imported">Audio añadido a tu escritorio</string>
+ <string name="voice_export">Guardar en Descargas</string>
+ <string name="voice_export_name">Nota de voz</string>
+ <string name="preview_edit">Editar</string>
+ <string name="preview_edit_picture">Editar la imagen</string>
+ <string name="files_kind_mindmaps">Mapas mentales</string>
+ <string name="msg_not_opml">Este archivo no es un esquema de mapa mental (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="one">%d idea</item>
+ <item quantity="other">%d ideas</item>
+ </plurals>
+ <string name="sheet_stats">Suma %1$s · Promedio %2$s · Recuento %3$d</string>
+ <string name="sheet_stats_count">Recuento %1$d</string>
+ <string name="kind_short_pdf">PDF</string>
+ <string name="kind_short_word">Documentos</string>
+ <string name="kind_short_slides">Diapos</string>
+ <string name="kind_short_sheets">Hojas</string>
+ <string name="kind_short_text">Texto</string>
+ <string name="kind_short_images">Imágenes</string>
+ <string name="kind_short_maps">Mapas</string>
</resources>
diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml
index b59dc78..621efbc 100644
--- a/android/app/src/main/res/values-fr/strings.xml
+++ b/android/app/src/main/res/values-fr/strings.xml
@@ -1213,4 +1213,260 @@
<item>Vous ne contrôlez pas chaque vague, mais vous pouvez **choisir comment l\'accueillir**. Une respiration posée est **contagieuse**.</item>
<item>Une phrase, un croquis, une étagère rangée. **Créer** vous rappelle que vous pouvez **changer le monde autour de vous**, même un peu.</item>
</string-array>
+ <string name="tool_encryption">Chiffrement</string>
+ <string name="home_about_encryption">Définir le mot de passe d\'un PDF, ou le retirer pour de bon</string>
+ <string name="tools_set_password_body">Enregistrer une copie qui demande un mot de passe avant de s\'ouvrir</string>
+ <string name="msg_no_password_yet">Ce PDF n\'a pas de mot de passe</string>
+ <string name="tool_edit_photo">Modifier la photo</string>
+ <string name="home_about_edit_photo">Recadrer, redresser et retoucher une image</string>
+ <string name="photo_texture">Adoucir / Texture</string>
+ <string name="tool_text_to_pdf">Texte en PDF</string>
+ <string name="home_about_text_to_pdf">Saisir ou coller du texte et l\'enregistrer en PDF</string>
+ <string name="tool_pdf_to_text">PDF en texte</string>
+ <string name="home_about_pdf_to_text">Enregistrer le texte d\'un PDF dans un fichier texte brut</string>
+ <string name="home_about_find_fields">Transformer les blancs d\'un formulaire dessiné en champs à remplir</string>
+ <string name="home_about_unlock">Enregistrer une copie d\'un PDF protégé qui s\'ouvre sans son mot de passe</string>
+ <string name="msg_no_password">Ce PDF n\'a pas de mot de passe à retirer</string>
+ <string name="tools_unlock_title">Ce PDF est protégé par un mot de passe</string>
+ <string name="tools_unlock_body">Enregistrer une copie qui s\'ouvre sans mot de passe, pour de bon. Ses restrictions d\'impression, de copie et de modification sont levées aussi.</string>
+ <string name="tools_unlock_action">Retirer le mot de passe</string>
+ <string name="tools_format_text">Texte brut (txt)</string>
+ <string name="msg_no_text_to_export">Ce PDF n\'a pas de texte à exporter. Faites d\'abord reconnaître son texte.</string>
+ <string name="tools_create_from_text">Saisir ou coller du texte</string>
+ <string name="tools_create_action">Créer le PDF</string>
+ <string name="tools_text_name">Nom (facultatif)</string>
+ <string name="tools_text_hint">Écrivez ou collez le texte ici</string>
+ <string name="root_licence_wordcraft">WordCraft (moteur Word)</string>
+ <string name="root_licence_deckcraft">DeckCraft (moteur de diapositives)</string>
+ <string name="root_licence_gridcraft">GridCraft (moteur de tableur)</string>
+ <string name="root_licence_lightcraft">LightCraft (moteur photo)</string>
+ <string name="root_licence_wordcraft_terms">MIT OU Apache-2.0, par storytold et ses contributeurs</string>
+ <string name="viewer_translate">Traduire</string>
+ <string name="sheet_open_link">Ouvrir le lien</string>
+ <string name="msg_link_not_followed">Ce lien mène à un fichier qu\'Artefact ne peut pas ouvrir d\'ici</string>
+ <string name="read_aloud_stop_reading">Arrêter la lecture</string>
+ <string name="read_aloud_system_default">Par défaut du système (%1$s)</string>
+ <string name="read_aloud_language_selected">Sélectionnée</string>
+ <string name="read_aloud_languages_loading">Chargement des langues disponibles…</string>
+ <string name="settings_read_aloud_language">Langue de lecture à voix haute</string>
+ <string name="settings_read_aloud_language_body">Choisissez la langue utilisée pour lire les documents à voix haute.</string>
+ <string name="viewer_night_mode_on">Mode nuit activé</string>
+ <string name="viewer_night_mode_off">Mode nuit désactivé</string>
+ <string name="read_aloud_speed">Vitesse de lecture</string>
+ <string name="sheet_not_found">Introuvable</string>
+ <string name="sheet_two_pages">Deux pages</string>
+ <string name="toolbar_label_find_fields">Trouver les champs</string>
+ <string name="tool_find_fields">Trouver les champs du formulaire</string>
+ <string name="msg_busy_finding_fields">Recherche des endroits à remplir…</string>
+ <string name="msg_no_fields_found">Aucun endroit à remplir n\'a été trouvé dans ce document</string>
+ <plurals name="msg_fields_found">
+ <item quantity="one">%1$d champ trouvé. Touchez-le pour le remplir.</item>
+ <item quantity="other">%1$d champs trouvés. Touchez-en un pour le remplir.</item>
+ </plurals>
+ <string name="msg_word_reading_only">Les documents Word et les présentations s\'ouvrent en lecture pour l\'instant. La modification arrive bientôt.</string>
+ <string name="sheet_kind_word">Word</string>
+ <string name="sheet_kind_slides">Diapositives</string>
+ <string name="office_present">Présenter</string>
+ <string name="office_save_as_format">Enregistrer en %1$s</string>
+ <string name="sheet_edited">modifié</string>
+ <string name="sheet_of">%1$d sur %2$d</string>
+ <string name="sheet_tap_to_type">Touchez pour saisir une valeur ou une =formule</string>
+ <string name="sheet_fill">Couleur de remplissage</string>
+ <string name="sheet_fill_yellow">Jaune</string>
+ <string name="sheet_fill_green">Vert</string>
+ <string name="sheet_fill_blue">Bleu</string>
+ <string name="sheet_fill_pink">Rose</string>
+ <string name="sheet_fill_none">Aucun remplissage</string>
+ <string name="sheet_wrap">Renvoyer à la ligne</string>
+ <string name="sheet_percent">Pourcentage</string>
+ <string name="sheet_comma">Séparateur de milliers</string>
+ <string name="sheet_insert_row">Insérer une ligne</string>
+ <string name="sheet_insert_column">Insérer une colonne</string>
+ <string name="sheet_clear">Effacer le contenu</string>
+ <string name="word_undo">Annuler</string>
+ <string name="word_edit">Modifier le document</string>
+ <string name="word_tap_to_type">Touchez un paragraphe pour le modifier, comme dans un PDF. Terminé applique les changements.</string>
+ <string name="word_redo">Rétablir</string>
+ <string name="word_bold">Gras</string>
+ <string name="word_italic">Italique</string>
+ <string name="word_bullets">Puces</string>
+ <string name="word_numbering">Numérotation</string>
+ <string name="word_align_left">Aligner à gauche</string>
+ <string name="word_align_center">Centrer</string>
+ <string name="word_align_right">Aligner à droite</string>
+ <string name="word_heading">Titre</string>
+ <string name="word_body_text">Corps de texte</string>
+ <string name="office_export_pdf">Exporter en PDF</string>
+ <string name="office_save_as">Enregistrer sous</string>
+ <string name="office_format">%1$s (.%2$s)</string>
+ <string name="office_slide_of">%1$d sur %2$d</string>
+ <string name="format_pdf">PDF</string>
+ <string name="format_docx">Document Word</string>
+ <string name="format_odt">Texte OpenDocument</string>
+ <string name="format_rtf">Texte enrichi</string>
+ <string name="format_html">Page web</string>
+ <string name="format_md">Markdown</string>
+ <string name="format_txt">Texte brut</string>
+ <string name="format_pptx">Présentation PowerPoint</string>
+ <string name="format_xlsx">Classeur Excel</string>
+ <string name="format_csv">Valeurs séparées par des virgules</string>
+ <string name="format_other">Autre</string>
+ <string name="files_kind_all">Tous les fichiers</string>
+ <string name="files_kind_pdf">PDF</string>
+ <string name="files_kind_word">Documents Word</string>
+ <string name="files_kind_slides">Présentations</string>
+ <string name="files_kind_sheets">Tableurs</string>
+ <string name="files_kind_text">Fichiers texte</string>
+ <string name="files_kind_images">Images</string>
+ <string name="photo_exposure">Exposition</string>
+ <string name="photo_contrast">Contraste</string>
+ <string name="photo_highlights">Hautes lumières</string>
+ <string name="photo_shadows">Ombres</string>
+ <string name="photo_vibrance">Vibrance</string>
+ <string name="photo_saturation">Saturation</string>
+ <string name="photo_straighten">Redresser</string>
+ <string name="photo_crop">Recadrer</string>
+ <string name="photo_whites">Blancs</string>
+ <string name="photo_blacks">Noirs</string>
+ <string name="photo_clarity">Clarté</string>
+ <string name="photo_sharpen">Netteté</string>
+ <string name="photo_vignette">Vignettage</string>
+ <string name="photo_rotate">Pivoter</string>
+ <string name="photo_edit">Modifier l\'image</string>
+ <string name="msg_ppt_text_only">Ce fichier PowerPoint 97–2003 affiche le texte de ses diapositives. Enregistré en .pptx, il s\'ouvre avec ses images et sa mise en page.</string>
+ <string name="photo_original">Original</string>
+ <string name="photo_reset">Réinitialiser</string>
+ <string name="photo_adjust">Régler</string>
+ <string name="photo_blur">Flou</string>
+ <string name="photo_text">Texte</string>
+ <string name="photo_pixelate">Pixeliser</string>
+ <string name="photo_erase">Effacer</string>
+ <string name="photo_brush">Pinceau</string>
+ <string name="photo_add_text">Ajouter du texte</string>
+ <string name="photo_text_hint">Écrivez ici</string>
+ <string name="photo_text_help">Touchez l\'image pour écrire dessus. Faites glisser les mots pour les déplacer, pincez pour les redimensionner et les tourner.</string>
+ <string name="photo_free">Libre</string>
+ <string name="photo_shape_original">Original</string>
+ <string name="photo_mirror">Miroir</string>
+ <string name="photo_font_sample">Aa</string>
+ <string name="photo_not_saved">L\'image n\'a pas pu être enregistrée.</string>
+ <string name="msg_busy_removing_password">Retrait du mot de passe…</string>
+ <string name="msg_unlock_failed">La protection de ce fichier ne peut pas être retirée</string>
+ <string name="settings_custom">Personnalisé</string>
+ <string name="settings_general">Général</string>
+ <string name="settings_wallpaper">Fond d\'écran</string>
+ <string name="settings_wallpaper_liquid">Liquide</string>
+ <string name="settings_wallpaper_aurora">Aurore</string>
+ <string name="settings_wallpaper_custom">Galerie</string>
+ <string name="settings_wallpaper_failed">Impossible d\'utiliser cette image</string>
+ <string name="settings_personalization">Personnalisation</string>
+ <string name="gm_fine_tune">Réglage fin</string>
+ <string name="settings_glass_motion">Verre liquide &amp; mouvement</string>
+ <string name="gm_preview_body">Ces boutons bougent comme vous le réglez ci-dessous. Appuyez longuement dessus.</string>
+ <string name="gm_press_me">Appuyez-moi</string>
+ <string name="gm_chip">Puce</string>
+ <string name="gm_glass_look">Verre</string>
+ <string name="gm_blur">Givre</string>
+ <string name="gm_lens_height">Profondeur de la lentille</string>
+ <string name="gm_lens_amount">Force de la lentille</string>
+ <string name="gm_tint">Teinte</string>
+ <string name="gm_saturation">Couleur</string>
+ <string name="gm_brightness">Luminosité</string>
+ <string name="gm_highlight">Reflet de bord</string>
+ <string name="gm_depth">Profondeur</string>
+ <string name="gm_chromatic">Bord prismatique</string>
+ <string name="gm_adaptive">Luminance adaptative</string>
+ <string name="gm_adaptive_body">Le verre devient clair ou sombre selon ce qu\'il y a derrière. Les préréglages ci-dessus sont en pause tant qu\'elle est active</string>
+ <string name="gm_spring">Ressort du verre</string>
+ <string name="gm_spring_body">Comment le verre gonfle, dépasse et se pose. Touchez le graphique pour le mettre en pause.</string>
+ <string name="gm_spring_stats">Amortissement %1$s · raideur %2$s · se pose en %3$s s</string>
+ <string name="gm_bounce">Rebond</string>
+ <string name="gm_speed">Vitesse</string>
+ <string name="gm_press">Appui</string>
+ <string name="gm_wobble">Ondulation</string>
+ <string name="gm_stretch">Étirement</string>
+ <string name="gm_bloom">Éclosion</string>
+ <string name="gm_transitions">Transitions d\'écran</string>
+ <string name="gm_curve_body">Faites glisser les deux poignées pour dessiner la courbe que suivent les écrans, les feuilles et les fondus. Touchez le graphique pour le mettre en pause.</string>
+ <string name="gm_duration">Durée</string>
+ <string name="gm_curve_drawer">Tiroir</string>
+ <string name="gm_curve_standard">Standard</string>
+ <string name="gm_curve_emphasized">Accentuée</string>
+ <string name="gm_curve_ease">Entrée et sortie douces</string>
+ <string name="gm_curve_linear">Linéaire</string>
+ <string name="gm_reset">Rétablir les valeurs par défaut</string>
+ <string name="licences_row">Conçu avec l\'open source</string>
+ <string name="licences_intro">Artefact repose sur ces œuvres open source. Touchez-en une pour sa licence ; la flèche ouvre son code source.</string>
+ <string name="licences_engines">Moteurs de documents</string>
+ <string name="licences_interface">Interface</string>
+ <string name="licences_type">Polices</string>
+ <string name="licences_art">Icônes et illustrations</string>
+ <string name="licences_data">Données</string>
+ <string name="licences_platform">Plateforme</string>
+ <string name="licences_source">Code source de %1$s</string>
+ <string name="licences_text_at_source">Le texte complet de la licence se trouve avec son code source.</string>
+ <string name="licences_role_pdf">Lit, dessine, modifie, signe et enregistre les PDF</string>
+ <string name="licences_role_word">Documents Word, Markdown et texte</string>
+ <string name="licences_role_slides">Les présentations et le diaporama</string>
+ <string name="licences_role_sheets">Les tableurs et leurs formules</string>
+ <string name="licences_role_photos">Développe et retouche vos images</string>
+ <string name="licences_role_ocr">Reconnaît le texte des numérisations</string>
+ <string name="licences_role_app">L\'app Android dont Artefact est issu</string>
+ <string name="licences_role_glass">Le verre liquide</string>
+ <string name="licences_role_tracker">L\'écrasement et l\'étirement des curseurs de verre</string>
+ <string name="licences_role_toolkit">La boîte à outils de l\'interface</string>
+ <string name="licences_role_bridge">Relie l\'app à ses moteurs</string>
+ <string name="licences_role_ui_font">La police de l\'interface</string>
+ <string name="licences_role_titles">Les titres du bureau</string>
+ <string name="licences_role_lists">Les titres de listes</string>
+ <string name="licences_role_signatures">Les signatures saisies</string>
+ <string name="licences_role_doc_fonts">Les documents dans des polices absentes du téléphone</string>
+ <string name="licences_role_slide_font">La police de secours des diapositives</string>
+ <string name="licences_role_icons">Icônes</string>
+ <string name="licences_role_mascots">Les mascottes</string>
+ <string name="licences_role_pdf_fonts">Polices pour les PDF qui n\'intègrent pas les leurs</string>
+ <string name="licences_role_cmaps">Le texte chinois, japonais et coréen des PDF</string>
+ <string name="licences_role_rust">Le langage et les bibliothèques des moteurs</string>
+ <string name="voice_import">Importer un audio</string>
+ <string name="mindmap_title">Carte mentale</string>
+ <string name="mindmap_empty">Écrivez la note sous forme de plan : une idée par ligne, en retrait sous l\'idée à laquelle elle appartient. Elle est dessinée ici sous forme de carte.</string>
+ <string name="mindmap_save_image">Enregistrer en image</string>
+ <string name="mindmap_save_pdf">Enregistrer en PDF</string>
+ <string name="mindmap_save_opml">Exporter en OPML</string>
+ <string name="mindmap_root_hint">Idée centrale</string>
+ <string name="mindmap_node_hint">Nouvelle idée</string>
+ <string name="mindmap_child">Enfant</string>
+ <string name="mindmap_sibling">Voisine</string>
+ <string name="mindmap_edit">Modifier</string>
+ <string name="mindmap_colour">Couleur</string>
+ <string name="mindmap_branch_colour">Couleur de la branche</string>
+ <string name="mindmap_fold">Replier</string>
+ <string name="mindmap_unfold">Déplier</string>
+ <string name="mindmap_add_idea">Ajouter une idée</string>
+ <string name="mindmap_fit">Ajuster à l\'écran</string>
+ <string name="mindmap_one_side">Branches à droite</string>
+ <string name="mindmap_both_sides">Branches des deux côtés</string>
+ <string name="mindmap_make">En faire une carte mentale</string>
+ <string name="mindmap_hint">Touchez une idée pour la choisir, puis encore pour écrire. Faites-la glisser pour la déplacer, ou déposez-la sur une autre idée.</string>
+ <string name="create_mindmap">Carte mentale</string>
+ <string name="voice_imported">Audio ajouté à votre bureau</string>
+ <string name="voice_export">Enregistrer dans Téléchargements</string>
+ <string name="voice_export_name">Note vocale</string>
+ <string name="preview_edit">Modifier</string>
+ <string name="preview_edit_picture">Modifier l\'image</string>
+ <string name="files_kind_mindmaps">Cartes mentales</string>
+ <string name="msg_not_opml">Ce fichier n\'est pas un plan de carte mentale (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="one">%d idée</item>
+ <item quantity="other">%d idées</item>
+ </plurals>
+ <string name="sheet_stats">Somme %1$s · Moyenne %2$s · Nombre %3$d</string>
+ <string name="sheet_stats_count">Nombre %1$d</string>
+ <string name="kind_short_pdf">PDF</string>
+ <string name="kind_short_word">Documents</string>
+ <string name="kind_short_slides">Diapos</string>
+ <string name="kind_short_sheets">Tableurs</string>
+ <string name="kind_short_text">Texte</string>
+ <string name="kind_short_images">Images</string>
+ <string name="kind_short_maps">Cartes</string>
</resources>
diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml
index b6e3215..3757d26 100644
--- a/android/app/src/main/res/values-it/strings.xml
+++ b/android/app/src/main/res/values-it/strings.xml
@@ -1323,4 +1323,260 @@
<item>Non puoi controllare ogni onda, ma puoi **scegliere come affrontarla**. Un respiro tranquillo è **contagioso**.</item>
<item>Una frase, uno schizzo, uno scaffale in ordine. **Creare** ti ricorda che puoi **cambiare il mondo intorno a te**, anche solo un poco.</item>
</string-array>
+ <string name="tool_encryption">Crittografia</string>
+ <string name="home_about_encryption">Imposta la password di un PDF o rimuovila per sempre</string>
+ <string name="tools_set_password_body">Salva una copia che chiede una password prima di aprirsi</string>
+ <string name="msg_no_password_yet">Questo PDF non ha una password</string>
+ <string name="tool_edit_photo">Modifica foto</string>
+ <string name="home_about_edit_photo">Ritaglia, raddrizza e regola un\'immagine</string>
+ <string name="photo_texture">Ammorbidisci / Texture</string>
+ <string name="tool_text_to_pdf">Da testo a PDF</string>
+ <string name="home_about_text_to_pdf">Scrivi o incolla del testo e salvalo come PDF</string>
+ <string name="tool_pdf_to_text">Da PDF a testo</string>
+ <string name="home_about_pdf_to_text">Salva il testo di un PDF come file di testo semplice</string>
+ <string name="home_about_find_fields">Trasforma gli spazi vuoti di un modulo disegnato in campi da compilare</string>
+ <string name="home_about_unlock">Salva una copia di un PDF protetto che si apre senza password</string>
+ <string name="msg_no_password">Questo PDF non ha una password da rimuovere</string>
+ <string name="tools_unlock_title">Questo PDF è protetto da password</string>
+ <string name="tools_unlock_body">Salva una copia che si apre senza password, per sempre. Vengono tolte anche le restrizioni su stampa, copia e modifica.</string>
+ <string name="tools_unlock_action">Rimuovi password</string>
+ <string name="tools_format_text">Testo semplice (txt)</string>
+ <string name="msg_no_text_to_export">Questo PDF non ha testo da esportare. Prima fanne riconoscere il testo.</string>
+ <string name="tools_create_from_text">Scrivi o incolla del testo</string>
+ <string name="tools_create_action">Crea PDF</string>
+ <string name="tools_text_name">Nome (facoltativo)</string>
+ <string name="tools_text_hint">Scrivi o incolla qui il testo</string>
+ <string name="root_licence_wordcraft">WordCraft (motore Word)</string>
+ <string name="root_licence_deckcraft">DeckCraft (motore delle diapositive)</string>
+ <string name="root_licence_gridcraft">GridCraft (motore dei fogli di calcolo)</string>
+ <string name="root_licence_lightcraft">LightCraft (motore delle foto)</string>
+ <string name="root_licence_wordcraft_terms">MIT O Apache-2.0, di storytold e collaboratori</string>
+ <string name="viewer_translate">Traduci</string>
+ <string name="sheet_open_link">Apri link</string>
+ <string name="msg_link_not_followed">Questo link porta a un file che Artefact non può aprire da qui</string>
+ <string name="read_aloud_stop_reading">Interrompi lettura</string>
+ <string name="read_aloud_system_default">Predefinita di sistema (%1$s)</string>
+ <string name="read_aloud_language_selected">Selezionata</string>
+ <string name="read_aloud_languages_loading">Caricamento delle lingue disponibili…</string>
+ <string name="settings_read_aloud_language">Lingua della lettura ad alta voce</string>
+ <string name="settings_read_aloud_language_body">Scegli la lingua usata per leggere i documenti ad alta voce.</string>
+ <string name="viewer_night_mode_on">Modalità notte attiva</string>
+ <string name="viewer_night_mode_off">Modalità notte disattiva</string>
+ <string name="read_aloud_speed">Velocità di riproduzione</string>
+ <string name="sheet_not_found">Non trovato</string>
+ <string name="sheet_two_pages">Due pagine</string>
+ <string name="toolbar_label_find_fields">Trova campi</string>
+ <string name="tool_find_fields">Trova i campi del modulo</string>
+ <string name="msg_busy_finding_fields">Ricerca dei punti da compilare…</string>
+ <string name="msg_no_fields_found">In questo documento non sono stati trovati punti da compilare</string>
+ <plurals name="msg_fields_found">
+ <item quantity="one">%1$d campo trovato. Toccalo per compilarlo.</item>
+ <item quantity="other">%1$d campi trovati. Toccane uno per compilarlo.</item>
+ </plurals>
+ <string name="msg_word_reading_only">Per ora i documenti Word e le presentazioni si aprono in sola lettura. La modifica arriverà presto.</string>
+ <string name="sheet_kind_word">Word</string>
+ <string name="sheet_kind_slides">Diapositive</string>
+ <string name="office_present">Presenta</string>
+ <string name="office_save_as_format">Salva come %1$s</string>
+ <string name="sheet_edited">modificato</string>
+ <string name="sheet_of">%1$d di %2$d</string>
+ <string name="sheet_tap_to_type">Tocca per scrivere un valore o una =formula</string>
+ <string name="sheet_fill">Colore di riempimento</string>
+ <string name="sheet_fill_yellow">Giallo</string>
+ <string name="sheet_fill_green">Verde</string>
+ <string name="sheet_fill_blue">Blu</string>
+ <string name="sheet_fill_pink">Rosa</string>
+ <string name="sheet_fill_none">Nessun riempimento</string>
+ <string name="sheet_wrap">Testo a capo</string>
+ <string name="sheet_percent">Percentuale</string>
+ <string name="sheet_comma">Separatore delle migliaia</string>
+ <string name="sheet_insert_row">Inserisci riga</string>
+ <string name="sheet_insert_column">Inserisci colonna</string>
+ <string name="sheet_clear">Cancella contenuto</string>
+ <string name="word_undo">Annulla</string>
+ <string name="word_edit">Modifica documento</string>
+ <string name="word_tap_to_type">Tocca un paragrafo per modificarlo, come in un PDF. Fine applica le modifiche.</string>
+ <string name="word_redo">Ripeti</string>
+ <string name="word_bold">Grassetto</string>
+ <string name="word_italic">Corsivo</string>
+ <string name="word_bullets">Elenco puntato</string>
+ <string name="word_numbering">Numerazione</string>
+ <string name="word_align_left">Allinea a sinistra</string>
+ <string name="word_align_center">Centra</string>
+ <string name="word_align_right">Allinea a destra</string>
+ <string name="word_heading">Titolo</string>
+ <string name="word_body_text">Testo normale</string>
+ <string name="office_export_pdf">Esporta come PDF</string>
+ <string name="office_save_as">Salva come</string>
+ <string name="office_format">%1$s (.%2$s)</string>
+ <string name="office_slide_of">%1$d di %2$d</string>
+ <string name="format_pdf">PDF</string>
+ <string name="format_docx">Documento Word</string>
+ <string name="format_odt">Testo OpenDocument</string>
+ <string name="format_rtf">Testo formattato</string>
+ <string name="format_html">Pagina web</string>
+ <string name="format_md">Markdown</string>
+ <string name="format_txt">Testo semplice</string>
+ <string name="format_pptx">Presentazione PowerPoint</string>
+ <string name="format_xlsx">Cartella di lavoro Excel</string>
+ <string name="format_csv">Valori separati da virgole</string>
+ <string name="format_other">Altro</string>
+ <string name="files_kind_all">Tutti i file</string>
+ <string name="files_kind_pdf">PDF</string>
+ <string name="files_kind_word">Documenti Word</string>
+ <string name="files_kind_slides">Presentazioni</string>
+ <string name="files_kind_sheets">Fogli di calcolo</string>
+ <string name="files_kind_text">File di testo</string>
+ <string name="files_kind_images">Immagini</string>
+ <string name="photo_exposure">Esposizione</string>
+ <string name="photo_contrast">Contrasto</string>
+ <string name="photo_highlights">Luci</string>
+ <string name="photo_shadows">Ombre</string>
+ <string name="photo_vibrance">Vividezza</string>
+ <string name="photo_saturation">Saturazione</string>
+ <string name="photo_straighten">Raddrizza</string>
+ <string name="photo_crop">Ritaglia</string>
+ <string name="photo_whites">Bianchi</string>
+ <string name="photo_blacks">Neri</string>
+ <string name="photo_clarity">Chiarezza</string>
+ <string name="photo_sharpen">Nitidezza</string>
+ <string name="photo_vignette">Vignettatura</string>
+ <string name="photo_rotate">Ruota</string>
+ <string name="photo_edit">Modifica immagine</string>
+ <string name="msg_ppt_text_only">Questo file PowerPoint 97–2003 mostra il testo delle sue diapositive. Salvato come .pptx, si apre con immagini e impaginazione.</string>
+ <string name="photo_original">Originale</string>
+ <string name="photo_reset">Ripristina</string>
+ <string name="photo_adjust">Regola</string>
+ <string name="photo_blur">Sfoca</string>
+ <string name="photo_text">Testo</string>
+ <string name="photo_pixelate">Pixella</string>
+ <string name="photo_erase">Cancella</string>
+ <string name="photo_brush">Pennello</string>
+ <string name="photo_add_text">Aggiungi testo</string>
+ <string name="photo_text_hint">Scrivi qui</string>
+ <string name="photo_text_help">Tocca l\'immagine per scriverci sopra. Trascina le parole per spostarle, pizzica per ridimensionarle e ruotarle.</string>
+ <string name="photo_free">Libero</string>
+ <string name="photo_shape_original">Originale</string>
+ <string name="photo_mirror">Specchia</string>
+ <string name="photo_font_sample">Aa</string>
+ <string name="photo_not_saved">Impossibile salvare l\'immagine.</string>
+ <string name="msg_busy_removing_password">Rimozione della password…</string>
+ <string name="msg_unlock_failed">La protezione di questo file non può essere rimossa</string>
+ <string name="settings_custom">Personalizzato</string>
+ <string name="settings_general">Generali</string>
+ <string name="settings_wallpaper">Sfondo</string>
+ <string name="settings_wallpaper_liquid">Liquido</string>
+ <string name="settings_wallpaper_aurora">Aurora</string>
+ <string name="settings_wallpaper_custom">Galleria</string>
+ <string name="settings_wallpaper_failed">Impossibile usare quell\'immagine</string>
+ <string name="settings_personalization">Personalizzazione</string>
+ <string name="gm_fine_tune">Regolazione fine</string>
+ <string name="settings_glass_motion">Vetro liquido &amp; movimento</string>
+ <string name="gm_preview_body">Questi pulsanti si muovono come li imposti qui sotto. Tienili premuti.</string>
+ <string name="gm_press_me">Premimi</string>
+ <string name="gm_chip">Chip</string>
+ <string name="gm_glass_look">Vetro</string>
+ <string name="gm_blur">Brina</string>
+ <string name="gm_lens_height">Profondità della lente</string>
+ <string name="gm_lens_amount">Forza della lente</string>
+ <string name="gm_tint">Tinta</string>
+ <string name="gm_saturation">Colore</string>
+ <string name="gm_brightness">Luminosità</string>
+ <string name="gm_highlight">Luce sul bordo</string>
+ <string name="gm_depth">Profondità</string>
+ <string name="gm_chromatic">Bordo prismatico</string>
+ <string name="gm_adaptive">Luminanza adattiva</string>
+ <string name="gm_adaptive_body">Il vetro diventa chiaro o scuro in base a ciò che ha dietro. I preset qui sopra restano in pausa mentre è attiva</string>
+ <string name="gm_spring">Molla del vetro</string>
+ <string name="gm_spring_body">Come il vetro si gonfia, oltrepassa e si assesta. Tocca il grafico per metterlo in pausa.</string>
+ <string name="gm_spring_stats">Smorzamento %1$s · rigidità %2$s · si assesta in %3$s s</string>
+ <string name="gm_bounce">Rimbalzo</string>
+ <string name="gm_speed">Velocità</string>
+ <string name="gm_press">Pressione</string>
+ <string name="gm_wobble">Oscillazione</string>
+ <string name="gm_stretch">Allungamento</string>
+ <string name="gm_bloom">Fioritura</string>
+ <string name="gm_transitions">Transizioni dello schermo</string>
+ <string name="gm_curve_body">Trascina le due maniglie per disegnare la curva che seguono schermate, schede e dissolvenze. Tocca il grafico per metterlo in pausa.</string>
+ <string name="gm_duration">Durata</string>
+ <string name="gm_curve_drawer">Cassetto</string>
+ <string name="gm_curve_standard">Standard</string>
+ <string name="gm_curve_emphasized">Enfatizzata</string>
+ <string name="gm_curve_ease">Entrata e uscita morbide</string>
+ <string name="gm_curve_linear">Lineare</string>
+ <string name="gm_reset">Ripristina i valori predefiniti</string>
+ <string name="licences_row">Fatto con l\'open source</string>
+ <string name="licences_intro">Artefact si regge su queste opere open source. Toccane una per la licenza; la freccia apre il codice sorgente.</string>
+ <string name="licences_engines">Motori dei documenti</string>
+ <string name="licences_interface">Interfaccia</string>
+ <string name="licences_type">Caratteri</string>
+ <string name="licences_art">Icone e illustrazioni</string>
+ <string name="licences_data">Dati</string>
+ <string name="licences_platform">Piattaforma</string>
+ <string name="licences_source">Codice sorgente di %1$s</string>
+ <string name="licences_text_at_source">Il testo completo della licenza è insieme al codice sorgente.</string>
+ <string name="licences_role_pdf">Legge, disegna, modifica, firma e salva i PDF</string>
+ <string name="licences_role_word">Documenti Word, Markdown e testo</string>
+ <string name="licences_role_slides">Le presentazioni e la proiezione</string>
+ <string name="licences_role_sheets">I fogli di calcolo e le loro formule</string>
+ <string name="licences_role_photos">Sviluppa e modifica le tue immagini</string>
+ <string name="licences_role_ocr">Riconosce il testo nelle scansioni</string>
+ <string name="licences_role_app">L\'app Android da cui è nato Artefact</string>
+ <string name="licences_role_glass">Il vetro liquido</string>
+ <string name="licences_role_tracker">Lo schiacciamento e l\'allungamento dei cursori di vetro</string>
+ <string name="licences_role_toolkit">Il toolkit dell\'interfaccia</string>
+ <string name="licences_role_bridge">Collega l\'app ai suoi motori</string>
+ <string name="licences_role_ui_font">Il carattere dell\'interfaccia</string>
+ <string name="licences_role_titles">I titoli della scrivania</string>
+ <string name="licences_role_lists">I titoli degli elenchi</string>
+ <string name="licences_role_signatures">Le firme digitate</string>
+ <string name="licences_role_doc_fonts">Documenti in caratteri che il telefono non ha</string>
+ <string name="licences_role_slide_font">Il carattere di riserva delle diapositive</string>
+ <string name="licences_role_icons">Icone</string>
+ <string name="licences_role_mascots">Le mascotte</string>
+ <string name="licences_role_pdf_fonts">Caratteri per i PDF che non includono i propri</string>
+ <string name="licences_role_cmaps">Testo cinese, giapponese e coreano nei PDF</string>
+ <string name="licences_role_rust">Il linguaggio e le librerie dei motori</string>
+ <string name="voice_import">Importa audio</string>
+ <string name="mindmap_title">Mappa mentale</string>
+ <string name="mindmap_empty">Scrivi la nota come uno schema: un\'idea per riga, rientrata sotto l\'idea a cui appartiene. Qui viene disegnata come una mappa.</string>
+ <string name="mindmap_save_image">Salva come immagine</string>
+ <string name="mindmap_save_pdf">Salva come PDF</string>
+ <string name="mindmap_save_opml">Esporta come OPML</string>
+ <string name="mindmap_root_hint">Idea centrale</string>
+ <string name="mindmap_node_hint">Nuova idea</string>
+ <string name="mindmap_child">Figlia</string>
+ <string name="mindmap_sibling">Sorella</string>
+ <string name="mindmap_edit">Modifica</string>
+ <string name="mindmap_colour">Colore</string>
+ <string name="mindmap_branch_colour">Colore del ramo</string>
+ <string name="mindmap_fold">Comprimi</string>
+ <string name="mindmap_unfold">Espandi</string>
+ <string name="mindmap_add_idea">Aggiungi idea</string>
+ <string name="mindmap_fit">Adatta allo schermo</string>
+ <string name="mindmap_one_side">Rami a destra</string>
+ <string name="mindmap_both_sides">Rami su entrambi i lati</string>
+ <string name="mindmap_make">Trasformala in mappa mentale</string>
+ <string name="mindmap_hint">Tocca un\'idea per sceglierla e di nuovo per scrivere. Trascinala per spostarla o lasciala su un\'altra idea.</string>
+ <string name="create_mindmap">Mappa mentale</string>
+ <string name="voice_imported">Audio aggiunto alla tua scrivania</string>
+ <string name="voice_export">Salva in Download</string>
+ <string name="voice_export_name">Nota vocale</string>
+ <string name="preview_edit">Modifica</string>
+ <string name="preview_edit_picture">Modifica l\'immagine</string>
+ <string name="files_kind_mindmaps">Mappe mentali</string>
+ <string name="msg_not_opml">Questo file non è lo schema di una mappa mentale (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="one">%d idea</item>
+ <item quantity="other">%d idee</item>
+ </plurals>
+ <string name="sheet_stats">Somma %1$s · Media %2$s · Conteggio %3$d</string>
+ <string name="sheet_stats_count">Conteggio %1$d</string>
+ <string name="kind_short_pdf">PDF</string>
+ <string name="kind_short_word">Documenti</string>
+ <string name="kind_short_slides">Slide</string>
+ <string name="kind_short_sheets">Fogli</string>
+ <string name="kind_short_text">Testo</string>
+ <string name="kind_short_images">Immagini</string>
+ <string name="kind_short_maps">Mappe</string>
</resources>
diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xml
index 6211bca..77e6353 100644
--- a/android/app/src/main/res/values-pt-rBR/strings.xml
+++ b/android/app/src/main/res/values-pt-rBR/strings.xml
@@ -918,4 +918,260 @@
<item>Você não controla cada onda, mas pode **escolher como recebê-la**. Uma respiração tranquila é **contagiante**.</item>
<item>Uma frase, um desenho, uma prateleira arrumada. **Criar** lembra que você pode **mudar o mundo ao seu redor**, mesmo que um pouco.</item>
</string-array>
+ <string name="tool_encryption">Criptografia</string>
+ <string name="home_about_encryption">Defina a senha de um PDF ou remova-a de vez</string>
+ <string name="tools_set_password_body">Salvar uma cópia que pede senha antes de abrir</string>
+ <string name="msg_no_password_yet">Este PDF não tem senha</string>
+ <string name="tool_edit_photo">Editar foto</string>
+ <string name="home_about_edit_photo">Corte, endireite e ajuste uma imagem</string>
+ <string name="photo_texture">Suavizar / Textura</string>
+ <string name="tool_text_to_pdf">Texto para PDF</string>
+ <string name="home_about_text_to_pdf">Digite ou cole um texto e salve como PDF</string>
+ <string name="tool_pdf_to_text">PDF para texto</string>
+ <string name="home_about_pdf_to_text">Salve o texto de um PDF como arquivo de texto simples</string>
+ <string name="home_about_find_fields">Transforme os espaços em branco de um formulário desenhado em campos para preencher</string>
+ <string name="home_about_unlock">Salve uma cópia de um PDF protegido que abre sem senha</string>
+ <string name="msg_no_password">Este PDF não tem senha para remover</string>
+ <string name="tools_unlock_title">Este PDF é protegido por senha</string>
+ <string name="tools_unlock_body">Salvar uma cópia que abre sem senha, de vez. As restrições de impressão, cópia e edição também são removidas.</string>
+ <string name="tools_unlock_action">Remover senha</string>
+ <string name="tools_format_text">Texto simples (txt)</string>
+ <string name="msg_no_text_to_export">Este PDF não tem texto para exportar. Reconheça o texto dele primeiro.</string>
+ <string name="tools_create_from_text">Digitar ou colar texto</string>
+ <string name="tools_create_action">Criar PDF</string>
+ <string name="tools_text_name">Nome (opcional)</string>
+ <string name="tools_text_hint">Escreva ou cole o texto aqui</string>
+ <string name="root_licence_wordcraft">WordCraft (mecanismo do Word)</string>
+ <string name="root_licence_deckcraft">DeckCraft (mecanismo de slides)</string>
+ <string name="root_licence_gridcraft">GridCraft (mecanismo de planilhas)</string>
+ <string name="root_licence_lightcraft">LightCraft (mecanismo de fotos)</string>
+ <string name="root_licence_wordcraft_terms">MIT OU Apache-2.0, por storytold e colaboradores</string>
+ <string name="viewer_translate">Traduzir</string>
+ <string name="sheet_open_link">Abrir link</string>
+ <string name="msg_link_not_followed">Este link leva a um arquivo que o Artefact não consegue abrir daqui</string>
+ <string name="read_aloud_stop_reading">Parar leitura</string>
+ <string name="read_aloud_system_default">Padrão do sistema (%1$s)</string>
+ <string name="read_aloud_language_selected">Selecionado</string>
+ <string name="read_aloud_languages_loading">Carregando idiomas disponíveis…</string>
+ <string name="settings_read_aloud_language">Idioma da leitura em voz alta</string>
+ <string name="settings_read_aloud_language_body">Escolha o idioma usado para ler documentos em voz alta.</string>
+ <string name="viewer_night_mode_on">Modo noturno ativado</string>
+ <string name="viewer_night_mode_off">Modo noturno desativado</string>
+ <string name="read_aloud_speed">Velocidade de reprodução</string>
+ <string name="sheet_not_found">Não encontrado</string>
+ <string name="sheet_two_pages">Duas páginas</string>
+ <string name="toolbar_label_find_fields">Encontrar campos</string>
+ <string name="tool_find_fields">Encontrar campos do formulário</string>
+ <string name="msg_busy_finding_fields">Procurando lugares para preencher…</string>
+ <string name="msg_no_fields_found">Nenhum lugar para preencher foi encontrado neste documento</string>
+ <plurals name="msg_fields_found">
+ <item quantity="one">%1$d campo encontrado. Toque nele para preencher.</item>
+ <item quantity="other">%1$d campos encontrados. Toque em um para preencher.</item>
+ </plurals>
+ <string name="msg_word_reading_only">Por enquanto, documentos do Word e apresentações abrem só para leitura. A edição chega em breve.</string>
+ <string name="sheet_kind_word">Word</string>
+ <string name="sheet_kind_slides">Slides</string>
+ <string name="office_present">Apresentar</string>
+ <string name="office_save_as_format">Salvar como %1$s</string>
+ <string name="sheet_edited">editado</string>
+ <string name="sheet_of">%1$d de %2$d</string>
+ <string name="sheet_tap_to_type">Toque para digitar um valor ou uma =fórmula</string>
+ <string name="sheet_fill">Cor de preenchimento</string>
+ <string name="sheet_fill_yellow">Amarelo</string>
+ <string name="sheet_fill_green">Verde</string>
+ <string name="sheet_fill_blue">Azul</string>
+ <string name="sheet_fill_pink">Rosa</string>
+ <string name="sheet_fill_none">Sem preenchimento</string>
+ <string name="sheet_wrap">Quebrar texto</string>
+ <string name="sheet_percent">Porcentagem</string>
+ <string name="sheet_comma">Separador de milhar</string>
+ <string name="sheet_insert_row">Inserir linha</string>
+ <string name="sheet_insert_column">Inserir coluna</string>
+ <string name="sheet_clear">Limpar conteúdo</string>
+ <string name="word_undo">Desfazer</string>
+ <string name="word_edit">Editar documento</string>
+ <string name="word_tap_to_type">Toque em um parágrafo para editá-lo, como em um PDF. Concluído aplica as alterações.</string>
+ <string name="word_redo">Refazer</string>
+ <string name="word_bold">Negrito</string>
+ <string name="word_italic">Itálico</string>
+ <string name="word_bullets">Marcadores</string>
+ <string name="word_numbering">Numeração</string>
+ <string name="word_align_left">Alinhar à esquerda</string>
+ <string name="word_align_center">Centralizar</string>
+ <string name="word_align_right">Alinhar à direita</string>
+ <string name="word_heading">Título</string>
+ <string name="word_body_text">Texto normal</string>
+ <string name="office_export_pdf">Exportar como PDF</string>
+ <string name="office_save_as">Salvar como</string>
+ <string name="office_format">%1$s (.%2$s)</string>
+ <string name="office_slide_of">%1$d de %2$d</string>
+ <string name="format_pdf">PDF</string>
+ <string name="format_docx">Documento do Word</string>
+ <string name="format_odt">Texto OpenDocument</string>
+ <string name="format_rtf">Texto formatado</string>
+ <string name="format_html">Página da web</string>
+ <string name="format_md">Markdown</string>
+ <string name="format_txt">Texto simples</string>
+ <string name="format_pptx">Apresentação do PowerPoint</string>
+ <string name="format_xlsx">Pasta de trabalho do Excel</string>
+ <string name="format_csv">Valores separados por vírgula</string>
+ <string name="format_other">Outro</string>
+ <string name="files_kind_all">Todos os arquivos</string>
+ <string name="files_kind_pdf">PDFs</string>
+ <string name="files_kind_word">Documentos do Word</string>
+ <string name="files_kind_slides">Apresentações</string>
+ <string name="files_kind_sheets">Planilhas</string>
+ <string name="files_kind_text">Arquivos de texto</string>
+ <string name="files_kind_images">Imagens</string>
+ <string name="photo_exposure">Exposição</string>
+ <string name="photo_contrast">Contraste</string>
+ <string name="photo_highlights">Realces</string>
+ <string name="photo_shadows">Sombras</string>
+ <string name="photo_vibrance">Vibração</string>
+ <string name="photo_saturation">Saturação</string>
+ <string name="photo_straighten">Endireitar</string>
+ <string name="photo_crop">Cortar</string>
+ <string name="photo_whites">Brancos</string>
+ <string name="photo_blacks">Pretos</string>
+ <string name="photo_clarity">Claridade</string>
+ <string name="photo_sharpen">Nitidez</string>
+ <string name="photo_vignette">Vinheta</string>
+ <string name="photo_rotate">Girar</string>
+ <string name="photo_edit">Editar imagem</string>
+ <string name="msg_ppt_text_only">Este arquivo do PowerPoint 97–2003 mostra o texto dos slides. Salvo como .pptx, ele abre com as imagens e o layout.</string>
+ <string name="photo_original">Original</string>
+ <string name="photo_reset">Redefinir</string>
+ <string name="photo_adjust">Ajustar</string>
+ <string name="photo_blur">Desfocar</string>
+ <string name="photo_text">Texto</string>
+ <string name="photo_pixelate">Pixelizar</string>
+ <string name="photo_erase">Apagar</string>
+ <string name="photo_brush">Pincel</string>
+ <string name="photo_add_text">Adicionar texto</string>
+ <string name="photo_text_hint">Digite aqui</string>
+ <string name="photo_text_help">Toque na imagem para escrever nela. Arraste as palavras para movê-las e use dois dedos para redimensionar e girar.</string>
+ <string name="photo_free">Livre</string>
+ <string name="photo_shape_original">Original</string>
+ <string name="photo_mirror">Espelhar</string>
+ <string name="photo_font_sample">Aa</string>
+ <string name="photo_not_saved">Não foi possível salvar a imagem.</string>
+ <string name="msg_busy_removing_password">Removendo a senha…</string>
+ <string name="msg_unlock_failed">Não é possível remover a proteção deste arquivo</string>
+ <string name="settings_custom">Personalizado</string>
+ <string name="settings_general">Geral</string>
+ <string name="settings_wallpaper">Plano de fundo</string>
+ <string name="settings_wallpaper_liquid">Líquido</string>
+ <string name="settings_wallpaper_aurora">Aurora</string>
+ <string name="settings_wallpaper_custom">Galeria</string>
+ <string name="settings_wallpaper_failed">Não foi possível usar essa imagem</string>
+ <string name="settings_personalization">Personalização</string>
+ <string name="gm_fine_tune">Ajuste fino</string>
+ <string name="settings_glass_motion">Vidro líquido &amp; movimento</string>
+ <string name="gm_preview_body">Estes botões se movem como você definir abaixo. Mantenha-os pressionados.</string>
+ <string name="gm_press_me">Toque em mim</string>
+ <string name="gm_chip">Chip</string>
+ <string name="gm_glass_look">Vidro</string>
+ <string name="gm_blur">Geada</string>
+ <string name="gm_lens_height">Profundidade da lente</string>
+ <string name="gm_lens_amount">Força da lente</string>
+ <string name="gm_tint">Tonalidade</string>
+ <string name="gm_saturation">Cor</string>
+ <string name="gm_brightness">Brilho</string>
+ <string name="gm_highlight">Luz de borda</string>
+ <string name="gm_depth">Profundidade</string>
+ <string name="gm_chromatic">Borda prismática</string>
+ <string name="gm_adaptive">Luminância adaptável</string>
+ <string name="gm_adaptive_body">O vidro fica claro ou escuro conforme o que está atrás dele. As predefinições acima ficam pausadas enquanto ela está ativa</string>
+ <string name="gm_spring">Mola do vidro</string>
+ <string name="gm_spring_body">Como o vidro incha, passa do ponto e se acomoda. Toque no gráfico para pausar.</string>
+ <string name="gm_spring_stats">Amortecimento %1$s · rigidez %2$s · acomoda em %3$s s</string>
+ <string name="gm_bounce">Quique</string>
+ <string name="gm_speed">Velocidade</string>
+ <string name="gm_press">Pressão</string>
+ <string name="gm_wobble">Oscilação</string>
+ <string name="gm_stretch">Esticar</string>
+ <string name="gm_bloom">Florescer</string>
+ <string name="gm_transitions">Transições de tela</string>
+ <string name="gm_curve_body">Arraste as duas alças para desenhar a curva que telas, painéis e esmaecimentos seguem. Toque no gráfico para pausar.</string>
+ <string name="gm_duration">Duração</string>
+ <string name="gm_curve_drawer">Gaveta</string>
+ <string name="gm_curve_standard">Padrão</string>
+ <string name="gm_curve_emphasized">Enfatizada</string>
+ <string name="gm_curve_ease">Entrada e saída suaves</string>
+ <string name="gm_curve_linear">Linear</string>
+ <string name="gm_reset">Redefinir padrões</string>
+ <string name="licences_row">Feito com código aberto</string>
+ <string name="licences_intro">O Artefact se apoia nestas obras de código aberto. Toque em uma para ver a licença; a seta abre o código-fonte.</string>
+ <string name="licences_engines">Mecanismos de documentos</string>
+ <string name="licences_interface">Interface</string>
+ <string name="licences_type">Fontes</string>
+ <string name="licences_art">Ícones e ilustrações</string>
+ <string name="licences_data">Dados</string>
+ <string name="licences_platform">Plataforma</string>
+ <string name="licences_source">Código-fonte de %1$s</string>
+ <string name="licences_text_at_source">O texto completo da licença está junto do código-fonte.</string>
+ <string name="licences_role_pdf">Lê, desenha, edita, assina e salva PDFs</string>
+ <string name="licences_role_word">Documentos do Word, Markdown e texto</string>
+ <string name="licences_role_slides">As apresentações e o modo de apresentação</string>
+ <string name="licences_role_sheets">As planilhas e suas fórmulas</string>
+ <string name="licences_role_photos">Revela e edita suas imagens</string>
+ <string name="licences_role_ocr">Reconhece texto em digitalizações</string>
+ <string name="licences_role_app">O app Android de onde o Artefact nasceu</string>
+ <string name="licences_role_glass">O vidro líquido</string>
+ <string name="licences_role_tracker">O achatar e esticar dos controles de vidro</string>
+ <string name="licences_role_toolkit">O kit da interface</string>
+ <string name="licences_role_bridge">Liga o app aos seus mecanismos</string>
+ <string name="licences_role_ui_font">A fonte da interface</string>
+ <string name="licences_role_titles">Os títulos da mesa</string>
+ <string name="licences_role_lists">Os títulos das listas</string>
+ <string name="licences_role_signatures">As assinaturas digitadas</string>
+ <string name="licences_role_doc_fonts">Documentos em fontes que o celular não tem</string>
+ <string name="licences_role_slide_font">A fonte reserva dos slides</string>
+ <string name="licences_role_icons">Ícones</string>
+ <string name="licences_role_mascots">Os mascotes</string>
+ <string name="licences_role_pdf_fonts">Fontes para PDFs que não incorporam as suas</string>
+ <string name="licences_role_cmaps">Texto chinês, japonês e coreano em PDFs</string>
+ <string name="licences_role_rust">A linguagem e as bibliotecas dos mecanismos</string>
+ <string name="voice_import">Importar áudio</string>
+ <string name="mindmap_title">Mapa mental</string>
+ <string name="mindmap_empty">Escreva a nota como um tópico: uma ideia por linha, recuada sob a ideia a que pertence. Aqui ela é desenhada como um mapa.</string>
+ <string name="mindmap_save_image">Salvar como imagem</string>
+ <string name="mindmap_save_pdf">Salvar como PDF</string>
+ <string name="mindmap_save_opml">Exportar como OPML</string>
+ <string name="mindmap_root_hint">Ideia central</string>
+ <string name="mindmap_node_hint">Nova ideia</string>
+ <string name="mindmap_child">Filha</string>
+ <string name="mindmap_sibling">Irmã</string>
+ <string name="mindmap_edit">Editar</string>
+ <string name="mindmap_colour">Cor</string>
+ <string name="mindmap_branch_colour">Cor do ramo</string>
+ <string name="mindmap_fold">Recolher</string>
+ <string name="mindmap_unfold">Expandir</string>
+ <string name="mindmap_add_idea">Adicionar ideia</string>
+ <string name="mindmap_fit">Ajustar à tela</string>
+ <string name="mindmap_one_side">Ramos à direita</string>
+ <string name="mindmap_both_sides">Ramos dos dois lados</string>
+ <string name="mindmap_make">Transformar em mapa mental</string>
+ <string name="mindmap_hint">Toque em uma ideia para escolhê-la e de novo para digitar. Arraste-a para mover ou solte-a sobre outra ideia.</string>
+ <string name="create_mindmap">Mapa mental</string>
+ <string name="voice_imported">Áudio adicionado à sua mesa</string>
+ <string name="voice_export">Salvar em Downloads</string>
+ <string name="voice_export_name">Nota de voz</string>
+ <string name="preview_edit">Editar</string>
+ <string name="preview_edit_picture">Editar a imagem</string>
+ <string name="files_kind_mindmaps">Mapas mentais</string>
+ <string name="msg_not_opml">Este arquivo não é um tópico de mapa mental (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="one">%d ideia</item>
+ <item quantity="other">%d ideias</item>
+ </plurals>
+ <string name="sheet_stats">Soma %1$s · Média %2$s · Contagem %3$d</string>
+ <string name="sheet_stats_count">Contagem %1$d</string>
+ <string name="kind_short_pdf">PDFs</string>
+ <string name="kind_short_word">Documentos</string>
+ <string name="kind_short_slides">Slides</string>
+ <string name="kind_short_sheets">Planilhas</string>
+ <string name="kind_short_text">Texto</string>
+ <string name="kind_short_images">Imagens</string>
+ <string name="kind_short_maps">Mapas</string>
</resources>
diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml
index 57c11d8..bdb61bb 100644
--- a/android/app/src/main/res/values-pt/strings.xml
+++ b/android/app/src/main/res/values-pt/strings.xml
@@ -918,4 +918,260 @@
<item>Você não controla cada onda, mas pode **escolher como recebê-la**. Uma respiração tranquila é **contagiante**.</item>
<item>Uma frase, um desenho, uma prateleira arrumada. **Criar** lembra que você pode **mudar o mundo ao seu redor**, mesmo que um pouco.</item>
</string-array>
+ <string name="tool_encryption">Encriptação</string>
+ <string name="home_about_encryption">Definir a palavra-passe de um PDF ou removê-la de vez</string>
+ <string name="tools_set_password_body">Guardar uma cópia que pede uma palavra-passe antes de abrir</string>
+ <string name="msg_no_password_yet">Este PDF não tem palavra-passe</string>
+ <string name="tool_edit_photo">Editar fotografia</string>
+ <string name="home_about_edit_photo">Recortar, endireitar e ajustar uma imagem</string>
+ <string name="photo_texture">Suavizar / Textura</string>
+ <string name="tool_text_to_pdf">Texto para PDF</string>
+ <string name="home_about_text_to_pdf">Escreva ou cole texto e guarde-o como PDF</string>
+ <string name="tool_pdf_to_text">PDF para texto</string>
+ <string name="home_about_pdf_to_text">Guardar o texto de um PDF como ficheiro de texto simples</string>
+ <string name="home_about_find_fields">Transformar os espaços de um formulário desenhado em campos para preencher</string>
+ <string name="home_about_unlock">Guardar uma cópia de um PDF protegido que abre sem palavra-passe</string>
+ <string name="msg_no_password">Este PDF não tem palavra-passe para remover</string>
+ <string name="tools_unlock_title">Este PDF está protegido por palavra-passe</string>
+ <string name="tools_unlock_body">Guardar uma cópia que abre sem palavra-passe, de vez. As restrições de impressão, cópia e edição também são levantadas.</string>
+ <string name="tools_unlock_action">Remover palavra-passe</string>
+ <string name="tools_format_text">Texto simples (txt)</string>
+ <string name="msg_no_text_to_export">Este PDF não tem texto para exportar. Reconheça primeiro o seu texto.</string>
+ <string name="tools_create_from_text">Escrever ou colar texto</string>
+ <string name="tools_create_action">Criar PDF</string>
+ <string name="tools_text_name">Nome (opcional)</string>
+ <string name="tools_text_hint">Escreva ou cole o texto aqui</string>
+ <string name="root_licence_wordcraft">WordCraft (motor do Word)</string>
+ <string name="root_licence_deckcraft">DeckCraft (motor de diapositivos)</string>
+ <string name="root_licence_gridcraft">GridCraft (motor de folhas de cálculo)</string>
+ <string name="root_licence_lightcraft">LightCraft (motor de fotografias)</string>
+ <string name="root_licence_wordcraft_terms">MIT OU Apache-2.0, por storytold e colaboradores</string>
+ <string name="viewer_translate">Traduzir</string>
+ <string name="sheet_open_link">Abrir ligação</string>
+ <string name="msg_link_not_followed">Esta ligação leva a um ficheiro que o Artefact não consegue abrir daqui</string>
+ <string name="read_aloud_stop_reading">Parar a leitura</string>
+ <string name="read_aloud_system_default">Predefinição do sistema (%1$s)</string>
+ <string name="read_aloud_language_selected">Selecionado</string>
+ <string name="read_aloud_languages_loading">A carregar os idiomas disponíveis…</string>
+ <string name="settings_read_aloud_language">Idioma da leitura em voz alta</string>
+ <string name="settings_read_aloud_language_body">Escolha o idioma usado para ler documentos em voz alta.</string>
+ <string name="viewer_night_mode_on">Modo noturno ativado</string>
+ <string name="viewer_night_mode_off">Modo noturno desativado</string>
+ <string name="read_aloud_speed">Velocidade de reprodução</string>
+ <string name="sheet_not_found">Não encontrado</string>
+ <string name="sheet_two_pages">Duas páginas</string>
+ <string name="toolbar_label_find_fields">Encontrar campos</string>
+ <string name="tool_find_fields">Encontrar campos do formulário</string>
+ <string name="msg_busy_finding_fields">À procura de sítios para preencher…</string>
+ <string name="msg_no_fields_found">Não foram encontrados sítios para preencher neste documento</string>
+ <plurals name="msg_fields_found">
+ <item quantity="one">%1$d campo encontrado. Toque nele para o preencher.</item>
+ <item quantity="other">%1$d campos encontrados. Toque num para o preencher.</item>
+ </plurals>
+ <string name="msg_word_reading_only">Por agora, os documentos do Word e as apresentações abrem apenas para leitura. A edição chega em breve.</string>
+ <string name="sheet_kind_word">Word</string>
+ <string name="sheet_kind_slides">Diapositivos</string>
+ <string name="office_present">Apresentar</string>
+ <string name="office_save_as_format">Guardar como %1$s</string>
+ <string name="sheet_edited">editado</string>
+ <string name="sheet_of">%1$d de %2$d</string>
+ <string name="sheet_tap_to_type">Toque para escrever um valor ou uma =fórmula</string>
+ <string name="sheet_fill">Cor de preenchimento</string>
+ <string name="sheet_fill_yellow">Amarelo</string>
+ <string name="sheet_fill_green">Verde</string>
+ <string name="sheet_fill_blue">Azul</string>
+ <string name="sheet_fill_pink">Rosa</string>
+ <string name="sheet_fill_none">Sem preenchimento</string>
+ <string name="sheet_wrap">Moldar texto</string>
+ <string name="sheet_percent">Percentagem</string>
+ <string name="sheet_comma">Separador de milhares</string>
+ <string name="sheet_insert_row">Inserir linha</string>
+ <string name="sheet_insert_column">Inserir coluna</string>
+ <string name="sheet_clear">Limpar conteúdo</string>
+ <string name="word_undo">Anular</string>
+ <string name="word_edit">Editar documento</string>
+ <string name="word_tap_to_type">Toque num parágrafo para o editar, como num PDF. Concluído aplica as alterações.</string>
+ <string name="word_redo">Refazer</string>
+ <string name="word_bold">Negrito</string>
+ <string name="word_italic">Itálico</string>
+ <string name="word_bullets">Marcas</string>
+ <string name="word_numbering">Numeração</string>
+ <string name="word_align_left">Alinhar à esquerda</string>
+ <string name="word_align_center">Centrar</string>
+ <string name="word_align_right">Alinhar à direita</string>
+ <string name="word_heading">Título</string>
+ <string name="word_body_text">Texto normal</string>
+ <string name="office_export_pdf">Exportar como PDF</string>
+ <string name="office_save_as">Guardar como</string>
+ <string name="office_format">%1$s (.%2$s)</string>
+ <string name="office_slide_of">%1$d de %2$d</string>
+ <string name="format_pdf">PDF</string>
+ <string name="format_docx">Documento do Word</string>
+ <string name="format_odt">Texto OpenDocument</string>
+ <string name="format_rtf">Texto formatado</string>
+ <string name="format_html">Página web</string>
+ <string name="format_md">Markdown</string>
+ <string name="format_txt">Texto simples</string>
+ <string name="format_pptx">Apresentação do PowerPoint</string>
+ <string name="format_xlsx">Livro do Excel</string>
+ <string name="format_csv">Valores separados por vírgulas</string>
+ <string name="format_other">Outro</string>
+ <string name="files_kind_all">Todos os ficheiros</string>
+ <string name="files_kind_pdf">PDF</string>
+ <string name="files_kind_word">Documentos do Word</string>
+ <string name="files_kind_slides">Apresentações</string>
+ <string name="files_kind_sheets">Folhas de cálculo</string>
+ <string name="files_kind_text">Ficheiros de texto</string>
+ <string name="files_kind_images">Imagens</string>
+ <string name="photo_exposure">Exposição</string>
+ <string name="photo_contrast">Contraste</string>
+ <string name="photo_highlights">Realces</string>
+ <string name="photo_shadows">Sombras</string>
+ <string name="photo_vibrance">Vivacidade</string>
+ <string name="photo_saturation">Saturação</string>
+ <string name="photo_straighten">Endireitar</string>
+ <string name="photo_crop">Recortar</string>
+ <string name="photo_whites">Brancos</string>
+ <string name="photo_blacks">Pretos</string>
+ <string name="photo_clarity">Claridade</string>
+ <string name="photo_sharpen">Nitidez</string>
+ <string name="photo_vignette">Vinheta</string>
+ <string name="photo_rotate">Rodar</string>
+ <string name="photo_edit">Editar imagem</string>
+ <string name="msg_ppt_text_only">Este ficheiro do PowerPoint 97–2003 mostra o texto dos seus diapositivos. Guardado como .pptx, abre com as imagens e o esquema.</string>
+ <string name="photo_original">Original</string>
+ <string name="photo_reset">Repor</string>
+ <string name="photo_adjust">Ajustar</string>
+ <string name="photo_blur">Desfocar</string>
+ <string name="photo_text">Texto</string>
+ <string name="photo_pixelate">Pixelizar</string>
+ <string name="photo_erase">Apagar</string>
+ <string name="photo_brush">Pincel</string>
+ <string name="photo_add_text">Adicionar texto</string>
+ <string name="photo_text_hint">Escreva aqui</string>
+ <string name="photo_text_help">Toque na imagem para escrever nela. Arraste as palavras para as mover e junte os dedos para as redimensionar e rodar.</string>
+ <string name="photo_free">Livre</string>
+ <string name="photo_shape_original">Original</string>
+ <string name="photo_mirror">Espelhar</string>
+ <string name="photo_font_sample">Aa</string>
+ <string name="photo_not_saved">Não foi possível guardar a imagem.</string>
+ <string name="msg_busy_removing_password">A remover a palavra-passe…</string>
+ <string name="msg_unlock_failed">Não é possível remover a proteção deste ficheiro</string>
+ <string name="settings_custom">Personalizado</string>
+ <string name="settings_general">Geral</string>
+ <string name="settings_wallpaper">Imagem de fundo</string>
+ <string name="settings_wallpaper_liquid">Líquido</string>
+ <string name="settings_wallpaper_aurora">Aurora</string>
+ <string name="settings_wallpaper_custom">Galeria</string>
+ <string name="settings_wallpaper_failed">Não foi possível usar essa imagem</string>
+ <string name="settings_personalization">Personalização</string>
+ <string name="gm_fine_tune">Ajuste fino</string>
+ <string name="settings_glass_motion">Vidro líquido &amp; movimento</string>
+ <string name="gm_preview_body">Estes botões movem-se como os definir abaixo. Mantenha-os premidos.</string>
+ <string name="gm_press_me">Prima-me</string>
+ <string name="gm_chip">Chip</string>
+ <string name="gm_glass_look">Vidro</string>
+ <string name="gm_blur">Geada</string>
+ <string name="gm_lens_height">Profundidade da lente</string>
+ <string name="gm_lens_amount">Força da lente</string>
+ <string name="gm_tint">Tonalidade</string>
+ <string name="gm_saturation">Cor</string>
+ <string name="gm_brightness">Brilho</string>
+ <string name="gm_highlight">Luz de contorno</string>
+ <string name="gm_depth">Profundidade</string>
+ <string name="gm_chromatic">Aresta prismática</string>
+ <string name="gm_adaptive">Luminância adaptável</string>
+ <string name="gm_adaptive_body">O vidro fica claro ou escuro consoante o que está por trás. As predefinições acima ficam em pausa enquanto está ativa</string>
+ <string name="gm_spring">Mola do vidro</string>
+ <string name="gm_spring_body">Como o vidro incha, ultrapassa e assenta. Toque no gráfico para o pausar.</string>
+ <string name="gm_spring_stats">Amortecimento %1$s · rigidez %2$s · assenta em %3$s s</string>
+ <string name="gm_bounce">Ressalto</string>
+ <string name="gm_speed">Velocidade</string>
+ <string name="gm_press">Pressão</string>
+ <string name="gm_wobble">Oscilação</string>
+ <string name="gm_stretch">Esticar</string>
+ <string name="gm_bloom">Florescer</string>
+ <string name="gm_transitions">Transições de ecrã</string>
+ <string name="gm_curve_body">Arraste as duas pegas para desenhar a curva que os ecrãs, as folhas e os desvanecimentos seguem. Toque no gráfico para o pausar.</string>
+ <string name="gm_duration">Duração</string>
+ <string name="gm_curve_drawer">Gaveta</string>
+ <string name="gm_curve_standard">Padrão</string>
+ <string name="gm_curve_emphasized">Enfatizada</string>
+ <string name="gm_curve_ease">Entrada e saída suaves</string>
+ <string name="gm_curve_linear">Linear</string>
+ <string name="gm_reset">Repor predefinições</string>
+ <string name="licences_row">Feito com código aberto</string>
+ <string name="licences_intro">O Artefact assenta nestas obras de código aberto. Toque numa para ver a licença; a seta abre o código-fonte.</string>
+ <string name="licences_engines">Motores de documentos</string>
+ <string name="licences_interface">Interface</string>
+ <string name="licences_type">Tipos de letra</string>
+ <string name="licences_art">Ícones e ilustrações</string>
+ <string name="licences_data">Dados</string>
+ <string name="licences_platform">Plataforma</string>
+ <string name="licences_source">Código-fonte de %1$s</string>
+ <string name="licences_text_at_source">O texto completo da licença está junto do código-fonte.</string>
+ <string name="licences_role_pdf">Lê, desenha, edita, assina e guarda PDFs</string>
+ <string name="licences_role_word">Documentos do Word, Markdown e texto</string>
+ <string name="licences_role_slides">As apresentações e a projeção</string>
+ <string name="licences_role_sheets">As folhas de cálculo e as suas fórmulas</string>
+ <string name="licences_role_photos">Revela e edita as suas imagens</string>
+ <string name="licences_role_ocr">Reconhece texto em digitalizações</string>
+ <string name="licences_role_app">A app Android de onde o Artefact nasceu</string>
+ <string name="licences_role_glass">O vidro líquido</string>
+ <string name="licences_role_tracker">O esmagar e esticar dos controlos de vidro</string>
+ <string name="licences_role_toolkit">O kit da interface</string>
+ <string name="licences_role_bridge">Liga a app aos seus motores</string>
+ <string name="licences_role_ui_font">O tipo de letra da interface</string>
+ <string name="licences_role_titles">Os títulos da secretária</string>
+ <string name="licences_role_lists">Os títulos das listas</string>
+ <string name="licences_role_signatures">As assinaturas escritas</string>
+ <string name="licences_role_doc_fonts">Documentos em tipos de letra que o telefone não tem</string>
+ <string name="licences_role_slide_font">O tipo de letra de recurso dos diapositivos</string>
+ <string name="licences_role_icons">Ícones</string>
+ <string name="licences_role_mascots">As mascotes</string>
+ <string name="licences_role_pdf_fonts">Tipos de letra para PDFs que não incorporam os seus</string>
+ <string name="licences_role_cmaps">Texto chinês, japonês e coreano em PDFs</string>
+ <string name="licences_role_rust">A linguagem e as bibliotecas dos motores</string>
+ <string name="voice_import">Importar áudio</string>
+ <string name="mindmap_title">Mapa mental</string>
+ <string name="mindmap_empty">Escreva a nota como um esquema: uma ideia por linha, recuada sob a ideia a que pertence. Aqui é desenhada como um mapa.</string>
+ <string name="mindmap_save_image">Guardar como imagem</string>
+ <string name="mindmap_save_pdf">Guardar como PDF</string>
+ <string name="mindmap_save_opml">Exportar como OPML</string>
+ <string name="mindmap_root_hint">Ideia central</string>
+ <string name="mindmap_node_hint">Nova ideia</string>
+ <string name="mindmap_child">Filha</string>
+ <string name="mindmap_sibling">Irmã</string>
+ <string name="mindmap_edit">Editar</string>
+ <string name="mindmap_colour">Cor</string>
+ <string name="mindmap_branch_colour">Cor do ramo</string>
+ <string name="mindmap_fold">Recolher</string>
+ <string name="mindmap_unfold">Expandir</string>
+ <string name="mindmap_add_idea">Adicionar ideia</string>
+ <string name="mindmap_fit">Ajustar ao ecrã</string>
+ <string name="mindmap_one_side">Ramos à direita</string>
+ <string name="mindmap_both_sides">Ramos dos dois lados</string>
+ <string name="mindmap_make">Transformar em mapa mental</string>
+ <string name="mindmap_hint">Toque numa ideia para a escolher e outra vez para escrever. Arraste-a para a mover ou largue-a sobre outra ideia.</string>
+ <string name="create_mindmap">Mapa mental</string>
+ <string name="voice_imported">Áudio adicionado à sua secretária</string>
+ <string name="voice_export">Guardar em Transferências</string>
+ <string name="voice_export_name">Nota de voz</string>
+ <string name="preview_edit">Editar</string>
+ <string name="preview_edit_picture">Editar a imagem</string>
+ <string name="files_kind_mindmaps">Mapas mentais</string>
+ <string name="msg_not_opml">Este ficheiro não é um esquema de mapa mental (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="one">%d ideia</item>
+ <item quantity="other">%d ideias</item>
+ </plurals>
+ <string name="sheet_stats">Soma %1$s · Média %2$s · Contagem %3$d</string>
+ <string name="sheet_stats_count">Contagem %1$d</string>
+ <string name="kind_short_pdf">PDF</string>
+ <string name="kind_short_word">Documentos</string>
+ <string name="kind_short_slides">Diapositivos</string>
+ <string name="kind_short_sheets">Folhas</string>
+ <string name="kind_short_text">Texto</string>
+ <string name="kind_short_images">Imagens</string>
+ <string name="kind_short_maps">Mapas</string>
</resources>
diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml
index ac81fce..ad16fa2 100644
--- a/android/app/src/main/res/values-ru/strings.xml
+++ b/android/app/src/main/res/values-ru/strings.xml
@@ -946,4 +946,264 @@
<item>Вы не можете управлять каждой волной, но можете **выбрать, как её встретить**. Ровное дыхание **заразительно**.</item>
<item>Фразу, набросок, прибранную полку. **Творчество** напоминает, что вы можете **менять мир вокруг себя**, хотя бы чуть-чуть.</item>
</string-array>
+ <string name="tool_encryption">Шифрование</string>
+ <string name="home_about_encryption">Задать пароль для PDF или снять его насовсем</string>
+ <string name="tools_set_password_body">Сохранить копию, которая перед открытием запрашивает пароль</string>
+ <string name="msg_no_password_yet">У этого PDF нет пароля</string>
+ <string name="tool_edit_photo">Изменить фото</string>
+ <string name="home_about_edit_photo">Обрезать, выровнять и настроить изображение</string>
+ <string name="photo_texture">Смягчение / Текстура</string>
+ <string name="tool_text_to_pdf">Текст в PDF</string>
+ <string name="home_about_text_to_pdf">Введите или вставьте текст и сохраните его как PDF</string>
+ <string name="tool_pdf_to_text">PDF в текст</string>
+ <string name="home_about_pdf_to_text">Сохранить текст PDF в обычный текстовый файл</string>
+ <string name="home_about_find_fields">Превратить пустые места нарисованной формы в поля для заполнения</string>
+ <string name="home_about_unlock">Сохранить копию защищённого PDF, которая открывается без пароля</string>
+ <string name="msg_no_password">У этого PDF нет пароля, который можно снять</string>
+ <string name="tools_unlock_title">Этот PDF защищён паролем</string>
+ <string name="tools_unlock_body">Сохранить копию, которая открывается без пароля, насовсем. Ограничения на печать, копирование и изменение тоже снимаются.</string>
+ <string name="tools_unlock_action">Снять пароль</string>
+ <string name="tools_format_text">Обычный текст (txt)</string>
+ <string name="msg_no_text_to_export">В этом PDF нет текста для экспорта. Сначала распознайте его текст.</string>
+ <string name="tools_create_from_text">Ввести или вставить текст</string>
+ <string name="tools_create_action">Создать PDF</string>
+ <string name="tools_text_name">Название (необязательно)</string>
+ <string name="tools_text_hint">Напишите или вставьте текст сюда</string>
+ <string name="root_licence_wordcraft">WordCraft (движок Word)</string>
+ <string name="root_licence_deckcraft">DeckCraft (движок слайдов)</string>
+ <string name="root_licence_gridcraft">GridCraft (движок таблиц)</string>
+ <string name="root_licence_lightcraft">LightCraft (движок фото)</string>
+ <string name="root_licence_wordcraft_terms">MIT ИЛИ Apache-2.0, storytold и участники</string>
+ <string name="viewer_translate">Перевести</string>
+ <string name="sheet_open_link">Открыть ссылку</string>
+ <string name="msg_link_not_followed">Эта ссылка ведёт к файлу, который Artefact не может открыть отсюда</string>
+ <string name="read_aloud_stop_reading">Остановить чтение</string>
+ <string name="read_aloud_system_default">Как в системе (%1$s)</string>
+ <string name="read_aloud_language_selected">Выбрано</string>
+ <string name="read_aloud_languages_loading">Загрузка доступных языков…</string>
+ <string name="settings_read_aloud_language">Язык чтения вслух</string>
+ <string name="settings_read_aloud_language_body">Выберите язык, на котором документы читаются вслух.</string>
+ <string name="viewer_night_mode_on">Ночной режим включён</string>
+ <string name="viewer_night_mode_off">Ночной режим выключен</string>
+ <string name="read_aloud_speed">Скорость воспроизведения</string>
+ <string name="sheet_not_found">Не найдено</string>
+ <string name="sheet_two_pages">Две страницы</string>
+ <string name="toolbar_label_find_fields">Найти поля</string>
+ <string name="tool_find_fields">Найти поля формы</string>
+ <string name="msg_busy_finding_fields">Поиск мест для заполнения…</string>
+ <string name="msg_no_fields_found">В этом документе не найдено мест для заполнения</string>
+ <plurals name="msg_fields_found">
+ <item quantity="one">Найдено %1$d поле. Нажмите на него, чтобы заполнить.</item>
+ <item quantity="few">Найдено %1$d поля. Нажмите на одно, чтобы заполнить.</item>
+ <item quantity="many">Найдено %1$d полей. Нажмите на одно, чтобы заполнить.</item>
+ <item quantity="other">Найдено %1$d поля. Нажмите на одно, чтобы заполнить.</item>
+ </plurals>
+ <string name="msg_word_reading_only">Документы Word и презентации пока открываются только для чтения. Редактирование скоро появится.</string>
+ <string name="sheet_kind_word">Word</string>
+ <string name="sheet_kind_slides">Слайды</string>
+ <string name="office_present">Показ</string>
+ <string name="office_save_as_format">Сохранить как %1$s</string>
+ <string name="sheet_edited">изменён</string>
+ <string name="sheet_of">%1$d из %2$d</string>
+ <string name="sheet_tap_to_type">Нажмите, чтобы ввести значение или =формулу</string>
+ <string name="sheet_fill">Цвет заливки</string>
+ <string name="sheet_fill_yellow">Жёлтый</string>
+ <string name="sheet_fill_green">Зелёный</string>
+ <string name="sheet_fill_blue">Синий</string>
+ <string name="sheet_fill_pink">Розовый</string>
+ <string name="sheet_fill_none">Без заливки</string>
+ <string name="sheet_wrap">Перенос текста</string>
+ <string name="sheet_percent">Процент</string>
+ <string name="sheet_comma">Разделитель групп разрядов</string>
+ <string name="sheet_insert_row">Вставить строку</string>
+ <string name="sheet_insert_column">Вставить столбец</string>
+ <string name="sheet_clear">Очистить содержимое</string>
+ <string name="word_undo">Отменить</string>
+ <string name="word_edit">Изменить документ</string>
+ <string name="word_tap_to_type">Нажмите на абзац, чтобы изменить его, как в PDF. «Готово» применяет изменения.</string>
+ <string name="word_redo">Повторить</string>
+ <string name="word_bold">Полужирный</string>
+ <string name="word_italic">Курсив</string>
+ <string name="word_bullets">Маркеры</string>
+ <string name="word_numbering">Нумерация</string>
+ <string name="word_align_left">По левому краю</string>
+ <string name="word_align_center">По центру</string>
+ <string name="word_align_right">По правому краю</string>
+ <string name="word_heading">Заголовок</string>
+ <string name="word_body_text">Основной текст</string>
+ <string name="office_export_pdf">Экспорт в PDF</string>
+ <string name="office_save_as">Сохранить как</string>
+ <string name="office_format">%1$s (.%2$s)</string>
+ <string name="office_slide_of">%1$d из %2$d</string>
+ <string name="format_pdf">PDF</string>
+ <string name="format_docx">Документ Word</string>
+ <string name="format_odt">Текст OpenDocument</string>
+ <string name="format_rtf">Форматированный текст</string>
+ <string name="format_html">Веб-страница</string>
+ <string name="format_md">Markdown</string>
+ <string name="format_txt">Обычный текст</string>
+ <string name="format_pptx">Презентация PowerPoint</string>
+ <string name="format_xlsx">Книга Excel</string>
+ <string name="format_csv">Значения, разделённые запятыми</string>
+ <string name="format_other">Другое</string>
+ <string name="files_kind_all">Все файлы</string>
+ <string name="files_kind_pdf">PDF</string>
+ <string name="files_kind_word">Документы Word</string>
+ <string name="files_kind_slides">Презентации</string>
+ <string name="files_kind_sheets">Таблицы</string>
+ <string name="files_kind_text">Текстовые файлы</string>
+ <string name="files_kind_images">Изображения</string>
+ <string name="photo_exposure">Экспозиция</string>
+ <string name="photo_contrast">Контраст</string>
+ <string name="photo_highlights">Светлые участки</string>
+ <string name="photo_shadows">Тени</string>
+ <string name="photo_vibrance">Красочность</string>
+ <string name="photo_saturation">Насыщенность</string>
+ <string name="photo_straighten">Выровнять</string>
+ <string name="photo_crop">Обрезать</string>
+ <string name="photo_whites">Белые</string>
+ <string name="photo_blacks">Чёрные</string>
+ <string name="photo_clarity">Чёткость</string>
+ <string name="photo_sharpen">Резкость</string>
+ <string name="photo_vignette">Виньетка</string>
+ <string name="photo_rotate">Повернуть</string>
+ <string name="photo_edit">Изменить изображение</string>
+ <string name="msg_ppt_text_only">Этот файл PowerPoint 97–2003 показывает текст своих слайдов. Сохранённый как .pptx, он открывается с изображениями и макетом.</string>
+ <string name="photo_original">Оригинал</string>
+ <string name="photo_reset">Сбросить</string>
+ <string name="photo_adjust">Настройка</string>
+ <string name="photo_blur">Размытие</string>
+ <string name="photo_text">Текст</string>
+ <string name="photo_pixelate">Пикселизация</string>
+ <string name="photo_erase">Стереть</string>
+ <string name="photo_brush">Кисть</string>
+ <string name="photo_add_text">Добавить текст</string>
+ <string name="photo_text_hint">Пишите здесь</string>
+ <string name="photo_text_help">Нажмите на изображение, чтобы написать на нём. Перетаскивайте слова, чтобы двигать их, и сводите пальцы, чтобы менять размер и поворачивать.</string>
+ <string name="photo_free">Свободно</string>
+ <string name="photo_shape_original">Оригинал</string>
+ <string name="photo_mirror">Отразить</string>
+ <string name="photo_font_sample">Aa</string>
+ <string name="photo_not_saved">Не удалось сохранить изображение.</string>
+ <string name="msg_busy_removing_password">Снятие пароля…</string>
+ <string name="msg_unlock_failed">Защиту этого файла снять нельзя</string>
+ <string name="settings_custom">Своё</string>
+ <string name="settings_general">Общие</string>
+ <string name="settings_wallpaper">Обои</string>
+ <string name="settings_wallpaper_liquid">Жидкость</string>
+ <string name="settings_wallpaper_aurora">Аврора</string>
+ <string name="settings_wallpaper_custom">Галерея</string>
+ <string name="settings_wallpaper_failed">Не удалось использовать это изображение</string>
+ <string name="settings_personalization">Персонализация</string>
+ <string name="gm_fine_tune">Тонкая настройка</string>
+ <string name="settings_glass_motion">Жидкое стекло &amp; движение</string>
+ <string name="gm_preview_body">Эти кнопки двигаются так, как вы настроите ниже. Нажмите и удерживайте их.</string>
+ <string name="gm_press_me">Нажми меня</string>
+ <string name="gm_chip">Чип</string>
+ <string name="gm_glass_look">Стекло</string>
+ <string name="gm_blur">Иней</string>
+ <string name="gm_lens_height">Глубина линзы</string>
+ <string name="gm_lens_amount">Сила линзы</string>
+ <string name="gm_tint">Оттенок</string>
+ <string name="gm_saturation">Цвет</string>
+ <string name="gm_brightness">Яркость</string>
+ <string name="gm_highlight">Свет по краю</string>
+ <string name="gm_depth">Глубина</string>
+ <string name="gm_chromatic">Призменная кромка</string>
+ <string name="gm_adaptive">Адаптивная яркость</string>
+ <string name="gm_adaptive_body">Стекло становится светлым или тёмным под то, что за ним. Пока она включена, наборы выше не действуют</string>
+ <string name="gm_spring">Пружина стекла</string>
+ <string name="gm_spring_body">Как стекло набухает, проскакивает и успокаивается. Нажмите на график, чтобы приостановить его.</string>
+ <string name="gm_spring_stats">Затухание %1$s · жёсткость %2$s · успокаивается за %3$s с</string>
+ <string name="gm_bounce">Отскок</string>
+ <string name="gm_speed">Скорость</string>
+ <string name="gm_press">Нажатие</string>
+ <string name="gm_wobble">Колебание</string>
+ <string name="gm_stretch">Растяжение</string>
+ <string name="gm_bloom">Расцвет</string>
+ <string name="gm_transitions">Переходы экранов</string>
+ <string name="gm_curve_body">Перетащите две ручки, чтобы нарисовать кривую, по которой движутся экраны, панели и затухания. Нажмите на график, чтобы приостановить его.</string>
+ <string name="gm_duration">Длительность</string>
+ <string name="gm_curve_drawer">Шторка</string>
+ <string name="gm_curve_standard">Стандартная</string>
+ <string name="gm_curve_emphasized">Акцентная</string>
+ <string name="gm_curve_ease">Плавно в начале и в конце</string>
+ <string name="gm_curve_linear">Линейная</string>
+ <string name="gm_reset">Восстановить значения по умолчанию</string>
+ <string name="licences_row">Сделано на открытом коде</string>
+ <string name="licences_intro">Artefact стоит на этих открытых проектах. Нажмите на любой, чтобы увидеть лицензию; стрелка открывает исходный код.</string>
+ <string name="licences_engines">Движки документов</string>
+ <string name="licences_interface">Интерфейс</string>
+ <string name="licences_type">Шрифты</string>
+ <string name="licences_art">Значки и иллюстрации</string>
+ <string name="licences_data">Данные</string>
+ <string name="licences_platform">Платформа</string>
+ <string name="licences_source">Исходный код %1$s</string>
+ <string name="licences_text_at_source">Полный текст лицензии лежит рядом с исходным кодом.</string>
+ <string name="licences_role_pdf">Читает, рисует, изменяет, подписывает и сохраняет PDF</string>
+ <string name="licences_role_word">Документы Word, Markdown и текст</string>
+ <string name="licences_role_slides">Презентации и показ слайдов</string>
+ <string name="licences_role_sheets">Таблицы и их формулы</string>
+ <string name="licences_role_photos">Проявляет и редактирует ваши изображения</string>
+ <string name="licences_role_ocr">Распознаёт текст в сканах</string>
+ <string name="licences_role_app">Приложение Android, из которого вырос Artefact</string>
+ <string name="licences_role_glass">Жидкое стекло</string>
+ <string name="licences_role_tracker">Сжатие и растяжение стеклянных ползунков</string>
+ <string name="licences_role_toolkit">Набор инструментов интерфейса</string>
+ <string name="licences_role_bridge">Связывает приложение с его движками</string>
+ <string name="licences_role_ui_font">Шрифт интерфейса</string>
+ <string name="licences_role_titles">Заголовки на столе</string>
+ <string name="licences_role_lists">Заголовки списков</string>
+ <string name="licences_role_signatures">Набранные подписи</string>
+ <string name="licences_role_doc_fonts">Документы со шрифтами, которых нет на телефоне</string>
+ <string name="licences_role_slide_font">Запасной шрифт слайдов</string>
+ <string name="licences_role_icons">Значки</string>
+ <string name="licences_role_mascots">Талисманы</string>
+ <string name="licences_role_pdf_fonts">Шрифты для PDF, в которые не встроены свои</string>
+ <string name="licences_role_cmaps">Китайский, японский и корейский текст в PDF</string>
+ <string name="licences_role_rust">Язык и библиотеки движков</string>
+ <string name="voice_import">Импортировать аудио</string>
+ <string name="mindmap_title">Ментальная карта</string>
+ <string name="mindmap_empty">Напишите заметку в виде плана: одна мысль в строке, с отступом под мыслью, к которой она относится. Здесь она рисуется картой.</string>
+ <string name="mindmap_save_image">Сохранить как изображение</string>
+ <string name="mindmap_save_pdf">Сохранить как PDF</string>
+ <string name="mindmap_save_opml">Экспорт в OPML</string>
+ <string name="mindmap_root_hint">Главная мысль</string>
+ <string name="mindmap_node_hint">Новая мысль</string>
+ <string name="mindmap_child">Дочерняя</string>
+ <string name="mindmap_sibling">Соседняя</string>
+ <string name="mindmap_edit">Изменить</string>
+ <string name="mindmap_colour">Цвет</string>
+ <string name="mindmap_branch_colour">Цвет ветки</string>
+ <string name="mindmap_fold">Свернуть</string>
+ <string name="mindmap_unfold">Развернуть</string>
+ <string name="mindmap_add_idea">Добавить мысль</string>
+ <string name="mindmap_fit">По размеру экрана</string>
+ <string name="mindmap_one_side">Ветки справа</string>
+ <string name="mindmap_both_sides">Ветки с обеих сторон</string>
+ <string name="mindmap_make">Сделать ментальной картой</string>
+ <string name="mindmap_hint">Нажмите на мысль, чтобы выбрать её, и ещё раз, чтобы писать. Перетащите её, чтобы переместить, или отпустите на другой мысли.</string>
+ <string name="create_mindmap">Ментальная карта</string>
+ <string name="voice_imported">Аудио добавлено на ваш стол</string>
+ <string name="voice_export">Сохранить в Загрузки</string>
+ <string name="voice_export_name">Голосовая заметка</string>
+ <string name="preview_edit">Изменить</string>
+ <string name="preview_edit_picture">Изменить изображение</string>
+ <string name="files_kind_mindmaps">Ментальные карты</string>
+ <string name="msg_not_opml">Этот файл не план ментальной карты (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="one">%d мысль</item>
+ <item quantity="few">%d мысли</item>
+ <item quantity="many">%d мыслей</item>
+ <item quantity="other">%d мысли</item>
+ </plurals>
+ <string name="sheet_stats">Сумма %1$s · Среднее %2$s · Количество %3$d</string>
+ <string name="sheet_stats_count">Количество %1$d</string>
+ <string name="kind_short_pdf">PDF</string>
+ <string name="kind_short_word">Документы</string>
+ <string name="kind_short_slides">Слайды</string>
+ <string name="kind_short_sheets">Таблицы</string>
+ <string name="kind_short_text">Текст</string>
+ <string name="kind_short_images">Фото</string>
+ <string name="kind_short_maps">Карты</string>
</resources>
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 57db1de..98aa22a 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -1056,6 +1056,7 @@
<string name="files_kind_slides">Presentations</string>
<string name="files_kind_sheets">Spreadsheets</string>
<string name="files_kind_text">Text files</string>
+ <string name="files_kind_images">Pictures</string>
<string name="photo_exposure">Exposure</string>
<string name="photo_contrast">Contrast</string>
<string name="photo_highlights">Highlights</string>
@@ -1074,6 +1075,19 @@
<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_adjust">Adjust</string>
+ <string name="photo_blur">Blur</string>
+ <string name="photo_text">Text</string>
+ <string name="photo_pixelate">Pixelate</string>
+ <string name="photo_erase">Erase</string>
+ <string name="photo_brush">Brush</string>
+ <string name="photo_add_text">Add text</string>
+ <string name="photo_text_hint">Type here</string>
+ <string name="photo_text_help">Tap the picture to write on it. Drag words to move them, pinch to size and turn them.</string>
+ <string name="photo_free">Free</string>
+ <string name="photo_shape_original">Original</string>
+ <string name="photo_mirror">Mirror</string>
+ <string name="photo_font_sample">Aa</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>
@@ -1419,6 +1433,23 @@
<string name="mindmap_empty">Write the note as an outline: one idea a line, indented under the idea it belongs to. It is drawn here as a map.</string>
<string name="mindmap_save_image">Save as image</string>
<string name="mindmap_save_pdf">Save as PDF</string>
+ <string name="mindmap_save_opml">Export as OPML</string>
+ <string name="mindmap_root_hint">Central idea</string>
+ <string name="mindmap_node_hint">New idea</string>
+ <string name="mindmap_child">Child</string>
+ <string name="mindmap_sibling">Sibling</string>
+ <string name="mindmap_edit">Edit</string>
+ <string name="mindmap_colour">Colour</string>
+ <string name="mindmap_branch_colour">Branch colour</string>
+ <string name="mindmap_fold">Fold</string>
+ <string name="mindmap_unfold">Unfold</string>
+ <string name="mindmap_add_idea">Add idea</string>
+ <string name="mindmap_fit">Fit to screen</string>
+ <string name="mindmap_one_side">Branches to the right</string>
+ <string name="mindmap_both_sides">Branches on both sides</string>
+ <string name="mindmap_make">Make it a mind map</string>
+ <string name="mindmap_hint">Tap an idea to pick it, tap it again to type. Drag it to move it, or drop it on another idea.</string>
+ <string name="create_mindmap">Mind map</string>
<string name="voice_imported">Audio added to your desk</string>
<string name="voice_export">Save to Downloads</string>
<string name="voice_export_name">Voice note</string>
@@ -1491,6 +1522,8 @@
<string name="preview_expand">Open in Artefact</string>
<string name="preview_open_in_app">Open in Artefact</string>
<string name="preview_open">Open</string>
+ <string name="preview_edit">Edit</string>
+ <string name="preview_edit_picture">Edit the picture</string>
<string name="preview_save_downloads">Save to Downloads</string>
<string name="preview_saved_downloads">Saved to Downloads</string>
<string name="preview_locked_body">This PDF is locked. Type its password to look inside.</string>
@@ -1567,4 +1600,19 @@
<item>You can\'t control every wave, but you can **choose how you meet it**. A steady breath is **contagious**.</item>
<item>A sentence, a sketch, a tidy shelf. **Creating** reminds you that you can **change the world around you**, even a little.</item>
</string-array>
+ <string name="files_kind_mindmaps">Mind maps</string>
+ <string name="msg_not_opml">This file isn\'t a mind map outline (OPML).</string>
+ <plurals name="preview_ideas">
+ <item quantity="one">%d idea</item>
+ <item quantity="other">%d ideas</item>
+ </plurals>
+ <string name="sheet_stats">Sum %1$s · Average %2$s · Count %3$d</string>
+ <string name="sheet_stats_count">Count %1$d</string>
+ <string name="kind_short_pdf">PDFs</string>
+ <string name="kind_short_word">Docs</string>
+ <string name="kind_short_slides">Slides</string>
+ <string name="kind_short_sheets">Sheets</string>
+ <string name="kind_short_text">Text</string>
+ <string name="kind_short_images">Pictures</string>
+ <string name="kind_short_maps">Maps</string>
</resources>
diff --git a/android/app/src/test/java/com/chethan616/clearpdf/ui/PhotoFrameAndMapTest.kt b/android/app/src/test/java/com/chethan616/clearpdf/ui/PhotoFrameAndMapTest.kt
new file mode 100644
index 0000000..d0f552a
--- /dev/null
+++ b/android/app/src/test/java/com/chethan616/clearpdf/ui/PhotoFrameAndMapTest.kt
@@ -0,0 +1,97 @@
+package com.chethan616.clearpdf.ui
+
+import com.chethan616.clearpdf.ui.notes.CropBox
+import com.chethan616.clearpdf.ui.notes.MindDoc
+import com.chethan616.clearpdf.ui.notes.PhotoFrame
+import com.chethan616.clearpdf.ui.notes.constrain
+import com.chethan616.clearpdf.ui.notes.fitInside
+import com.chethan616.clearpdf.ui.notes.fits
+import com.chethan616.clearpdf.ui.notes.largest
+import com.chethan616.clearpdf.ui.notes.mindFromOpml
+import com.chethan616.clearpdf.ui.notes.opml
+import com.chethan616.clearpdf.ui.notes.outline
+import com.chethan616.clearpdf.ui.notes.parseOutline
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class PhotoFrameAndMapTest {
+ private val w = 4000f
+ private val h = 3000f
+
+ private fun near(a: CropBox, b: CropBox) {
+ assertEquals(a.x0, b.x0, 1e-4f)
+ assertEquals(a.y0, b.y0, 1e-4f)
+ assertEquals(a.x1, b.x1, 1e-4f)
+ assertEquals(a.y1, b.y1, 1e-4f)
+ }
+
+ @Test
+ fun aCropStaysOnAStraightenedPicture() {
+ assertTrue(fits(CropBox(), 0f, w, h))
+ assertFalse(fits(CropBox(), 10f, w, h))
+ // straightened, the whole frame shrinks about the middle and keeps its shape
+ val inside = fitInside(CropBox(), 10f, w, h)
+ assertTrue(fits(inside, 10f, w, h))
+ assertEquals(0.5f, inside.cx, 1e-3f)
+ assertEquals(4f / 3f, inside.w * w / (inside.h * h), 1e-2f)
+ assertTrue(inside.w > 0.7f)
+ }
+
+ @Test
+ fun aShapeIsTheLargestThatFits() {
+ val square = largest(1f, CropBox(), 0f, w, h)
+ assertEquals(1f, square.w * w / (square.h * h), 1e-3f)
+ assertEquals(1f, square.h, 1e-3f)
+ val tall = largest(9f / 16f, CropBox(), 0f, w, h)
+ assertEquals(9f / 16f, tall.w * w / (tall.h * h), 1e-3f)
+ }
+
+ @Test
+ fun aDraggedCropStopsAtTheEdge() {
+ val moved = constrain(CropBox(0.1f, 0.1f, 0.5f, 0.5f), CropBox(0.7f, 0.1f, 1.1f, 0.5f), 0f, w, h)
+ assertEquals(1f, moved.x1, 1e-3f)
+ assertEquals(0.4f, moved.w, 1e-3f)
+ }
+
+ @Test
+ fun turnsAndMirrorsComeRoundAgain() {
+ val c = CropBox(0.1f, 0.2f, 0.5f, 0.6f)
+ near(c, c.turned().turned().turned().turned())
+ near(c, c.mirrored().mirrored())
+ // a quarter turn puts the left edge at the top
+ near(CropBox(0.4f, 0.1f, 0.8f, 0.5f), c.turned())
+ assertEquals("Normal", PhotoFrame().orientation)
+ assertEquals("Rotate90", PhotoFrame(turns = 1).orientation)
+ assertEquals("Transverse", PhotoFrame(turns = 1, mirror = true).orientation)
+ assertEquals("Transpose", PhotoFrame(turns = 3, mirror = true).orientation)
+ }
+
+ @Test
+ fun aMapKeepsItsOutline() {
+ val doc = MindDoc(parseOutline("Trip", "Before\n Tickets\n Hotel\nThere"))
+ assertEquals("Trip", doc.root.text)
+ assertEquals("Before\n Tickets\n Hotel\nThere", doc.outline())
+ }
+
+ @Test
+ fun anOpmlFileIsReadAsAMap() {
+ val xml = """<?xml version="1.0"?><opml version="2.0"><head><title>Trip</title></head><body>""" +
+ """<outline text="Trip"><outline text="Tokyo &amp; Kyoto"><outline text="Temples"/></outline><outline title="Budget"/></outline></body></opml>"""
+ val doc = mindFromOpml(xml)!!
+ assertEquals("Trip", doc.root.text)
+ assertEquals(listOf("Tokyo & Kyoto", "Budget"), doc.root.children.map { it.text })
+ assertEquals(listOf("Temples"), doc.root.children[0].children.map { it.text })
+ // several top outlines hang from the head's title
+ val many = mindFromOpml("<opml><head><title>Plan</title></head><body><outline text='A'/><outline text='B'/></body></opml>")!!
+ assertEquals("Plan", many.root.text)
+ assertEquals(listOf("A", "B"), many.root.children.map { it.text })
+ assertNull(mindFromOpml("<opml><body></body></opml>"))
+ // what Artefact exports, it reads back the same
+ val back = mindFromOpml(doc.opml())!!
+ assertEquals(doc.outline(), back.outline())
+ assertEquals(doc.root.text, back.root.text)
+ }
+}
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index ad98a26..31b4b30 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -134,6 +134,7 @@ dependencies = [
"deckcraft-pdf",
"deckcraft-pptx",
"deckcraft-render",
+ "gridcraft-chart",
"gridcraft-engine",
"gridcraft-xlsx",
"kurbo",
@@ -145,6 +146,7 @@ dependencies = [
"pdfcraft-automation",
"pdfcraft-engine",
"pdfcraft-render",
+ "png",
"serde_json",
"thiserror 2.0.21",
"uniffi",
diff --git a/engine/Cargo.toml b/engine/Cargo.toml
index 8c7e079..02954bb 100644
--- a/engine/Cargo.toml
+++ b/engine/Cargo.toml
@@ -76,6 +76,7 @@ deckcraft-pdf = { git = "https://github.com/storytold/deckcraft", rev = "159ed07
# Excel (.xlsx, .xlsb, .ods, .csv): storytold/gridcraft's engine (formulas, number formats), pinned.
gridcraft-engine = { git = "https://github.com/storytold/gridcraft", rev = "6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214", version = "0.16.0" }
gridcraft-xlsx = { git = "https://github.com/storytold/gridcraft", rev = "6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214", version = "0.16.0" }
+gridcraft-chart = { git = "https://github.com/storytold/gridcraft", rev = "6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214", version = "0.16.0" }
# Pictures (notes' photos): storytold/lightcraft's codecs, develop settings and CPU pipeline, pinned.
# Not its engine (GPU, faces, catalog); no AVIF or JPEG XL encoders.
diff --git a/engine/mobile/Cargo.toml b/engine/mobile/Cargo.toml
index 9fe838c..a10fce8 100644
--- a/engine/mobile/Cargo.toml
+++ b/engine/mobile/Cargo.toml
@@ -35,6 +35,7 @@ cfb = "0.15"
# Excel workbooks (src/sheets.rs): GridCraft's engine
gridcraft-engine = { workspace = true }
gridcraft-xlsx = { workspace = true }
+gridcraft-chart = { workspace = true }
# Pictures (src/photo.rs): LightCraft's decoding, develop settings and pipeline
lightcraft-codecs = { workspace = true }
lightcraft-develop = { workspace = true }
@@ -54,3 +55,5 @@ android_logger = { version = "0.15", default-features = false }
[dev-dependencies]
# its test helper that password-protects a package (the encrypted presentation test)
gridcraft-xlsx = { workspace = true, features = ["test-support"] }
+# writes the pictures of the photo tests
+png = "0.18"
diff --git a/engine/mobile/src/lib.rs b/engine/mobile/src/lib.rs
index b1b153c..571a521 100644
--- a/engine/mobile/src/lib.rs
+++ b/engine/mobile/src/lib.rs
@@ -30,9 +30,10 @@ mod photo;
mod ppt;
mod sheets;
mod slides;
+mod xls_art;
pub use photo::PhotoEditor;
-pub use sheets::{CellEdge, CellSpan, CellView, SheetAxes, SheetInfo, SheetPicture};
+pub use sheets::{CellEdge, CellSpan, CellView, SheetAxes, SheetChart, SheetInfo, SheetPicture, SheetStats};
pub use word::{WordCaret, WordParagraph};
#[cfg(test)]
mod tests;
@@ -968,6 +969,16 @@ impl MobileSession {
self.with_sheets(doc, |b| b.pictures(sheet))
}
+ /// What the cells of `area` on sheet `sheet` hold: counts, and the sum, smallest and largest of its numbers.
+ pub fn sheet_stats(&self, doc: u64, sheet: u32, area: CellSpan) -> Result<SheetStats, MobileError> {
+ self.with_sheets(doc, |b| b.stats(sheet, area))
+ }
+
+ /// The charts over sheet `sheet` of workbook `doc`, laid out by GridCraft as drawing steps.
+ pub fn sheet_charts(&self, doc: u64, sheet: u32) -> Result<Vec<SheetChart>, MobileError> {
+ self.with_sheets(doc, |b| b.charts(sheet))
+ }
+
/// The merged areas of sheet `sheet`.
pub fn sheet_merges(&self, doc: u64, sheet: u32) -> Result<Vec<CellSpan>, MobileError> {
self.with_sheets(doc, |b| b.merges(sheet))
diff --git a/engine/mobile/src/photo.rs b/engine/mobile/src/photo.rs
index fa531b4..e31c3b5 100644
--- a/engine/mobile/src/photo.rs
+++ b/engine/mobile/src/photo.rs
@@ -44,7 +44,10 @@ impl PhotoEditor {
let bytes = crate::office::read(path)?;
let opts = DecodeOptions { max_size: preview.then_some((PREVIEW_SOURCE, PREVIEW_SOURCE)), ..DecodeOptions::default() };
let decoded = lightcraft_codecs::decode(&bytes, opts).map_err(|e| MobileError::Open(format!("{path}: {e}")))?;
- let img = Arc::new(decoded.image);
+ // the decoder hands linear light in the picture's own primaries (sRGB, Display P3, its ICC
+ // profile's): the pipeline works in linear Rec.2020, so it is converted, or every colour
+ // comes out washed towards grey (a yellow as cream, a blue as slate)
+ let img = Arc::new(decoded.to_working());
*s = Some((path.to_string(), preview, img.clone()));
Ok(img)
}
diff --git a/engine/mobile/src/ppt.rs b/engine/mobile/src/ppt.rs
index 6eee5a4..1dea556 100644
--- a/engine/mobile/src/ppt.rs
+++ b/engine/mobile/src/ppt.rs
@@ -82,14 +82,14 @@ struct Outline {
}
/// 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],
+pub(crate) struct Record<'a> {
+ pub(crate) kind: u16,
+ pub(crate) instance: u16,
+ pub(crate) container: bool,
+ pub(crate) body: &'a [u8],
}
-fn records(data: &[u8]) -> impl Iterator<Item = Record<'_>> {
+pub(crate) fn records(data: &[u8]) -> impl Iterator<Item = Record<'_>> {
let mut at = 0usize;
std::iter::from_fn(move || {
let (r, next) = record_at(data, at)?;
@@ -99,7 +99,7 @@ fn records(data: &[u8]) -> impl Iterator<Item = Record<'_>> {
}
/// The record starting at `at`, and where the next one starts.
-fn record_at(data: &[u8], at: usize) -> Option<(Record<'_>, usize)> {
+pub(crate) fn record_at(data: &[u8], at: usize) -> Option<(Record<'_>, usize)> {
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]]);
@@ -109,11 +109,11 @@ fn record_at(data: &[u8], at: usize) -> Option<(Record<'_>, usize)> {
Some((Record { kind, instance: ver_inst >> 4, container: ver_inst & 0xF == 0xF, body: data.get(start..end)? }, start.checked_add(len)?))
}
-fn u16_at(b: &[u8], at: usize) -> Option<u16> {
+pub(crate) fn u16_at(b: &[u8], at: usize) -> Option<u16> {
b.get(at..at.checked_add(2)?).map(|v| u16::from_le_bytes([v[0], v[1]]))
}
-fn u32_at(b: &[u8], at: usize) -> Option<u32> {
+pub(crate) fn u32_at(b: &[u8], at: usize) -> Option<u32> {
b.get(at..at.checked_add(4)?).map(|v| u32::from_le_bytes([v[0], v[1], v[2], v[3]]))
}
@@ -516,10 +516,10 @@ fn persist_offsets(data: &[u8]) -> HashMap<u32, u32> {
}
/// A picture of the file: its bytes and their type.
-struct Picture {
- data: Vec<u8>,
- mime: &'static str,
- ext: &'static str,
+pub(crate) struct Picture {
+ pub(crate) data: Vec<u8>,
+ pub(crate) mime: &'static str,
+ pub(crate) ext: &'static str,
}
/// The picture a blip record holds: a JPEG or PNG as it is, a bitmap given the file header it
@@ -569,6 +569,13 @@ fn read_pictures(data: &[u8], pictures: &[u8]) -> Vec<Option<Picture>> {
}
// Document ▸ drawing group ▸ OfficeArt's group container ▸ its picture store
let Some(store) = find(data, &[0x03E8, DRAWING_GROUP, ART_DGG, ART_BSTORE]) else { return Vec::new() };
+ store_pictures(store, pictures)
+}
+
+/// The pictures of an OfficeArt picture store (`OfficeArtBStoreContainer`'s contents), in the
+/// order shapes number them; a picture not held in its entry is read from `pictures` (a
+/// presentation's Pictures stream). `None` for one that can't be shown.
+pub(crate) fn store_pictures(store: &[u8], pictures: &[u8]) -> Vec<Option<Picture>> {
let mut out = Vec::new();
let mut total = 0usize;
for r in records(store).take(10_000) {
diff --git a/engine/mobile/src/sheets.rs b/engine/mobile/src/sheets.rs
index 74f844d..a676c95 100644
--- a/engine/mobile/src/sheets.rs
+++ b/engine/mobile/src/sheets.rs
@@ -60,6 +60,50 @@ pub struct SheetPicture {
pub data: Vec<u8>,
}
+/// A chart floating over a sheet: where it sits (as a picture is), its own size in points, and
+/// GridCraft's layout of it as drawing steps (`gridcraft_chart::Prim`, JSON) in those points.
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct SheetChart {
+ pub x: f32,
+ pub y: f32,
+ pub width: f32,
+ pub height: f32,
+ pub chart_width: f32,
+ pub chart_height: f32,
+ pub prims: String,
+}
+
+/// Text widths for chart layout: a sans-serif's average advance, close to the phone's own.
+struct PhoneMeasure;
+
+impl gridcraft_chart::Measure for PhoneMeasure {
+ fn text_width(&self, text: &str, size: f32, bold: bool) -> f32 {
+ text.chars()
+ .map(|c| {
+ if c.is_ascii_uppercase() || c.is_ascii_digit() {
+ 0.6
+ } else if c.is_ascii() {
+ 0.5
+ } else {
+ 0.9
+ }
+ })
+ .sum::<f32>()
+ * size
+ * if bold { 1.06 } else { 1.0 }
+ }
+}
+
+/// What a selection of cells holds (see `SheetBook::stats`).
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct SheetStats {
+ pub filled: u32,
+ pub numbers: u32,
+ pub sum: f64,
+ pub min: f64,
+ pub max: f64,
+}
+
/// A cell as the grid draws it: the text it shows, in its looks. Colours are `0xRRGGBB`.
#[derive(Debug, Clone, uniffi::Record)]
pub struct CellView {
@@ -133,8 +177,12 @@ impl SheetBook {
let name = crate::office::file_name(path);
let stem = std::path::Path::new(&name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let encrypted = gridcraft_xlsx::sniff(bytes) == gridcraft_xlsx::Format::Encrypted;
- let (wb, _warnings) =
+ let (mut wb, _warnings) =
gridcraft_engine::io::open_bytes_with_password(&format!("{stem}.{ext}"), bytes, password).map_err(|e| open_error(e.to_string()))?;
+ // GridCraft's .xls reader leaves pictures and charts out: they are read here
+ if matches!(ext, "xls" | "xlt") && !encrypted {
+ crate::xls_art::import(bytes, &mut wb);
+ }
// the desktop app's document: computed on open (values the file left stale are brought up to
// date), with its selection and undo history
let mut session = gridcraft_engine::Session::new();
@@ -166,6 +214,44 @@ impl SheetBook {
s.execute(command, params).map_err(err)
}
+ /// What a selection holds, for the line under the formula bar: how many cells have something
+ /// in them, how many of those are numbers, and the numbers' sum, smallest and largest. Only the
+ /// part of `area` the sheet uses is read (a whole column is its used rows), two million cells at most.
+ pub(crate) fn stats(&self, sheet: u32, area: CellSpan) -> Result<SheetStats, MobileError> {
+ let wb = self.wb();
+ let s = self.sheet_in(&wb, sheet)?;
+ let mut out = SheetStats { filled: 0, numbers: 0, sum: 0.0, min: 0.0, max: 0.0 };
+ let Some(used) = s.used_range() else { return Ok(out) };
+ let (r0, r1) = (area.row0.max(used.start.row), area.row1.min(used.end.row));
+ let (c0, c1) = (area.col0.max(used.start.col), area.col1.min(used.end.col));
+ let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
+ let mut budget = 2_000_000u32;
+ 'rows: for r in r0..=r1 {
+ for c in c0..=c1 {
+ budget = budget.saturating_sub(1);
+ if budget == 0 {
+ break 'rows;
+ }
+ match s.value_ref(CellRef::new(r, c)) {
+ None | Some(gridcraft_engine::core::Value::Empty) => {}
+ Some(gridcraft_engine::core::Value::Number(n)) if n.is_finite() => {
+ out.filled += 1;
+ out.numbers += 1;
+ out.sum += n;
+ lo = lo.min(*n);
+ hi = hi.max(*n);
+ }
+ Some(_) => out.filled += 1,
+ }
+ }
+ }
+ if out.numbers > 0 {
+ out.min = lo;
+ out.max = hi;
+ }
+ Ok(out)
+ }
+
/// What the formula bar shows for a cell: its formula (`=SUM(A1:A3)`), else its value as typed.
pub(crate) fn input(&self, sheet: u32, row: u32, col: u32) -> Result<String, MobileError> {
let wb = self.wb();
@@ -436,6 +522,31 @@ impl SheetBook {
.collect())
}
+ /// The charts over sheet `sheet`: each laid out by GridCraft (from the workbook's values) at its
+ /// anchor's size, placed in points from A1 as the pictures are.
+ pub(crate) fn charts(&self, sheet: u32) -> Result<Vec<SheetChart>, MobileError> {
+ let wb = self.wb();
+ let s = self.sheet_in(&wb, sheet)?;
+ Ok(s.charts
+ .iter()
+ .filter(|c| c.anchor.width >= 8.0 && c.anchor.height >= 8.0)
+ .take(32)
+ .filter_map(|c| {
+ let data = gridcraft_chart::resolve(&wb, sheet as usize, c);
+ let prims = gridcraft_chart::render(c, &data, c.anchor.width, c.anchor.height, &PhoneMeasure);
+ Some(SheetChart {
+ x: (s.col_left(c.anchor.cell.col) as f32 + c.anchor.dx) * PT,
+ y: (s.row_top(c.anchor.cell.row) as f32 + c.anchor.dy) * PT,
+ width: c.anchor.width * PT,
+ height: c.anchor.height * PT,
+ chart_width: c.anchor.width,
+ chart_height: c.anchor.height,
+ prims: serde_json::to_string(&prims).ok()?,
+ })
+ })
+ .collect())
+ }
+
/// The merged areas of sheet `sheet`.
pub(crate) fn merges(&self, sheet: u32) -> Result<Vec<CellSpan>, MobileError> {
let wb = self.wb();
diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rs
index a284dc1..767346f 100644
--- a/engine/mobile/src/tests.rs
+++ b/engine/mobile/src/tests.rs
@@ -898,3 +898,101 @@ fn links_are_found_in_every_kind_of_document() {
let cell = cells.iter().find(|c| c.row == 1 && c.col == 0).unwrap();
assert_eq!(cell.link.as_deref(), Some("https://example.com/sheet"));
}
+
+/// Charts and pictures come with a workbook: an .xlsx's from GridCraft, an .xls's (which GridCraft
+/// leaves out) from Artefact's own reader. Both files hold a column, a pie and a line chart of the
+/// same cells, and one picture (made with LibreOffice from the .xlsx).
+#[test]
+fn charts_and_pictures_of_xlsx_and_xls_are_shown() {
+ let s = MobileSession::new();
+ for name in ["charts.xlsx", "charts.xls"] {
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data").join(name);
+ let book = s.open(path.to_string_lossy().into_owned(), None).unwrap();
+ let charts = s.sheet_charts(book.id, 0).unwrap();
+ assert_eq!(charts.len(), 3, "{name}: charts");
+ for c in &charts {
+ assert!(c.width > 50.0 && c.height > 50.0, "{name}: {} x {}", c.width, c.height);
+ // a chart with words on it (its title, the months) and bars, wedges or lines
+ assert!(c.prims.contains("\"Text\""), "{name}: no text");
+ assert!(c.prims.contains("\"Rect\"") || c.prims.contains("\"Wedge\"") || c.prims.contains("\"Line\""), "{name}: nothing drawn");
+ }
+ assert!(charts.iter().any(|c| c.prims.contains("Jan")), "{name}: categories");
+ assert!(charts.iter().any(|c| c.prims.contains("\"Wedge\"")), "{name}: the pie");
+ let pictures = s.sheet_pictures(book.id, 0).unwrap();
+ assert_eq!(pictures.len(), 1, "{name}: pictures");
+ assert!(
+ pictures[0].data.starts_with(&[0x89, b'P', b'N', b'G'])
+ || pictures[0].data.starts_with(&[0xFF, 0xD8])
+ || pictures[0].data.starts_with(b"BM"),
+ "{name}: picture bytes"
+ );
+ }
+}
+
+/// An untouched picture comes out of the photo editor as it went in (no edit, no change of colour).
+#[test]
+fn an_untouched_picture_keeps_its_colours() {
+ let w = 64u32;
+ let h = 32u32;
+ let mut px = Vec::with_capacity((w * h * 3) as usize);
+ for y in 0..h {
+ for x in 0..w {
+ let c: [u8; 3] = if y < h / 2 {
+ if x < w / 2 { [255, 194, 26] } else { [18, 24, 38] }
+ } else if x < w / 2 {
+ [10, 132, 255]
+ } else {
+ [128, 128, 128]
+ };
+ px.extend_from_slice(&c);
+ }
+ }
+ let png = scratch().join("colours.png");
+ image_png(&png, w, h, &px);
+ let e = crate::photo::PhotoEditor::new();
+ let out = e.render(png.to_string_lossy().into_owned(), String::new(), 64).unwrap();
+ let at = |x: u32, y: u32| {
+ let i = ((y * out.width + x) * 4) as usize;
+ [out.rgba[i], out.rgba[i + 1], out.rgba[i + 2]]
+ };
+ for (x, y, want) in [(8, 4, [255u8, 194, 26]), (40, 4, [18, 24, 38]), (8, 24, [10, 132, 255]), (40, 24, [128, 128, 128])] {
+ let got = at(x * out.width / w, y * out.height / h);
+ let off = got.iter().zip(want).map(|(a, b)| (i32::from(*a) - i32::from(b)).abs()).max().unwrap();
+ assert!(off <= 4, "{want:?} came out as {got:?}");
+ }
+}
+
+fn image_png(path: &std::path::Path, w: u32, h: u32, rgb: &[u8]) {
+ let mut data = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut data, w, h);
+ enc.set_color(png::ColorType::Rgb);
+ enc.set_depth(png::BitDepth::Eight);
+ enc.write_header().unwrap().write_image_data(rgb).unwrap();
+ }
+ std::fs::write(path, data).unwrap();
+}
+
+/// A selection's summary counts its filled cells and adds up its numbers, the way a spreadsheet's
+/// status bar does; a whole column reads only the rows in use.
+#[test]
+fn a_selection_is_summed_and_counted() {
+ let s = MobileSession::new();
+ let csv = scratch().join("Stats.csv");
+ std::fs::write(
+ &csv,
+ "Item,Price
+Tea,3.5
+Cake,4
+Note,
+Jam,2.5
+",
+ )
+ .unwrap();
+ let book = s.open(csv.to_string_lossy().into_owned(), None).unwrap();
+ let col = s.sheet_stats(book.id, 0, CellSpan { row0: 0, col0: 1, row1: 1_048_575, col1: 1 }).unwrap();
+ assert_eq!((col.filled, col.numbers), (4, 3));
+ assert!((col.sum - 10.0).abs() < 1e-9 && col.min == 2.5 && col.max == 4.0, "{col:?}");
+ let both = s.sheet_stats(book.id, 0, CellSpan { row0: 1, col0: 0, row1: 4, col1: 1 }).unwrap();
+ assert_eq!((both.filled, both.numbers), (7, 3));
+}
diff --git a/engine/mobile/src/xls_art.rs b/engine/mobile/src/xls_art.rs
new file mode 100644
index 0000000..674cd2b
--- /dev/null
+++ b/engine/mobile/src/xls_art.rs
@@ -0,0 +1,541 @@
+//! The pictures and charts of a legacy Excel 97-2003 `.xls` workbook, which GridCraft's BIFF8
+//! reader leaves out. Read from Microsoft's public specifications: [MS-XLS] (the Workbook
+//! stream: `BoundSheet8`, `ExternSheet`, `MsoDrawingGroup`, `MsoDrawing`, `Obj` and the chart
+//! substreams) and [MS-ODRAW] (the OfficeArt drawing records inside them).
+//!
+//! A sheet's drawing is one OfficeArt record tree cut into its `MsoDrawing` records; every shape
+//! in it that carries client data is matched, in order, with the sheet's `Obj` records, which say
+//! what the shape is (a picture, a chart, …). A picture's bytes are in the workbook's picture
+//! store; a chart is the chart substream that follows its `Obj`, and becomes a GridCraft chart
+//! whose series point at the same cells, so GridCraft draws it from the workbook's own values.
+
+use std::io::Read;
+use std::sync::Arc;
+
+use gridcraft_engine::core::CellRef;
+use gridcraft_engine::model::{Anchor, AnchorMode, Chart, ChartKind, Image, LegendPos, Series, Sheet, Workbook};
+
+use crate::ppt::{Picture, records, store_pictures, u16_at, u32_at};
+
+/// Records read from the Workbook stream at most.
+const MAX_RECORDS: usize = 2_000_000;
+/// Pictures and charts taken from one workbook at most.
+const MAX_OBJECTS: usize = 400;
+
+const BOF: u16 = 0x0809;
+const EOF: u16 = 0x000A;
+const CONTINUE: u16 = 0x003C;
+const BOUND_SHEET: u16 = 0x0085;
+const EXTERN_SHEET: u16 = 0x0017;
+const DRAWING_GROUP: u16 = 0x00EB;
+const DRAWING: u16 = 0x00EC;
+const OBJ: u16 = 0x005D;
+
+const ART_DGG: u16 = 0xF000;
+const ART_BSTORE: u16 = 0xF001;
+const ART_SPGR: u16 = 0xF003;
+const ART_SP: u16 = 0xF004;
+const ART_FOPT: u16 = 0xF00B;
+const ART_CLIENT_ANCHOR: u16 = 0xF010;
+const ART_CLIENT_DATA: u16 = 0xF011;
+
+/// One BIFF record: its type and body.
+struct Biff<'a> {
+ kind: u16,
+ body: &'a [u8],
+}
+
+fn biff_at(data: &[u8], at: usize) -> Option<(Biff<'_>, usize)> {
+ let kind = u16_at(data, at)?;
+ let len = usize::from(u16_at(data, at + 2)?);
+ let end = (at + 4).checked_add(len)?;
+ Some((Biff { kind, body: data.get(at + 4..end.min(data.len()))? }, end))
+}
+
+/// A sheet as `BoundSheet8` lists it: where its substream starts, its type and its name.
+struct Bound {
+ at: usize,
+ worksheet: bool,
+ name: String,
+}
+
+/// An `XLUnicodeString`-like run of `count` characters at `at` (one byte each, or two when
+/// `wide`), and where it ends.
+fn chars(b: &[u8], at: usize, count: usize, wide: bool) -> (String, usize) {
+ if wide {
+ let units: Vec<u16> = (0..count).filter_map(|i| u16_at(b, at + i * 2)).collect();
+ (String::from_utf16_lossy(&units), at + count * 2)
+ } else {
+ let s = b.get(at..(at + count).min(b.len())).unwrap_or_default().iter().map(|&c| char::from(c)).collect();
+ (s, at + count)
+ }
+}
+
+/// A `ShortXLUnicodeString` at `at`: a byte count, a flags byte, then the characters.
+fn short_string(b: &[u8], at: usize) -> String {
+ let n = usize::from(b.get(at).copied().unwrap_or(0));
+ let wide = b.get(at + 1).copied().unwrap_or(0) & 1 == 1;
+ chars(b, at + 2, n, wide).0
+}
+
+fn col_name(mut c: u32) -> String {
+ let mut s = Vec::new();
+ loop {
+ s.push(b'A' + (c % 26) as u8);
+ if c < 26 {
+ break;
+ }
+ c = c / 26 - 1;
+ }
+ s.reverse();
+ String::from_utf8_lossy(&s).into_owned()
+}
+
+/// What the workbook-wide records say: its sheets, its external sheet list and its picture store.
+struct Globals {
+ bounds: Vec<Bound>,
+ /// `ExternSheet`'s entries: the first sheet each points at (an index into `bounds`).
+ xti: Vec<i16>,
+ pictures: Vec<Option<Picture>>,
+}
+
+fn globals(data: &[u8]) -> Globals {
+ let mut g = Globals { bounds: Vec::new(), xti: Vec::new(), pictures: Vec::new() };
+ let mut group = Vec::new();
+ let mut in_group = false;
+ let mut at = 0usize;
+ for _ in 0..MAX_RECORDS {
+ let Some((r, next)) = biff_at(data, at) else { break };
+ at = next;
+ match r.kind {
+ EOF => break,
+ BOUND_SHEET => {
+ let pos = u32_at(r.body, 0).unwrap_or(0) as usize;
+ let dt = r.body.get(5).copied().unwrap_or(0);
+ g.bounds.push(Bound { at: pos, worksheet: dt == 0, name: short_string(r.body, 6) });
+ }
+ EXTERN_SHEET => {
+ let n = usize::from(u16_at(r.body, 0).unwrap_or(0));
+ g.xti = (0..n).map(|i| u16_at(r.body, 2 + i * 6 + 2).unwrap_or(0) as i16).collect();
+ }
+ DRAWING_GROUP => {
+ group.extend_from_slice(r.body);
+ in_group = true;
+ continue;
+ }
+ CONTINUE if in_group => {
+ group.extend_from_slice(r.body);
+ continue;
+ }
+ _ => {}
+ }
+ in_group = false;
+ }
+ // the drawing group ▸ its picture store
+ let store = records(&group).find(|r| r.kind == ART_DGG).and_then(|dgg| records(dgg.body).find(|r| r.kind == ART_BSTORE).map(|s| s.body.to_vec()));
+ if let Some(store) = store {
+ g.pictures = store_pictures(&store, &[]);
+ }
+ g
+}
+
+/// A shape of a sheet's drawing that has an `Obj`: where it is anchored ([MS-XLS]
+/// `OfficeArtClientAnchorSheet`: columns and rows, with offsets in 1/1024 of a column and 1/256
+/// of a row) and the picture it shows (1-based in the store), if any.
+struct Shape {
+ anchor: Option<[u16; 8]>,
+ picture: Option<u32>,
+}
+
+fn shapes(drawing: &[u8], out: &mut Vec<Shape>, depth: usize) {
+ if depth > 12 {
+ return;
+ }
+ for r in records(drawing).take(100_000) {
+ match r.kind {
+ ART_SP => {
+ let mut shape = Shape { anchor: None, picture: None };
+ let mut client = false;
+ for c in records(r.body) {
+ match c.kind {
+ ART_CLIENT_ANCHOR => {
+ let mut a = [0u16; 8];
+ for (i, v) in a.iter_mut().enumerate() {
+ *v = u16_at(c.body, 2 + i * 2).unwrap_or(0);
+ }
+ shape.anchor = Some(a);
+ }
+ ART_FOPT => {
+ // properties: 6 bytes each, the picture is `pib` (0x0104)
+ let n = usize::from(c.instance);
+ for i in 0..n {
+ let id = u16_at(c.body, i * 6).unwrap_or(0);
+ if id & 0x3FFF == 0x0104 {
+ shape.picture = u32_at(c.body, i * 6 + 2);
+ }
+ }
+ }
+ ART_CLIENT_DATA => client = true,
+ _ => {}
+ }
+ }
+ if client {
+ out.push(shape);
+ }
+ }
+ ART_SPGR => shapes(r.body, out, depth + 1),
+ _ if r.container => shapes(r.body, out, depth + 1),
+ _ => {}
+ }
+ }
+}
+
+/// What a chart substream holds that a GridCraft chart needs.
+#[derive(Default)]
+struct ChartBits {
+ kind: Option<ChartKind>,
+ series: Vec<SeriesBits>,
+ title: Option<String>,
+ x_title: Option<String>,
+ y_title: Option<String>,
+ legend: Option<LegendPos>,
+ hole: u8,
+ angle: u16,
+}
+
+#[derive(Default)]
+struct SeriesBits {
+ name: Option<String>,
+ values: Option<String>,
+ categories: Option<String>,
+}
+
+/// A chart reference (`PtgRef3d` or `PtgArea3d`, the first of a list) as `'Sheet'!$A$1:$B$2`, or a
+/// literal string (`PtgStr`) quoted.
+fn chart_ref(rgce: &[u8], g: &Globals) -> Option<String> {
+ let ptg = *rgce.first()?;
+ let sheet = |ixti: u16| -> Option<String> {
+ let tab = *g.xti.get(usize::from(ixti))?;
+ let name = &g.bounds.get(usize::try_from(tab).ok()?)?.name;
+ Some(format!("'{}'", name.replace('\'', "''")))
+ };
+ match ptg {
+ 0x3A | 0x5A | 0x7A => {
+ let s = sheet(u16_at(rgce, 1)?)?;
+ let row = u32::from(u16_at(rgce, 3)?);
+ let col = u32::from(u16_at(rgce, 5)? & 0x3FFF);
+ Some(format!("{s}!${}${}", col_name(col), row + 1))
+ }
+ 0x3B | 0x5B | 0x7B => {
+ let s = sheet(u16_at(rgce, 1)?)?;
+ let (r0, r1) = (u32::from(u16_at(rgce, 3)?), u32::from(u16_at(rgce, 5)?));
+ let (c0, c1) = (u32::from(u16_at(rgce, 7)? & 0x3FFF), u32::from(u16_at(rgce, 9)? & 0x3FFF));
+ Some(format!("{s}!${}${}:${}${}", col_name(c0), r0 + 1, col_name(c1), r1 + 1))
+ }
+ 0x17 => {
+ let n = usize::from(*rgce.get(1)?);
+ let wide = rgce.get(2).copied().unwrap_or(0) & 1 == 1;
+ Some(format!("\"{}\"", chars(rgce, 3, n, wide).0.replace('"', "\"\"")))
+ }
+ _ => None,
+ }
+}
+
+/// The chart substream starting after its `BOF` at `at`: what it charts, and where it ends.
+fn chart_bits(data: &[u8], mut at: usize, g: &Globals) -> (ChartBits, usize) {
+ let mut c = ChartBits::default();
+ let mut depth = 0usize;
+ let mut series_depth: Option<usize> = None;
+ let mut text_depth: Option<usize> = None;
+ let mut text: Option<String> = None;
+ let mut link = 0u16;
+ for _ in 0..MAX_RECORDS {
+ let Some((r, next)) = biff_at(data, at) else { break };
+ at = next;
+ let b = r.body;
+ match r.kind {
+ EOF => break,
+ // a chart substream inside this one (not expected) is skipped whole
+ BOF => {
+ let (_, end) = chart_bits(data, at, g);
+ at = end;
+ }
+ 0x1033 => depth += 1,
+ 0x1034 => {
+ depth = depth.saturating_sub(1);
+ if series_depth == Some(depth) {
+ series_depth = None;
+ }
+ if text_depth == Some(depth) {
+ let t = text.take().filter(|t| !t.trim().is_empty());
+ match link {
+ 1 => c.title = c.title.take().or(t),
+ 2 => c.y_title = c.y_title.take().or(t),
+ 3 => c.x_title = c.x_title.take().or(t),
+ _ => {}
+ }
+ text_depth = None;
+ link = 0;
+ }
+ }
+ // Series
+ 0x1003 => {
+ c.series.push(SeriesBits::default());
+ series_depth = Some(depth);
+ }
+ // BRAI: where a series' name, values or categories come from
+ 0x1051 if series_depth.is_some() => {
+ let id = b.first().copied().unwrap_or(9);
+ let rt = b.get(1).copied().unwrap_or(0);
+ let cce = usize::from(u16_at(b, 6).unwrap_or(0));
+ let found = if rt == 2 { b.get(8..8 + cce).and_then(|rgce| chart_ref(rgce, g)) } else { None };
+ if let (Some(s), Some(f)) = (c.series.last_mut(), found) {
+ match id {
+ 0 => s.name = Some(f),
+ 1 => s.values = Some(f),
+ 2 => s.categories = Some(f),
+ _ => {}
+ }
+ }
+ }
+ // SeriesText: a series' own name, or a title's words
+ 0x100D => {
+ let words = short_string(b, 2);
+ if text_depth.is_some() {
+ text = Some(words);
+ } else if series_depth.is_some()
+ && let Some(s) = c.series.last_mut()
+ && s.name.is_none()
+ {
+ s.name = Some(format!("\"{}\"", words.replace('"', "\"\"")));
+ }
+ }
+ // Text, and the ObjectLink that says what it labels
+ 0x1025 => {
+ text_depth = Some(depth);
+ text = None;
+ link = 0;
+ }
+ 0x1027 if text_depth.is_some() => link = u16_at(b, 0).unwrap_or(0),
+ 0x1015 => {
+ c.legend = Some(match b.get(16).copied().unwrap_or(3) {
+ 0 => LegendPos::Bottom,
+ 2 => LegendPos::Top,
+ 4 => LegendPos::Left,
+ _ => LegendPos::Right,
+ });
+ }
+ // the chart's kind: the first chart group's
+ 0x1017 if c.kind.is_none() => {
+ let f = u16_at(b, 4).unwrap_or(0);
+ let (bar, stacked, full) = (f & 1 == 1, f & 2 == 2, f & 4 == 4);
+ c.kind = Some(match (bar, stacked, full) {
+ (true, true, true) => ChartKind::BarStacked100,
+ (true, true, false) => ChartKind::BarStacked,
+ (true, false, _) => ChartKind::BarClustered,
+ (false, true, true) => ChartKind::ColumnStacked100,
+ (false, true, false) => ChartKind::ColumnStacked,
+ (false, false, _) => ChartKind::ColumnClustered,
+ });
+ }
+ 0x1018 if c.kind.is_none() => {
+ let f = u16_at(b, 0).unwrap_or(0);
+ c.kind = Some(if f & 1 == 1 { ChartKind::LineStacked } else { ChartKind::LineMarkers });
+ }
+ 0x1019 if c.kind.is_none() => {
+ c.angle = u16_at(b, 0).unwrap_or(0) % 360;
+ let hole = u16_at(b, 2).unwrap_or(0);
+ c.hole = hole.min(90) as u8;
+ c.kind = Some(if hole > 0 { ChartKind::Doughnut } else { ChartKind::Pie });
+ }
+ 0x101A if c.kind.is_none() => {
+ let f = u16_at(b, 0).unwrap_or(0);
+ c.kind = Some(match (f & 1 == 1, f & 2 == 2) {
+ (true, true) => ChartKind::AreaStacked100,
+ (true, false) => ChartKind::AreaStacked,
+ _ => ChartKind::Area,
+ });
+ }
+ 0x101B if c.kind.is_none() => {
+ let f = u16_at(b, 4).unwrap_or(0);
+ c.kind = Some(if f & 1 == 1 { ChartKind::Bubble } else { ChartKind::Scatter });
+ }
+ 0x103E | 0x1040 if c.kind.is_none() => c.kind = Some(ChartKind::Radar),
+ _ => {}
+ }
+ }
+ (c, at)
+}
+
+/// A sheet's drawing, its `Obj` records (object type, and the chart substream after a chart's).
+fn sheet_objects(data: &[u8], start: usize, g: &Globals) -> (Vec<u8>, Vec<(u16, Option<ChartBits>)>) {
+ let mut drawing = Vec::new();
+ let mut objects: Vec<(u16, Option<ChartBits>)> = Vec::new();
+ let mut at = start;
+ let mut first = true;
+ let mut in_drawing = false;
+ for _ in 0..MAX_RECORDS {
+ let Some((r, next)) = biff_at(data, at) else { break };
+ at = next;
+ match r.kind {
+ BOF if first => first = false,
+ BOF => {
+ // a chart's own substream follows its Obj
+ let chart = u16_at(r.body, 2) == Some(0x0020);
+ let (bits, end) = chart_bits(data, at, g);
+ at = end;
+ if chart && let Some(last) = objects.last_mut().filter(|o| o.0 == 5 && o.1.is_none()) {
+ last.1 = Some(bits);
+ }
+ in_drawing = false;
+ continue;
+ }
+ EOF => break,
+ DRAWING => {
+ drawing.extend_from_slice(r.body);
+ in_drawing = true;
+ continue;
+ }
+ CONTINUE if in_drawing => {
+ drawing.extend_from_slice(r.body);
+ continue;
+ }
+ // Obj: its first part (ftCmo) gives the object's type
+ OBJ => objects.push((u16_at(r.body, 4).unwrap_or(0), None)),
+ _ => {}
+ }
+ in_drawing = false;
+ }
+ (drawing, objects)
+}
+
+/// Where an OfficeArt anchor puts a shape on `sheet`, in GridCraft's terms (points from its cell).
+fn anchor_on(sheet: &Sheet, a: [u16; 8]) -> Option<Anchor> {
+ let [c0, dx0, r0, dy0, c1, dx1, r1, dy1] = a.map(u32::from);
+ let x = |c: u32, d: u32| sheet.col_left(c) as f32 + sheet.col_width(c) * (d.min(1024) as f32 / 1024.0);
+ let y = |r: u32, d: u32| sheet.row_top(r) as f32 + sheet.row_height(r) * (d.min(256) as f32 / 256.0);
+ let (left, top, right, bottom) = (x(c0, dx0), y(r0, dy0), x(c1, dx1), y(r1, dy1));
+ if !(right > left && bottom > top) {
+ return None;
+ }
+ Some(Anchor {
+ cell: CellRef { row: r0, col: c0 },
+ dx: left - sheet.col_left(c0) as f32,
+ dy: top - sheet.row_top(r0) as f32,
+ width: right - left,
+ height: bottom - top,
+ mode: AnchorMode::default(),
+ })
+}
+
+/// Adds the pictures and charts of the `.xls` file `bytes` to `wb` (read from it by GridCraft).
+/// Anything unreadable is left out: the cells are what matter.
+pub(crate) fn import(bytes: &[u8], wb: &mut Workbook) {
+ let Ok(mut cfb) = cfb::CompoundFile::open(std::io::Cursor::new(bytes)) else { return };
+ let mut data = Vec::new();
+ {
+ let Ok(mut stream) = cfb.open_stream("Workbook").or_else(|_| cfb.open_stream("Book")) else { return };
+ if stream.by_ref().take(512 << 20).read_to_end(&mut data).is_err() {
+ return;
+ }
+ }
+ let g = globals(&data);
+ let mut taken = 0usize;
+ let mut next_id = 10_000u32;
+ for bound in g.bounds.iter().filter(|b| b.worksheet) {
+ let Some(index) = wb.sheets.iter().position(|s| s.name == bound.name) else { continue };
+ let (drawing, objects) = sheet_objects(&data, bound.at, &g);
+ if objects.is_empty() {
+ continue;
+ }
+ let mut found = Vec::new();
+ shapes(&drawing, &mut found, 0);
+ let sheet = Arc::make_mut(&mut wb.sheets[index]);
+ let mut charts = Vec::new();
+ let mut images = Vec::new();
+ for (shape, (kind, chart)) in found.into_iter().zip(objects) {
+ if taken >= MAX_OBJECTS {
+ break;
+ }
+ let Some(anchor) = shape.anchor.and_then(|a| anchor_on(sheet, a)) else { continue };
+ match (kind, chart) {
+ // a picture
+ (8, _) => {
+ let Some(p) = shape.picture.and_then(|i| g.pictures.get((i as usize).checked_sub(1)?)?.as_ref()) else { continue };
+ next_id += 1;
+ taken += 1;
+ images.push(Image { id: next_id, anchor, data: Arc::new(p.data.clone()), mime: p.mime.to_string(), alt: String::new() });
+ }
+ // a chart
+ (5, Some(bits)) => {
+ let series: Vec<Series> = bits
+ .series
+ .into_iter()
+ .filter_map(|s| Some(Series { name: s.name, categories: s.categories, values: s.values?, ..Default::default() }))
+ .collect();
+ if series.is_empty() {
+ continue;
+ }
+ next_id += 1;
+ taken += 1;
+ let kind = bits.kind.unwrap_or_default();
+ let round = matches!(kind, ChartKind::Pie | ChartKind::Doughnut);
+ charts.push(Chart {
+ id: next_id,
+ kind,
+ anchor,
+ title: bits.title,
+ series,
+ legend: bits.legend.unwrap_or(LegendPos::None),
+ data_labels: false,
+ data_table: None,
+ gridlines: !round,
+ style: 2,
+ hole_size: if bits.hole > 0 { bits.hole.max(10) } else { 50 },
+ first_slice_angle: bits.angle,
+ x_title: bits.x_title,
+ y_title: bits.y_title,
+ source: None,
+ by_rows: false,
+ pivot: None,
+ });
+ }
+ _ => {}
+ }
+ }
+ sheet.images.extend(images);
+ sheet.charts.extend(charts);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn column_names_go_past_z() {
+ assert_eq!(col_name(0), "A");
+ assert_eq!(col_name(25), "Z");
+ assert_eq!(col_name(26), "AA");
+ assert_eq!(col_name(701), "ZZ");
+ assert_eq!(col_name(702), "AAA");
+ }
+
+ #[test]
+ fn a_chart_reference_names_its_sheet_and_cells() {
+ let g = Globals {
+ bounds: vec![Bound { at: 0, worksheet: true, name: "Sales Q1".into() }, Bound { at: 0, worksheet: true, name: "It's".into() }],
+ xti: vec![0, 1],
+ pictures: Vec::new(),
+ };
+ // PtgArea3d: ixti 0, rows 1..=4, column B
+ let area = [0x3B, 0, 0, 1, 0, 4, 0, 1, 0xC0, 1, 0xC0];
+ assert_eq!(chart_ref(&area, &g).as_deref(), Some("'Sales Q1'!$B$2:$B$5"));
+ // PtgRef3d: ixti 1, row 0, column A
+ let one = [0x3A, 1, 0, 0, 0, 0, 0xC0];
+ assert_eq!(chart_ref(&one, &g).as_deref(), Some("'It''s'!$A$1"));
+ // PtgStr
+ let s = [0x17, 3, 0, b'T', b'o', b'p'];
+ assert_eq!(chart_ref(&s, &g).as_deref(), Some("\"Top\""));
+ }
+}
diff --git a/engine/mobile/tests/data/charts.xls b/engine/mobile/tests/data/charts.xls
new file mode 100644
index 0000000..fdfd53f
Binary files /dev/null and b/engine/mobile/tests/data/charts.xls differ
diff --git a/engine/mobile/tests/data/charts.xlsx b/engine/mobile/tests/data/charts.xlsx
new file mode 100644
index 0000000..c67a8d9
Binary files /dev/null and b/engine/mobile/tests/data/charts.xlsx differ