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.

Liquid glass morph, home screen widgets, Office additions

chethan616d55d04f3ad80
diff --git a/PLAN.md b/PLAN.md
index 7416ac1..f122576 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -87,18 +87,44 @@ bot-avatars) for empty, waiting and error states only.
## Next (UI first)
-- [ ] Viewer: check every tool sheet against the new sheet parts (VoiceSheet, NoteSheet, ReadAloud,
- DigitalSign, FillSign still use their own layouts inside `PdfSheet`); CommentList, Pages screens.
-- [ ] (2026-11-14, `fast` 3.0.0-beta.10 on the OnePlus: welcome, desk, + fan, Files, Tools, viewer and the Fill & Sign bar all drew and animated correctly; Crystal style, Jelly mic and the long-press sheet not yet looked at) Device check of the four 2026-11-06 passes on the `fast` build (pass 4: Crystal + / welcome page 2 / Jelly mic / long-press sheet) (no phone was attached): welcome swipe
+- [x] Viewer: every tool sheet checked against the new sheet parts (2026-11-15): VoiceSheet now uses
+ `SheetHeader`, DigitalSign's list is a `SheetSection`, FillSign has a `SheetTitle`; CommentList,
+ Pages, Save as already used them; NoteSheet, ReadAloud and CommentPanel are docked bars, not
+ sheets. Built and installed; [ ] not yet looked at on the phone.
+- [ ] (2026-11-14, `fast` 3.0.0-beta.10 on the OnePlus: welcome, desk, + fan, Files, Tools, viewer and the Fill & Sign bar all drew and animated correctly; Crystal style and Jelly mic not yet looked at; 2026-11-15: the file row's sheet in Files drew correctly on the `fast` build, as did the dark sheet viewer) Device check of the four 2026-11-06 passes on the `fast` build (pass 4: Crystal + / welcome page 2 / Jelly mic / long-press sheet) (no phone was attached): welcome swipe
smoothness, + fan with a busy desk, menu/dialog/sheet/toast springs, recorder pill expand/shrink
bounce (tune `GlassMotion.shape` stiffness if still too quick/slow), GlassChip rows, dark theme.
- [x] Files / Tools / Settings checked against the mocks on the phone (2026-11-14): same glass, type and
colour as the mocks, nothing to change.
-- [ ] Collection deck (mock 2) for Pdf & notes.
- [x] Signature validation badges drawn by the viewer (Acrobat-style tick), never in the file.
- [x] Translations: ar, de, es, fr, it, pt-BR complete + **pt** and **ru**.
- [x] Folder restructure, README/NOTICE/ATTRIBUTION/fastlane to Artefact (9 store languages).
- [ ] Release build, `master` branch on GitHub, "Building the version 2" issue + discussion.
+ (2026-11-15: [x] the arm64 release APK builds and is signed with the Play upload key, 95 MB, from
+ this branch; the issue/discussion text is drafted locally; [ ] nothing pushed or published.)
+
+- [x] Home screen widgets (2026-11-15): **Thought of the day / Notes** (square, 2×2 to 3×3), **To-Do** and
+ **Recent** (square, 2×2 to 3×3, opening at 3×3 where the desk card shows whole). Each is the desk's own composable (`ListCard`, `NoteCard`,
+ `RecentCard`, real liquid glass, the user's glass settings) rendered off screen on a private
+ virtual display (`widget/ComposeSnapshot.kt`) at the widget's own size, Apple style: never
+ scaled, the content adapts (fewer pills + "N more"; the note's body gives way to the date; the
+ fan of pages shrinks). To-Do pills tick from the home screen (tap targets over the real pills,
+ press ripple, the app's ToggleOn/Off haptic, ticks go through the app's live notes when it runs).
+ Recent is drawn by the app when its recents change (thumbnails live there) and kept in cache.
+ Seen on the phone. A widget can't run live glass or its press springs: home screens only show
+ pictures and send taps.
+- [x] `MorphButton` (2026-11-15, `ui/glass/MorphButton.kt` + `LiquidMorph.kt`; GlassMenu left as it was): the
+ viewer's ⋯ circle itself becomes its menu, as liquid glass (iOS 26 GlassEffectContainer idea, from
+ StewartLynch/Liquid-Glass-Controls-And-Views `Completed`): one shape made of the circle and a rounded
+ rectangle melted by a smooth minimum of their distance fields (AGSL refraction + surface shaders on
+ that outline). Three springs, each starting as the one before settles: drip (a narrower drop runs
+ ~1 cm down out of the circle, joined by a liquid neck), spread (to the menu's width), pour (to its
+ height; the circle melts away, only the menu is left over the button's place). ~0.7 s; close runs it
+ back. Ink adapts to what is behind (white over Night mode). Android 13+; older phones get the plain
+ rounded-rectangle expansion. Seen on the phone, frame by frame at 10x animator scale.
+- [ ] Widgets left to look at on the phone: To-Do's scrolling list (`RemoteCollectionItems` of the real
+ pills; card hugs title + pills, scrolls past the widget's height; seen hugging, ticks through the
+ list not yet tried), Recent drawn at the desk card's exact size and fitted (built, not seen).
## Folder layout
@@ -145,12 +171,12 @@ all three → editing, one format at a time, each built and run on the phone bef
.xlsx/.xlsb/.ods/.csv (recalculated on open) and serves tabs, axes, cell windows with looks,
merges, find; `ui/sheets/SheetViewer.kt` draws the grid on a canvas (pan, pinch zoom, heading
strips, frozen panes, cells in 50×20 blocks) under glass. [x] seen on the phone 2026-11-14 (an .xlsx and a Cyrillic .xls: merges, fills, borders, bars); [x] search UI
- (bridge `sheet_find` is there); [ ] charts (gridcraft-chart) and pictures on sheets.
+ (bridge `sheet_find` is there); [x] charts (gridcraft-chart, `SheetCharts.kt`) and pictures on sheets (`sheetPictures`) are in the code; [ ] not yet seen on the phone.
- [x] **Pictures in notes** (lightcraft `8a0b91a`, 2026-11-07, built and host-tested): `photo.rs`
(`PhotoEditor`: decode, develop with LightCraft's `DevelopSettings` JSON, export JPEG; codecs,
develop, pipeline only: no GPU, faces or catalog). Tap a note's picture: glass editor with
Exposure, Contrast, Highlights, Shadows, Vibrance, Saturation and rotate; Done saves a new JPEG.
- [ ] seen on the phone; [ ] crop; [ ] markup.
+ [x] seen on the phone 2026-11-15 (opens from Files with Adjust, Crop, Blur, Draw, Text); [x] crop (`PhotoEditor.kt`, LightCraft's crop model; not yet seen on the phone); [x] markup: a freehand **Draw** pen (width, ten colours, undo; `Pen` mark in `PhotoMarks.kt`, saved with the picture; stroke drawing seen on the phone, saving not tried).
- [x] **Export and print for all three** (2026-11-07): `export_office(doc, format, path)` /
`export_formats(doc)`: Word → pdf, docx, odt, rtf, html, md, txt; slides → pdf, pptx; sheets →
pdf (gridcraft's `file.exportPdf`, every sheet), xlsx, csv. Office bars: Word = Read aloud ·
@@ -159,7 +185,11 @@ all three → editing, one format at a time, each built and run on the phone bef
[x] checked gridcraft's PDF with non-Latin text 2026-11-14: **fails**. A Cyrillic .xls exports with
the text missing (digits and Latin show). gridcraft's `pdf` crate uses the 14 standard fonts and,
for anything WinAnsi lacks, a non-embedded Adobe CID font, which the viewer cannot draw. Needs
- embedded fonts in the export (a patch to the vendored crate); not done.
+ embedded fonts in the export: **fixed 2026-11-15** by vendoring `gridcraft-pdf` with Source Sans 3
+ subsets embedded (Cyrillic, Greek, Latin Extended; CJK/Arabic/Indic still use the old fallback).
+ [x] seen on the phone 2026-11-15: a Cyrillic + Greek .csv exports (17.5 KB) and the PDF shows all
+ the text in the viewer. Sheets in the dark theme use Google Sheets' neutral greys (#1F1F1F ground,
+ #3C4043 lines, #2D2E30 headings) instead of the indigo.
- [x] **Editing, first pass** (2026-11-07, built, host-tested, not yet seen on the phone):
Word: Edit → tap places the caret, the keyboard types, glass dock (undo, redo, bold, italic,
underline, bullets, numbering, align, heading, body); saved in its own format. Sheets: tap a
@@ -167,6 +197,14 @@ all three → editing, one format at a time, each built and run on the phone bef
(bold, italic, fill, align, wrap, %, thousands, insert row/column, clear, undo, redo); ⋯ menu:
Export PDF, Save as, Print, Share; Quick Preview shows the real grid. `.xls` opens; `.ppt`
explains itself (DeckCraft has no 97-2003 reader). Selection menu = the desk menu's frosted glass.
+- [x] Word's navigation pane (2026-11-15): a document's headings (outline levels) fill Bookmarks &
+ Contents with their pages (`headings_of` in `word.rs`, `OfficeDoc::outline`); seen on the phone
+ (the sample's Summary, Figures, Next year; tapping one jumps to its page). Test:
+ `a_word_document_lists_its_headings_with_their_pages`.
+- [x] Slide notes and thumbnails (2026-11-15): More ▸ Speaker notes opens a sheet with the slide in
+ view's notes (`slide_notes` in the bridge, `SlideNotesSheet`); the sheet seen on the phone on a
+ 21-slide deck (that deck has no notes, so only the empty state was seen; the notes text is
+ covered by `a_slide_reports_its_speaker_notes`). Thumbnails: More ▸ Pages already lists slides.
- [ ] Map each engine's remaining features into the UI, one format at a time (they are large: Word
422 commands, slides 320, sheets 313, LightCraft's develop panel): next are Word's navigation
pane (headings), slide notes and thumbnails, sheet charts and pictures, LightCraft crop,
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 690a215..d2cc5c7 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -39,6 +39,50 @@
android:supportsRtl="true"
android:theme="@style/Theme.Artefact">
+ <activity
+ android:name=".widget.WidgetPickActivity"
+ android:exported="true"
+ android:excludeFromRecents="true"
+ android:taskAffinity=""
+ android:theme="@style/Theme.Artefact">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
+ </intent-filter>
+ </activity>
+ <receiver
+ android:name=".widget.TodoWidget"
+ android:exported="false"
+ android:label="@string/widget_todo_name">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+ </intent-filter>
+ <meta-data
+ android:name="android.appwidget.provider"
+ android:resource="@xml/widget_todo_info" />
+ </receiver>
+ <receiver
+ android:name=".widget.RecentWidget"
+ android:exported="false"
+ android:label="@string/widget_recent_name">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+ </intent-filter>
+ <meta-data
+ android:name="android.appwidget.provider"
+ android:resource="@xml/widget_recent_info" />
+ </receiver>
+ <receiver
+ android:name=".widget.NoteWidget"
+ android:exported="false"
+ android:label="@string/widget_note_name">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+ </intent-filter>
+ <meta-data
+ android:name="android.appwidget.provider"
+ android:resource="@xml/widget_note_info" />
+ </receiver>
+
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden|uiMode|density"
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 44816cb..704345b 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt
@@ -205,6 +205,9 @@ class MainActivity : ComponentActivity() {
// from Quick Preview: its own copy when Android didn't pass the original on
val local = intent?.getStringExtra(EXTRA_LOCAL_COPY)?.let(::File)?.takeIf { it.isFile && it.canonicalPath.startsWith(filesDir.canonicalPath) }
val fromPreview = intent?.getBooleanExtra(EXTRA_FROM_PREVIEW, false) == true
+ intent?.getStringExtra(com.chethan616.clearpdf.widget.EXTRA_OPEN_NOTE)?.let(vm::openNoteFromWidget)
+ intent?.getStringExtra(com.chethan616.clearpdf.widget.EXTRA_OPEN_RECENT)?.let { vm.open(Uri.parse(it)) }
+ if (intent?.getBooleanExtra(com.chethan616.clearpdf.widget.EXTRA_OPEN_FILES, false) == true) vm.homeTab = com.chethan616.clearpdf.ui.home.HomeTab.Files
when {
uri != null -> vm.open(uri, fromOtherApp = true, copy = local, fromPreview = fromPreview)
local != null -> vm.open(Uri.fromFile(local), fromOtherApp = true, fromPreview = fromPreview)
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 2640dce..b76f21f 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
@@ -55,6 +55,13 @@ data class Note(
* after each change, atomically). Media sits beside it in `files/notes/media`.
*/
class Notes(private val context: Context, private val scope: CoroutineScope) {
+ companion object {
+ /** The app's notes while its view model lives: widget ticks go through them. */
+ @Volatile
+ var live: Notes? = null
+ private set
+ }
+
private val dir = File(context.filesDir, "notes").apply { mkdirs() }
private val media = File(dir, "media").apply { mkdirs() }
private val store = File(dir, "notes.json")
@@ -67,6 +74,7 @@ class Notes(private val context: Context, private val scope: CoroutineScope) {
private var saveJob: Job? = null
init {
+ live = this
scope.launch {
val list = withContext(Dispatchers.IO) { runCatching { read() }.getOrDefault(emptyList()) }
all = list
@@ -136,6 +144,20 @@ class Notes(private val context: Context, private val scope: CoroutineScope) {
saveJob = scope.launch(Dispatchers.IO) {
delay(250)
runCatching { write(snapshot) }
+ // the home screen widgets show these notes too
+ runCatching { com.chethan616.clearpdf.widget.Widgets.refreshSoon(context) }
+ }
+ }
+
+ /** Whether these notes still belong to a living view model (its scope not cancelled). */
+ val isActive: Boolean get() = scope.coroutineContext[Job]?.isActive != false
+
+ /** Read the file again (a home screen widget may have ticked an item while the app was away). */
+ fun reload() {
+ if (saveJob?.isActive == true) return
+ scope.launch {
+ val list = withContext(Dispatchers.IO) { runCatching { read() }.getOrNull() } ?: return@launch
+ if (saveJob?.isActive != true && list != all) all = list
}
}
@@ -212,3 +234,46 @@ fun waveOf(levels: List<Float>, bars: Int = 48): List<Float> {
(0.12f + 0.88f * v).coerceIn(0.12f, 1f)
}
}
+
+/** The notes file read and changed without the app running: what the home screen widgets use. */
+object NoteFile {
+ /** Tick [itemId] through the app's notes when they are loaded (so the app never writes over it), else in the file. */
+ fun toggleLive(c: Context, noteId: String, itemId: String) {
+ val notes = Notes.live
+ if (notes != null && notes.loaded) {
+ android.os.Handler(android.os.Looper.getMainLooper()).post { notes.toggle(noteId, itemId) }
+ } else {
+ toggle(c, noteId, itemId)
+ }
+ }
+
+ private fun store(c: Context) = File(File(c.filesDir, "notes"), "notes.json")
+
+ fun read(c: Context): List<Note> {
+ val f = store(c)
+ if (!f.exists()) return emptyList()
+ return runCatching {
+ val arr = JSONArray(f.readText())
+ (0 until arr.length()).mapNotNull { i -> runCatching { arr.getJSONObject(i).toNote() }.getOrNull() }
+ }.getOrDefault(emptyList())
+ }
+
+ /** Tick or untick [itemId] of [noteId]; false when either is gone. */
+ @Synchronized
+ fun toggle(c: Context, noteId: String, itemId: String): Boolean {
+ val all = read(c)
+ val n = all.firstOrNull { it.id == noteId } ?: return false
+ if (n.items.none { it.id == itemId }) return false
+ val changed = n.copy(items = n.items.map { if (it.id == itemId) it.copy(done = !it.done) else it }, updated = System.currentTimeMillis())
+ val arr = JSONArray()
+ (all.map { if (it.id == noteId) changed else it }).forEach { arr.put(it.toJson()) }
+ val dir = File(c.filesDir, "notes")
+ val tmp = File(dir, "notes.json.tmp")
+ tmp.writeText(arr.toString())
+ if (!tmp.renameTo(store(c))) {
+ store(c).delete()
+ tmp.renameTo(store(c))
+ }
+ return true
+ }
+}
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 4a7f86e..f326839 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
@@ -460,12 +460,15 @@ private fun Header(
}
}
if (ready != null || picture != null || map != null) {
- QuietButton(
- { menu = true }, stringResource(R.string.common_more_options),
- Modifier.onGloballyPositioned { anchor = it.boundsInWindow() },
- ) { Icon(LucideIcons.Ellipsis, null, tint = c.ink, modifier = Modifier.size(20.dp)) }
+ // the app's liquid glass buttons (More opens its menu out of itself, as everywhere)
+ com.chethan616.clearpdf.ui.glass.GlassCircle(
+ onClick = { menu = true }, size = 38.dp, label = stringResource(R.string.common_more_options), ink = c.ink,
+ modifier = Modifier.onGloballyPositioned { anchor = it.boundsInWindow() },
+ ) { com.chethan616.clearpdf.ui.glass.GlassIcon(LucideIcons.Ellipsis, null, Modifier.size(20.dp)) }
+ }
+ com.chethan616.clearpdf.ui.glass.GlassCircle(onClick = onClose, size = 38.dp, label = stringResource(R.string.preview_close), ink = c.ink) {
+ com.chethan616.clearpdf.ui.glass.GlassIcon(LucideIcons.X, null, Modifier.size(18.dp))
}
- QuietButton(onClose, stringResource(R.string.preview_close)) { Icon(LucideIcons.X, null, tint = c.ink, modifier = Modifier.size(18.dp)) }
}
}
if (menu) {
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 49b5624..b6ea4a1 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
@@ -120,6 +120,8 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
runCatching { files.pruneCopies(list.map { it.uri }, open) }
}
}
+ // the home screen's Recent widget is the desk's Recent card
+ runCatching { com.chethan616.clearpdf.widget.Widgets.refreshRecent(this@AppViewModel) }
}
}
@@ -3087,7 +3089,16 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
}
/** Back from the access page (or the app resumed): look again. */
+ /** A note a home screen widget asked for, opened once the notes have loaded. */
+ fun openNoteFromWidget(id: String) {
+ viewModelScope.launch {
+ snapshotFlow { notes.loaded }.first { it }
+ if (notes.get(id) != null) openNote = id
+ }
+ }
+
fun onResumed() {
+ notes.reload()
val had = hasFileAccess
hasFileAccess = com.chethan616.clearpdf.engine.LocalFiles.hasAccess(getApplication())
if (hasFileAccess && !had) scanLocal(force = true)
@@ -3142,6 +3153,9 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
return all.filter { q in it.name.lowercase() }.distinctBy { it.key }.distinctBy { sameFile(it.name, it.size) }
}
+ /** Where [uri] lives, as Files names it ("Downloads", "This device" …). */
+ fun locationOfDocument(uri: String): String = locationOf(uri)
+
private fun locationOf(uri: String): String = runCatching { files.displayLocation(Uri.parse(uri)) }.getOrDefault(text(R.string.files_location_this_device))
fun clearRecents() {
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Buttons.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Buttons.kt
index 2f23093..aa5a878 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Buttons.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Buttons.kt
@@ -1,5 +1,15 @@
package com.chethan616.clearpdf.ui.glass
+import androidx.compose.ui.draw.drawWithContent
+
+import androidx.compose.runtime.setValue
+
+import androidx.compose.ui.graphics.graphicsLayer
+
+import androidx.compose.ui.layout.boundsInWindow
+
+import androidx.compose.ui.layout.onGloballyPositioned
+
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
@@ -338,9 +348,26 @@ fun GlassCircle(
) {
// over a document the glyph takes dark or white ink from the page around it, as the old app's
val probe = if (tint.isSpecified) InkProbe(Modifier, Color.White) else rememberGlassInk(if (ink.isSpecified) ink else clear.ink)
+ // where it is, so a menu it opens can grow out of it (MorphButtonSurface) and it can step aside meanwhile
+ var at by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
+ val glyph by androidx.compose.runtime.rememberUpdatedState(content)
+ val inkNow = probe.color
+ androidx.compose.runtime.DisposableEffect(at) {
+ val r = at
+ if (r != null) {
+ MorphAnchors.register(r) { CompositionLocalProvider(LocalGlassInk provides inkNow) { glyph() } }
+ MorphAnchors.setTint(r, tint)
+ }
+ onDispose { if (r != null) MorphAnchors.unregister(r) }
+ }
CompositionLocalProvider(LocalGlassInk provides probe.color) {
Box(
- modifier.then(probe.modifier).size(size).glassControl(CircleShape, onClick, onLongClick, tint, surface, 2.dp, label, tap = tap, bloom = true, candyBase = false),
+ modifier.then(probe.modifier)
+ .onGloballyPositioned { at = it.boundsInWindow() }
+ // stepped aside while its glass is a menu: not drawn at all (a layer's alpha alone left it in
+ // the copy of the screen the menu's glass bends, where the lens smeared its glyph)
+ .drawWithContent { if (at?.let { MorphAnchors.hides(it) } != true) drawContent() }
+ .size(size).glassControl(CircleShape, onClick, onLongClick, tint, surface, 2.dp, label, tap = tap, bloom = true, candyBase = false),
contentAlignment = Alignment.Center,
) { content() }
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/LiquidMorph.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/LiquidMorph.kt
new file mode 100644
index 0000000..2c5cab0
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/LiquidMorph.kt
@@ -0,0 +1,461 @@
+package com.chethan616.clearpdf.ui.glass
+
+import android.graphics.RuntimeShader
+import android.os.Build
+import androidx.activity.compose.BackHandler
+import androidx.annotation.RequiresApi
+import androidx.compose.animation.core.Animatable
+import androidx.compose.animation.core.spring
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.systemBars
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.wrapContentHeight
+import androidx.compose.foundation.layout.wrapContentWidth
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.remember
+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.clip
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.RectangleShape
+import androidx.compose.ui.graphics.isSpecified
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ShaderBrush
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.onGloballyPositioned
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalView
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.util.lerp
+import com.chethan616.clearpdf.ui.theme.clear
+import com.kyant.backdrop.drawBackdrop
+import com.kyant.backdrop.effects.runtimeShaderEffect
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.roundToInt
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+
+/**
+ * The shape of liquid glass made of two pieces, as iOS 26's GlassEffectContainer joins them: the
+ * button's circle and the menu's rounded rectangle, melted into one by a smooth minimum (a metaball
+ * union) of their distance fields. While they are close, a neck of glass joins them; as [k] falls it
+ * thins and lets go.
+ */
+private const val LiquidSdf = """
+uniform float4 circle;
+uniform float4 rect;
+uniform float rectRadius;
+uniform float k;
+
+float sdCircle(float2 p, float2 c, float r) { return length(p - c) - r; }
+
+float sdRRect(float2 p, float4 b, float r) {
+ float2 c = (b.xy + b.zw) * 0.5;
+ float2 hs = max((b.zw - b.xy) * 0.5, float2(0.0));
+ float rr = min(r, min(hs.x, hs.y));
+ float2 q = abs(p - c) - (hs - float2(rr));
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - rr;
+}
+
+float smin(float a, float b, float kk) {
+ if (kk <= 0.001) return min(a, b);
+ float h = clamp(0.5 + 0.5 * (b - a) / kk, 0.0, 1.0);
+ return mix(b, a, h) - kk * h * (1.0 - h);
+}
+
+float sdLiquid(float2 p) {
+ return smin(sdCircle(p, circle.xy, circle.z), sdRRect(p, rect, rectRadius), k);
+}
+
+float2 gradLiquid(float2 p) {
+ float e = 1.0;
+ float2 g = float2(sdLiquid(p + float2(e, 0.0)) - sdLiquid(p - float2(e, 0.0)),
+ sdLiquid(p + float2(0.0, e)) - sdLiquid(p - float2(0.0, e)));
+ float l = length(g);
+ return l > 0.0001 ? g / l : float2(0.0, -1.0);
+}
+"""
+
+/** The glass's bending of what is behind it, along the liquid shape's edge (the app's lens, on a melted outline). */
+private const val LiquidRefractionShader = """
+uniform shader content;
+uniform float2 offset;
+uniform float refractionHeight;
+uniform float refractionAmount;
+uniform float depth;
+uniform float dispersion;
+$LiquidSdf
+
+float circleMap(float x) { return 1.0 - sqrt(max(1.0 - x * x, 0.0)); }
+
+// the same bend and colour split as the app's own glass (backdrop's rounded-rect refraction shaders),
+// on the liquid outline: the split only toward the corners, a pixel or two, three taps
+half4 main(float2 coord) {
+ float2 p = coord + offset;
+ float sd = sdLiquid(p);
+ if (sd > 1.0) return half4(0.0);
+ float cover = clamp(0.5 - sd, 0.0, 1.0);
+ if (-sd >= refractionHeight) return content.eval(coord) * cover;
+ float d = circleMap(1.0 - (-min(sd, 0.0)) / refractionHeight) * refractionAmount;
+ // the centre and size each part of the glass bends around: the circle's own for the circle, the
+ // menu's for the menu, blended across the neck (one centre for both bent the circle the wrong way)
+ float dc = sdCircle(p, circle.xy, circle.z);
+ float dr = sdRRect(p, rect, rectRadius);
+ float w = clamp(0.5 + 0.5 * (dr - dc) / max(k, 1.0), 0.0, 1.0);
+ float2 rc = (rect.xy + rect.zw) * 0.5;
+ float2 rh = max((rect.zw - rect.xy) * 0.5, float2(1.0));
+ float2 center = mix(rc, circle.xy, w);
+ float2 halfSize = mix(rh, float2(max(circle.z, 1.0)), w);
+ float2 centered = p - center;
+ float2 g = gradLiquid(p);
+ if (depth > 0.5 && length(centered) > 0.001) g = normalize(g + normalize(centered));
+ float2 refracted = coord - d * g;
+ if (dispersion > 0.5) {
+ float intensity = clamp((centered.x * centered.y) / max(halfSize.x * halfSize.y, 1.0), -1.0, 1.0);
+ float2 dc = -d * g * intensity;
+ if (dot(dc, dc) >= 0.25) {
+ half4 r = content.eval(refracted + dc * 0.4286);
+ half4 gg = content.eval(refracted + dc * 0.0952);
+ half4 bl = content.eval(refracted - dc * 0.6667);
+ return half4(r.r, gg.g, bl.b, (r.a + gg.a + bl.a) / 3.0) * cover;
+ }
+ }
+ return content.eval(refracted) * cover;
+}
+"""
+
+/** The glass's wash and its lit rim, on the same melted outline. */
+private const val LiquidSurfaceShader = """
+uniform float4 wash;
+uniform float rimAlpha;
+$LiquidSdf
+
+half4 main(float2 p) {
+ float sd = sdLiquid(p);
+ float cover = clamp(0.5 - sd, 0.0, 1.0);
+ if (cover <= 0.0) return half4(0.0);
+ float2 g = gradLiquid(p);
+ float2 light = normalize(float2(-0.55, -1.0));
+ float facing = max(dot(g, light), 0.0) + 0.45 * max(dot(-g, light), 0.0);
+ float rim = (1.0 - smoothstep(0.0, 1.8, -sd)) * rimAlpha * (0.35 + 0.65 * facing);
+ float a = wash.a * cover;
+ float r = rim * cover;
+ half3 col = half3(wash.rgb) * a + half3(1.0) * r;
+ return half4(col, a + r * (1.0 - a));
+}
+"""
+
+/**
+ * [MorphButtonSurface] on Android 13 and later: the menu's glass flows out of the round button, as iOS
+ * 26's glass does with a matched-geometry transition in a glass container. It starts as the button,
+ * slides and grows to its place just below (or above) the button, and while the two are close they
+ * are one piece of glass joined by a neck that thins and lets go as the menu settles. Closing, the menu
+ * flows back up into the button and melts into it. The glass refracts along that liquid outline,
+ * reads what is behind it (dark ink over light, white over dark) and follows the user's glass style.
+ */
+@RequiresApi(Build.VERSION_CODES.TIRAMISU)
+@Composable
+internal fun LiquidMorphSurface(
+ anchor: Rect,
+ open: Boolean,
+ onDismiss: () -> Unit,
+ onGone: () -> Unit,
+ items: List<GlassMenuItem>,
+ menuWidth: Dp,
+ maxHeight: Dp,
+ icon: @Composable () -> Unit,
+) {
+ val gone by rememberUpdatedState(onGone)
+ GlassOverlay(animatesOut = true) {
+ val presence = LocalOverlayPresence.current
+ val shut = !open || presence?.leaving == true
+ // removed from the portal for good (finished or cut short): the button is back either way
+ androidx.compose.runtime.DisposableEffect(Unit) { onDispose { gone() } }
+ // the button's own tint (a blue Done, a candy button): the glass keeps it at both ends
+ val tint = MorphAnchors.tintAt(anchor) ?: Color.Unspecified
+ BackHandler(enabled = !shut, onBack = onDismiss)
+ val host = LocalGlassOverlayHost.current ?: return@GlassOverlay
+ val bars = WindowInsets.systemBars
+ val view = LocalView.current
+ val density = LocalDensity.current
+
+ // The circle itself becomes the menu, in three flowing movements, each starting as the one before
+ // settles: it drips (a drop of glass runs down out of the circle, about a centimetre, joined to it
+ // by a liquid neck), it spreads (the drop widens to the menu's full width, the circle melting into
+ // it), it pours (down to the menu's full height). At rest there is only the menu, lying where the
+ // button was. Closing runs it all back into the circle.
+ // One motion, not three: a single spring drives the whole morph, and the three movements are
+ // overlapping slices of it, so the speed flows from one into the next with no stop between them
+ // (gated springs read as a machine). The spring's swell past 1 lands in the pour, as glass settling.
+ val p = remember { Animatable(0f) }
+ // a row chosen: the menu folds back into its button first, and the row's action runs only once
+ // it is the button again (a row that opens Tools, Settings … never leaves glass on the next screen)
+ var chosenAction by remember { androidx.compose.runtime.mutableStateOf<(() -> Unit)?>(null) }
+ val runChosen = {
+ val a = chosenAction
+ chosenAction = null
+ a?.invoke()
+ Unit
+ }
+ val fade = remember { Animatable(1f) }
+ LaunchedEffect(shut) {
+ if (!shut) {
+ // the very spring the close runs on (the owner liked its states and pace): the opening is
+ // the close played backwards
+ p.animateTo(1f, spring(1f, MotionSettings.stiffness(129f), 0.0005f))
+ } else {
+ // its button gone with its screen: dissolve too, never fold into a place that is no longer there
+ if (MorphAnchors.glyphAt(anchor) == null) fade.animateTo(0f, androidx.compose.animation.core.tween(150))
+ // an option picked: a quicker fold that ends the moment it looks landed (the action waits on
+ // it); dismissed: the unhurried fold
+ else if (chosenAction != null) p.animateTo(0f, spring(1f, MotionSettings.stiffness(260f), 0.03f))
+ else p.animateTo(0f, spring(1f, MotionSettings.stiffness(129f), 0.01f))
+ // the glass has landed: the real button takes its place and the morph is gone before the
+ // row's action starts (an action that changes screen would otherwise slide the button away
+ // while the morph's circle stayed put: two circles); then the action
+ gone()
+ presence?.done()
+ val action = chosenAction
+ chosenAction = null
+ // straight after (on the next frame, once the morph has left the screen)
+ if (action != null) android.os.Handler(android.os.Looper.getMainLooper()).post { action() }
+ }
+ }
+ /** 0 while the glass is still the button's circle, 1 once it is liquid (raw progress, both ways). */
+ fun liquidIn(): Float { val c = (p.value / 0.12f).coerceIn(0f, 1f); return c * c * (3f - 2f * c) }
+ fun ease(x: Float): Float { val c = x.coerceIn(0f, 1f); return c * c * (3f - 2f * c) }
+
+ androidx.compose.foundation.layout.Box(Modifier.fillMaxSize().clickable(remember { MutableInteractionSource() }, null, onClick = onDismiss))
+ val local = Rect(host.windowToLocal(anchor.topLeft), host.windowToLocal(anchor.bottomRight))
+ val px = { d: Dp -> with(density) { d.toPx() } }
+ val widthPx = px(menuWidth)
+ var full by remember { mutableIntStateOf(0) }
+ val menuH = if (full > 0) full.toFloat() else local.height * 4f
+
+ // the menu's place: over the button, from its corner (iOS 26), kept off the bars
+ val origin = host.originInWindow
+ val root = view.rootView
+ val barTop = (bars.getTop(density) - origin.y).coerceAtLeast(0f)
+ val barBottom = (bars.getBottom(density) - (root.height - origin.y - view.height)).coerceAtLeast(0f)
+ val margin = px(12.dp)
+ val screenW = view.width.toFloat()
+ val screenH = view.height.toFloat()
+ val fromRight = local.center.x > screenW / 2f
+ val below = local.top + menuH < screenH - barBottom - margin
+ val endL = (if (fromRight) local.right - widthPx else local.left).coerceIn(margin, (screenW - widthPx - margin).coerceAtLeast(margin))
+ val endT = (if (below) local.top else local.bottom - menuH).coerceIn(barTop + margin, (screenH - barBottom - menuH - margin).coerceAtLeast(barTop + margin))
+ val endR = endL + widthPx
+ val endB = endT + menuH
+ val r0 = min(local.width, local.height) / 2f
+ // how far the drop runs down before it spreads: about 1.8 cm (less if the menu is shorter)
+ val peek = (androidx.compose.ui.platform.LocalContext.current.resources.displayMetrics.ydpi / 2.54f * 1.8f).coerceAtMost((menuH - local.height).coerceAtLeast(0f))
+ val swellPx = px(6.dp)
+ val radius24 = px(24.dp)
+ val neckPx = px(22.dp)
+ val opening = !shut
+
+ // The glass is ONE node of a fixed size for the whole morph (the button and the menu's place,
+ // with room for the lens and the swell): nothing is laid out, resized or re-allocated per frame.
+ // Each frame only the shape (shader uniforms) and the clip change, read in draw.
+ val pad = px(28.dp)
+ val stage = Rect(min(local.left, endL) - pad, min(local.top, endT) - pad - swellPx, max(local.right, endR) + pad, max(local.bottom, endB) + pad + swellPx)
+
+ /** Where everything is this frame (read only in draw and layer blocks). */
+ class Geo(val menu: Rect, val radius: Float, val k: Float, val circleR: Float, val motion: Float)
+ fun geo(): Geo {
+ val raw = p.value
+ // opening, time runs slow at first (the drop gathers) and then at its normal pace through the
+ // spread and the pour; closing runs straight, as it is
+ // the same path both ways (no slow start on the way out)
+ val pv = raw
+ val d = ease(pv / 0.38f)
+ val sp = ease((pv - 0.16f) / 0.46f)
+ // the pour is left unclamped above, so the spring's settle shows as a swell of a few dp at most
+ val pourV = if (pv >= 1f) 1f + (pv - 1f) / 0.6f else ease((pv - 0.36f) / 0.64f)
+ val swellCap = swellPx / (menuH - local.height).coerceAtLeast(1f)
+ val po = if (full > 0) (if (pourV > 1f) 1f + min(pourV - 1f, swellCap) else pourV) else 0f
+ // the drop is born inside the circle (a small core at its middle) and grows out of it, and sinks
+ // back into it the same way: it never sits beside the circle as a bubble of its own
+ val dc = d.coerceIn(0f, 1f)
+ val dropW = lerp(local.width * 0.5f, local.width * 0.86f, dc)
+ val rl = lerp(local.center.x - dropW / 2f, endL, sp)
+ val rr = lerp(local.center.x + dropW / 2f, endR, sp)
+ val menu = if (below) {
+ val top = lerp(local.center.y - local.height * 0.25f, endT, sp)
+ val bottom = lerp(local.center.y + local.height * 0.25f, local.bottom + peek, d) + (endB - local.bottom - peek) * po
+ Rect(rl, min(top, bottom - 1f), rr, max(bottom, top + 1f))
+ } else {
+ val bottom = lerp(local.center.y + local.height * 0.25f, endB, sp)
+ val top = lerp(local.center.y - local.height * 0.25f, local.top - peek, d) - (local.top - peek - endT) * po
+ Rect(rl, min(top, bottom - 1f), rr, max(bottom, top + 1f))
+ }
+ val radius = min(min(menu.width, menu.height) / 2f, lerp(r0, radius24, po.coerceIn(0f, 1f)))
+ // a liquid neck joins the circle and the drop while the drop is out of it, and fades as the
+ // circle melts into the menu
+ val apart = (d / 0.35f).coerceIn(0f, 1f)
+ val k = neckPx * apart * apart * (3f - 2f * apart) * (1f - po.coerceIn(0f, 1f))
+ val circleR = r0 * (1f - po.coerceIn(0f, 1f)).coerceAtLeast(0f)
+ val motion = kotlin.math.sin(Math.PI.toFloat() * ((d + sp + po) / 3f).coerceIn(0f, 1f))
+ return Geo(menu, radius, k, circleR, motion)
+ }
+
+ val luminance = rememberGlassLuminance(enabled = true)
+ val ink = adaptiveInk(luminance, clear.ink)
+ val style = GlassSettings.style
+ val dark = clear.dark
+ val surface = remember { RuntimeShader(LiquidSurfaceShader) }
+ val rimAlpha = (if (dark) 0.32f else 0.6f) * style.highlight.coerceIn(0f, 1f)
+ // the menu's milk or smoke comes in as it opens and is gone by the time it is the circle again
+ fun washIn() = ((p.value - 0.08f) / 0.4f).coerceIn(0f, 1f)
+ // the luminance reading copies the backdrop: every few frames is plenty (its ink eases anyway)
+ val frame = remember { intArrayOf(0) }
+
+ fun RuntimeShader.shapeUniforms(g: Geo) {
+ setFloatUniform("circle", local.center.x - stage.left, local.center.y - stage.top, g.circleR, 0f)
+ setFloatUniform("rect", g.menu.left - stage.left, g.menu.top - stage.top, g.menu.right - stage.left, g.menu.bottom - stage.top)
+ setFloatUniform("rectRadius", g.radius)
+ setFloatUniform("k", g.k)
+ }
+
+ Box(
+ Modifier
+ .offset { IntOffset(stage.left.roundToInt(), stage.top.roundToInt()) }
+ .size(with(density) { stage.width.toDp() }, with(density) { stage.height.toDp() })
+ .graphicsLayer { alpha = fade.value * liquidIn() }
+ .drawBackdrop(
+ backdrop = LocalBackdrop.current,
+ shape = { RectangleShape },
+ effects = {
+ val g = geo()
+ // the button's own colour and frost (as GlassCircle's), never a different tone
+ glassEffects(style, px(lerp(2f, 12f, washIn()).dp), 0f, 0f)
+ runtimeShaderEffect("LiquidMorphRefraction", LiquidRefractionShader, "content") {
+ setFloatUniform("offset", -padding, -padding)
+ // the button's own lens (12 / 24 dp at the user's style), a little livelier while it moves
+ setFloatUniform("refractionHeight", px((12f + 2f * g.motion).dp) * style.refractionHeight)
+ setFloatUniform("refractionAmount", px((24f + 4f * g.motion).dp) * style.refractionAmount)
+ setFloatUniform("depth", if (style.depthEffect) 1f else 0f)
+ setFloatUniform("dispersion", if (style.chromaticAberration) 1f else 0f)
+ shapeUniforms(g)
+ }
+ },
+ highlight = null,
+ shadow = null,
+ onDrawBackdrop = { drawIt ->
+ val rec = luminance?.recorder
+ if (rec != null && frame[0]++ % 6 == 0) rec(drawIt) else drawIt()
+ },
+ onDrawSurface = {
+ val g = geo()
+ val w = washIn()
+ val lum = luminance?.value ?: if (dark) 0.14f else 0.86f
+ val plain = adaptiveWash(lum).glassTint(style).let { it.copy(alpha = it.alpha * w) }
+ val wash = if (tint.isSpecified) androidx.compose.ui.graphics.lerp(tint.copy(alpha = 0.75f), plain, w) else plain
+ surface.setFloatUniform("wash", wash.red, wash.green, wash.blue, wash.alpha)
+ surface.setFloatUniform("rimAlpha", rimAlpha)
+ surface.shapeUniforms(g)
+ drawRect(ShaderBrush(surface))
+ },
+ ),
+ )
+
+ // At the ends the glass IS the button: the very glass every round glass button wears (GlassCircle's
+ // effects, lens and rim light), so the hand-off to the real button changes nothing. The liquid
+ // shape takes over as the circle starts to drip, and gives it back before the circle lands.
+ Box(
+ Modifier
+ .offset { IntOffset(local.left.roundToInt(), local.top.roundToInt()) }
+ .size(with(density) { local.width.toDp() }, with(density) { local.height.toDp() })
+ // on screen over the button now: the real button can step aside (from the next frame)
+ .onGloballyPositioned { MorphAnchors.shownAt(anchor) }
+ .graphicsLayer { alpha = fade.value * (1f - liquidIn()) }
+ .drawBackdrop(
+ backdrop = LocalBackdrop.current,
+ shape = { androidx.compose.foundation.shape.CircleShape },
+ effects = { glassEffects(style, px(2.dp), px(12.dp), px(24.dp)) },
+ highlight = { glassHighlight(style) },
+ shadow = null,
+ onDrawSurface = {
+ // as GlassCircle paints a tinted button
+ if (tint.isSpecified) {
+ drawRect(tint, blendMode = androidx.compose.ui.graphics.BlendMode.Hue)
+ drawRect(tint.copy(alpha = 0.75f))
+ }
+ },
+ ),
+ )
+ CompositionLocalProvider(LocalGlassInk provides ink, LocalMenuInk provides ink) {
+ Box(Modifier.fillMaxSize().graphicsLayer { alpha = fade.value }) {
+ // the button's glyph, fading as its circle becomes the menu
+ Box(
+ Modifier
+ .offset { IntOffset(local.left.roundToInt(), local.top.roundToInt()) }
+ .size(with(density) { local.width.toDp() }, with(density) { local.height.toDp() })
+ .graphicsLayer { alpha = (1f - p.value / 0.22f).coerceIn(0f, 1f) },
+ contentAlignment = Alignment.Center,
+ ) { icon() }
+ // the rows at the menu's resting place (a fixed node), clipped each frame to the glass's
+ // current rectangle in their layer: shown through the menu glass as it arrives
+ Box(
+ Modifier
+ .offset { IntOffset(endL.roundToInt(), (endT - swellPx).roundToInt()) }
+ .size(with(density) { widthPx.toDp() }, with(density) { (menuH + 2f * swellPx).toDp() })
+ .graphicsLayer {
+ val g = geo()
+ val ox = endL
+ val oy = endT - swellPx
+ val r = Rect(g.menu.left - ox, g.menu.top - oy, g.menu.right - ox, g.menu.bottom - oy)
+ shape = RectClip(r, g.radius)
+ clip = true
+ },
+ ) {
+ Box(
+ Modifier
+ .align(if (below) Alignment.TopStart else Alignment.BottomStart)
+ .padding(top = if (below) with(density) { swellPx.toDp() } else 0.dp, bottom = if (below) 0.dp else with(density) { swellPx.toDp() })
+ .wrapContentHeight(if (below) Alignment.Top else Alignment.Bottom, unbounded = true)
+ .width(menuWidth)
+ .onSizeChanged { full = it.height }
+ .graphicsLayer { alpha = ((p.value - 0.55f) / 0.35f).coerceIn(0f, 1f) },
+ ) {
+ Column(Modifier.heightIn(max = maxHeight).verticalScroll(rememberScrollState())) {
+ Spacer(Modifier.height(6.dp))
+ items.forEach { item -> MorphMenuRow(item, shut) { chosenAction = item.onClick; onDismiss() } }
+ Spacer(Modifier.height(6.dp))
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/** A rounded rectangle at [r] inside its layer: the rows' clip, following the glass frame by frame. */
+private class RectClip(private val r: Rect, private val radius: Float) : androidx.compose.ui.graphics.Shape {
+ override fun createOutline(size: androidx.compose.ui.geometry.Size, layoutDirection: androidx.compose.ui.unit.LayoutDirection, density: androidx.compose.ui.unit.Density) =
+ androidx.compose.ui.graphics.Outline.Rounded(androidx.compose.ui.geometry.RoundRect(r, androidx.compose.ui.geometry.CornerRadius(radius)))
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/MorphButton.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/MorphButton.kt
new file mode 100644
index 0000000..e6704dd
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/MorphButton.kt
@@ -0,0 +1,392 @@
+package com.chethan616.clearpdf.ui.glass
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.core.Animatable
+import androidx.compose.animation.core.spring
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
+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.WindowInsets
+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.padding
+import androidx.compose.foundation.layout.requiredSize
+import androidx.compose.foundation.layout.requiredWidth
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.systemBars
+import androidx.compose.foundation.layout.wrapContentHeight
+import androidx.compose.foundation.layout.wrapContentSize
+import androidx.compose.foundation.layout.wrapContentWidth
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+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.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+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.clip
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.isSpecified
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.Layout
+import androidx.compose.ui.layout.boundsInWindow
+import androidx.compose.ui.layout.onGloballyPositioned
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalView
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Constraints
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.util.lerp
+import com.chethan616.clearpdf.ui.theme.Candy
+import com.chethan616.clearpdf.ui.theme.ClearType
+import com.chethan616.clearpdf.ui.theme.clear
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.roundToInt
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+
+/** The menu's corners once it has opened, as [MenuCard]'s. */
+private val MorphMenuRadius = 24.dp
+
+/** How long a chosen row waits for the menu to fold back before it runs (as [GlassMenu]'s rows). */
+private const val MorphRowDelayMillis = 200L
+
+/**
+ * A round glass button that is itself its menu, as iOS 26's: tapped, the circle stretches out of
+ * its place (wider first, so for a moment it is a capsule), then grows down into the menu's rounded
+ * rectangle, the same glass all the way, its glyph fading as the rows come in. Dismissed, the menu
+ * flows back into the circle. There is never a button and a menu at once: while the glass is open the
+ * button in the layout is hidden and [MorphButtonSurface] is the button.
+ */
+@Composable
+fun MorphButton(
+ items: List<GlassMenuItem>,
+ label: String,
+ modifier: Modifier = Modifier,
+ size: Dp = HeaderButtonSize,
+ menuWidth: Dp = 236.dp,
+ enabled: Boolean = true,
+ icon: @Composable () -> Unit,
+) {
+ var open by remember { mutableStateOf(false) }
+ var up by remember { mutableStateOf(false) }
+ var anchor by remember { mutableStateOf(Rect.Zero) }
+ GlassCircle(
+ onClick = { if (enabled && !up) { open = true; up = true } },
+ modifier = modifier.onGloballyPositioned { anchor = it.boundsInWindow() }.graphicsLayer { alpha = if (up) 0f else 1f },
+ size = size,
+ label = label,
+ ) { icon() }
+ if (up) MorphButtonSurface(anchor, open, onDismiss = { open = false }, onGone = { up = false }, items = items, menuWidth = menuWidth, icon = icon)
+}
+
+/**
+ * The circle at [anchor] as it opens into a menu of [items] and back. The caller hides its own button
+ * from the first frame until [onGone] (the glass back in the circle), so the two are never seen
+ * together. It opens when composed and closes when [open] turns false or its caller leaves.
+ */
+@Composable
+fun MorphButtonSurface(
+ anchor: Rect,
+ open: Boolean,
+ onDismiss: () -> Unit,
+ onGone: () -> Unit,
+ items: List<GlassMenuItem>,
+ menuWidth: Dp = 236.dp,
+ maxHeight: Dp = 480.dp,
+ icon: (@Composable () -> Unit)? = null,
+) {
+ // the round button it grows from is this glass now: hidden until the glass is back in its circle
+ // (not cleared when the caller leaves: its menu is still folding back into the button then, in the
+ // overlay; the button comes back only when that is done, through gone() below)
+ // (the button steps aside only once the morph's glass is on screen: see MorphAnchors.shownAt; hidden
+ // any earlier, the frame between the two showed nothing there, a blink)
+ val gone: () -> Unit = {
+ if (MorphAnchors.active == anchor) MorphAnchors.active = null
+ onGone()
+ }
+ val glyph: @Composable () -> Unit = icon ?: MorphAnchors.glyphAt(anchor) ?: {}
+ // Android 13+: the liquid version (the glass shaders it needs); before that the plain expansion
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
+ LiquidMorphSurface(anchor, open, onDismiss, gone, items, menuWidth, maxHeight, glyph)
+ } else {
+ RectMorphSurface(anchor, open, onDismiss, gone, items, menuWidth, maxHeight, glyph)
+ }
+}
+
+/** Whether a menu at [anchor] opens from a round glass button (24 to 72 dp, near-square). */
+internal fun isMorphAnchor(anchor: Rect, density: androidx.compose.ui.unit.Density): Boolean {
+ val lo = with(density) { 24.dp.toPx() }
+ val hi = with(density) { 72.dp.toPx() }
+ return anchor.width in lo..hi && anchor.height in lo..hi && kotlin.math.abs(anchor.width - anchor.height) <= anchor.width * 0.2f
+}
+
+/**
+ * Round glass buttons and the menu glass they become: the button at [active] hides while its glass is
+ * a menu, and each button leaves its glyph here so the glass can show it while it is still the circle.
+ */
+object MorphAnchors {
+ var active: Rect? by androidx.compose.runtime.mutableStateOf(null)
+ private val glyphs = HashMap<Long, @Composable () -> Unit>()
+
+ private fun key(r: Rect): Long = (r.left.toInt().toLong() / 4 shl 32) or (r.top.toInt().toLong() / 4 and 0xffffffffL)
+
+ internal fun register(r: Rect, glyph: @Composable () -> Unit) { glyphs[key(r)] = glyph }
+
+ internal fun unregister(r: Rect) { glyphs.remove(key(r)) }
+
+ /** The morph's glass is laid out over the button at [r]: from the next frame the button can step aside. */
+ internal fun shownAt(r: Rect) { if (active != r) active = r }
+
+ internal fun glyphAt(r: Rect): (@Composable () -> Unit)? = glyphs[key(r)]
+
+ private val tints = HashMap<Long, Color>()
+
+ internal fun setTint(r: Rect, tint: Color) { if (tint.isSpecified) tints[key(r)] = tint else tints.remove(key(r)) }
+
+ internal fun tintAt(r: Rect): Color? = tints[key(r)]
+
+ /** Whether the button laid out at [r] is the one being a menu now. */
+ internal fun hides(r: Rect): Boolean {
+ val a = active ?: return false
+ return kotlin.math.abs(a.left - r.left) < 3f && kotlin.math.abs(a.top - r.top) < 3f && kotlin.math.abs(a.width - r.width) < 3f
+ }
+}
+
+/** The morph without the liquid shaders (before Android 13): one rounded rectangle growing out of the button. */
+@Composable
+private fun RectMorphSurface(
+ anchor: Rect,
+ open: Boolean,
+ onDismiss: () -> Unit,
+ onGone: () -> Unit,
+ items: List<GlassMenuItem>,
+ menuWidth: Dp = 236.dp,
+ maxHeight: Dp = 480.dp,
+ icon: @Composable () -> Unit,
+) {
+ val gone by rememberUpdatedState(onGone)
+ GlassOverlay(animatesOut = true) {
+ val presence = LocalOverlayPresence.current
+ val shut = !open || presence?.leaving == true
+ // removed from the portal for good (finished or cut short): the button is back either way
+ androidx.compose.runtime.DisposableEffect(Unit) { onDispose { gone() } }
+ BackHandler(enabled = !shut, onBack = onDismiss)
+ val host = LocalGlassOverlayHost.current ?: return@GlassOverlay
+ val bars = WindowInsets.systemBars
+ val view = LocalView.current
+ val density = LocalDensity.current
+
+ // Three flowing movements, each starting as the one before settles: the circle first drops
+ // about a centimetre (a tall capsule), then spreads to the menu's full width, then pours down to
+ // the menu's full height. Closing runs them back: the height drains, the width draws in, the
+ // drop rises back into the circle.
+ val drop = remember { Animatable(0f) }
+ val wide = remember { Animatable(0f) }
+ val tall = remember { Animatable(0f) }
+ // a row chosen: the menu folds back into its button first, and the row's action runs only once
+ // it is the button again (a row that opens Tools, Settings … never leaves glass on the next screen)
+ var chosenAction by remember { androidx.compose.runtime.mutableStateOf<(() -> Unit)?>(null) }
+ val runChosen = {
+ val a = chosenAction
+ chosenAction = null
+ a?.invoke()
+ Unit
+ }
+ val fade = remember { Animatable(1f) }
+ LaunchedEffect(shut) {
+ if (!shut) {
+ coroutineScope {
+ launch { drop.animateTo(1f, spring(MotionSettings.damping(0.82f), MotionSettings.stiffness(318f), 0.0005f)) }
+ launch {
+ androidx.compose.runtime.snapshotFlow { drop.value >= 0.6f }.first { it }
+ wide.animateTo(1f, spring(MotionSettings.damping(0.8f), MotionSettings.stiffness(272f), 0.0005f))
+ }
+ launch {
+ androidx.compose.runtime.snapshotFlow { wide.value >= 0.6f }.first { it }
+ tall.animateTo(1f, spring(MotionSettings.damping(0.84f), MotionSettings.stiffness(181f), 0.0005f))
+ }
+ }
+ } else if (MorphAnchors.glyphAt(anchor) == null) {
+ fade.animateTo(0f, androidx.compose.animation.core.tween(150))
+ gone()
+ presence?.done()
+ runChosen()
+ } else {
+ coroutineScope {
+ launch { tall.animateTo(0f, spring(1f, MotionSettings.stiffness(469f), 0.0005f)) }
+ launch {
+ androidx.compose.runtime.snapshotFlow { tall.value <= 0.4f }.first { it }
+ wide.animateTo(0f, spring(1f, MotionSettings.stiffness(393f), 0.0005f))
+ }
+ launch {
+ androidx.compose.runtime.snapshotFlow { tall.value <= 0.05f && wide.value <= 0.4f }.first { it }
+ drop.animateTo(0f, spring(1f, MotionSettings.stiffness(423f), 0.0005f))
+ }
+ }
+ gone()
+ presence?.done()
+ runChosen()
+ }
+ }
+ // a centimetre on this screen: how far the glass drops while it spreads sideways
+ val peekPx = androidx.compose.ui.platform.LocalContext.current.resources.displayMetrics.ydpi / 2.54f
+
+ Box(Modifier.fillMaxSize().clickable(remember { MutableInteractionSource() }, null, onClick = onDismiss))
+ val local = Rect(host.windowToLocal(anchor.topLeft), host.windowToLocal(anchor.bottomRight))
+ val margin = with(density) { 12.dp.toPx() }
+ val widthPx = with(density) { menuWidth.toPx() }
+ var full by remember { mutableIntStateOf(0) }
+ var fromRight by remember { mutableStateOf(true) }
+ var fromBelow by remember { mutableStateOf(true) }
+ // the glass's outline now: the app's own rounded rectangle (the lens needs that very shape), its
+ // corners as round as its height allows while it is a capsule, settling to the menu's as it grows
+ // tall, so circle, capsule and menu are one continuous curve
+ val menuNow = if (full > 0) full.toFloat() else local.height
+ val curW = lerp(local.width, widthPx, wide.value)
+ val curH = morphHeight(local.height, menuNow, peekPx, drop.value, if (full > 0) tall.value else 0f)
+ val grown = ((curH - local.height) / (menuNow - local.height).coerceAtLeast(1f)).coerceIn(0f, 1f)
+ val radiusPx = min(min(curW, curH) / 2f, lerp(min(local.width, local.height) / 2f, with(density) { MorphMenuRadius.toPx() }, grown)).coerceAtLeast(0f)
+ val shape = RoundedRectangle(with(density) { radiusPx.toDp() })
+ // the glass bends what is behind it more while it is moving, and settles to the button's own lens
+ val flow = kotlin.math.sin(Math.PI.toFloat() * tall.value.coerceIn(0f, 1f)) +
+ 0.6f * kotlin.math.sin(Math.PI.toFloat() * wide.value.coerceIn(0f, 1f)) +
+ 0.4f * kotlin.math.sin(Math.PI.toFloat() * drop.value.coerceIn(0f, 1f))
+ val corner = when {
+ fromBelow && fromRight -> Alignment.TopEnd
+ fromBelow -> Alignment.TopStart
+ fromRight -> Alignment.BottomEnd
+ else -> Alignment.BottomStart
+ }
+ // the frost comes in as the glass opens (the button's own clear glass at first); never a new tint
+ val frost = lerp(2f, 14f, tall.value.coerceIn(0f, 1f)).dp
+ // the glass reads what is behind it and takes dark ink over light, white over dark (Night mode's
+ // black pages, a white document, the aurora): the glyph and rows always stand out
+ val luminance = rememberGlassLuminance(enabled = true)
+ val inkColor = adaptiveInk(luminance, clear.ink)
+ Layout(
+ content = {
+ CompositionLocalProvider(LocalGlassInk provides inkColor, LocalMenuInk provides inkColor) {
+ Box(
+ Modifier
+ .graphicsLayer { alpha = fade.value }
+ .glass(shape, wash = Color.Transparent, blur = frost, lensHeight = (12f + 7f * flow).dp, lensAmount = (24f + 18f * flow).dp, luminance = luminance)
+ .clip(shape),
+ ) {
+ // the button's glyph, where it was, fading as the glass opens
+ Box(
+ Modifier.align(corner)
+ .wrapContentSize(corner, unbounded = true)
+ .size(with(density) { local.width.toDp() }, with(density) { local.height.toDp() })
+ .graphicsLayer { alpha = (1f - drop.value / 0.5f).coerceIn(0f, 1f) },
+ contentAlignment = Alignment.Center,
+ ) { icon() }
+ // the rows where they will rest, coming in as the glass reaches them
+ Box(
+ // pinned to the button's corner (never centred in the glass while it is still small)
+ Modifier.align(corner)
+ .wrapContentWidth(if (fromRight) Alignment.End else Alignment.Start, unbounded = true)
+ .wrapContentHeight(if (fromBelow) Alignment.Top else Alignment.Bottom, unbounded = true)
+ .width(menuWidth)
+ .onSizeChanged { full = it.height }
+ .graphicsLayer { alpha = ((tall.value - 0.25f) / 0.5f).coerceIn(0f, 1f) },
+ ) {
+ Column(Modifier.heightIn(max = maxHeight).verticalScroll(rememberScrollState())) {
+ Spacer(Modifier.height(6.dp))
+ items.forEach { item -> MorphMenuRow(item, shut) { chosenAction = item.onClick; onDismiss() } }
+ Spacer(Modifier.height(6.dp))
+ }
+ }
+ }
+ }
+ },
+ modifier = Modifier.fillMaxSize().onGloballyPositioned { MorphAnchors.shownAt(anchor) },
+ ) { measurables, constraints ->
+ val origin = host.originInWindow
+ val root = view.rootView
+ val barTop = (bars.getTop(this) - origin.y).coerceAtLeast(0f)
+ val barBottom = (bars.getBottom(this) - (root.height - origin.y - constraints.maxHeight)).coerceAtLeast(0f)
+ val barLeft = (bars.getLeft(this, layoutDirection) - origin.x).coerceAtLeast(0f)
+ val barRight = (bars.getRight(this, layoutDirection) - (root.width - origin.x - constraints.maxWidth)).coerceAtLeast(0f)
+ val menuH = (if (full > 0) full else local.height.roundToInt()).toFloat()
+ val right = local.center.x > constraints.maxWidth / 2f
+ fromRight = right
+ val below = local.top + menuH < constraints.maxHeight - barBottom - margin
+ fromBelow = below
+ val minX = barLeft + margin
+ val maxX = (constraints.maxWidth - barRight - widthPx - margin).coerceAtLeast(minX)
+ val minY = barTop + margin
+ val maxY = (constraints.maxHeight - barBottom - menuH - margin).coerceAtLeast(minY)
+ // the menu grows from the button's own corner and rests over the place the button was
+ val endL = (if (right) local.right - widthPx else local.left).coerceIn(minX, maxX)
+ val endT = (if (below) local.top else local.bottom - menuH).coerceIn(minY, maxY)
+ val gw = wide.value
+ val gh = if (full > 0) tall.value else 0f
+ val l = lerp(local.left, endL, gw)
+ val r = lerp(local.right, endL + widthPx, gw)
+ // the height grows away from the button's edge (down from its top, or up from its bottom)
+ val hNow = morphHeight(local.height, menuH, peekPx, drop.value, gh)
+ val edgeT = lerp(local.top, endT, gw)
+ val edgeB = lerp(local.bottom, endT + menuH, gw)
+ val t = if (below) edgeT else edgeB - hNow
+ val b = if (below) edgeT + hNow else edgeB
+ val w = max(1, (r - l).roundToInt())
+ val h = max(1, (b - t).roundToInt())
+ val placeable = measurables.first().measure(Constraints.fixed(w, h))
+ layout(constraints.maxWidth, constraints.maxHeight) {
+ placeable.place(IntOffset(l.roundToInt(), t.roundToInt()))
+ }
+ }
+ }
+}
+
+/** One of the menu's rows, as [GlassMenu]'s: the label, its glyph at the end; it runs once the glass has folded. */
+@Composable
+internal fun MorphMenuRow(item: GlassMenuItem, shut: Boolean, close: () -> Unit) {
+ var chosen by remember { mutableStateOf(false) }
+ val ink = LocalGlassInk.current
+ Row(
+ Modifier.fillMaxWidth().pressable({
+ if (!chosen && !shut) {
+ chosen = true
+ // the surface runs the row's action once its glass has folded back into the button
+ close()
+ }
+ }).padding(horizontal = 16.dp, vertical = 11.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(item.label, style = ClearType.BodyStrong, color = if (item.destructive) Candy.Tomato else ink, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ if (item.icon != null) Icon(item.icon, null, tint = if (item.destructive) Candy.Tomato else ink.copy(alpha = 0.65f), modifier = Modifier.size(19.dp))
+ }
+}
+
+/**
+ * The glass's height: [drop] (0..1) takes it from the button's height down by [peek] (a centimetre,
+ * or less if the menu is shorter), [tall] (0..1) pours it the rest of the way to the menu's height.
+ * A spring past 1 swells it a touch further, as glass settling.
+ */
+private fun morphHeight(button: Float, menu: Float, peek: Float, drop: Float, tall: Float): Float {
+ val first = min(peek, (menu - button).coerceAtLeast(0f))
+ val rest = (menu - button - first).coerceAtLeast(0f)
+ return (button + first * drop + rest * tall).coerceAtLeast(1f)
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Overlays.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Overlays.kt
index b80d8af..bea1a53 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Overlays.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Overlays.kt
@@ -356,6 +356,11 @@ fun MenuCard(modifier: Modifier = Modifier, shape: androidx.compose.ui.graphics.
@Composable
fun GlassMenu(anchor: Rect, onDismiss: () -> Unit, items: List<GlassMenuItem>) {
+ // opened from a round glass button: that button's glass becomes the menu (MorphButtonSurface)
+ if (isMorphAnchor(anchor, LocalDensity.current)) {
+ MorphButtonSurface(anchor, open = true, onDismiss = onDismiss, onGone = {}, items = items)
+ return
+ }
var closing by remember { mutableStateOf(false) }
GlassMenuLayout(anchor, onDismiss) {
Spacer(Modifier.height(6.dp))
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Style.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Style.kt
index 2240dc1..614a947 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Style.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Style.kt
@@ -135,6 +135,13 @@ object GlassSettings {
tint = p.getFloat("tint", d.tint),
highlight = p.getFloat("highlight", d.highlight),
)
+ // this update turns the glass to Crystal once (the owner's choice); after that
+ // the user's own choice stands
+ if (!p.getBoolean("crystal_default_v1", false)) {
+ style = GlassStyle.Crystal
+ p.edit().putBoolean("crystal_default_v1", true).apply()
+ update(context, GlassStyle.Crystal)
+ }
haptics = p.getBoolean("haptics", true)
adaptive = p.getBoolean("adaptive", false)
wallpaper = runCatching { Wallpaper.valueOf(p.getString("wallpaper", null) ?: "Aurora") }.getOrDefault(Wallpaper.Aurora)
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 24d75fc..d7e239c 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
@@ -1,5 +1,8 @@
package com.chethan616.clearpdf.ui.home
+import androidx.compose.ui.layout.boundsInRoot
+import androidx.compose.ui.layout.onGloballyPositioned
+
import android.graphics.BitmapFactory
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
@@ -134,9 +137,19 @@ fun shortDate(t: Long): String = DateFormat.getDateInstance(DateFormat.MEDIUM).f
/** A list: its name in dot-matrix type, then its first items as glass pills you can tick right here. */
@Composable
-fun ListCard(note: Note, onOpen: () -> Unit, onLong: () -> Unit, onToggle: (CheckItem) -> Unit, modifier: Modifier = Modifier) {
+fun ListCard(
+ note: Note,
+ onOpen: () -> Unit,
+ onLong: () -> Unit,
+ onToggle: (CheckItem) -> Unit,
+ modifier: Modifier = Modifier,
+ /** Where each item's pill lands (the home screen widget lays its tap targets over them). */
+ onItemPlaced: ((CheckItem, androidx.compose.ui.geometry.Rect) -> Unit)? = null,
+ /** How many items show (the desk shows four; a small widget fewer). */
+ maxItems: Int = 4,
+) {
val tone = clear.tone(Tone.Sage)
- val shown = note.items.filter { it.text.isNotBlank() }.take(4)
+ val shown = note.items.filter { it.text.isNotBlank() }.take(maxItems)
val more = note.items.count { it.text.isNotBlank() } - shown.size
// the card's paint is its own layer so the glass pills on it refract the card, not the wallpaper
GlassHost(
@@ -153,7 +166,10 @@ fun ListCard(note: Note, onOpen: () -> Unit, onLong: () -> Unit, onToggle: (Chec
)
Spacer(Modifier.height(18.dp))
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- shown.forEach { item -> CheckPill(item, tone) { onToggle(item) } }
+ shown.forEach { item ->
+ val placed = if (onItemPlaced != null) Modifier.onGloballyPositioned { onItemPlaced(item, it.boundsInRoot()) } else Modifier
+ CheckPill(item, tone, placed) { onToggle(item) }
+ }
}
if (more > 0) {
Spacer(Modifier.height(8.dp))
@@ -193,7 +209,7 @@ fun WordFitText(text: String, style: androidx.compose.ui.text.TextStyle, modifie
* Needs a [GlassHost] around it (the card) to refract the card's colour.
*/
@Composable
-fun CheckPill(item: CheckItem, tone: CardTone, onToggle: () -> Unit) {
+fun CheckPill(item: CheckItem, tone: CardTone, modifier: Modifier = Modifier, onToggle: () -> Unit) {
val haptics = com.chethan616.clearpdf.ui.glass.LocalHaptics.current
val dark = clear.dark
val done = item.done
@@ -204,7 +220,7 @@ fun CheckPill(item: CheckItem, tone: CardTone, onToggle: () -> Unit) {
val tick by animateFloatAsState(if (done) 1f else 0f, com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "tick")
GlassChip(
onClick = { haptics?.play(if (done) com.chethan616.clearpdf.ui.glass.Feel.ToggleOff else com.chethan616.clearpdf.ui.glass.Feel.ToggleOn); onToggle() },
- modifier = Modifier.fillMaxWidth(),
+ modifier = Modifier.fillMaxWidth().then(modifier),
height = 40.dp,
fill = { wash },
contentPadding = PaddingValues(start = 8.dp, end = 12.dp),
@@ -228,7 +244,14 @@ fun CheckPill(item: CheckItem, tone: CardTone, onToggle: () -> Unit) {
/** A note: frosted white paper, its title big and bold in the note's blue, the date in the corner. */
@Composable
-fun NoteCard(note: Note, onOpen: () -> Unit, onLong: () -> Unit, modifier: Modifier = Modifier) {
+fun NoteCard(
+ note: Note,
+ onOpen: () -> Unit,
+ onLong: () -> Unit,
+ modifier: Modifier = Modifier,
+ /** Laid out at a fixed size (a home screen widget): the body takes only the lines that fit above the date. */
+ fitHeight: Boolean = false,
+) {
val tone = clear.tone(Tone.Paper)
val title = note.title.ifBlank { note.body.lineSequence().firstOrNull { it.isNotBlank() }?.trim()?.removePrefix("# ").orEmpty() }
val body = if (note.title.isBlank()) "" else note.body.lineSequence().filter { it.isNotBlank() }.joinToString(" ") { it.trim().removePrefix("# ").replace("**", "") }
@@ -238,7 +261,7 @@ fun NoteCard(note: Note, onOpen: () -> Unit, onLong: () -> Unit, modifier: Modif
WordFitText(title.ifBlank { stringResource(R.string.notes_untitled_note) }, ClearType.CardTitle.copy(color = tone.accent), maxLines = 4)
if (body.isNotBlank() && title.length < 40) {
Spacer(Modifier.height(8.dp))
- Text(body, style = ClearType.Label, color = tone.ink.copy(alpha = 0.62f), maxLines = 3, overflow = TextOverflow.Ellipsis)
+ Text(body, style = ClearType.Label, color = tone.ink.copy(alpha = 0.62f), maxLines = 3, overflow = TextOverflow.Ellipsis, modifier = if (fitHeight) Modifier.weight(1f, fill = false) else Modifier)
}
note.images.firstOrNull()?.let { name ->
Spacer(Modifier.height(12.dp))
@@ -317,8 +340,10 @@ fun ThoughtCard(onOpen: () -> Unit, modifier: Modifier = Modifier) {
@Composable
fun NoteImage(name: String, modifier: Modifier, maxPx: Int = 720) {
val vm = LocalHomeVm.current
+ val ctx = androidx.compose.ui.platform.LocalContext.current
var img by remember(name) { mutableStateOf<ImageBitmap?>(null) }
- LaunchedEffect(name) { img = withContext(Dispatchers.IO) { decodeScaled(vm?.notes?.file(name), maxPx) } }
+ // outside the desk (a home screen widget) there is no view model: the notes' media folder directly
+ LaunchedEffect(name) { img = withContext(Dispatchers.IO) { decodeScaled(vm?.notes?.file(name) ?: File(File(File(ctx.filesDir, "notes"), "media"), name), maxPx) } }
Box(modifier.background(Color.White.copy(alpha = 0.2f))) {
img?.let { Image(it, null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) }
}
@@ -585,7 +610,14 @@ fun BoxScope.PageFill(vm: AppViewModel, path: String?) {
* sky card (the newest in front, opening it), "Recent" and when, and "+N" / PDFs chips for the rest.
*/
@Composable
-fun RecentCard(vm: AppViewModel, rows: List<FileRow>, onAll: () -> Unit, modifier: Modifier = Modifier) {
+fun RecentCard(
+ vm: AppViewModel,
+ rows: List<FileRow>,
+ onAll: () -> Unit,
+ modifier: Modifier = Modifier,
+ /** The fan of pages at this size (a small home screen widget draws it smaller to keep clear of the title and chips). */
+ pagesScale: Float = 1f,
+) {
val tone = clear.tone(Tone.Sky)
val top = rows.first()
Box(modifier.height(226.dp).pressable(top.open, { vm.fileSheet = top to true }, pressedScale = 0.95f)) {
@@ -602,7 +634,7 @@ fun RecentCard(vm: AppViewModel, rows: List<FileRow>, onAll: () -> Unit, modifie
}
// up to three first pages, fanned; the newest on top
val shown = rows.take(3)
- Box(Modifier.align(Alignment.Center).padding(top = 18.dp).size(140.dp, 132.dp)) {
+ Box(Modifier.align(Alignment.Center).padding(top = 18.dp).size(140.dp, 132.dp).graphicsLayer { scaleX = pagesScale; scaleY = pagesScale }) {
shown.indices.reversed().forEach { i ->
val r = shown[i]
val tilt = listOf(-4f, 7f, -12f)[i]
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 dd52b68..434a74a 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
@@ -185,6 +185,7 @@ 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),
+ Draw(R.string.photo_draw, LucideIcons.PenLine),
Text(R.string.photo_text, LucideIcons.Type),
}
@@ -242,6 +243,7 @@ private fun decodeMutable(file: File): Bitmap {
* - 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);
+ * - Draw: a pen in any of the colours, with a width, for marking up the picture (undo takes a stroke 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.
@@ -297,6 +299,8 @@ private fun PhotoEditScreen(
val marks = remember(name) { mutableStateListOf<Mark>() }
var marksVersion by remember { mutableIntStateOf(0) }
var brush by remember { mutableFloatStateOf(0.06f) }
+ var penWidth by remember { mutableFloatStateOf(0.012f) }
+ var penInk by remember { mutableIntStateOf(Candy.Tomato.toArgb()) }
var smudgeKind by remember { mutableIntStateOf(SMUDGE_BLUR) }
var brushAt by remember { mutableStateOf<Offset?>(null) }
var chosen by remember { mutableStateOf<Label?>(null) }
@@ -616,6 +620,32 @@ private fun PhotoEditScreen(
} while (event.changes.any { it.pressed })
brushAt = null
}
+ Mode.Draw -> 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 pen = Pen(penInk, penWidth)
+ pen.points.add(at(down.position))
+ marks.add(pen)
+ 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() > 2f * density) {
+ pen.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
@@ -767,7 +797,7 @@ private fun PhotoEditScreen(
}
brushAt?.let { at ->
val pl = place ?: return@let
- val radius = brush * pl.long * k / 2f
+ val radius = (if (mode == Mode.Draw) penWidth else 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))
}
@@ -904,6 +934,33 @@ private fun PhotoEditScreen(
}
}
}
+ Mode.Draw -> {
+ Row(bar().height(72.dp).glassBar().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ ValueReadout(stringResource(R.string.photo_pen), "${(penWidth * 1000).roundToInt()}", false, ink.color)
+ FeltSlider(penWidth, 0.004f..0.04f, ink.color, Modifier.weight(1f), key = "pen") { penWidth = it }
+ Box(Modifier.size(34.dp), contentAlignment = Alignment.Center) {
+ val dot by animateDpAsState((6f + (penWidth - 0.004f) / 0.036f * 26f).dp, Fluid.quick(), label = "penDot")
+ Box(Modifier.size(dot).clip(CircleShape).background(Color(penInk)))
+ }
+ }
+ Row(bar().height(62.dp).glassBar().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ for (c in INKS) {
+ val on = penInk == c.toArgb()
+ Box(
+ Modifier.size(if (on) 30.dp else 24.dp).clip(CircleShape).background(c)
+ .border(if (on) 2.dp else 1.dp, if (on) Color.White else Color.Black.copy(alpha = 0.25f), CircleShape)
+ .pressable({ penInk = c.toArgb(); feel(Feel.Tick) }, pressedScale = 0.88f),
+ )
+ }
+ Spacer(Modifier.weight(1f))
+ val strokes = marksVersion >= 0 && marks.any { it is Pen }
+ RoundTool(LucideIcons.Undo2, stringResource(R.string.common_undo), enabled = strokes) {
+ marks.lastOrNull { it is Pen }?.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) {
@@ -1089,7 +1146,7 @@ private fun exifFrame(file: File): PhotoFrame {
return PhotoFrame(turns = turns, mirror = mirror)
}
-/** The switch between Adjust, Crop, Blur and Text: a lit capsule slides to the one in use. */
+/** The switch between Adjust, Crop, Blur, Draw and Text: a lit capsule slides to the one in use. */
@Composable
private fun ModeSwitch(mode: Mode, modifier: Modifier, onPick: (Mode) -> Unit) {
val ink = rememberGlassInk(Color.White)
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
index d0142f6..d5096c6 100644
--- 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
@@ -146,6 +146,11 @@ internal class Smudge(val kind: Int, val width: Float) : Mark() {
val points = ArrayList<PointF>()
}
+/** A pen stroke in [color]: freehand marking. Normalized like [Smudge]; [width] is a share of the long side. */
+internal class Pen(val color: Int, val width: Float) : Mark() {
+ 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
@@ -169,6 +174,7 @@ internal const val LABEL_STYLES = 3
internal fun Mark.turn() {
when (this) {
is Smudge -> points.forEach { val x = it.x; it.x = 1f - it.y; it.y = x }
+ is Pen -> points.forEach { val x = it.x; it.x = 1f - it.y; it.y = x }
is Label -> {
val x0 = x
x = 1f - y
@@ -182,6 +188,7 @@ internal fun Mark.turn() {
internal fun Mark.mirror() {
when (this) {
is Smudge -> points.forEach { it.x = 1f - it.x }
+ is Pen -> points.forEach { it.x = 1f - it.x }
is Label -> {
x = 1f - x
rotation = -rotation
@@ -446,5 +453,34 @@ internal fun paintMarks(canvas: Canvas, place: Placement, marks: List<Mark>, fx:
}
}
}
+ // pen strokes lie over the blur and under the words
+ val pens = marks.filterIsInstance<Pen>()
+ if (pens.isNotEmpty()) {
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeCap = Paint.Cap.ROUND
+ strokeJoin = Paint.Join.ROUND
+ }
+ val dot = Paint(Paint.ANTI_ALIAS_FLAG)
+ val path = Path()
+ val pt = PointF()
+ for (pen in pens) {
+ val width = pen.width * place.long
+ paint.color = pen.color
+ dot.color = pen.color
+ paint.strokeWidth = width
+ if (pen.points.size == 1) {
+ place.out(pen.points[0].x, pen.points[0].y, pt)
+ canvas.drawCircle(pt.x, pt.y, width / 2f, dot)
+ continue
+ }
+ path.reset()
+ pen.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, paint)
+ }
+ }
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/SheetViewer.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
index ccb0767..26ff85a 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
@@ -437,11 +437,11 @@ fun SheetGrid(
onRange: (() -> Unit)? = null,
) {
val c = pdfColors
- val sheetSurface = if (c.dark) Color(0xFF18192F) else Color.White
+ val sheetSurface = if (c.dark) Color(0xFF1F1F1F) else Color.White
val density = LocalDensity.current
val measurer = rememberTextMeasurer(cacheSize = 8)
val l = state.layout
- Box(modifier.fillMaxSize().background(c.surface)) {
+ Box(modifier.fillMaxSize().background(if (c.dark) Color(0xFF1F1F1F) else c.surface)) {
if (l == null) {
Box(Modifier.fillMaxSize().padding(top = with(density) { top.toDp() } + 40.dp), contentAlignment = Alignment.TopCenter) { GlassLoader(size = 64.dp) }
return@Box
@@ -657,7 +657,7 @@ fun SheetGrid(
},
) {
translate(top = top) {
- drawSheet(l, state, px * state.scale, texts, sheetSurface, c.text, c.dark)
+ drawSheet(l, state, px * state.scale, texts, sheetSurface, if (c.dark) Color(0xFFE3E3E3) else c.text, c.dark)
}
}
}
@@ -1126,7 +1126,7 @@ private fun DrawScope.drawSheet(
// text is laid out at zoom 1 and drawn scaled
val zoom = k / density
val accent = Color(0xFF0A84FF)
- val gridLine = if (dark) Color(0xFF343650) else Color(0xFFE1E4EA)
+ val gridLine = if (dark) Color(0xFF3C4043) else Color(0xFFE1E4EA)
val dashes = androidx.compose.ui.graphics.PathEffect.dashPathEffect(floatArrayOf(3f * k, 2f * k))
val dots = androidx.compose.ui.graphics.PathEffect.dashPathEffect(floatArrayOf(1f * k, 1.2f * k))
val shown = ArrayList<DrawCell>(512)
@@ -1371,17 +1371,17 @@ private fun DrawScope.drawSheet(
}
}
}
- val frozenDivider = if (dark) Color(0xFF777D9A) else Color(0xFF9AA3B2)
+ val frozenDivider = if (dark) Color(0xFF5F6368) 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)
// the heading strips: only the letters and numbers in view, each measured once
- val strip = if (dark) Color(0xFF20213B) else Color(0xFFF2F4F8)
+ val strip = if (dark) Color(0xFF2D2E30) else Color(0xFFF2F4F8)
val chosen = accent.copy(alpha = if (dark) 0.30f else 0.16f)
val labelZoom = min(zoom, 1.5f)
val label = TextStyle(color = ink.copy(alpha = 0.6f), fontSize = (11 / fontScale).sp)
drawRect(strip, Offset(0f, 0f), Size(size.width, head.y))
drawRect(strip, Offset(0f, 0f), Size(head.x, size.height))
- val lineC = if (dark) Color(0xFF343650) else Color(0xFFD5D9E0)
+ val lineC = if (dark) Color(0xFF444746) else Color(0xFFD5D9E0)
clipRect(head.x, 0f, size.width, head.y) {
fun columns(from: Int, to: Int, shift: Float, clipFrom: Float) {
if (from >= to) return
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DigitalSign.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DigitalSign.kt
index e3506f2..b15e615 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DigitalSign.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DigitalSign.kt
@@ -535,6 +535,8 @@ fun SignaturesSheet(vm: AppViewModel, doc: OpenDocument) {
if (list.isEmpty()) {
Text(stringResource(R.string.sign_none), color = c.textSecondary, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp))
}
+ if (list.isNotEmpty()) com.chethan616.clearpdf.ui.SheetSection(inset = 52.dp) {
+ Column {
for (s in list) {
val (icon, tint) = statusIcon(s)
Row(
@@ -556,9 +558,10 @@ fun SignaturesSheet(vm: AppViewModel, doc: OpenDocument) {
}
Icon(if (open == s.field) LucideIcons.ChevronUp else LucideIcons.ChevronDown, null, tint = c.icon, modifier = Modifier.size(20.dp))
}
- SheetDivider()
}
- SheetRow(LucideIcons.ShieldCheck, stringResource(R.string.sign_add_signature), { close(); vm.startCertPlacing(doc) })
+ }
+ }
+ com.chethan616.clearpdf.ui.SheetSection { SheetRow(LucideIcons.ShieldCheck, stringResource(R.string.sign_add_signature), { close(); vm.startCertPlacing(doc) }) }
Spacer(Modifier.height(8.dp))
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/FillSign.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/FillSign.kt
index 9ee7f35..6715231 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/FillSign.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/FillSign.kt
@@ -154,7 +154,7 @@ fun SignPanel(vm: AppViewModel, doc: OpenDocument, onDismiss: () -> Unit) {
val version = vm.signaturesChanged
// over the Fill & Sign bar, which stays in view: two dashed boxes, Add signature and Add initials
PdfSheet(onDismiss = onDismiss, modifier = Modifier.padding(bottom = BottomBarHeight + 1.dp).navigationBarsPadding(), bottomBand = false) {
- Spacer(Modifier.height(7.dp))
+ SheetTitle(stringResource(R.string.common_tool_fill_sign))
for (initials in listOf(false, true)) {
val file = vm.signatures.fileFor(initials)
val placeHint = stringResource(if (initials) R.string.fill_tap_place_initials else R.string.fill_tap_place_signature)
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt
index 87e5c46..b60cb2e 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt
@@ -123,6 +123,8 @@ fun ViewerTopBar(
contentAlpha: Float = 1f,
undoLabel: String? = null,
redoLabel: String? = null,
+ /** More has become its menu ([com.chethan616.clearpdf.ui.glass.MorphButtonSurface]): the circle is that glass now. */
+ moreHidden: Boolean = false,
) {
Row(
Modifier.fillMaxWidth().height(TopBarHeight).padding(horizontal = 12.dp),
@@ -177,7 +179,7 @@ fun ViewerTopBar(
onClick = { if (contentAlpha > 0.5f) onMore(moreAnchor) },
label = stringResource(R.string.common_more_options),
modifier = Modifier.onGloballyPositioned { moreAnchor = it.boundsInWindow() }
- .graphicsLayer { alpha = contentAlpha.coerceIn(0f, 1f) },
+ .graphicsLayer { alpha = if (moreHidden) 0f else contentAlpha.coerceIn(0f, 1f) },
) {
GlassIcon(LucideIcons.Ellipsis, null, Modifier.size(21.dp))
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerController.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerController.kt
index 29949c7..4f9b0e2 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerController.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerController.kt
@@ -36,7 +36,7 @@ enum class TextMarkup { Highlight, Underline, Strikethrough }
enum class CommentMode { Text, Voice }
/** What the bottom sheet over the viewer shows. */
-enum class ViewerSheet { None, More, ViewSettings, Attachments, Bookmarks, Comments, MoreTools, Signatures, SaveAs }
+enum class ViewerSheet { None, More, ViewSettings, Attachments, Bookmarks, Comments, MoreTools, Signatures, SaveAs, SlideNotes, Info }
/**
* The viewer's own state for one document, beside the page view ([ViewerState]): whether the
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt
index 5bf7a4a..b328ffc 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt
@@ -100,6 +100,9 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {
val view = LocalView.current
val context = LocalContext.current
var moreMenuAnchor by remember { mutableStateOf(Rect.Zero) }
+ // More opened from its circle: the circle itself becomes the menu (MorphButtonSurface), hidden in the bar meanwhile
+ var moreFromButton by remember { mutableStateOf(false) }
+ var moreMorphUp by remember { mutableStateOf(false) }
var moreToolsMenuAnchor by remember { mutableStateOf(Rect.Zero) }
// The system bars go with the viewer's bars.
@@ -405,10 +408,8 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {
},
onUndo = { vm.undo(doc) },
onRedo = { vm.redo(doc) },
- onTitle = { anchor ->
- moreMenuAnchor = anchor
- ctl.sheet = if (ctl.sheet == ViewerSheet.More) ViewerSheet.None else ViewerSheet.More
- },
+ // the title opens what the document is (as iOS Files' title); the commands are in ⋯
+ onTitle = { _ -> ctl.sheet = if (ctl.sheet == ViewerSheet.Info) ViewerSheet.None else ViewerSheet.Info },
onSearch = if (vm.readingMode) null else ({
selection.clear()
ctl.searching = true
@@ -417,8 +418,15 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {
onShare = { vm.share(doc) },
onMore = { anchor ->
moreMenuAnchor = anchor
- ctl.sheet = if (ctl.sheet == ViewerSheet.More) ViewerSheet.None else ViewerSheet.More
+ if (ctl.sheet == ViewerSheet.More) {
+ ctl.sheet = ViewerSheet.None
+ } else if (!moreMorphUp) {
+ moreFromButton = true
+ moreMorphUp = true
+ ctl.sheet = ViewerSheet.More
+ }
},
+ moreHidden = moreMorphUp,
contentAlpha = 1f - sp.value,
undoLabel = if (doc.localUndo != null) stringResource(R.string.viewer_undo_drawing) else doc.info.undo,
redoLabel = if (doc.localUndo != null) stringResource(R.string.viewer_undo_drawing) else doc.info.redo,
@@ -497,13 +505,15 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {
// Sheets and dialogs.
SheetHost(ctl.sheet.takeIf { it != ViewerSheet.None }) { sheet ->
when (sheet) {
- ViewerSheet.More -> MoreSheet(vm, doc, moreMenuAnchor)
+ ViewerSheet.More -> MoreSheet(vm, doc, moreMenuAnchor, fromButton = moreFromButton, onGone = { moreMorphUp = false })
ViewerSheet.ViewSettings -> ViewSettingsSheet(vm, doc)
ViewerSheet.Bookmarks -> BookmarksSheet(vm, doc)
ViewerSheet.Attachments -> AttachmentsSheet(vm, doc)
ViewerSheet.Comments -> Unit
ViewerSheet.MoreTools -> MoreToolsSheet(vm, doc, moreToolsMenuAnchor)
ViewerSheet.SaveAs -> SaveAsSheet(vm, doc)
+ ViewerSheet.SlideNotes -> SlideNotesSheet(vm, doc)
+ ViewerSheet.Info -> DocumentInfoSheet(vm, doc)
ViewerSheet.Signatures -> SignaturesSheet(vm, doc)
ViewerSheet.None -> Unit
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt
index 1c8ead9..b2200af 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt
@@ -60,6 +60,7 @@ import com.chethan616.clearpdf.ui.OpenDocument
import com.chethan616.clearpdf.ui.PdfSheet
import com.chethan616.clearpdf.ui.PdfSwitch
import com.chethan616.clearpdf.ui.SheetBackHeader
+import com.chethan616.clearpdf.ui.SheetHeader
import com.chethan616.clearpdf.ui.GroupDivider
import com.chethan616.clearpdf.ui.SheetDivider
import com.chethan616.clearpdf.ui.SheetRow
@@ -84,7 +85,15 @@ import java.util.Date
* reference's order. Drill-in rows (with a chevron) open their own sheet.
*/
@Composable
-fun MoreSheet(vm: AppViewModel, doc: OpenDocument, anchor: Rect) {
+fun MoreSheet(
+ vm: AppViewModel,
+ doc: OpenDocument,
+ anchor: Rect,
+ /** Opened from the More circle: that circle opens into the menu ([com.chethan616.clearpdf.ui.glass.MorphButtonSurface]). */
+ fromButton: Boolean = false,
+ /** The circle is back in the bar (the glass has folded into it). */
+ onGone: () -> Unit = {},
+) {
val ctl = doc.controller
val bookmarked = vm.bookmarks.isBookmarked(doc, doc.viewer.currentPage)
val starred = vm.isStarred(doc)
@@ -93,6 +102,7 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument, anchor: Rect) {
add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(if (bookmarked) R.string.sheet_remove_bookmark else R.string.sheet_add_bookmark), if (bookmarked) LucideIcons.BookmarkMinus else LucideIcons.BookmarkPlus) { vm.toggleBookmark(doc) })
add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(R.string.common_tool_read_aloud), LucideIcons.Volume2) { vm.startReadAloud(doc) })
if (doc.isSlides) add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(R.string.office_present), LucideIcons.Presentation) { vm.presenting = doc })
+ if (doc.isSlides) add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(R.string.office_slide_notes), LucideIcons.FileText) { ctl.sheet = ViewerSheet.SlideNotes })
else if (!doc.isOffice) add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(R.string.common_tool_edit_pdf), LucideIcons.FilePenLine) { vm.enterTool(doc, ViewerTool.Edit) })
add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(R.string.sheet_print), LucideIcons.Printer) { vm.print(doc) })
add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(R.string.sheet_view_settings), LucideIcons.Glasses) { ctl.sheet = ViewerSheet.ViewSettings })
@@ -121,7 +131,13 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument, anchor: Rect) {
doc.info.undo?.let { label -> add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(R.string.sheet_undo_action, label), LucideIcons.Undo2) { vm.undo(doc) }) }
doc.info.redo?.let { label -> add(com.chethan616.clearpdf.ui.glass.GlassMenuItem(stringResource(R.string.sheet_redo_action, label), LucideIcons.Redo2) { vm.redo(doc) }) }
}
- com.chethan616.clearpdf.ui.glass.GlassMenu(anchor, { ctl.sheet = ViewerSheet.None }, items)
+ if (fromButton) {
+ com.chethan616.clearpdf.ui.glass.MorphButtonSurface(anchor, open = true, onDismiss = { ctl.sheet = ViewerSheet.None }, onGone = onGone, items = items) {
+ com.chethan616.clearpdf.ui.glass.GlassIcon(LucideIcons.Ellipsis, null, Modifier.size(21.dp))
+ }
+ } else {
+ com.chethan616.clearpdf.ui.glass.GlassMenu(anchor, { ctl.sheet = ViewerSheet.None }, items)
+ }
}
/** A PDF as a little paper in a sheet's header: grey lines and the red PDF corner. */
@@ -566,6 +582,83 @@ fun MoreToolsSheet(vm: AppViewModel, doc: OpenDocument, anchor: Rect) {
/** Save as: the formats the document's engine writes, each saved to Downloads. */
+/** What the document is: its name, kind, size, pages, where it lives, and what it says about itself. */
+@Composable
+fun DocumentInfoSheet(vm: AppViewModel, doc: OpenDocument) {
+ val ctl = doc.controller
+ val c = pdfColors
+ val info = doc.info
+ val context = androidx.compose.ui.platform.LocalContext.current
+ val location = remember(doc.source) { doc.source?.toString()?.let { vm.locationOfDocument(it) } }
+ val kind = stringResource(com.chethan616.clearpdf.engine.DocumentTypes.kindOf(info.name).short)
+ val first = info.pages.firstOrNull()
+ @Composable
+ fun line(label: String, value: String?) {
+ if (value.isNullOrBlank()) return
+ androidx.compose.foundation.layout.Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.Top) {
+ Text(label, color = c.textSecondary, fontSize = 15.sp, modifier = Modifier.weight(0.42f))
+ Text(value, color = c.text, fontSize = 15.sp, modifier = Modifier.weight(0.58f), textAlign = TextAlign.End)
+ }
+ }
+ PdfSheet(onDismiss = { ctl.sheet = ViewerSheet.None }, maxHeightFraction = 0.8f) {
+ SheetHeader(doc.title, subtitle = kind)
+ Column(Modifier.verticalScroll(rememberScrollState())) {
+ SheetSection(inset = 16.dp) {
+ Column {
+ line(stringResource(R.string.info_kind), kind + (if (info.pdfVersion.isNotBlank() && !doc.isOffice) " " + info.pdfVersion else ""))
+ line(stringResource(R.string.info_size), android.text.format.Formatter.formatShortFileSize(context, info.fileSize.toLong()))
+ line(stringResource(if (doc.isSlides) R.string.info_slides else R.string.info_pages), doc.pageCount.toString())
+ if (first != null && !doc.isSheets) line(stringResource(R.string.info_page_size), "%.0f × %.0f pt".format(first.width, first.height))
+ line(stringResource(R.string.info_where), location)
+ }
+ }
+ SheetSection(inset = 16.dp) {
+ Column {
+ line(stringResource(R.string.info_title), info.title)
+ line(stringResource(R.string.info_author), info.author)
+ line(stringResource(R.string.info_subject), info.subject)
+ line(stringResource(R.string.info_keywords), info.keywords)
+ line(stringResource(R.string.info_creator), info.creator)
+ line(stringResource(R.string.info_producer), info.producer)
+ }
+ }
+ SheetSection(inset = 16.dp) {
+ Column {
+ val yes = stringResource(R.string.info_yes)
+ val no = stringResource(R.string.info_no)
+ line(stringResource(R.string.info_protected), if (info.encrypted) yes else no)
+ if (!doc.isOffice) {
+ line(stringResource(R.string.info_signed), if (info.signed) yes else no)
+ line(stringResource(R.string.info_tagged), if (info.tagged) yes else no)
+ if (info.fields > 0u) line(stringResource(R.string.info_fields), info.fields.toString())
+ if (info.attachments > 0u) line(stringResource(R.string.info_attachments), info.attachments.toString())
+ }
+ }
+ }
+ Spacer(Modifier.height(10.dp))
+ }
+ }
+}
+
+/** The speaker notes of the slide in view. */
+@Composable
+fun SlideNotesSheet(vm: AppViewModel, doc: OpenDocument) {
+ val ctl = doc.controller
+ val c = pdfColors
+ val page = doc.viewer.currentPage
+ var notes by remember(page) { mutableStateOf<String?>(null) }
+ LaunchedEffect(page, doc.id) { notes = vm.engine?.let { e -> runCatching { e.command { slideNotes(doc.id, page.toUInt()) } }.getOrNull() }.orEmpty() }
+ PdfSheet(onDismiss = { ctl.sheet = ViewerSheet.None }, maxHeightFraction = 0.6f) {
+ SheetHeader(stringResource(R.string.office_slide_notes), subtitle = stringResource(R.string.office_slide_n, page + 1), onBack = { ctl.sheet = ViewerSheet.More })
+ val text = notes
+ Column(Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 22.dp, vertical = 8.dp)) {
+ if (text.isNullOrBlank()) Text(stringResource(R.string.office_slide_notes_none), color = c.textSecondary, fontSize = 15.sp)
+ else Text(text, color = c.text, fontSize = 16.sp)
+ }
+ Spacer(Modifier.height(10.dp))
+ }
+}
+
@Composable
fun SaveAsSheet(vm: AppViewModel, doc: OpenDocument) {
val ctl = doc.controller
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/VoiceSheet.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/VoiceSheet.kt
index 4c5ca40..4258485 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/VoiceSheet.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/VoiceSheet.kt
@@ -48,6 +48,7 @@ import com.chethan616.clearpdf.ui.AppViewModel
import com.chethan616.clearpdf.ui.LucideIcons
import com.chethan616.clearpdf.ui.OpenDocument
import com.chethan616.clearpdf.ui.PdfSheet
+import com.chethan616.clearpdf.ui.SheetHeader
import com.chethan616.clearpdf.ui.pdfColors
import kotlinx.coroutines.launch
@@ -112,25 +113,24 @@ fun VoiceSheet(vm: AppViewModel, prompt: VoicePrompt) {
DisposableEffect(prompt) { onDispose { player.release() } }
PdfSheet(onDismiss = ::close, dim = true) {
- Row(Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
- Text(stringResource(R.string.voice_record_comment), color = c.text, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f))
- com.chethan616.clearpdf.ui.glass.GlassTextAction(
- stringResource(R.string.common_post),
- {
- player.release()
- vm.postVoice(prompt, file)
- },
- enabled = recorded, primary = true,
- )
- }
- Text(
- when {
+ SheetHeader(
+ title = stringResource(R.string.voice_record_comment),
+ subtitle = when {
recorder.recording -> stringResource(R.string.voice_recording)
player.playing -> stringResource(R.string.voice_playing)
recorded -> stringResource(R.string.voice_listen_first)
- else -> ""
+ else -> null
+ },
+ trailing = {
+ com.chethan616.clearpdf.ui.glass.GlassTextAction(
+ stringResource(R.string.common_post),
+ {
+ player.release()
+ vm.postVoice(prompt, file)
+ },
+ enabled = recorded, primary = true,
+ )
},
- color = c.textSecondary, fontSize = 14.sp, modifier = Modifier.padding(horizontal = 20.dp),
)
Spacer(Modifier.height(12.dp))
if (!recorded) {
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/widget/ArtefactWidgets.kt b/android/app/src/main/java/com/chethan616/clearpdf/widget/ArtefactWidgets.kt
new file mode 100644
index 0000000..a376a16
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/widget/ArtefactWidgets.kt
@@ -0,0 +1,534 @@
+package com.chethan616.clearpdf.widget
+
+import android.app.PendingIntent
+import android.appwidget.AppWidgetManager
+import android.appwidget.AppWidgetProvider
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.net.Uri
+import android.os.Build
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.util.TypedValue
+import android.widget.RemoteViews
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.ui.layout.SubcomposeLayout
+import androidx.compose.ui.unit.Constraints
+import androidx.compose.foundation.layout.wrapContentHeight
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.layout.boundsInRoot
+import androidx.compose.ui.layout.onGloballyPositioned
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.chethan616.clearpdf.MainActivity
+import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.notes.Note
+import com.chethan616.clearpdf.notes.NoteFile
+import com.chethan616.clearpdf.notes.NoteKind
+import com.chethan616.clearpdf.notes.Notes
+import com.chethan616.clearpdf.ui.AppViewModel
+import com.chethan616.clearpdf.ui.ThemeChoice
+import com.chethan616.clearpdf.ui.glass.Feel
+import com.chethan616.clearpdf.ui.glass.GlassSettings
+import com.chethan616.clearpdf.ui.glass.Haptics
+import com.chethan616.clearpdf.ui.home.CardShape
+import com.chethan616.clearpdf.ui.home.cardPaint
+import com.chethan616.clearpdf.ui.home.ListCard
+import com.chethan616.clearpdf.ui.home.LocalHomeVm
+import com.chethan616.clearpdf.ui.home.NoteCard
+import com.chethan616.clearpdf.ui.home.RecentCard
+import com.chethan616.clearpdf.ui.theme.ClearTheme
+import com.chethan616.clearpdf.ui.theme.clear
+import java.io.File
+
+/** What a widget tap asks the app to open: a note by its id. */
+const val EXTRA_OPEN_NOTE = "com.chethan616.clearpdf.OPEN_NOTE"
+
+/** What a widget tap asks the app to open: a recent document by its uri. */
+const val EXTRA_OPEN_RECENT = "com.chethan616.clearpdf.OPEN_RECENT"
+
+/** A widget tap that asks for Files (Recent). */
+const val EXTRA_OPEN_FILES = "com.chethan616.clearpdf.OPEN_FILES"
+
+/**
+ * The home screen widgets. Each is the desk's very card: the app's own `ListCard`, `NoteCard` and
+ * `RecentCard` composables, liquid glass and all, under the user's glass settings, rendered off
+ * screen ([ComposeSnapshot]) at the widget's own size, with tap targets laid exactly over the list's
+ * pills. (A home screen can only show a widget's pictures and send its taps; the glass can't run
+ * live there, so a tap answers with a press light, the app's haptic and the card redrawn.)
+ */
+object Widgets {
+ private val main = Handler(Looper.getMainLooper())
+ private val queue = ArrayDeque<() -> Unit>()
+ private var busy = false
+
+ /** Runs the renders one after another on the main thread (one virtual display at a time). */
+ internal fun enqueue(job: (next: () -> Unit) -> Unit) {
+ main.post {
+ queue.addLast {
+ job {
+ main.post {
+ busy = false
+ drain()
+ }
+ }
+ }
+ drain()
+ }
+ }
+
+ private fun drain() {
+ if (busy) return
+ val job = queue.removeFirstOrNull() ?: return
+ busy = true
+ job()
+ }
+
+ private val soon = Runnable { pendingCtx?.let { refreshAll(it) }; pendingCtx = null }
+ @Volatile private var pendingCtx: Context? = null
+
+ /**
+ * Redraw the notes widgets once the notes have been still for a moment: drawing a widget card runs
+ * on the main thread, so doing it on every tick stuttered the very tap that ticked. Any thread.
+ */
+ fun refreshSoon(ctx: Context) {
+ val app = ctx.applicationContext
+ val mgr = AppWidgetManager.getInstance(app)
+ if (mgr.getAppWidgetIds(ComponentName(app, TodoWidget::class.java)).isEmpty() &&
+ mgr.getAppWidgetIds(ComponentName(app, NoteWidget::class.java)).isEmpty()) return
+ pendingCtx = app
+ main.removeCallbacks(soon)
+ main.postDelayed(soon, 1500L)
+ }
+
+ /** Redraw the notes widgets (the notes changed). Any thread. */
+ fun refreshAll(ctx: Context, then: (() -> Unit)? = null) {
+ val app = ctx.applicationContext
+ val mgr = AppWidgetManager.getInstance(app)
+ val todo = mgr.getAppWidgetIds(ComponentName(app, TodoWidget::class.java))
+ val notes = mgr.getAppWidgetIds(ComponentName(app, NoteWidget::class.java))
+ var left = todo.size + notes.size
+ if (left == 0) {
+ then?.invoke()
+ return
+ }
+ val one = { if (--left == 0) then?.invoke() }
+ todo.forEach { id -> TodoWidget.update(app, mgr, id, one) }
+ notes.forEach { id -> NoteWidget.update(app, mgr, id, one) }
+ }
+
+ /** The widget's size in pixels (its current size on the home screen, portrait or landscape). */
+ internal fun size(ctx: Context, options: Bundle): Pair<Int, Int> {
+ val dm = ctx.resources.displayMetrics
+ // Android 12+: the sizes the launcher really lays the widget out at (the min/max pair can be off)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ val sizes = androidx.core.os.BundleCompat.getParcelableArrayList(options, AppWidgetManager.OPTION_APPWIDGET_SIZES, android.util.SizeF::class.java)
+ val portrait = ctx.resources.configuration.orientation != android.content.res.Configuration.ORIENTATION_LANDSCAPE
+ val pick = sizes?.let { list -> if (portrait) list.minByOrNull { it.width } else list.maxByOrNull { it.width } }
+ if (pick != null && pick.width > 0f && pick.height > 0f) {
+ fun px(v: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, dm).toInt()
+ return px(pick.width) to px(pick.height)
+ }
+ }
+ val portrait = ctx.resources.configuration.orientation != android.content.res.Configuration.ORIENTATION_LANDSCAPE
+ val wDp = options.getInt(if (portrait) AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH else AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, 160)
+ val hDp = options.getInt(if (portrait) AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT else AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, 220)
+ fun px(v: Int) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v.coerceAtLeast(40).toFloat(), dm).toInt()
+ return px(wDp) to px(hDp)
+ }
+
+ internal fun activity(ctx: Context, requestKey: String, extras: Intent.() -> Unit): PendingIntent {
+ val intent = Intent(ctx, MainActivity::class.java)
+ .setData(Uri.parse("artefact://widget/$requestKey"))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ .apply(extras)
+ return PendingIntent.getActivity(ctx, requestKey.hashCode(), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ }
+
+ internal fun open(ctx: Context, noteId: String?, requestKey: String): PendingIntent =
+ activity(ctx, requestKey) { if (noteId != null) putExtra(EXTRA_OPEN_NOTE, noteId) }
+
+ internal fun mediaFile(ctx: Context, name: String) = File(File(File(ctx.filesDir, "notes"), "media"), name)
+
+ internal fun cornerPx(ctx: Context) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, ctx.resources.displayMetrics)
+
+ internal fun toDp(ctx: Context, px: Int): Dp = (px / ctx.resources.displayMetrics.density).dp
+
+ internal fun themeChoice(ctx: Context): ThemeChoice =
+ runCatching { ThemeChoice.valueOf(ctx.getSharedPreferences("app", Context.MODE_PRIVATE).getString("theme", "System") ?: "System") }.getOrDefault(ThemeChoice.System)
+
+ /** A desk card's width: the desk is two columns, 16 dp from the screen's edges and 12 dp apart. */
+ internal fun deskWidth(ctx: Context): Dp = ((ctx.resources.configuration.screenWidthDp - 44) / 2f).coerceIn(120f, 240f).dp
+
+ /** How far [SquareCard] widens a card at each try. */
+ internal fun stepPx(ctx: Context) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6f, ctx.resources.displayMetrics).toInt().coerceAtLeast(1)
+
+ /** Room to lay a card out in before it is cut to its own height: twice the widget's height. */
+ internal fun canvasHeight(boxH: Int) = boxH * 2
+
+ /**
+ * The card as the desk lays it out, as wide as the widget and at least as tall, on what the desk
+ * shows behind it (the wallpaper's gradient), in the app's theme; [placed] gets its bounds.
+ */
+ @Composable
+ internal fun Desk(choice: ThemeChoice, placed: (android.graphics.Rect) -> Unit, content: @Composable () -> Unit) {
+ ClearTheme(choice) {
+ Box(Modifier.fillMaxSize()) {
+ Box(
+ Modifier.fillMaxWidth().wrapContentHeight().clip(CardShape).background(Brush.verticalGradient(clear.wall))
+ .onGloballyPositioned { placed(it.boundsInRoot().toRect()) },
+ ) { content() }
+ }
+ }
+ }
+
+ internal fun androidx.compose.ui.geometry.Rect.toRect() = android.graphics.Rect(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
+
+ /** How the card sits in the widget (fit inside, centred, never enlarged): its scale and where its corner lands. */
+ internal class Fit(val scale: Float, val dx: Float, val dy: Float)
+
+ internal fun fit(boxW: Int, boxH: Int, cardW: Int, cardH: Int): Fit {
+ val s = minOf(boxW / cardW.toFloat(), boxH / cardH.toFloat())
+ // centred across, resting on the bottom: the card meets the label the launcher writes under it
+ return Fit(s, (boxW - cardW * s) / 2f, boxH - cardH * s)
+ }
+
+ /** [card] drawn into a picture of the widget's own size where [fit] puts it (the image view shows it as is). */
+ internal fun onBox(card: Bitmap, boxW: Int, boxH: Int): Bitmap {
+ if (boxW <= 0 || boxH <= 0) return card
+ val f = fit(boxW, boxH, card.width, card.height)
+ val out = Bitmap.createBitmap(boxW, boxH, Bitmap.Config.ARGB_8888)
+ android.graphics.Canvas(out).drawBitmap(
+ card, null,
+ android.graphics.RectF(f.dx, f.dy, f.dx + card.width * f.scale, f.dy + card.height * f.scale),
+ android.graphics.Paint(android.graphics.Paint.FILTER_BITMAP_FLAG or android.graphics.Paint.ANTI_ALIAS_FLAG),
+ )
+ return out
+ }
+
+ /** Lays the whole-card tap target over the card itself (not the clear room around it). */
+ internal fun placeCardTarget(views: RemoteViews, f: Fit, cardW: Int, cardH: Int) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return
+ views.setViewLayoutWidth(R.id.card_open, cardW * f.scale, TypedValue.COMPLEX_UNIT_PX)
+ views.setViewLayoutHeight(R.id.card_open, cardH * f.scale, TypedValue.COMPLEX_UNIT_PX)
+ views.setViewLayoutMargin(R.id.card_open, RemoteViews.MARGIN_LEFT, f.dx, TypedValue.COMPLEX_UNIT_PX)
+ views.setViewLayoutMargin(R.id.card_open, RemoteViews.MARGIN_TOP, f.dy, TypedValue.COMPLEX_UNIT_PX)
+ }
+
+ internal val ROWS = intArrayOf(R.id.row0, R.id.row1, R.id.row2, R.id.row3, R.id.row4, R.id.row5, R.id.row6, R.id.row7)
+
+ /** A row target laid over [r] (card pixels) of the fitted card. */
+ internal fun placeRow(views: RemoteViews, rowId: Int, f: Fit, r: android.graphics.RectF) {
+ views.setViewVisibility(rowId, android.view.View.VISIBLE)
+ views.setViewLayoutWidth(rowId, r.width() * f.scale, TypedValue.COMPLEX_UNIT_PX)
+ views.setViewLayoutHeight(rowId, r.height() * f.scale, TypedValue.COMPLEX_UNIT_PX)
+ views.setViewLayoutMargin(rowId, RemoteViews.MARGIN_LEFT, f.dx + r.left * f.scale, TypedValue.COMPLEX_UNIT_PX)
+ views.setViewLayoutMargin(rowId, RemoteViews.MARGIN_TOP, f.dy + r.top * f.scale, TypedValue.COMPLEX_UNIT_PX)
+ }
+
+ // ---- Recent: drawn by the app (its thumbnails live there), kept for when the app is away ------
+
+ private fun recentFile(ctx: Context) = File(ctx.cacheDir, "widget_recent.png")
+
+ private fun recentTopFile(ctx: Context) = File(ctx.cacheDir, "widget_recent_top.txt")
+
+ /** The app's view model while it runs: Recent's thumbnails come from it. */
+ @Volatile
+ internal var liveVm: java.lang.ref.WeakReference<AppViewModel>? = null
+
+ /** The app's recent documents changed (or a Recent widget was resized): draw the Recent card for every Recent widget. */
+ fun refreshRecent(vm: AppViewModel, force: Boolean = false) {
+ liveVm = java.lang.ref.WeakReference(vm)
+ val app = vm.getApplication<android.app.Application>()
+ val mgr = AppWidgetManager.getInstance(app)
+ val ids = mgr.getAppWidgetIds(ComponentName(app, RecentWidget::class.java))
+ if (ids.isEmpty()) return
+ // only when the list really changed (every return to the app asks), and not during the moment
+ // the app is coming back, when its own screens are animating
+ val sig = vm.recentList.joinToString("|") { it.uri + it.opened } + "#" + ids.joinToString(",")
+ if (!force && sig == lastRecentSig) return
+ lastRecentSig = sig
+ main.removeCallbacks(recentSoon)
+ recentVm = java.lang.ref.WeakReference(vm)
+ main.postDelayed(recentSoon, 1200L)
+ }
+
+ @Volatile private var lastRecentSig: String? = null
+ @Volatile private var recentVm: java.lang.ref.WeakReference<AppViewModel>? = null
+ private val recentSoon = Runnable { recentVm?.get()?.let { drawRecent(it) } }
+
+ private fun drawRecent(vm: AppViewModel) {
+ val app = vm.getApplication<android.app.Application>()
+ val mgr = AppWidgetManager.getInstance(app)
+ val ids = mgr.getAppWidgetIds(ComponentName(app, RecentWidget::class.java))
+ if (ids.isEmpty()) return
+ val rows = vm.recentRows()
+ val top = vm.recentList.firstOrNull()?.uri
+ if (rows.isEmpty()) {
+ recentFile(app).delete()
+ ids.forEach { RecentWidget.show(app, mgr, it, null, null) }
+ return
+ }
+ ids.forEach { id ->
+ val (w, h) = size(app, mgr.getAppWidgetOptions(id))
+ enqueue { next ->
+ GlassSettings.load(app)
+ val choice = themeChoice(app)
+ // the desk's own Recent card, exactly: its width on the desk (two columns, 16 dp edges,
+ // 12 dp apart), its 226 dp, its fan of pages as it is; the widget fits the whole picture
+ // to its size, so every size shows the same card, only larger or smaller
+ val pad = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12f, app.resources.displayMetrics).toInt()
+ val deskW = ((app.resources.configuration.screenWidthDp - 44) / 2f).coerceIn(120f, 240f).dp
+ val deskWPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, deskW.value, app.resources.displayMetrics).toInt()
+ val deskHPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 226f, app.resources.displayMetrics).toInt()
+ val inner = minOf(w, h)
+ ComposeSnapshot.render(
+ app, deskWPx + 2 * pad, deskHPx + 2 * pad, 0f, settleMs = 1100,
+ content = {
+ ClearTheme(choice) {
+ CompositionLocalProvider(LocalHomeVm provides vm) {
+ Box(Modifier.fillMaxSize().padding(toDp(app, pad))) {
+ RecentCard(vm, rows, onAll = {}, modifier = Modifier.width(deskW))
+ }
+ }
+ }
+ },
+ ) { frame ->
+ if (frame != null) runCatching { recentFile(app).outputStream().use { frame.compress(Bitmap.CompressFormat.PNG, 100, it) } }
+ if (top != null) runCatching { recentTopFile(app).writeText(top) }
+ if (inner > 0) RecentWidget.show(app, mgr, id, frame, top)
+ next()
+ }
+ }
+ }
+ }
+
+ internal fun savedRecent(ctx: Context): Pair<Bitmap?, String?> =
+ (runCatching { BitmapFactory.decodeFile(recentFile(ctx).path) }.getOrNull()) to runCatching { recentTopFile(ctx).readText() }.getOrNull()
+}
+
+/** The most recent list (pinned first), its first items ticked right on the home screen. */
+class TodoWidget : AppWidgetProvider() {
+ override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
+ val pending = goAsync()
+ var left = ids.size
+ if (left == 0) return pending.finish()
+ ids.forEach { update(context, manager, it) { if (--left == 0) pending.finish() } }
+ }
+
+ override fun onAppWidgetOptionsChanged(context: Context, manager: AppWidgetManager, id: Int, newOptions: Bundle) {
+ val pending = goAsync()
+ update(context, manager, id) { pending.finish() }
+ }
+
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action == ACTION_TOGGLE) {
+ val note = intent.getStringExtra(EXTRA_NOTE)
+ val item = intent.getStringExtra(EXTRA_ITEM)
+ if (note == null || item == null) return
+ // the app's own feel for ticking a pill, under its haptics setting
+ val app = context.applicationContext
+ GlassSettings.load(app)
+ val wasDone = NoteFile.read(app).firstOrNull { it.id == note }?.items?.firstOrNull { it.id == item }?.done == true
+ runCatching { Haptics(app, android.view.View(app)).play(if (wasDone) Feel.ToggleOff else Feel.ToggleOn) }
+ // the file is the truth for a tick from the home screen: written at once, then the app (if it
+ // runs) reads it again, so its own copy never writes over the tick
+ NoteFile.toggle(app, note, item)
+ Notes.live?.takeIf { it.isActive && it.loaded }?.let { live -> Handler(Looper.getMainLooper()).post { live.reload() } }
+ val pending = goAsync()
+ Widgets.refreshAll(app) { pending.finish() }
+ return
+ }
+ super.onReceive(context, intent)
+ }
+
+ companion object {
+ const val ACTION_TOGGLE = "com.chethan616.clearpdf.widget.TOGGLE"
+ private const val EXTRA_NOTE = "note"
+ private const val EXTRA_ITEM = "item"
+
+ fun update(ctx: Context, mgr: AppWidgetManager, id: Int, done: () -> Unit = {}) {
+ val app = ctx.applicationContext
+ val (w, h) = Widgets.size(app, mgr.getAppWidgetOptions(id))
+ // the list chosen for this widget, else the latest
+ val list = WidgetPicks.resolve(app, id, NoteKind.List)
+ val res = app.resources
+ val shown = list ?: Note("", NoteKind.List)
+ Widgets.enqueue { next ->
+ GlassSettings.load(app)
+ val choice = Widgets.themeChoice(app)
+ // the desk's own list card, exactly as the desk lays it out (its width, its own height,
+ // its first four items and "N more"); the widget fits that very picture to its size
+ val deskW = Widgets.deskWidth(app)
+ val deskWPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, deskW.value, res.displayMetrics).toInt()
+ val placed = LinkedHashMap<String, androidx.compose.ui.geometry.Rect>()
+ var card: android.graphics.Rect? = null
+ ComposeSnapshot.render(app, deskWPx, deskWPx * 3, Widgets.cornerPx(app), crop = { card }, content = {
+ Widgets.Desk(choice, placed = { card = it }) {
+ ListCard(shown, onOpen = {}, onLong = {}, onToggle = {}, modifier = Modifier.width(deskW), onItemPlaced = { item, r -> placed[item.id] = r })
+ }
+ }) { frame ->
+ val top = card?.top ?: 0
+ val bitmap = frame ?: WidgetCards(app, w, h).list(
+ shown, res.getString(R.string.notes_untitled_list), res.getString(R.string.notes_list_empty),
+ moreText = { res.getQuantityString(R.plurals.notes_more_items, it, it) },
+ ).bitmap
+ val spots = if (frame != null) placed.entries.map { (itemId, r) -> itemId to android.graphics.RectF(r.left, r.top - top, r.right, r.bottom - top) } else emptyList()
+ val f = Widgets.fit(w, h, bitmap.width, bitmap.height)
+ val views = RemoteViews(app.packageName, R.layout.widget_card)
+ views.setImageViewBitmap(R.id.card_image, Widgets.onBox(bitmap, w, h))
+ views.setContentDescription(R.id.card_image, shown.title.ifBlank { res.getString(R.string.notes_untitled_list) })
+ views.setOnClickPendingIntent(R.id.card_open, Widgets.open(app, list?.id, "list/$id"))
+ Widgets.placeCardTarget(views, f, bitmap.width, bitmap.height)
+ Widgets.ROWS.forEachIndexed { i, rowId ->
+ val spot = if (list != null) spots.getOrNull(i) else null
+ if (spot == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
+ views.setViewVisibility(rowId, android.view.View.GONE)
+ return@forEachIndexed
+ }
+ val (itemId, r) = spot
+ Widgets.placeRow(views, rowId, f, r)
+ val toggle = Intent(app, TodoWidget::class.java).setAction(ACTION_TOGGLE)
+ .setData(Uri.parse("artefact://widget/toggle/${list!!.id}/$itemId"))
+ .putExtra(EXTRA_NOTE, list.id).putExtra(EXTRA_ITEM, itemId)
+ views.setOnClickPendingIntent(
+ rowId,
+ PendingIntent.getBroadcast(app, "${list.id}/$itemId".hashCode(), toggle, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT),
+ )
+ }
+ runCatching { mgr.updateAppWidget(id, views) }
+ next()
+ done()
+ }
+ }
+ }
+ }
+}
+
+/** The most recent text note (pinned first) as the desk's paper card: the starter "Thought of the day" on a fresh install. */
+class NoteWidget : AppWidgetProvider() {
+ override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
+ val pending = goAsync()
+ var left = ids.size
+ if (left == 0) return pending.finish()
+ ids.forEach { update(context, manager, it) { if (--left == 0) pending.finish() } }
+ }
+
+ override fun onAppWidgetOptionsChanged(context: Context, manager: AppWidgetManager, id: Int, newOptions: Bundle) {
+ val pending = goAsync()
+ update(context, manager, id) { pending.finish() }
+ }
+
+ companion object {
+ fun update(ctx: Context, mgr: AppWidgetManager, id: Int, done: () -> Unit = {}) {
+ val app = ctx.applicationContext
+ val (w, h) = Widgets.size(app, mgr.getAppWidgetOptions(id))
+ // the note chosen for this widget, else the latest
+ val note = WidgetPicks.resolve(app, id, NoteKind.Text)
+ val res = app.resources
+ val shown = note ?: Note("", NoteKind.Text, title = res.getString(R.string.thought_title), body = res.getString(R.string.seed_note_body))
+ Widgets.enqueue { next ->
+ GlassSettings.load(app)
+ val choice = Widgets.themeChoice(app)
+ val side = minOf(w, h)
+ val sideDp = Widgets.toDp(app, side)
+ ComposeSnapshot.render(app, side, side, Widgets.cornerPx(app), content = {
+ ClearTheme(choice) {
+ Box(Modifier.size(sideDp).clip(CardShape).background(Brush.verticalGradient(clear.wall))) {
+ NoteCard(shown, onOpen = {}, onLong = {}, modifier = Modifier.fillMaxSize(), fitHeight = true)
+ }
+ }
+ }) { frame ->
+ val bitmap = frame ?: WidgetCards(app, w, h).note(shown, res.getString(R.string.notes_untitled_note)) { Widgets.mediaFile(app, it) }
+ val views = RemoteViews(app.packageName, R.layout.widget_card)
+ views.setImageViewBitmap(R.id.card_image, Widgets.onBox(bitmap, w, h))
+ views.setContentDescription(R.id.card_image, shown.title.ifBlank { res.getString(R.string.notes_untitled_note) })
+ views.setOnClickPendingIntent(R.id.card_open, Widgets.open(app, note?.id, "note/$id"))
+ Widgets.placeCardTarget(views, Widgets.fit(w, h, bitmap.width, bitmap.height), bitmap.width, bitmap.height)
+ Widgets.ROWS.forEach { views.setViewVisibility(it, android.view.View.GONE) }
+ runCatching { mgr.updateAppWidget(id, views) }
+ next()
+ done()
+ }
+ }
+ }
+ }
+}
+
+/** The desk's Recent card: the newest documents' first pages fanned, opening the newest. */
+class RecentWidget : AppWidgetProvider() {
+ override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
+ val (bitmap, top) = Widgets.savedRecent(context)
+ ids.forEach { show(context, manager, it, bitmap, top) }
+ Widgets.liveVm?.get()?.let { vm -> Handler(Looper.getMainLooper()).post { Widgets.refreshRecent(vm, force = true) } }
+ }
+
+ override fun onAppWidgetOptionsChanged(context: Context, manager: AppWidgetManager, id: Int, newOptions: Bundle) {
+ val (bitmap, top) = Widgets.savedRecent(context)
+ // at once: the last picture fitted to the new size; then, if the app runs, the card drawn anew
+ show(context, manager, id, bitmap, top)
+ Widgets.liveVm?.get()?.let { vm -> Handler(Looper.getMainLooper()).post { Widgets.refreshRecent(vm, force = true) } }
+ }
+
+ companion object {
+ fun show(ctx: Context, mgr: AppWidgetManager, id: Int, bitmap: Bitmap?, top: String?) {
+ val app = ctx.applicationContext
+ val views = RemoteViews(app.packageName, R.layout.widget_card)
+ val (w, h) = Widgets.size(app, mgr.getAppWidgetOptions(id))
+ if (bitmap != null) views.setImageViewBitmap(R.id.card_image, Widgets.onBox(bitmap, w, h))
+ views.setContentDescription(R.id.card_image, app.getString(R.string.desk_recent))
+ if (bitmap != null) Widgets.placeCardTarget(views, Widgets.fit(w, h, bitmap.width, bitmap.height), bitmap.width, bitmap.height)
+ // the card opens the newest document, as on the desk; without one, the app's Files
+ views.setOnClickPendingIntent(
+ R.id.card_open,
+ Widgets.activity(app, "recent/$id/${top.orEmpty()}") { if (top != null) putExtra(EXTRA_OPEN_RECENT, top) else putExtra(EXTRA_OPEN_FILES, true) },
+ )
+ Widgets.ROWS.forEach { views.setViewVisibility(it, android.view.View.GONE) }
+ runCatching { mgr.updateAppWidget(id, views) }
+ }
+ }
+}
+
+/**
+ * The list card as a square of [sidePx], showing as many of its items as fit (four at most, as on
+ * the desk), the rest as "N more": each size shows the card at its own scale, as Apple's widgets do.
+ */
+@Composable
+private fun FitList(wPx: Int, hPx: Int, note: Note, onItemPlaced: (com.chethan616.clearpdf.notes.CheckItem, androidx.compose.ui.geometry.Rect) -> Unit) {
+ val wall = clear.wall
+ SubcomposeLayout { _ ->
+ val wDp = wPx.toDp()
+ val hDp = hPx.toDp()
+ // as many pills as the widget's height holds (the default 2x3 holds three), at most eight
+ var k = 8
+ while (k > 1) {
+ val n = k
+ val probe = subcompose("probe$n") { ListCard(note, onOpen = {}, onLong = {}, onToggle = {}, modifier = Modifier.width(wDp), maxItems = n) }
+ .firstOrNull()?.measure(Constraints(minWidth = wPx, maxWidth = wPx)) ?: break
+ if (probe.height <= hPx) break
+ k--
+ }
+ val shown = k
+ val card = subcompose("card") {
+ Box(Modifier.size(wDp, hDp).clip(CardShape).background(Brush.verticalGradient(wall))) {
+ ListCard(note, onOpen = {}, onLong = {}, onToggle = {}, modifier = Modifier.fillMaxSize(), onItemPlaced = onItemPlaced, maxItems = shown)
+ }
+ }.firstOrNull()?.measure(Constraints.fixed(wPx, hPx))
+ layout(wPx, hPx) { card?.place(0, 0) }
+ }
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/widget/ComposeSnapshot.kt b/android/app/src/main/java/com/chethan616/clearpdf/widget/ComposeSnapshot.kt
new file mode 100644
index 0000000..f6dd7a8
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/widget/ComposeSnapshot.kt
@@ -0,0 +1,174 @@
+package com.chethan616.clearpdf.widget
+
+import android.app.Presentation
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapShader
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.PixelFormat
+import android.graphics.RectF
+import android.graphics.Shader
+import android.graphics.drawable.ColorDrawable
+import android.hardware.display.DisplayManager
+import android.hardware.display.VirtualDisplay
+import android.media.ImageReader
+import android.os.Handler
+import android.os.Looper
+import android.view.ViewGroup
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.platform.ComposeView
+import androidx.compose.ui.platform.ViewCompositionStrategy
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.LifecycleRegistry
+import androidx.lifecycle.ViewModelStore
+import androidx.lifecycle.ViewModelStoreOwner
+import androidx.lifecycle.setViewTreeLifecycleOwner
+import androidx.lifecycle.setViewTreeViewModelStoreOwner
+import androidx.savedstate.SavedStateRegistry
+import androidx.savedstate.SavedStateRegistryController
+import androidx.savedstate.SavedStateRegistryOwner
+import androidx.savedstate.setViewTreeSavedStateRegistryOwner
+
+/**
+ * Draws real Compose UI (the desk's own cards, liquid glass and all) into a bitmap for a home screen
+ * widget. The composable runs in a window on a private virtual display, so it gets the same
+ * hardware renderer, shaders and backdrop layers as on the desk; the display's frames come back
+ * through an [ImageReader]. Main thread only.
+ */
+internal object ComposeSnapshot {
+ /** Lifecycle, saved state and view models for a ComposeView with no activity around it. */
+ private class Owner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner {
+ private val registry = LifecycleRegistry(this)
+ private val saved = SavedStateRegistryController.create(this)
+ override val lifecycle: Lifecycle get() = registry
+ override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
+ override val viewModelStore = ViewModelStore()
+
+ fun start() {
+ saved.performAttach()
+ saved.performRestore(null)
+ registry.currentState = Lifecycle.State.RESUMED
+ }
+
+ fun stop() {
+ registry.currentState = Lifecycle.State.DESTROYED
+ viewModelStore.clear()
+ }
+ }
+
+ /**
+ * Renders [content] at [w] × [h] pixels and calls [done] with the frame, its outside cut to a
+ * rounded rectangle of [cornerPx] (the card's own corners), or null if it could not be drawn.
+ * [settleMs] lets pictures load and the glass draw its first settled frame.
+ */
+ fun render(
+ ctx: Context,
+ w: Int,
+ h: Int,
+ cornerPx: Float,
+ settleMs: Long = 200,
+ /** The part of the frame to keep (the card's own bounds), read when the frame is taken; null keeps it all. */
+ crop: () -> android.graphics.Rect? = { null },
+ content: @Composable () -> Unit,
+ done: (Bitmap?) -> Unit,
+ ) {
+ val main = Handler(Looper.getMainLooper())
+ var reader: ImageReader? = null
+ var display: VirtualDisplay? = null
+ var presentation: Presentation? = null
+ val owner = Owner()
+ var latest: Bitmap? = null
+ var frames = 0
+ var firstAt = 0L
+ var finished = false
+ fun cleanUp() {
+ runCatching { presentation?.dismiss() }
+ runCatching { display?.release() }
+ runCatching { reader?.close() }
+ runCatching { owner.stop() }
+ }
+ try {
+ val r = ImageReader.newInstance(w, h, PixelFormat.RGBA_8888, 3)
+ reader = r
+ r.setOnImageAvailableListener({ ir ->
+ if (finished) return@setOnImageAvailableListener
+ val img = runCatching { ir.acquireLatestImage() }.getOrNull() ?: return@setOnImageAvailableListener
+ try {
+ val plane = img.planes[0]
+ val rowPx = plane.rowStride / plane.pixelStride
+ val full = Bitmap.createBitmap(rowPx, h, Bitmap.Config.ARGB_8888)
+ full.copyPixelsFromBuffer(plane.buffer)
+ latest?.recycle()
+ latest = if (rowPx == w) full else Bitmap.createBitmap(full, 0, 0, w, h).also { full.recycle() }
+ if (frames++ == 0) firstAt = android.os.SystemClock.uptimeMillis()
+ } finally {
+ img.close()
+ }
+ }, main)
+ val dm = ctx.getSystemService(DisplayManager::class.java)
+ val vd = dm.createVirtualDisplay("artefact-widget", w, h, ctx.resources.displayMetrics.densityDpi, r.surface, 0)
+ display = vd
+ val p = Presentation(ctx, vd.display)
+ presentation = p
+ owner.start()
+ val view = ComposeView(p.context).apply {
+ setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow)
+ setViewTreeLifecycleOwner(owner)
+ setViewTreeSavedStateRegistryOwner(owner)
+ setViewTreeViewModelStoreOwner(owner)
+ setContent(content)
+ }
+ p.window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
+ p.setContentView(view, ViewGroup.LayoutParams(w, h))
+ p.window?.decorView?.let {
+ it.setViewTreeLifecycleOwner(owner)
+ it.setViewTreeSavedStateRegistryOwner(owner)
+ it.setViewTreeViewModelStoreOwner(owner)
+ }
+ p.window?.setLayout(w, h)
+ p.show()
+ } catch (t: Throwable) {
+ android.util.Log.w("ArtefactWidget", "could not draw the card", t)
+ cleanUp()
+ done(null)
+ return
+ }
+ val started = android.os.SystemClock.uptimeMillis()
+ val take = object : Runnable {
+ override fun run() {
+ val now = android.os.SystemClock.uptimeMillis()
+ // wait for the first frame, then let pictures load and the glass draw its settled frame
+ val ready = frames > 0 && now - firstAt >= settleMs
+ if (!ready && now - started < 1500L) {
+ main.postDelayed(this, 40L)
+ return
+ }
+ finished = true
+ val frame = latest
+ if (frame == null) android.util.Log.w("ArtefactWidget", "no frame after ${now - started} ms ($w x $h)")
+ latest = null
+ cleanUp()
+ val cut = crop()?.takeIf { it.width() > 0 && it.height() > 0 }
+ val kept = if (frame != null && cut != null) {
+ val r = android.graphics.Rect(cut).apply { intersect(0, 0, frame.width, frame.height) }
+ Bitmap.createBitmap(frame, r.left, r.top, r.width(), r.height()).also { if (it !== frame) frame.recycle() }
+ } else {
+ frame
+ }
+ done(kept?.let { clipCorners(it, cornerPx) })
+ }
+ }
+ main.postDelayed(take, 40L)
+ }
+
+ /** The frame with everything outside the card's rounded rectangle made clear. */
+ private fun clipCorners(src: Bitmap, r: Float): Bitmap {
+ val out = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888)
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { shader = BitmapShader(src, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) }
+ Canvas(out).drawRoundRect(RectF(0f, 0f, src.width.toFloat(), src.height.toFloat()), r, r, paint)
+ src.recycle()
+ return out
+ }
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetCards.kt b/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetCards.kt
new file mode 100644
index 0000000..3d0131a
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetCards.kt
@@ -0,0 +1,317 @@
+package com.chethan616.clearpdf.widget
+
+import android.content.Context
+import android.content.res.Configuration
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Canvas
+import android.graphics.LinearGradient
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.RadialGradient
+import android.graphics.RectF
+import android.graphics.Shader
+import android.graphics.Typeface
+import android.text.Layout
+import android.text.StaticLayout
+import android.text.TextPaint
+import android.text.TextUtils
+import android.util.TypedValue
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.toArgb
+import androidx.core.content.res.ResourcesCompat
+import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.notes.CheckItem
+import com.chethan616.clearpdf.notes.Note
+import com.chethan616.clearpdf.ui.theme.CardTone
+import com.chethan616.clearpdf.ui.theme.DarkClear
+import com.chethan616.clearpdf.ui.theme.LightClear
+import com.chethan616.clearpdf.ui.theme.Tone
+import java.io.File
+import java.text.DateFormat
+import java.util.Date
+
+/**
+ * The desk's cards drawn for the home screen: the same gradients, glow, rim, type, sizes and
+ * spacing as `ListCard` and `NoteCard` (ui/home/Cards.kt), laid out in dp at the widget's own size.
+ * A widget can't host the app's live glass (it refracts only what is behind it inside the app), so
+ * the list's pills are painted as the glass looks over their card: a lighter capsule with a rim.
+ */
+internal class WidgetCards(private val ctx: Context, private val w: Int, private val h: Int) {
+ private val dm = ctx.resources.displayMetrics
+ private val fontScale = ctx.resources.configuration.fontScale
+ private fun dp(v: Float) = v * dm.density
+ private fun sp(v: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, v, dm)
+ val dark: Boolean = isDark(ctx)
+ private val colors = if (dark) DarkClear else LightClear
+
+ private fun face(res: Int): Typeface? = ResourcesCompat.getFont(ctx, res)
+
+ private fun paint(res: Int, sizeSp: Float, color: Int, variation: String, trackingSp: Float = 0f) = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
+ typeface = face(res)
+ textSize = sp(sizeSp)
+ this.color = color
+ letterSpacing = if (sizeSp > 0f) trackingSp / sizeSp else 0f
+ fontVariationSettings = variation
+ }
+
+ private fun layout(text: CharSequence, p: TextPaint, width: Int, lineSp: Float, maxLines: Int, align: Layout.Alignment = Layout.Alignment.ALIGN_NORMAL): StaticLayout {
+ val natural = p.fontMetrics.let { it.descent - it.ascent }
+ val extra = (sp(lineSp) - natural).coerceAtLeast(0f)
+ return StaticLayout.Builder.obtain(text, 0, text.length, p, width.coerceAtLeast(1))
+ .setAlignment(align)
+ .setMaxLines(maxLines)
+ .setEllipsize(TextUtils.TruncateAt.END)
+ .setIncludePad(false)
+ .setLineSpacing(extra, 1f)
+ .build()
+ }
+
+ /** `WordFitText`: the size shrinks when the longest word would not fit the width. */
+ private fun fitScale(text: String, p: TextPaint, room: Int): Float {
+ val widest = text.split(' ', '\n').filter { it.isNotBlank() }.maxOfOrNull { p.measureText(it) } ?: 0f
+ return if (widest <= room || widest == 0f) 1f else (room / widest * 0.98f).coerceAtLeast(0.5f)
+ }
+
+ // ---- the card itself: cardPaint ----------------------------------------------------------------
+
+ private fun base(tone: CardTone, glowX: Float, glowY: Float): Pair<Bitmap, Canvas> {
+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ val c = Canvas(bmp)
+ val radius = dp(30f)
+ val shape = Path().apply { addRoundRect(RectF(0f, 0f, w.toFloat(), h.toFloat()), radius, radius, Path.Direction.CW) }
+ c.save()
+ c.clipPath(shape)
+ // what the desk shows behind a translucent card: the wallpaper's middle
+ c.drawColor(colors.wall[colors.wall.size / 2].toArgb())
+ val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { shader = LinearGradient(0f, 0f, 0f, h.toFloat(), tone.top.toArgb(), tone.bottom.toArgb(), Shader.TileMode.CLAMP) }
+ c.drawRect(0f, 0f, w.toFloat(), h.toFloat(), fill)
+ val reach = maxOf(w, h) * 0.75f
+ val glow = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ shader = RadialGradient(
+ glowX * w, glowY * h, reach,
+ Color.White.copy(alpha = if (dark) 0.10f else 0.32f).toArgb(), android.graphics.Color.TRANSPARENT, Shader.TileMode.CLAMP,
+ )
+ }
+ c.drawCircle(glowX * w, glowY * h, reach, glow)
+ c.restore()
+ // the 1 dp rim: bright at the top, nearly gone at the bottom
+ val inset = dp(0.5f)
+ val rim = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = dp(1f)
+ shader = LinearGradient(
+ 0f, 0f, 0f, h.toFloat(),
+ Color.White.copy(alpha = if (dark) 0.18f else 0.6f).toArgb(), Color.White.copy(alpha = 0.05f).toArgb(), Shader.TileMode.CLAMP,
+ )
+ }
+ c.drawRoundRect(RectF(inset, inset, w - inset, h - inset), radius - inset, radius - inset, rim)
+ return bmp to c
+ }
+
+ private fun Color.argb(alpha: Float) = copy(alpha = alpha).toArgb()
+
+ // ---- the list: ListCard ---------------------------------------------------------------------------
+
+ /** Where each ticked-able pill landed, in pixels, for the widget's tap targets. */
+ class Spot(val item: CheckItem, val top: Int, val height: Int)
+
+ class Drawn(val bitmap: Bitmap, val spots: List<Spot>)
+
+ fun list(note: Note, untitled: String, empty: String, moreText: (Int) -> String): Drawn {
+ val tone = colors.tone(Tone.Sage)
+ val (bmp, c) = base(tone, 0.15f, 0f)
+ val items = note.items.filter { it.text.isNotBlank() }
+ val padX = dp(12f)
+ val inner = (w - 2 * padX).toInt()
+ var y = dp(20f)
+
+ // the title in dot-matrix type, centred, its longest word kept whole
+ val titleText = note.title.ifBlank { untitled }
+ val titleBase = paint(R.font.doto, 30f, tone.ink.argb(0.92f), "'wght' 800, 'ROND' 60")
+ val titleRoom = inner - dp(4f).toInt()
+ val k = fitScale(titleText, titleBase, titleRoom)
+ val titlePaint = paint(R.font.doto, 30f * k, tone.ink.argb(0.92f), "'wght' 800, 'ROND' 60")
+ val title = layout(titleText, titlePaint, titleRoom, 32f * k, 3, Layout.Alignment.ALIGN_CENTER)
+ c.save()
+ c.translate(padX + dp(2f), y)
+ title.draw(c)
+ c.restore()
+ y += title.height + dp(18f)
+
+ // as many pills as fit (the desk shows four), 40 dp tall with 8 dp between
+ val pillH = dp(40f)
+ val gap = dp(8f)
+ val moreRoom = dp(8f) + sp(15f) + dp(14f)
+ var fit = 0
+ while (fit < items.size && y + (fit + 1) * pillH + fit * gap + dp(14f) <= h) fit++
+ if (fit < items.size && y + fit * (pillH + gap) - gap + moreRoom > h && fit > 1) fit-- // room for "+N more"
+ fit = fit.coerceAtLeast(if (items.isEmpty()) 0 else 1).coerceAtMost(8)
+ val spots = ArrayList<Spot>()
+ for (i in 0 until fit.coerceAtMost(items.size)) {
+ pill(c, items[i], tone, padX, y, w - padX, y + pillH)
+ spots.add(Spot(items[i], y.toInt(), pillH.toInt()))
+ y += pillH + gap
+ }
+ val more = items.size - spots.size
+ if (more > 0) {
+ val p = paint(R.font.jakarta, 11.5f, tone.ink.argb(0.6f), "'wght' 400")
+ c.save()
+ c.translate(padX + dp(10f), y)
+ layout(moreText(more), p, inner, 15f, 1).draw(c)
+ c.restore()
+ }
+ if (items.isEmpty()) {
+ val p = paint(R.font.jakarta, 13f, tone.ink.argb(0.6f), "'wght' 500")
+ c.save()
+ c.translate(padX, y)
+ layout(empty, p, inner, 18f, 2, Layout.Alignment.ALIGN_CENTER).draw(c)
+ c.restore()
+ }
+ return Drawn(bmp, spots)
+ }
+
+ /** `CheckPill`: a glass capsule with a round tick; ticked, it darkens and the tick fills. */
+ private fun pill(c: Canvas, item: CheckItem, tone: CardTone, left: Float, top: Float, right: Float, bottom: Float) {
+ val r = (bottom - top) / 2f
+ val rect = RectF(left, top, right, bottom)
+ // the glass over the card: a lift of light, a rim bright at the top
+ val glass = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ shader = LinearGradient(
+ 0f, top, 0f, bottom,
+ Color.White.copy(alpha = if (dark) 0.16f else 0.34f).toArgb(), Color.White.copy(alpha = if (dark) 0.07f else 0.2f).toArgb(), Shader.TileMode.CLAMP,
+ )
+ }
+ c.drawRoundRect(rect, r, r, glass)
+ if (item.done) {
+ val wash = if (dark) Color.Black.copy(alpha = 0.34f) else tone.ink.copy(alpha = 0.58f)
+ c.drawRoundRect(rect, r, r, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = wash.toArgb() })
+ }
+ val rim = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = dp(1f)
+ shader = LinearGradient(
+ 0f, top, 0f, bottom,
+ Color.White.copy(alpha = if (dark) 0.35f else 0.8f).toArgb(), Color.White.copy(alpha = if (dark) 0.08f else 0.22f).toArgb(), Shader.TileMode.CLAMP,
+ )
+ }
+ val half = dp(0.5f)
+ c.drawRoundRect(RectF(left + half, top + half, right - half, bottom - half), r - half, r - half, rim)
+
+ val ink = if (item.done) Color.White else tone.ink
+ val cx = left + dp(8f) + dp(12f)
+ val cy = (top + bottom) / 2f
+ if (item.done) {
+ c.drawCircle(cx, cy, dp(12f), Paint(Paint.ANTI_ALIAS_FLAG).apply { color = android.graphics.Color.WHITE })
+ val tick = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = dp(2f)
+ strokeCap = Paint.Cap.ROUND
+ strokeJoin = Paint.Join.ROUND
+ color = (if (dark) tone.bottom else tone.ink).toArgb()
+ }
+ val s = dp(14f) / 24f
+ val path = Path().apply {
+ moveTo(cx + (5f - 12f) * s * 1.0f, cy + (12.5f - 12f) * s)
+ lineTo(cx + (10f - 12f) * s, cy + (17f - 12f) * s)
+ lineTo(cx + (19f - 12f) * s, cy + (7f - 12f) * s)
+ }
+ c.drawPath(path, tick)
+ } else {
+ c.drawCircle(cx, cy, dp(12f) - dp(0.8f), Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = dp(1.6f)
+ color = ink.argb(0.75f)
+ })
+ }
+ val textX = left + dp(8f) + dp(24f) + dp(10f)
+ val tp = paint(R.font.jakarta, 14.5f, ink.toArgb(), "'wght' 400")
+ val room = (right - dp(12f) - textX).toInt()
+ val line = layout(item.text, tp, room, 22f, 1)
+ c.save()
+ c.translate(textX, cy - line.height / 2f)
+ line.draw(c)
+ c.restore()
+ }
+
+ // ---- the note: NoteCard -----------------------------------------------------------------------------
+
+ fun note(note: Note, untitled: String, mediaFile: (String) -> File): Bitmap {
+ val tone = colors.tone(Tone.Paper)
+ val (bmp, c) = base(tone, 0.1f, 0f)
+ val pad = dp(18f)
+ val inner = (w - 2 * pad).toInt()
+ val title = note.title.ifBlank { note.body.lineSequence().firstOrNull { it.isNotBlank() }?.trim()?.removePrefix("# ").orEmpty() }
+ val body = if (note.title.isBlank()) "" else note.body.lineSequence().filter { it.isNotBlank() }.joinToString(" ") { it.trim().removePrefix("# ").replace("**", "") }
+ var y = pad
+
+ val titleText = title.ifBlank { untitled }
+ val variation = "'wght' 800"
+ val base = paint(R.font.jakarta, 27f, tone.accent.toArgb(), variation, -0.6f)
+ val k = fitScale(titleText, base, inner)
+ val tp = paint(R.font.jakarta, 27f * k, tone.accent.toArgb(), variation, -0.6f * k)
+ val tl = layout(titleText, tp, inner, 29f * k, 4)
+ c.save(); c.translate(pad, y); tl.draw(c); c.restore()
+ y += tl.height
+
+ val date = shortDate(note.updated)
+ val dp0 = paint(R.font.jakarta, 10.5f, tone.ink.argb(0.55f), "'wght' 400")
+ val dateH = dp0.fontMetrics.let { it.descent - it.ascent }
+ val dateTop = h - pad - dateH
+ if (body.isNotBlank() && title.length < 40) {
+ // up to three lines, as many as fit above the date (the desk card grows instead)
+ val lines = ((dateTop - dp(12f) - (y + dp(8f))) / sp(18f)).toInt().coerceAtMost(3)
+ if (lines >= 1) {
+ y += dp(8f)
+ val bp = paint(R.font.jakarta, 13f, tone.ink.argb(0.62f), "'wght' 500")
+ val bl = layout(body, bp, inner, 18f, lines)
+ c.save(); c.translate(pad, y); bl.draw(c); c.restore()
+ y += bl.height
+ }
+ }
+ note.images.firstOrNull()?.let { name ->
+ val room = dateTop - dp(12f) - (y + dp(12f))
+ val imgH = minOf(dp(86f), room)
+ if (imgH > dp(24f)) {
+ decode(mediaFile(name), inner, imgH.toInt())?.let { pic ->
+ val clip = Path().apply { addRoundRect(RectF(pad, y + dp(12f), pad + inner, y + dp(12f) + imgH), dp(16f), dp(16f), Path.Direction.CW) }
+ c.save(); c.clipPath(clip)
+ // ContentScale.Crop
+ val s = maxOf(inner / pic.width.toFloat(), imgH / pic.height.toFloat())
+ val dw = pic.width * s
+ val dh = pic.height * s
+ c.drawBitmap(pic, null, RectF(pad + (inner - dw) / 2f, y + dp(12f) + (imgH - dh) / 2f, pad + (inner + dw) / 2f, y + dp(12f) + (imgH + dh) / 2f), Paint(Paint.FILTER_BITMAP_FLAG))
+ c.restore()
+ pic.recycle()
+ }
+ }
+ }
+ // the date, at the bottom right
+ val dl = layout(date, dp0, inner, 15f, 1, Layout.Alignment.ALIGN_OPPOSITE)
+ c.save(); c.translate(pad, h - pad - dl.height); dl.draw(c); c.restore()
+ return bmp
+ }
+
+ private fun decode(file: File, maxW: Int, maxH: Int): Bitmap? = runCatching {
+ if (!file.isFile) return null
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeFile(file.absolutePath, bounds)
+ var sample = 1
+ while (bounds.outWidth / (sample * 2) >= maxW && bounds.outHeight / (sample * 2) >= maxH) sample *= 2
+ BitmapFactory.decodeFile(file.absolutePath, BitmapFactory.Options().apply { inSampleSize = sample })
+ }.getOrNull()
+
+ private fun shortDate(t: Long): String = DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(t))
+
+ companion object {
+ /** The app's theme choice (System, Light, Dark), as the desk reads it. */
+ fun isDark(ctx: Context): Boolean {
+ val choice = ctx.getSharedPreferences("app", Context.MODE_PRIVATE).getString("theme", "System")
+ return when (choice) {
+ "Light" -> false
+ "Dark" -> true
+ else -> ctx.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetPickActivity.kt b/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetPickActivity.kt
new file mode 100644
index 0000000..6686d51
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetPickActivity.kt
@@ -0,0 +1,119 @@
+package com.chethan616.clearpdf.widget
+
+import android.app.Activity
+import android.appwidget.AppWidgetManager
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.notes.Note
+import com.chethan616.clearpdf.notes.NoteFile
+import com.chethan616.clearpdf.notes.NoteKind
+import com.chethan616.clearpdf.ui.LucideIcons
+import com.chethan616.clearpdf.ui.SheetRow
+import com.chethan616.clearpdf.ui.SheetSection
+import com.chethan616.clearpdf.ui.glass.GlassSettings
+import com.chethan616.clearpdf.ui.theme.ClearTheme
+import com.chethan616.clearpdf.ui.theme.ClearType
+import com.chethan616.clearpdf.ui.theme.clear
+
+/** Which note or list each widget shows (by widget id); none chosen: the latest. */
+internal object WidgetPicks {
+ private const val PREFS = "widget_picks"
+
+ fun get(ctx: Context, widgetId: Int): String? =
+ ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("pick_$widgetId", null)
+
+ fun set(ctx: Context, widgetId: Int, noteId: String?) {
+ ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().apply {
+ if (noteId == null) remove("pick_$widgetId") else putString("pick_$widgetId", noteId)
+ }.apply()
+ }
+
+ /** The note [widgetId] shows: the one chosen for it, while it still exists, else the latest of [kind]. */
+ fun resolve(ctx: Context, widgetId: Int, kind: NoteKind): Note? {
+ val all = NoteFile.read(ctx).filter { it.kind == kind && if (kind == NoteKind.List) it.items.any { i -> i.text.isNotBlank() } else !it.isEmpty }
+ val chosen = get(ctx, widgetId)?.let { id -> all.firstOrNull { it.id == id } }
+ return chosen ?: all.sortedWith(compareByDescending<Note> { it.pinned }.thenByDescending { it.updated }).firstOrNull()
+ }
+}
+
+/**
+ * Choosing what a widget shows, when it is placed and later from the launcher's widget settings (as
+ * iOS's Edit Widget): "Latest" or one of the lists (To-Do widget) or notes (Notes widget), in the
+ * app's own sheet rows on its wallpaper.
+ */
+class WidgetPickActivity : ComponentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val widgetId = intent?.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID
+ setResult(Activity.RESULT_CANCELED, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId))
+ if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) return finish()
+ val mgr = AppWidgetManager.getInstance(this)
+ val provider = mgr.getAppWidgetInfo(widgetId)?.provider
+ val lists = provider?.className == TodoWidget::class.java.name
+ val kind = if (lists) NoteKind.List else NoteKind.Text
+ val notes = NoteFile.read(this)
+ .filter { it.kind == kind && if (lists) it.items.any { i -> i.text.isNotBlank() } else !it.isEmpty }
+ .sortedWith(compareByDescending<Note> { it.pinned }.thenByDescending { it.updated })
+ val current = WidgetPicks.get(this, widgetId)
+ GlassSettings.load(this)
+ enableEdgeToEdge()
+ setContent {
+ ClearTheme(Widgets.themeChoice(this)) {
+ Box(Modifier.fillMaxSize().background(Brush.verticalGradient(clear.wall))) {
+ Column(Modifier.fillMaxSize().statusBarsPadding().verticalScroll(rememberScrollState()).padding(vertical = 24.dp)) {
+ Text(
+ stringResource(if (lists) R.string.widget_pick_list else R.string.widget_pick_note),
+ style = ClearType.Headline, color = clear.ink, modifier = Modifier.padding(horizontal = 24.dp),
+ )
+ Spacer(Modifier.height(16.dp))
+ SheetSection {
+ SheetRow(LucideIcons.Sparkles, stringResource(R.string.widget_pick_latest), { choose(widgetId, null) }, checked = current == null)
+ }
+ if (notes.isNotEmpty()) SheetSection {
+ notes.forEach { n ->
+ val title = n.title.ifBlank {
+ if (lists) getString(R.string.notes_untitled_list)
+ else n.body.lineSequence().firstOrNull { it.isNotBlank() }?.trim()?.removePrefix("# ") ?: getString(R.string.notes_untitled_note)
+ }
+ SheetRow(if (lists) LucideIcons.Check else LucideIcons.FileText, title, { choose(widgetId, n.id) }, checked = current == n.id)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private fun choose(widgetId: Int, noteId: String?) {
+ WidgetPicks.set(this, widgetId, noteId)
+ Widgets.refreshAll(applicationContext)
+ setResult(Activity.RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId))
+ finish()
+ }
+
+ companion object {
+ /** Whether [component] is one of the widgets that show a chosen note. */
+ fun picks(component: ComponentName?) = component?.className == TodoWidget::class.java.name || component?.className == NoteWidget::class.java.name
+ }
+}
diff --git a/android/app/src/main/res/drawable/widget_card_ripple.xml b/android/app/src/main/res/drawable/widget_card_ripple.xml
new file mode 100644
index 0000000..244b45c
--- /dev/null
+++ b/android/app/src/main/res/drawable/widget_card_ripple.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A card's press on the home screen widget, in the card's rounded corners. -->
+<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="#26FFFFFF">
+ <item android:id="@android:id/mask">
+ <shape android:shape="rectangle">
+ <corners android:radius="28dp" />
+ <solid android:color="#FFFFFFFF" />
+ </shape>
+ </item>
+</ripple>
diff --git a/android/app/src/main/res/drawable/widget_pill_ripple.xml b/android/app/src/main/res/drawable/widget_pill_ripple.xml
new file mode 100644
index 0000000..fe3f568
--- /dev/null
+++ b/android/app/src/main/res/drawable/widget_pill_ripple.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A list item's press on the home screen widget: a soft light in the pill's own capsule. -->
+<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="#4DFFFFFF">
+ <item android:id="@android:id/mask">
+ <shape android:shape="rectangle">
+ <corners android:radius="999dp" />
+ <solid android:color="#FFFFFFFF" />
+ </shape>
+ </item>
+</ripple>
diff --git a/android/app/src/main/res/layout/widget_card.xml b/android/app/src/main/res/layout/widget_card.xml
new file mode 100644
index 0000000..d2069e5
--- /dev/null
+++ b/android/app/src/main/res/layout/widget_card.xml
@@ -0,0 +1,79 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A home screen card: the picture of the desk's card, a tap target over all of it, and tap
+ targets that the list widget lays over each item (see widget/ArtefactWidgets.kt). -->
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/root"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <ImageView
+ android:id="@+id/card_image"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:importantForAccessibility="yes"
+ android:scaleType="fitXY" />
+
+ <FrameLayout
+ android:id="@+id/card_open"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_card_ripple" />
+
+ <FrameLayout
+ android:id="@+id/row0"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_pill_ripple"
+ android:visibility="gone" />
+ <FrameLayout
+ android:id="@+id/row1"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_pill_ripple"
+ android:visibility="gone" />
+ <FrameLayout
+ android:id="@+id/row2"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_pill_ripple"
+ android:visibility="gone" />
+ <FrameLayout
+ android:id="@+id/row3"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_pill_ripple"
+ android:visibility="gone" />
+ <FrameLayout
+ android:id="@+id/row4"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_pill_ripple"
+ android:visibility="gone" />
+ <FrameLayout
+ android:id="@+id/row5"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_pill_ripple"
+ android:visibility="gone" />
+ <FrameLayout
+ android:id="@+id/row6"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_pill_ripple"
+ android:visibility="gone" />
+ <FrameLayout
+ android:id="@+id/row7"
+ android:layout_width="match_parent"
+ android:layout_height="40dp"
+ android:layout_gravity="top|start"
+ android:background="@drawable/widget_pill_ripple"
+ android:visibility="gone" />
+</FrameLayout>
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index c5ae26b..74ad4d3 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -1006,6 +1006,37 @@
<string name="sheet_kind_word">Word</string>
<string name="sheet_kind_slides">Slides</string>
<string name="office_present">Present</string>
+ <string name="widget_todo_name">To-Do list</string>
+ <string name="widget_todo_description">Your latest list, with its items to tick right on the home screen.</string>
+ <string name="widget_recent_name">Recent</string>
+ <string name="widget_recent_description">The documents you read lately, the newest one a tap away.</string>
+ <string name="info_kind">Kind</string>
+ <string name="info_size">Size</string>
+ <string name="info_pages">Pages</string>
+ <string name="info_slides">Slides</string>
+ <string name="info_page_size">Page size</string>
+ <string name="info_where">Where</string>
+ <string name="info_title">Title</string>
+ <string name="info_author">Author</string>
+ <string name="info_subject">Subject</string>
+ <string name="info_keywords">Keywords</string>
+ <string name="info_creator">Made with</string>
+ <string name="info_producer">Saved by</string>
+ <string name="info_protected">Password</string>
+ <string name="info_signed">Signed</string>
+ <string name="info_tagged">Accessible (tagged)</string>
+ <string name="info_fields">Form fields</string>
+ <string name="info_attachments">Attachments</string>
+ <string name="info_yes">Yes</string>
+ <string name="info_no">No</string>
+ <string name="widget_pick_list">Which list?</string>
+ <string name="widget_pick_note">Which note?</string>
+ <string name="widget_pick_latest">The latest, always</string>
+ <string name="widget_note_name">Thought of the day / Notes</string>
+ <string name="widget_note_description">Your latest note as a paper card, the thought of the day to start.</string>
+ <string name="office_slide_notes">Speaker notes</string>
+ <string name="office_slide_n">Slide %1$d</string>
+ <string name="office_slide_notes_none">This slide has no speaker notes.</string>
<string name="office_save_as_format">Save as %1$s</string>
<string name="sheet_edited">edited</string>
<string name="sheet_of">%1$d of %2$d</string>
@@ -1077,6 +1108,8 @@
<string name="photo_reset">Reset</string>
<string name="photo_adjust">Adjust</string>
<string name="photo_blur">Blur</string>
+ <string name="photo_draw">Draw</string>
+ <string name="photo_pen">Pen</string>
<string name="photo_text">Text</string>
<string name="photo_pixelate">Pixelate</string>
<string name="photo_erase">Erase</string>
diff --git a/android/app/src/main/res/xml/widget_note_info.xml b/android/app/src/main/res/xml/widget_note_info.xml
new file mode 100644
index 0000000..f5d54b5
--- /dev/null
+++ b/android/app/src/main/res/xml/widget_note_info.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:description="@string/widget_note_description"
+ android:initialLayout="@layout/widget_card"
+ android:minWidth="110dp"
+ android:minHeight="110dp"
+ android:resizeMode="horizontal|vertical"
+ android:minResizeWidth="110dp"
+ android:minResizeHeight="110dp"
+ android:maxResizeWidth="250dp"
+ android:maxResizeHeight="250dp"
+ android:targetCellWidth="2"
+ android:targetCellHeight="2"
+ android:updatePeriodMillis="0"
+ android:configure="com.chethan616.clearpdf.widget.WidgetPickActivity"
+ android:widgetFeatures="reconfigurable|configuration_optional"
+ android:widgetCategory="home_screen" />
diff --git a/android/app/src/main/res/xml/widget_recent_info.xml b/android/app/src/main/res/xml/widget_recent_info.xml
new file mode 100644
index 0000000..4425cde
--- /dev/null
+++ b/android/app/src/main/res/xml/widget_recent_info.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Opens at 2x3, the desk card's own shape (the list's three items, the Recent card's 226 dp);
+ resizable, the card drawn anew for every size. -->
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:description="@string/widget_recent_description"
+ android:initialLayout="@layout/widget_card"
+ android:minWidth="110dp"
+ android:minHeight="200dp"
+ android:minResizeWidth="110dp"
+ android:minResizeHeight="110dp"
+ android:maxResizeWidth="340dp"
+ android:maxResizeHeight="420dp"
+ android:resizeMode="horizontal|vertical"
+ android:targetCellWidth="2"
+ android:targetCellHeight="3"
+ android:updatePeriodMillis="0"
+ android:widgetCategory="home_screen" />
diff --git a/android/app/src/main/res/xml/widget_todo_info.xml b/android/app/src/main/res/xml/widget_todo_info.xml
new file mode 100644
index 0000000..028fa07
--- /dev/null
+++ b/android/app/src/main/res/xml/widget_todo_info.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Opens at 2x3, the desk card's own shape (the list's three items, the Recent card's 226 dp);
+ resizable, the card drawn anew for every size. -->
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:description="@string/widget_todo_description"
+ android:initialLayout="@layout/widget_card"
+ android:minWidth="110dp"
+ android:minHeight="200dp"
+ android:minResizeWidth="110dp"
+ android:minResizeHeight="110dp"
+ android:maxResizeWidth="340dp"
+ android:maxResizeHeight="420dp"
+ android:resizeMode="horizontal|vertical"
+ android:targetCellWidth="2"
+ android:targetCellHeight="3"
+ android:updatePeriodMillis="0"
+ android:configure="com.chethan616.clearpdf.widget.WidgetPickActivity"
+ android:widgetFeatures="reconfigurable|configuration_optional"
+ android:widgetCategory="home_screen" />
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 31b4b30..ed84188 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -2176,7 +2176,10 @@ dependencies = [
[[package]]
name = "gridcraft-pdf"
version = "0.16.0"
-source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "skrifa 0.47.0",
+ "subsetter",
+]
[[package]]
name = "gridcraft-xlsx"
diff --git a/engine/Cargo.toml b/engine/Cargo.toml
index 02954bb..64f521f 100644
--- a/engine/Cargo.toml
+++ b/engine/Cargo.toml
@@ -157,6 +157,10 @@ krilla = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f904
[patch."https://github.com/storytold/wordcraft"]
wordcraft-fonts = { path = "vendor/wordcraft-fonts" }
+# gridcraft crates we carry a patch for (see vendor/README.md).
+[patch."https://github.com/storytold/gridcraft"]
+gridcraft-pdf = { path = "vendor/gridcraft-pdf" }
+
# deckcraft crates we carry a patch for (see vendor/README.md).
[patch."https://github.com/storytold/deckcraft"]
deckcraft-fonts = { path = "vendor/deckcraft-fonts" }
diff --git a/engine/mobile/src/lib.rs b/engine/mobile/src/lib.rs
index 571a521..74cd407 100644
--- a/engine/mobile/src/lib.rs
+++ b/engine/mobile/src/lib.rs
@@ -642,10 +642,16 @@ impl MobileSession {
self.with_doc(doc, document_info)
}
+ /// The speaker notes of slide `page` (0-based) of presentation `doc`; empty when it has none.
+ pub fn slide_notes(&self, doc: u64, page: u32) -> Result<String, MobileError> {
+ let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;
+ Ok(d.notes(page).unwrap_or_default())
+ }
+
/// Document `doc`'s bookmarks, flattened in reading order (at most as many as the engine reads).
pub fn outline(&self, doc: u64) -> Result<Vec<OutlineEntry>, MobileError> {
- if self.office(doc).is_some() {
- return Ok(Vec::new());
+ if let Some(d) = self.office(doc) {
+ return Ok(d.outline());
}
self.with_doc(doc, |d| {
let mut out = Vec::new();
diff --git a/engine/mobile/src/office.rs b/engine/mobile/src/office.rs
index ab27655..89bda91 100644
--- a/engine/mobile/src/office.rs
+++ b/engine/mobile/src/office.rs
@@ -42,6 +42,16 @@ pub(crate) trait OfficeDoc: Send + Sync {
Err(MobileError::Command("this document can't be edited yet, so there is nothing to save".into()))
}
+ /// The speaker notes of slide `page` (presentations only).
+ fn notes(&self, _page: u32) -> Option<String> {
+ None
+ }
+
+ /// The document's headings, for its outline (Word only).
+ fn outline(&self) -> Vec<crate::OutlineEntry> {
+ Vec::new()
+ }
+
/// A Word document, which the app edits with WordCraft's commands.
fn as_word(&self) -> Option<&crate::word::WordDocument> {
None
diff --git a/engine/mobile/src/slides.rs b/engine/mobile/src/slides.rs
index ea919d9..2697528 100644
--- a/engine/mobile/src/slides.rs
+++ b/engine/mobile/src/slides.rs
@@ -96,6 +96,11 @@ impl SlideDeck {
}
impl OfficeDoc for SlideDeck {
+ fn notes(&self, page: u32) -> Option<String> {
+ let slide = self.pres.slides.get(page as usize)?;
+ Some(slide.notes.text().trim().to_string())
+ }
+
fn info(&self, id: u64) -> DocumentInfo {
let p = &self.pres;
let (w, h) = (p.slide_size.width as f32, p.slide_size.height as f32);
diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rs
index 767346f..949f049 100644
--- a/engine/mobile/src/tests.rs
+++ b/engine/mobile/src/tests.rs
@@ -549,6 +549,21 @@ fn deck_file(title: &str, name: &str) -> String {
path.to_string_lossy().into_owned()
}
+#[test]
+fn a_slide_reports_its_speaker_notes() {
+ let mut p = deckcraft_model::defaults::new_presentation(None);
+ let slide = std::sync::Arc::make_mut(p.slides.first_mut().unwrap());
+ slide.notes = deckcraft_model::text::TextBody::from_text("Say hello, then show the chart.");
+ let path = scratch().join("Notes.pptx");
+ std::fs::write(&path, deckcraft_pptx::export(&p).unwrap()).unwrap();
+ let s = MobileSession::new();
+ let id = s.open(path.to_string_lossy().into_owned(), None).unwrap().id;
+ assert!(s.slide_notes(id, 0).unwrap().contains("Say hello"), "{:?}", s.slide_notes(id, 0));
+ assert_eq!(s.slide_notes(id, 99).unwrap(), "", "no such slide: empty");
+ let pdf = s.open(blank_pdf(1), None).unwrap().id;
+ assert_eq!(s.slide_notes(pdf, 0).is_err(), true, "a PDF has no slide notes");
+}
+
#[test]
fn opens_a_presentation_as_slides() {
let s = MobileSession::new();
@@ -655,6 +670,48 @@ fn office_documents_export_to_pdf_and_their_own_formats() {
}
}
+#[test]
+fn a_word_document_lists_its_headings_with_their_pages() {
+ let s = MobileSession::new();
+ let id = s.open(word_file("Overview
+Some body text here.
+Details
+More body text.", "Outline.docx"), None).unwrap().id;
+ assert!(!s.document(id).unwrap().has_outline, "no headings yet");
+ assert!(s.outline(id).unwrap().is_empty());
+ s.word_command(id, "caret.docStart".into(), "{}".into()).unwrap();
+ s.word_command(id, "para.heading1".into(), "{}".into()).unwrap();
+ s.word_command(id, "caret.docEnd".into(), "{}".into()).unwrap();
+ s.word_command(id, "caret.up".into(), "{}".into()).unwrap();
+ s.word_command(id, "para.heading2".into(), "{}".into()).unwrap();
+ let doc = s.document(id).unwrap();
+ assert!(doc.has_outline);
+ let heads = s.outline(id).unwrap();
+ assert_eq!(heads.iter().map(|h| h.title.as_str()).collect::<Vec<_>>(), ["Overview", "Details"], "{heads:?}");
+ assert_eq!((heads[0].level, heads[1].level), (0, 1), "Heading 2 nests under Heading 1");
+ assert_eq!(heads[0].children, 1);
+ assert_eq!(heads[0].page, Some(0));
+}
+
+#[test]
+fn a_sheet_with_cyrillic_text_exports_to_a_pdf_that_shows_it() {
+ // gridcraft's PDF writer is vendored with embedded faces: non-Latin text used to be a
+ // non-embedded CID font that the viewer could not draw.
+ let s = MobileSession::new();
+ let path = book_file("Привет,мир
+Γειά,Hello
+", "Cyr.xlsx");
+ let id = s.open(path, None).unwrap().id;
+ let out = scratch().join("cyr.pdf").to_string_lossy().into_owned();
+ s.export_office(id, "pdf".into(), out.clone()).unwrap();
+ let raw = std::fs::read(&out).unwrap();
+ let raw = String::from_utf8_lossy(&raw);
+ assert!(raw.contains("/FontFile2") && !raw.contains("STSong-Light"), "Cyrillic is embedded");
+ let pdf = s.open(out, None).unwrap().id;
+ let text = s.page_plain_text(pdf, 0).unwrap();
+ assert!(text.contains("Привет") && text.contains("Γειά") && text.contains("Hello"), "{text}");
+}
+
#[test]
fn a_workbook_is_edited_recalculated_undone_and_saved() {
let s = MobileSession::new();
diff --git a/engine/mobile/src/word.rs b/engine/mobile/src/word.rs
index d5dc6af..aaf23ea 100644
--- a/engine/mobile/src/word.rs
+++ b/engine/mobile/src/word.rs
@@ -8,7 +8,7 @@ use kurbo::Affine;
use pdfcraft_render::{PageText, TextGlyph};
use wordcraft_engine::Session;
-use wordcraft_engine::doc::Document;
+use wordcraft_engine::doc::{Block, Document};
use wordcraft_engine::layout::display::{DisplayOptions, Draw, page_display};
use wordcraft_engine::layout::{DocLayout, Page};
use wordcraft_engine::render::RenderOptions;
@@ -201,7 +201,7 @@ impl OfficeDoc for WordDocument {
undo: s.session.undo_label().map(str::to_string),
redo: s.session.redo_label().map(str::to_string),
fields: 0,
- has_outline: false,
+ has_outline: !headings_of(&doc, &layout).is_empty(),
attachments: 0,
signed: false,
comments_hidden: false,
@@ -270,6 +270,11 @@ impl OfficeDoc for WordDocument {
Ok(())
}
+ fn outline(&self) -> Vec<crate::OutlineEntry> {
+ let (doc, layout, _) = self.snapshot();
+ headings_of(&doc, &layout)
+ }
+
fn as_word(&self) -> Option<&WordDocument> {
Some(self)
}
@@ -280,6 +285,39 @@ impl OfficeDoc for WordDocument {
}
}
+/// The document's headings (paragraphs with an outline level, as its Navigation Pane lists them) in
+/// reading order, each with the page it starts on.
+fn headings_of(doc: &Document, layout: &DocLayout) -> Vec<crate::OutlineEntry> {
+ use wordcraft_engine::layout::outline::{BODY, levels};
+ let mut found: Vec<(u8, String, Option<u32>)> = Vec::new();
+ for (i, (level, block)) in levels(doc).into_iter().zip(doc.body.iter()).enumerate() {
+ if level >= BODY {
+ continue;
+ }
+ let Block::Para(p) = &**block else { continue };
+ let text = p.plain_text().replace(['\u{FFFC}', '\n', '\r'], " ").trim().to_string();
+ if text.is_empty() {
+ continue;
+ }
+ let page = layout.pages.iter().rposition(|pg| pg.first_block <= i).and_then(|n| u32::try_from(n).ok());
+ found.push((level, text, page));
+ }
+ // the shallowest level present is the top, so a document that starts at Heading 2 still nests sensibly
+ let top = found.iter().map(|f| f.0).min().unwrap_or(1);
+ (0..found.len())
+ .map(|k| {
+ let (level, ref title, page) = found[k];
+ let children = found[k + 1..].iter().take_while(|n| n.0 > level).count();
+ crate::OutlineEntry {
+ title: title.clone(),
+ level: u32::from(level - top),
+ page,
+ children: u32::try_from(children).unwrap_or(u32::MAX),
+ }
+ })
+ .collect()
+}
+
fn page_of(layout: &DocLayout, page: u32) -> Result<&Page, MobileError> {
let n = layout.pages.len();
layout
diff --git a/engine/vendor/README.md b/engine/vendor/README.md
index eeeaa01..caef3cb 100644
--- a/engine/vendor/README.md
+++ b/engine/vendor/README.md
@@ -138,3 +138,16 @@ of stand-ins in a face a phone has: Source Sans 3, Source Serif 4, Inter and Jet
faces Artefact bundles, given to the database by `ensure_fonts` in `mobile/src/slides.rs`) and
Android's Roboto, Noto Serif and Droid Sans Mono. Without it every family fell through to the
last-resort face on Android, and a deck's fonts all looked replaced (GitHub issue 130).
+
+## GridCraft (Excel PDF export)
+
+`gridcraft-pdf` is storytold/gridcraft's `crates/pdf` at `6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214`
+(the revision the other gridcraft crates are pinned to), a `[patch."https://github.com/storytold/gridcraft"]`
+entry. Upstream sets text WinAnsiEncoding lacks in a non-embedded Adobe CID font, which a phone's PDF
+viewer cannot draw: a Cyrillic or Greek sheet exported with its text missing. `Artefact patch:` in
+`src/embed.rs` and `src/lib.rs` sets such text in Source Sans 3 (Regular, Bold, Italic from
+`engine/assets/fonts`, SIL OFL), embedded as a subset (`subsetter`, `skrifa`) with a CIDToGIDMap and a
+ToUnicode map, and measures it with the face's real widths. Scripts Source Sans lacks (CJK, Arabic,
+Indic) still use the old fallback. Covered by `gridcraft-pdf`'s `cyrillic_text_is_embedded_and_measured`
+and `cjk_text_still_uses_the_fallback`, and `artefact-mobile`'s
+`a_sheet_with_cyrillic_text_exports_to_a_pdf_that_shows_it`.
diff --git a/engine/vendor/gridcraft-pdf/Cargo.toml b/engine/vendor/gridcraft-pdf/Cargo.toml
new file mode 100644
index 0000000..5c11ecc
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "gridcraft-pdf"
+version = "0.16.0"
+edition = "2024"
+license = "MIT OR Apache-2.0"
+description = "GridCraft's tiny self-contained PDF 1.7 writer (standard 14 fonts, vector drawing, RGBA images)"
+readme = "README.md"
+
+# Artefact patch: embeds subsets of Source Sans 3 for text the standard fonts cannot show
+# (Cyrillic, Greek, Latin Extended, Vietnamese...), so the viewer can draw it.
+[dependencies]
+skrifa = "0.47"
+subsetter = "0.2"
diff --git a/engine/vendor/gridcraft-pdf/LICENSE-APACHE b/engine/vendor/gridcraft-pdf/LICENSE-APACHE
new file mode 100644
index 0000000..f433b1a
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/LICENSE-APACHE
@@ -0,0 +1,177 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/engine/vendor/gridcraft-pdf/LICENSE-MIT b/engine/vendor/gridcraft-pdf/LICENSE-MIT
new file mode 100644
index 0000000..eba4152
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/LICENSE-MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 ArtCraft Team and the GridCraft contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/engine/vendor/gridcraft-pdf/NOTICE b/engine/vendor/gridcraft-pdf/NOTICE
new file mode 100644
index 0000000..d859d99
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/NOTICE
@@ -0,0 +1,307 @@
+GridCraft
+Copyright (c) 2026 ArtCraft Team and the GridCraft contributors.
+Licensed under the MIT License or the Apache License, Version 2.0, at your option
+(LICENSE-MIT, LICENSE-APACHE).
+
+The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are
+not open source and are not covered by the license above; their terms are in
+docs/brand/LICENSE-brand.txt.
+
+Third-party material
+
+This product bundles third-party material under its own licenses, listed below. The per-file
+list (author, source, license) is in ATTRIBUTION.md.
+
+GridCraft's original assets and the UI's bundled egui font inputs are listed in ATTRIBUTION.md.
+Builds made with craft-fonts (CRAFT_FONTS_DIR) also embed the fonts listed there under the SIL Open
+Font License 1.1.
+
+
+The UI's egui-icons.ttf subset and emoji-icon-font.ttf fallback are provided by epaint_default_fonts
+and registered through egui's default font definitions. They derive from emoji-icon-font by
+John Slegers, under the MIT License. The subset and full face share the following upstream notice.
+Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts
+Original: https://github.com/jslegers/emoji-icon-font
+The following text is reproduced verbatim from emoji-icon-font-mit-license.txt:
+
+MIT License
+
+Copyright (c) 2014 John Slegers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Hack-Regular.ttf is provided by epaint_default_fonts and is egui's bundled monospace face. The
+work is Copyright 2018 Source Foundry Authors and is distributed under the MIT License and the
+Bitstream Vera License. The DejaVu work it derives from was committed to the public domain.
+Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts
+Upstream: https://github.com/source-foundry/Hack
+The following text is reproduced verbatim from Hack-Regular.txt:
+
+The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License
+
+The work in the DejaVu project was committed to the public domain.
+
+Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera"
+MIT License
+
+Copyright (c) 2018 Source Foundry Authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+BITSTREAM VERA LICENSE
+
+Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
+
+The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
+
+The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".
+
+This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.
+
+The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
+
+Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
+
+NotoEmoji-Regular.ttf is provided by epaint_default_fonts and is enabled by egui's
+monochrome_emoji_fonts feature. It is distributed under the SIL Open Font License, Version 1.1.
+Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts
+Upstream: https://fonts.google.com/noto/specimen/Noto+Emoji
+The following text is reproduced verbatim from OFL.txt:
+
+This Font Software is licensed under the SIL Open Font License,
+Version 1.1.
+
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font
+creation efforts of academic and linguistic communities, and to
+provide a free and open framework in which fonts may be shared and
+improved in partnership with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply to
+any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software
+components as distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to,
+deleting, or substituting -- in part or in whole -- any of the
+components of the Original Version, by changing formats or by porting
+the Font Software to a new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed,
+modify, redistribute, and sell modified and unmodified copies of the
+Font Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components, in
+Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the
+corresponding Copyright Holder. This restriction only applies to the
+primary font name as presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created using
+the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
+
+Ubuntu-Light.ttf is provided by epaint_default_fonts and is egui's default proportional face. It
+is distributed under the Ubuntu Font Licence, Version 1.0.
+Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts
+Upstream: https://design.ubuntu.com/font
+The following text is reproduced verbatim from UFL.txt:
+
+-------------------------------
+UBUNTU FONT LICENCE Version 1.0
+-------------------------------
+
+PREAMBLE
+This licence allows the licensed fonts to be used, studied, modified and
+redistributed freely. The fonts, including any derivative works, can be
+bundled, embedded, and redistributed provided the terms of this licence
+are met. The fonts and derivatives, however, cannot be released under
+any other licence. The requirement for fonts to remain under this
+licence does not require any document created using the fonts or their
+derivatives to be published under this licence, as long as the primary
+purpose of the document is not to be a vehicle for the distribution of
+the fonts.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this licence and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Original Version" refers to the collection of Font Software components
+as received under this licence.
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to
+a new environment.
+
+"Copyright Holder(s)" refers to all individuals and companies who have a
+copyright ownership of the Font Software.
+
+"Substantially Changed" refers to Modified Versions which can be easily
+identified as dissimilar to the Font Software by users of the Font
+Software comparing the Original Version with the Modified Version.
+
+To "Propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification and with or without charging
+a redistribution fee), making available to the public, and in some
+countries other activities as well.
+
+PERMISSION & CONDITIONS
+This licence does not grant any rights under trademark law and all such
+rights are reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of the Font Software, to propagate the Font Software, subject to
+the below conditions:
+
+1) Each copy of the Font Software must contain the above copyright
+notice and this licence. These can be included either as stand-alone
+text files, human-readable headers or in the appropriate machine-
+readable metadata fields within text or binary files as long as those
+fields can be easily viewed by the user.
+
+2) The font name complies with the following:
+(a) The Original Version must retain its name, unmodified.
+(b) Modified Versions which are Substantially Changed must be renamed to
+avoid use of the name of the Original Version or similar names entirely.
+(c) Modified Versions which are not Substantially Changed must be
+renamed to both (i) retain the name of the Original Version and (ii) add
+additional naming elements to distinguish the Modified Version from the
+Original Version. The name of such Modified Versions must be the name of
+the Original Version, with "derivative X" where X represents the name of
+the new work, appended to that name.
+
+3) The name(s) of the Copyright Holder(s) and any contributor to the
+Font Software shall not be used to promote, endorse or advertise any
+Modified Version, except (i) as required by this licence, (ii) to
+acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with
+their explicit written permission.
+
+4) The Font Software, modified or unmodified, in part or in whole, must
+be distributed entirely under this licence, and must not be distributed
+under any other licence. The requirement for fonts to remain under this
+licence does not affect any document created using the Font Software,
+except any version of the Font Software extracted from a document
+created using the Font Software may only be distributed under this
+licence.
+
+TERMINATION
+This licence becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
+COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
+DEALINGS IN THE FONT SOFTWARE.
+
+Linux Wayland window decorations
+-------------------------------
+sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
+commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
+for vector window controls. Its title-font features are disabled: no Cantarell
+font is embedded by this dependency and no font file is added to this repo.
+
+sctk-adwaita's MIT licence:
+
+MIT License
+
+Copyright (c) 2022 Bartłomiej Maryńczak
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/engine/vendor/gridcraft-pdf/README.md b/engine/vendor/gridcraft-pdf/README.md
new file mode 100644
index 0000000..cdb6308
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/README.md
@@ -0,0 +1,33 @@
+# gridcraft-pdf
+
+A small, dependency-free PDF 1.7 writer for vector drawing and RGBA images.
+
+## API migration
+
+The geometry-taking methods now use `Point` and `Rect` values to name their coordinates, and
+`image_rgba` groups its pixel dimensions into an array. Update calls to the four changed methods as
+follows:
+
+```rust
+use gridcraft_pdf::{Font, PdfDoc, Point, Rect};
+
+let mut doc = PdfDoc::new();
+let page = doc.add_page(612.0, 792.0);
+
+// Before: page.link_page(20.0, 30.0, 80.0, 16.0, 1, 40.0, 50.0);
+page.link_page(Rect::new(20.0, 30.0, 80.0, 16.0), 1, Point::new(40.0, 50.0));
+
+// Before: page.stroke_line_dashed(0.0, 0.0, 100.0, 40.0, 1.0, [0, 0, 0], &[4.0, 2.0]);
+page.stroke_line_dashed(Point::new(0.0, 0.0), Point::new(100.0, 40.0), 1.0, [0, 0, 0], &[4.0, 2.0]);
+
+// Before: page.text_rotated(20.0, 40.0, 12.0, Font::Helvetica, [0, 0, 0], "Label", 0.2);
+page.text_rotated(Point::new(20.0, 40.0), 12.0, Font::Helvetica, [0, 0, 0], "Label", 0.2);
+
+let rgba = [255, 0, 0, 255];
+// Before: page.image_rgba(10.0, 10.0, 24.0, 24.0, &rgba, 1, 1);
+page.image_rgba(Rect::new(10.0, 10.0, 24.0, 24.0), &rgba, [1, 1]);
+```
+
+`Point::new(x, y)` uses the page's top-left origin, where y increases downward. `Rect::new(x, y,
+width, height)` describes the destination or link rectangle in the same coordinate system. The
+`image_rgba` pixel-size array is `[width, height]`.
diff --git a/engine/vendor/gridcraft-pdf/src/embed.rs b/engine/vendor/gridcraft-pdf/src/embed.rs
new file mode 100644
index 0000000..efb1946
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/src/embed.rs
@@ -0,0 +1,190 @@
+//! Artefact patch: embedded faces for text WinAnsiEncoding cannot show.
+//!
+//! The standard 14 fonts only cover Western European text, and the upstream crate sent
+//! everything else to a non-embedded Adobe CID font, which viewers without that font cannot
+//! draw. Here Cyrillic, Greek, Latin Extended and similar scripts are set in Source Sans 3
+//! (bundled in `engine/assets/fonts`, SIL OFL), embedded as a subset of the glyphs used.
+//! Scripts Source Sans lacks (CJK, Arabic, Indic...) still use the old fallback.
+
+use std::collections::BTreeMap;
+use std::fmt::Write as _;
+
+use skrifa::instance::{LocationRef, Size};
+use skrifa::{FontRef, MetadataProvider};
+use subsetter::GlyphRemapper;
+
+/// The three embedded faces. Bold italic uses `Bold`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Face {
+ Regular,
+ Bold,
+ Italic,
+}
+
+pub(crate) const FACES: [Face; 3] = [Face::Regular, Face::Bold, Face::Italic];
+
+static REGULAR: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
+static BOLD: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Bold.ttf");
+static ITALIC: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-It.ttf");
+
+/// Glyph ids used per face, with one character each (for the ToUnicode map).
+pub(crate) type Used = [BTreeMap<u16, char>; 3];
+
+impl Face {
+ pub(crate) fn index(self) -> usize {
+ match self {
+ Face::Regular => 0,
+ Face::Bold => 1,
+ Face::Italic => 2,
+ }
+ }
+
+ fn data(self) -> &'static [u8] {
+ match self {
+ Face::Regular => REGULAR,
+ Face::Bold => BOLD,
+ Face::Italic => ITALIC,
+ }
+ }
+
+ fn base_name(self) -> &'static str {
+ match self {
+ Face::Regular => "SourceSans3-Regular",
+ Face::Bold => "SourceSans3-Bold",
+ Face::Italic => "SourceSans3-It",
+ }
+ }
+
+ fn font(self) -> Option<FontRef<'static>> {
+ FontRef::new(self.data()).ok()
+ }
+
+ /// The glyph for `c` and its advance in 1/1000 em, if the face has it.
+ pub(crate) fn glyph(self, c: char) -> Option<(u16, u16)> {
+ let font = self.font()?;
+ let gid = font.charmap().map(c)?;
+ let id = u16::try_from(gid.to_u32()).ok().filter(|g| *g != 0)?;
+ let upem = font.metrics(Size::unscaled(), LocationRef::default()).units_per_em as f32;
+ let adv = font.glyph_metrics(Size::unscaled(), LocationRef::default()).advance_width(gid)?;
+ Some((id, (adv * 1000.0 / upem.max(1.0)).round().clamp(0.0, 65535.0) as u16))
+ }
+}
+
+/// True when the regular face has a glyph for `c`.
+pub(crate) fn covers(c: char) -> bool {
+ Face::Regular.glyph(c).is_some()
+}
+
+/// A PDF hex string of the glyph ids of `text` (two bytes each, `Identity-H`); the glyphs are
+/// noted in `used`.
+pub(crate) fn hex_string(face: Face, text: &str, used: &mut BTreeMap<u16, char>) -> String {
+ let mut s = String::with_capacity(text.len() * 4 + 2);
+ s.push('<');
+ for c in text.chars() {
+ let gid = face.glyph(c).map_or(0, |(g, _)| g);
+ if gid != 0 {
+ used.entry(gid).or_insert(c);
+ }
+ let _ = write!(s, "{gid:04X}");
+ }
+ s.push('>');
+ s
+}
+
+/// The objects for one embedded face: a Type0 font at `id`, then its descendant, descriptor,
+/// font file, CID-to-GID map and ToUnicode map (`id` .. `id + 5`). `None` if nothing is used
+/// or the subset fails.
+pub(crate) fn objects(face: Face, id: u32, used: &BTreeMap<u16, char>) -> Option<Vec<(u32, Vec<u8>)>> {
+ if used.is_empty() {
+ return None;
+ }
+ let font = face.font()?;
+ let mut remapper = GlyphRemapper::new();
+ for gid in used.keys() {
+ remapper.remap(*gid);
+ }
+ let subset = subsetter::subset(face.data(), 0, &remapper).ok()?;
+ let metrics = font.metrics(Size::unscaled(), LocationRef::default());
+ let k = 1000.0 / (metrics.units_per_em as f32).max(1.0);
+ let (ascent, descent) = (metrics.ascent * k, metrics.descent * k);
+ let bbox = metrics.bounds.map_or([-200.0, descent, 1200.0, ascent], |b| [b.x_min * k, b.y_min * k, b.x_max * k, b.y_max * k]);
+ let tag = format!("{}+{}", tag_for(used), face.base_name());
+ let (cid, desc, file, map, uni) = (id + 1, id + 2, id + 3, id + 4, id + 5);
+
+ let mut widths = String::new();
+ for (gid, c) in used {
+ let w = face.glyph(*c).map_or(500, |(_, w)| w);
+ let _ = write!(widths, "{gid} [{w}] ");
+ }
+ let italic = if face == Face::Italic { -12 } else { 0 };
+ let stem = if face == Face::Bold { 140 } else { 80 };
+ let mut out = vec![
+ (id, format!("<< /Type /Font /Subtype /Type0 /BaseFont /{tag} /Encoding /Identity-H /DescendantFonts [{cid} 0 R] /ToUnicode {uni} 0 R >>").into_bytes()),
+ (
+ cid,
+ format!(
+ "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{tag} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {desc} 0 R /CIDToGIDMap {map} 0 R /DW 500 /W [{widths}] >>"
+ )
+ .into_bytes(),
+ ),
+ (
+ desc,
+ format!(
+ "<< /Type /FontDescriptor /FontName /{tag} /Flags 32 /FontBBox [{:.0} {:.0} {:.0} {:.0}] /ItalicAngle {italic} /Ascent {:.0} /Descent {:.0} /CapHeight {:.0} /StemV {stem} /FontFile2 {file} 0 R >>",
+ bbox[0], bbox[1], bbox[2], bbox[3], ascent, descent, ascent * 0.7
+ )
+ .into_bytes(),
+ ),
+ ];
+ let mut f = format!("<< /Length {} /Length1 {} >>\nstream\n", subset.len(), subset.len()).into_bytes();
+ f.extend_from_slice(&subset);
+ f.extend_from_slice(b"\nendstream");
+ out.push((file, f));
+
+ // CID (the original glyph id) -> glyph id in the subset.
+ let top = used.keys().next_back().copied().unwrap_or(0) as usize;
+ let mut map_bytes = vec![0u8; (top + 1) * 2];
+ for gid in used.keys() {
+ if let Some(new) = remapper.get(*gid) {
+ let i = *gid as usize * 2;
+ map_bytes[i..i + 2].copy_from_slice(&new.to_be_bytes());
+ }
+ }
+ let mut m = format!("<< /Length {} >>\nstream\n", map_bytes.len()).into_bytes();
+ m.extend_from_slice(&map_bytes);
+ m.extend_from_slice(b"\nendstream");
+ out.push((map, m));
+
+ // ToUnicode, so text can be searched and copied.
+ let mut cmap = String::from(
+ "/CIDInit /ProcSet findresource begin 12 dict begin begincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def /CMapType 2 def\n1 begincodespacerange <0000> <FFFF> endcodespacerange\n",
+ );
+ let entries: Vec<(&u16, &char)> = used.iter().collect();
+ for chunk in entries.chunks(100) {
+ let _ = writeln!(cmap, "{} beginbfchar", chunk.len());
+ for (gid, c) in chunk {
+ let mut buf = [0u16; 2];
+ let hex: String = c.encode_utf16(&mut buf).iter().map(|u| format!("{u:04X}")).collect();
+ let _ = writeln!(cmap, "<{gid:04X}> <{hex}>");
+ }
+ cmap.push_str("endbfchar\n");
+ }
+ cmap.push_str("endcmap CMapName currentdict /CMap defineresource pop end end");
+ out.push((uni, format!("<< /Length {} >>\nstream\n{cmap}\nendstream", cmap.len()).into_bytes()));
+ Some(out)
+}
+
+/// A six-letter subset tag derived from the glyphs used.
+fn tag_for(used: &BTreeMap<u16, char>) -> String {
+ let mut h: u32 = 2_166_136_261;
+ for g in used.keys() {
+ h = (h ^ u32::from(*g)).wrapping_mul(16_777_619);
+ }
+ (0..6)
+ .map(|_| {
+ let c = char::from(b'A' + (h % 26) as u8);
+ h = (h / 26).wrapping_add(0x9E37_79B9 >> 4);
+ c
+ })
+ .collect()
+}
diff --git a/engine/vendor/gridcraft-pdf/src/lib.rs b/engine/vendor/gridcraft-pdf/src/lib.rs
new file mode 100644
index 0000000..c3fce23
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/src/lib.rs
@@ -0,0 +1,1022 @@
+//! A tiny, self-contained PDF 1.7 writer for GridCraft's print and PDF export.
+//!
+//! - The 14 standard fonts (no embedding) with WinAnsiEncoding, plus approximate width tables
+//! ([`text_width`]) so callers can measure, align and wrap text. Characters outside
+//! WinAnsiEncoding (CJK and other scripts) are set in a predefined, non-embedded Adobe-GB1 CID
+//! font with the `UniGB-UTF16-H` CMap instead of being replaced by `?`. Symbol uses its own
+//! built-in encoding ([`symbol_code`]), for Greek letters and mathematical operators.
+//! - Vector drawing: rectangles, lines (solid or dashed), polygons, circles (Bézier), clipping.
+//! - RGBA images as RGB image XObjects with a soft mask for alpha (run-length encoded).
+//! - Coordinates are points with a **top-left origin** (y grows down); text `y` is the baseline.
+//!
+//! Streams are written uncompressed (images use the trivial RunLengthDecode filter) so the crate
+//! needs no dependencies.
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+#![forbid(unsafe_code)]
+
+mod embed;
+mod metrics;
+mod symbol;
+
+pub use symbol::{symbol_code, symbol_width};
+
+use std::fmt::Write as _;
+
+/// RGB colour, 0–255 per channel.
+pub type Rgb = [u8; 3];
+
+/// A point in page coordinates, measured from the top-left corner.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Point {
+ pub x: f32,
+ pub y: f32,
+}
+
+impl Point {
+ pub const fn new(x: f32, y: f32) -> Self {
+ Self { x, y }
+ }
+}
+
+/// A page-space rectangle described by its top-left corner and extent.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Rect {
+ pub x: f32,
+ pub y: f32,
+ pub width: f32,
+ pub height: f32,
+}
+
+impl Rect {
+ pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
+ Self { x, y, width, height }
+ }
+}
+
+/// The standard 14 fonts minus ZapfDingbats.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub enum Font {
+ #[default]
+ Helvetica,
+ HelveticaBold,
+ HelveticaOblique,
+ HelveticaBoldOblique,
+ TimesRoman,
+ TimesBold,
+ TimesItalic,
+ TimesBoldItalic,
+ Courier,
+ CourierBold,
+ CourierOblique,
+ CourierBoldOblique,
+ /// Greek letters and mathematical symbols, in the font's own encoding.
+ Symbol,
+}
+
+/// How many fonts a document can use.
+const FONT_COUNT: usize = 13;
+
+/// A font family for [`Font::styled`].
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
+pub enum Family {
+ #[default]
+ Sans,
+ Serif,
+ Mono,
+}
+
+impl Font {
+ pub const ALL: [Font; FONT_COUNT] = [
+ Font::Helvetica,
+ Font::HelveticaBold,
+ Font::HelveticaOblique,
+ Font::HelveticaBoldOblique,
+ Font::TimesRoman,
+ Font::TimesBold,
+ Font::TimesItalic,
+ Font::TimesBoldItalic,
+ Font::Courier,
+ Font::CourierBold,
+ Font::CourierOblique,
+ Font::CourierBoldOblique,
+ Font::Symbol,
+ ];
+
+ /// PostScript base font name.
+ pub fn base_name(self) -> &'static str {
+ match self {
+ Font::Helvetica => "Helvetica",
+ Font::HelveticaBold => "Helvetica-Bold",
+ Font::HelveticaOblique => "Helvetica-Oblique",
+ Font::HelveticaBoldOblique => "Helvetica-BoldOblique",
+ Font::TimesRoman => "Times-Roman",
+ Font::TimesBold => "Times-Bold",
+ Font::TimesItalic => "Times-Italic",
+ Font::TimesBoldItalic => "Times-BoldItalic",
+ Font::Courier => "Courier",
+ Font::CourierBold => "Courier-Bold",
+ Font::CourierOblique => "Courier-Oblique",
+ Font::CourierBoldOblique => "Courier-BoldOblique",
+ Font::Symbol => "Symbol",
+ }
+ }
+
+ /// Artefact patch: the embedded face that stands in for this one on non-WinAnsi text.
+ fn embed_face(self) -> embed::Face {
+ match self {
+ Font::HelveticaBold | Font::HelveticaBoldOblique | Font::TimesBold | Font::TimesBoldItalic | Font::CourierBold | Font::CourierBoldOblique => embed::Face::Bold,
+ Font::HelveticaOblique | Font::TimesItalic | Font::CourierOblique => embed::Face::Italic,
+ _ => embed::Face::Regular,
+ }
+ }
+
+ fn index(self) -> usize {
+ Font::ALL.iter().position(|f| *f == self).unwrap_or(0)
+ }
+
+ /// The face of `family` with the given weight and slant.
+ pub fn styled(family: Family, bold: bool, italic: bool) -> Font {
+ match (family, bold, italic) {
+ (Family::Sans, false, false) => Font::Helvetica,
+ (Family::Sans, true, false) => Font::HelveticaBold,
+ (Family::Sans, false, true) => Font::HelveticaOblique,
+ (Family::Sans, true, true) => Font::HelveticaBoldOblique,
+ (Family::Serif, false, false) => Font::TimesRoman,
+ (Family::Serif, true, false) => Font::TimesBold,
+ (Family::Serif, false, true) => Font::TimesItalic,
+ (Family::Serif, true, true) => Font::TimesBoldItalic,
+ (Family::Mono, false, false) => Font::Courier,
+ (Family::Mono, true, false) => Font::CourierBold,
+ (Family::Mono, false, true) => Font::CourierOblique,
+ (Family::Mono, true, true) => Font::CourierBoldOblique,
+ }
+ }
+
+ /// Picks a standard family for a font name: serif faces map to Times, monospaced ones to
+ /// Courier, everything else to Helvetica.
+ pub fn family_for(name: &str) -> Family {
+ let n = name.to_ascii_lowercase();
+ const SERIF: [&str; 10] = ["times", "cambria", "georgia", "garamond", "serif", "book", "palatino", "baskerville", "tinos", "caladea"];
+ const MONO: [&str; 8] = ["courier", "consolas", "mono", "menlo", "lucida console", "cousine", "code", "typewriter"];
+ if MONO.iter().any(|m| n.contains(m)) {
+ Family::Mono
+ } else if SERIF.iter().any(|s| n.contains(s)) && !n.contains("sans") {
+ Family::Serif
+ } else {
+ Family::Sans
+ }
+ }
+
+ /// Whether this font can show `c` by itself (in its own encoding; for the text faces,
+ /// without the CID fallback).
+ pub fn can_encode(self, c: char) -> bool {
+ match self {
+ Font::Symbol => symbol_code(c).is_some(),
+ _ => c == '?' || win_ansi(c) != b'?',
+ }
+ }
+
+ /// Advance width of a character in 1/1000 em.
+ pub fn char_width(self, c: char) -> u16 {
+ if self == Font::Symbol {
+ return symbol_code(c).and_then(symbol_width).unwrap_or(500);
+ }
+ let table: Option<&[u16; 95]> = match self {
+ Font::Helvetica | Font::HelveticaOblique => Some(&metrics::HELVETICA),
+ Font::HelveticaBold | Font::HelveticaBoldOblique => Some(&metrics::HELVETICA_BOLD),
+ Font::TimesRoman | Font::TimesItalic => Some(&metrics::TIMES),
+ Font::TimesBold | Font::TimesBoldItalic => Some(&metrics::TIMES_BOLD),
+ _ => None,
+ };
+ if needs_cid(c) {
+ // Artefact patch: characters the embedded face has use its real widths.
+ return self.embed_face().glyph(c).map_or(CID_WIDTH, |(_, w)| w);
+ }
+ let Some(table) = table else { return 600 };
+ let ascii = |c: char| -> Option<u16> {
+ let i = (c as u32).checked_sub(32)? as usize;
+ table.get(i).copied()
+ };
+ if let Some(w) = ascii(c) {
+ return w;
+ }
+ match c {
+ '—' | '…' | '‰' | '™' => 1000,
+ _ => metrics::fold(c).and_then(ascii).unwrap_or(match self {
+ Font::TimesRoman | Font::TimesItalic | Font::TimesBold | Font::TimesBoldItalic => 500,
+ _ => 556,
+ }),
+ }
+ }
+}
+
+/// Width of `text` in points when set in `font` at `size` points.
+pub fn text_width(font: Font, size: f32, text: &str) -> f32 {
+ // u64: a u32 sum overflows for ~8 million characters.
+ let units: u64 = text.chars().map(|c| u64::from(font.char_width(c))).sum();
+ units as f32 * size / 1000.0
+}
+
+/// Unicode → WinAnsiEncoding (CP1252) byte; unmappable characters become `?`.
+pub fn win_ansi(c: char) -> u8 {
+ let u = c as u32;
+ if (0x20..0x7F).contains(&u) || (0xA0..=0xFF).contains(&u) {
+ return u as u8;
+ }
+ match c {
+ '€' => 0x80,
+ '‚' => 0x82,
+ 'ƒ' => 0x83,
+ '„' => 0x84,
+ '…' => 0x85,
+ '†' => 0x86,
+ '‡' => 0x87,
+ 'ˆ' => 0x88,
+ '‰' => 0x89,
+ 'Š' => 0x8A,
+ '‹' => 0x8B,
+ 'Œ' => 0x8C,
+ 'Ž' => 0x8E,
+ '‘' => 0x91,
+ '’' => 0x92,
+ '“' => 0x93,
+ '”' => 0x94,
+ '•' => 0x95,
+ '–' => 0x96,
+ '—' => 0x97,
+ '˜' => 0x98,
+ '™' => 0x99,
+ 'š' => 0x9A,
+ '›' => 0x9B,
+ 'œ' => 0x9C,
+ 'ž' => 0x9E,
+ 'Ÿ' => 0x9F,
+ '\t' => b' ',
+ _ => b'?',
+ }
+}
+
+/// Index of the CID font in a page's font flags (after the [`Font::ALL`] faces).
+const CID_FONT: usize = Font::ALL.len();
+/// Number of font resources a page can use.
+const FONT_SLOTS: usize = CID_FONT + 1;
+/// Base font of the CID font used for characters WinAnsiEncoding lacks.
+const CID_BASE_FONT: &str = "STSong-Light";
+/// Default glyph width of the CID font (full-width), in 1/1000 em.
+const CID_WIDTH: u16 = 1000;
+
+/// True when `c` has no WinAnsiEncoding byte and is drawn with the CID font.
+fn needs_cid(c: char) -> bool {
+ !c.is_control() && c != '?' && win_ansi(c) == b'?'
+}
+
+/// How a character is set (Artefact patch): in the standard font, in an embedded face, or in
+/// the non-embedded CID font.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum RunClass {
+ Plain,
+ Embedded,
+ Cid,
+}
+
+fn run_class(c: char) -> RunClass {
+ if !needs_cid(c) {
+ RunClass::Plain
+ } else if embed::covers(c) {
+ RunClass::Embedded
+ } else {
+ RunClass::Cid
+ }
+}
+
+/// A PDF hex string `< … >` of `text` in UTF-16BE (the `UniGB-UTF16-H` encoding).
+fn pdf_utf16_string(text: &str) -> String {
+ let mut s = String::with_capacity(text.len() * 4 + 2);
+ s.push('<');
+ for unit in text.encode_utf16() {
+ let _ = write!(s, "{unit:04X}");
+ }
+ s.push('>');
+ s
+}
+
+/// A PDF literal string `( … )` for `text` in WinAnsiEncoding.
+fn pdf_string(text: &str) -> String {
+ pdf_string_in(text, false)
+}
+
+/// A PDF literal string for `text` in WinAnsiEncoding, or in Symbol's encoding (where a
+/// character Symbol lacks becomes `?`).
+fn pdf_string_in(text: &str, symbol: bool) -> String {
+ let mut s = String::with_capacity(text.len() + 2);
+ s.push('(');
+ for c in text.chars() {
+ let b = if symbol { symbol_code(c).unwrap_or(b'?') } else { win_ansi(c) };
+ match b {
+ b'(' | b')' | b'\\' => {
+ s.push('\\');
+ s.push(b as char);
+ }
+ 0x20..=0x7E => s.push(b as char),
+ _ => {
+ let _ = write!(s, "\\{b:03o}");
+ }
+ }
+ }
+ s.push(')');
+ s
+}
+
+/// URI actions use byte strings. Percent-encode non-ASCII UTF-8 before PDF string escaping.
+fn pdf_uri_string(uri: &str) -> String {
+ let mut ascii = String::with_capacity(uri.len());
+ for byte in uri.bytes() {
+ if byte.is_ascii() {
+ ascii.push(byte as char);
+ } else {
+ let _ = write!(ascii, "%{byte:02X}");
+ }
+ }
+ pdf_string(&ascii)
+}
+
+/// A number for a content stream: finite, short.
+fn n(v: f32) -> String {
+ let v = if v.is_finite() { v.clamp(-1.0e7, 1.0e7) } else { 0.0 };
+ let r = (v * 1000.0).round() / 1000.0;
+ if r == r.trunc() {
+ format!("{}", r as i64)
+ } else {
+ let s = format!("{r:.3}");
+ s.trim_end_matches('0').trim_end_matches('.').to_string()
+ }
+}
+
+/// True when every value is finite (NaN and infinities are rejected).
+fn finite(v: &[f32]) -> bool {
+ v.iter().all(|x| x.is_finite())
+}
+
+/// A positive, finite extent (a width, height or radius).
+fn extent(v: f32) -> bool {
+ v > 0.0 && v.is_finite()
+}
+
+/// A stroke width: negative, NaN and infinite become 0 (the thinnest line).
+fn stroke_width(w: f32) -> f32 {
+ if w.is_finite() { w.max(0.0) } else { 0.0 }
+}
+
+/// The entries of a dash array (`[on, off, …]`, at most 8). A pattern the PDF specification
+/// forbids (any non-finite entry, or no entry that survives rounding to a positive number) is
+/// replaced by an empty array, i.e. a solid line.
+fn dash_values(dash: &[f32]) -> String {
+ let d: Vec<f32> = dash.iter().take(8).map(|v| if v.is_finite() { v.max(0.0) } else { f32::NAN }).collect();
+ if !finite(&d) || !d.iter().any(|v| (v.min(1.0e7) * 1000.0).round() > 0.0) {
+ return String::new();
+ }
+ d.iter().map(|v| n(*v)).collect::<Vec<_>>().join(" ")
+}
+
+fn rgb_op(c: Rgb, stroke: bool) -> String {
+ let f = |v: u8| n(v as f32 / 255.0);
+ format!("{} {} {} {}", f(c[0]), f(c[1]), f(c[2]), if stroke { "RG" } else { "rg" })
+}
+
+struct ImageData {
+ width: u32,
+ height: u32,
+ rgb: Vec<u8>,
+ alpha: Option<Vec<u8>>,
+}
+
+enum LinkTarget {
+ Uri(String),
+ Page { index: usize, x: f32, y: f32 },
+}
+
+struct LinkAnnotation {
+ /// PDF coordinates, with the origin at the bottom left.
+ rect: [f32; 4],
+ target: LinkTarget,
+}
+
+/// A page under construction. Obtain one with [`PdfDoc::add_page`].
+pub struct Page {
+ width: f32,
+ height: f32,
+ content: String,
+ fonts: [bool; FONT_SLOTS],
+ embedded: embed::Used,
+ images: Vec<ImageData>,
+ links: Vec<LinkAnnotation>,
+ depth: u32,
+}
+
+/// Most bytes of content per page before further drawing is dropped (keeps hostile inputs from
+/// exhausting memory).
+const MAX_PAGE_CONTENT: usize = 64 * 1024 * 1024;
+/// Largest image (pixels) embedded.
+const MAX_IMAGE_PIXELS: u64 = 40_000_000;
+const MAX_PAGE_LINKS: usize = 4096;
+const MAX_LINK_URI_BYTES: usize = 4096;
+
+impl Page {
+ pub fn width(&self) -> f32 {
+ self.width
+ }
+ pub fn height(&self) -> f32 {
+ self.height
+ }
+ fn y(&self, y: f32) -> f32 {
+ self.height - y
+ }
+ fn full(&self) -> bool {
+ self.content.len() > MAX_PAGE_CONTENT
+ }
+ fn op(&mut self, s: &str) {
+ if !self.full() {
+ self.content.push_str(s);
+ self.content.push('\n');
+ }
+ }
+
+ fn link_rect(&self, rect: Rect) -> Option<[f32; 4]> {
+ let Rect { x, y, width, height } = rect;
+ if !finite(&[x, y, width, height]) || !extent(width) || !extent(height) || self.links.len() >= MAX_PAGE_LINKS {
+ return None;
+ }
+ let (right, bottom) = (x + width, y + height);
+ if !finite(&[right, bottom]) {
+ return None;
+ }
+ let (left, right) = (x.max(0.0), right.min(self.width));
+ let (top, bottom) = (y.max(0.0), bottom.min(self.height));
+ (right > left && bottom > top).then(|| [left, self.y(bottom), right, self.y(top)])
+ }
+
+ /// Adds an invisible clickable area for an external URI. Invalid or excessive links are ignored.
+ pub fn link_uri(&mut self, x: f32, y: f32, w: f32, h: f32, uri: &str) {
+ let allowed = uri
+ .split_once(':')
+ .is_some_and(|(scheme, rest)| matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https" | "mailto") && !rest.is_empty());
+ if !allowed || uri.len() > MAX_LINK_URI_BYTES || uri.chars().any(char::is_control) {
+ return;
+ }
+ if let Some(rect) = self.link_rect(Rect::new(x, y, w, h)) {
+ self.links.push(LinkAnnotation { rect, target: LinkTarget::Uri(uri.to_string()) });
+ }
+ }
+
+ /// Adds a link to a location on another page of this document (zero-based page index).
+ pub fn link_page(&mut self, rect: Rect, page: usize, target: Point) {
+ if !finite(&[target.x, target.y]) {
+ return;
+ }
+ if let Some(rect) = self.link_rect(rect) {
+ self.links.push(LinkAnnotation { rect, target: LinkTarget::Page { index: page, x: target.x, y: target.y } });
+ }
+ }
+
+ /// Saves the graphics state (pair with [`Page::restore`]).
+ pub fn save(&mut self) {
+ self.depth = self.depth.saturating_add(1);
+ self.content.push_str("q\n");
+ }
+ /// Restores the graphics state saved by [`Page::save`]; extra calls are ignored.
+ pub fn restore(&mut self) {
+ if self.depth > 0 {
+ self.depth -= 1;
+ self.content.push_str("Q\n");
+ }
+ }
+ /// Intersects the clip with a rectangle (until the next [`Page::restore`]).
+ pub fn clip_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
+ let s = format!("{} {} {} {} re W n", n(x), n(self.y(y + h)), n(w.max(0.0)), n(h.max(0.0)));
+ self.op(&s);
+ }
+
+ pub fn fill_rect(&mut self, x: f32, y: f32, w: f32, h: f32, color: Rgb) {
+ if !(extent(w) && extent(h) && finite(&[x, y])) {
+ return;
+ }
+ let s = format!("{}\n{} {} {} {} re f", rgb_op(color, false), n(x), n(self.y(y + h)), n(w), n(h));
+ self.op(&s);
+ }
+
+ pub fn rect_stroke(&mut self, x: f32, y: f32, w: f32, h: f32, width: f32, color: Rgb) {
+ if !finite(&[x, y, w, h]) {
+ return;
+ }
+ let s = format!("{}\n{} w [] 0 d\n{} {} {} {} re S", rgb_op(color, true), n(stroke_width(width)), n(x), n(self.y(y + h)), n(w), n(h));
+ self.op(&s);
+ }
+
+ pub fn stroke_line(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, width: f32, color: Rgb) {
+ self.stroke_line_dashed(Point::new(x0, y0), Point::new(x1, y1), width, color, &[]);
+ }
+
+ /// A line with a dash pattern (`[on, off, …]` in points; empty = solid).
+ pub fn stroke_line_dashed(&mut self, start: Point, end: Point, width: f32, color: Rgb, dash: &[f32]) {
+ if !finite(&[start.x, start.y, end.x, end.y]) {
+ return;
+ }
+ let s = format!(
+ "{}\n{} w [{}] 0 d\n{} {} m {} {} l S",
+ rgb_op(color, true),
+ n(stroke_width(width)),
+ dash_values(dash),
+ n(start.x),
+ n(self.y(start.y)),
+ n(end.x),
+ n(self.y(end.y))
+ );
+ self.op(&s);
+ }
+
+ /// An open polyline.
+ pub fn polyline(&mut self, pts: &[[f32; 2]], width: f32, color: Rgb, dash: &[f32]) {
+ if pts.len() < 2 || !pts.iter().all(|p| finite(p)) {
+ return;
+ }
+ let mut s = format!("{}\n{} w [{}] 0 d 1 j\n", rgb_op(color, true), n(stroke_width(width)), dash_values(dash));
+ self.path(&mut s, pts, false);
+ s.push_str(" S");
+ self.op(&s);
+ }
+
+ fn path(&self, s: &mut String, pts: &[[f32; 2]], close: bool) {
+ for (i, p) in pts.iter().enumerate() {
+ let _ = write!(s, "{} {} {} ", n(p[0]), n(self.y(p[1])), if i == 0 { "m" } else { "l" });
+ }
+ if close {
+ s.push('h');
+ }
+ }
+
+ /// A closed polygon, filled and/or stroked.
+ pub fn polygon(&mut self, pts: &[[f32; 2]], fill: Option<Rgb>, stroke: Option<(Rgb, f32)>) {
+ if pts.len() < 2 || (fill.is_none() && stroke.is_none()) || !pts.iter().all(|p| finite(p)) {
+ return;
+ }
+ let mut s = String::new();
+ if let Some(f) = fill {
+ s.push_str(&rgb_op(f, false));
+ s.push('\n');
+ }
+ if let Some((c, w)) = stroke {
+ let _ = writeln!(s, "{}\n{} w [] 0 d 1 j", rgb_op(c, true), n(stroke_width(w)));
+ }
+ self.path(&mut s, pts, true);
+ s.push_str(match (fill.is_some(), stroke.is_some()) {
+ (true, true) => " B",
+ (true, false) => " f",
+ _ => " S",
+ });
+ self.op(&s);
+ }
+
+ /// A circle approximated by four cubic Béziers.
+ pub fn circle(&mut self, cx: f32, cy: f32, r: f32, fill: Option<Rgb>, stroke: Option<(Rgb, f32)>) {
+ if !extent(r) || !finite(&[cx, cy]) || (fill.is_none() && stroke.is_none()) {
+ return;
+ }
+ const K: f32 = 0.552_284_8;
+ let k = r * K;
+ let y = self.y(cy);
+ let mut s = String::new();
+ if let Some(f) = fill {
+ s.push_str(&rgb_op(f, false));
+ s.push('\n');
+ }
+ if let Some((c, w)) = stroke {
+ let _ = writeln!(s, "{}\n{} w [] 0 d", rgb_op(c, true), n(stroke_width(w)));
+ }
+ let _ = write!(
+ s,
+ "{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c h",
+ n(cx + r),
+ n(y),
+ n(cx + r),
+ n(y + k),
+ n(cx + k),
+ n(y + r),
+ n(cx),
+ n(y + r),
+ n(cx - k),
+ n(y + r),
+ n(cx - r),
+ n(y + k),
+ n(cx - r),
+ n(y),
+ n(cx - r),
+ n(y - k),
+ n(cx - k),
+ n(y - r),
+ n(cx),
+ n(y - r),
+ n(cx + k),
+ n(y - r),
+ n(cx + r),
+ n(y - k),
+ n(cx + r),
+ n(y)
+ );
+ s.push_str(match (fill.is_some(), stroke.is_some()) {
+ (true, true) => " B",
+ (true, false) => " f",
+ _ => " S",
+ });
+ self.op(&s);
+ }
+
+ /// Text with its baseline starting at `(x, y)`.
+ pub fn text(&mut self, x: f32, y: f32, size: f32, font: Font, color: Rgb, text: &str) {
+ self.text_rotated(Point::new(x, y), size, font, color, text, 0.0);
+ }
+
+ /// Text rotated by `angle` radians (clockwise on the page, like the y-down coordinate
+ /// system) about its baseline origin.
+ pub fn text_rotated(&mut self, origin: Point, size: f32, font: Font, color: Rgb, text: &str, angle: f32) {
+ if text.is_empty() || !extent(size) || !finite(&[origin.x, origin.y]) {
+ return;
+ }
+ let fi = font.index();
+ let size = n(size.min(10_000.0));
+ let (sn, cs) = if angle.is_finite() { angle.sin_cos() } else { (0.0, 1.0) };
+ // Clockwise in y-down = counter-clockwise negated in PDF's y-up space.
+ let mut s = format!("BT\n{}\n{} {} {} {} {} {} Tm\n", rgb_op(color, false), n(cs), n(-sn), n(sn), n(cs), n(origin.x), n(self.y(origin.y)));
+ // Symbol text is one run in Symbol's own encoding (the CID font has no maths symbols).
+ if font == Font::Symbol {
+ if let Some(f) = self.fonts.get_mut(fi) {
+ *f = true;
+ }
+ let _ = writeln!(s, "/F{} {} Tf\n{} Tj", fi + 1, size, pdf_string_in(text, true));
+ s.push_str("ET");
+ self.op(&s);
+ return;
+ }
+ // Runs of WinAnsi text use `font`; runs it cannot encode use the embedded face (Artefact
+ // patch) or, for scripts that lacks, the CID font. Each `Tj` advances the text position,
+ // so the runs follow each other on the baseline.
+ let mut rest = text;
+ let face = font.embed_face();
+ while let Some(first) = rest.chars().next() {
+ let class = run_class(first);
+ let end = rest.char_indices().find(|(_, c)| run_class(*c) != class).map_or(rest.len(), |(i, _)| i);
+ let (run, tail) = rest.split_at(end);
+ match class {
+ RunClass::Embedded => {
+ let string = embed::hex_string(face, run, &mut self.embedded[face.index()]);
+ let _ = writeln!(s, "/FE{} {} Tf\n{} Tj", face.index() + 1, size, string);
+ }
+ RunClass::Cid | RunClass::Plain => {
+ let (slot, string) = if class == RunClass::Cid { (CID_FONT, pdf_utf16_string(run)) } else { (fi, pdf_string(run)) };
+ if let Some(f) = self.fonts.get_mut(slot) {
+ *f = true;
+ }
+ let _ = writeln!(s, "/F{} {} Tf\n{} Tj", slot + 1, size, string);
+ }
+ }
+ rest = tail;
+ }
+ s.push_str("ET");
+ self.op(&s);
+ }
+
+ /// Draws an RGBA image (`pw`×`ph` pixels, row-major, straight alpha) into the box
+ /// `(x, y, w, h)`. Malformed or oversized buffers are ignored.
+ pub fn image_rgba(&mut self, destination: Rect, rgba: &[u8], pixel_size: [u32; 2]) {
+ let Rect { x, y, width: w, height: h } = destination;
+ let [pw, ph] = pixel_size;
+ let px = pw as u64 * ph as u64;
+ if pw == 0 || ph == 0 || px > MAX_IMAGE_PIXELS || (rgba.len() as u64) < px * 4 || !(extent(w) && extent(h) && finite(&[x, y])) {
+ return;
+ }
+ let px = px as usize;
+ let mut rgb = Vec::with_capacity(px * 3);
+ let mut alpha = Vec::with_capacity(px);
+ for p in rgba.as_chunks::<4>().0.iter().take(px) {
+ rgb.extend_from_slice(&[p[0], p[1], p[2]]);
+ alpha.push(p[3]);
+ }
+ let alpha = if alpha.iter().all(|a| *a == 255) { None } else { Some(alpha) };
+ let idx = self.images.len();
+ self.images.push(ImageData { width: pw, height: ph, rgb, alpha });
+ let s = format!("q {} 0 0 {} {} {} cm /Im{} Do Q", n(w), n(h), n(x), n(self.y(y + h)), idx + 1);
+ self.op(&s);
+ }
+}
+
+/// Document metadata.
+#[derive(Clone, Debug, Default)]
+pub struct Info {
+ pub title: String,
+ pub author: String,
+ pub creator: String,
+}
+
+/// A PDF document under construction.
+#[derive(Default)]
+pub struct PdfDoc {
+ pages: Vec<Page>,
+ pub info: Info,
+}
+
+/// PackBits-style run-length encoding (PDF `RunLengthDecode`).
+fn run_length(data: &[u8]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(data.len() / 2 + 16);
+ let mut i = 0;
+ while i < data.len() {
+ let b = data[i];
+ let mut run = 1;
+ while i + run < data.len() && run < 128 && data[i + run] == b {
+ run += 1;
+ }
+ if run >= 2 {
+ out.push((257 - run) as u8);
+ out.push(b);
+ i += run;
+ continue;
+ }
+ // Literal run until the next repeat of 3+ or 128 bytes.
+ let start = i;
+ let mut len = 0;
+ while i < data.len() && len < 128 {
+ if i + 2 < data.len() && data[i] == data[i + 1] && data[i] == data[i + 2] {
+ break;
+ }
+ i += 1;
+ len += 1;
+ }
+ if len == 0 {
+ // Next is a repeat; loop will handle it.
+ continue;
+ }
+ out.push((len - 1) as u8);
+ out.extend_from_slice(&data[start..start + len]);
+ }
+ out.push(128);
+ out
+}
+
+/// Longest Info string written, in characters; longer values are cut on a character boundary.
+const MAX_INFO_CHARS: usize = 1024;
+
+/// A PDF text string (document Info entries) for `text`: a literal `( … )` for printable ASCII,
+/// otherwise UTF-16BE with a byte-order mark as a hex string (ISO 32000-1 7.9.2.2).
+fn pdf_text_string(text: &str) -> String {
+ let text: String = text.chars().take(MAX_INFO_CHARS).collect();
+ if text.chars().all(|c| matches!(c, ' '..='~')) {
+ return pdf_string(&text);
+ }
+ let mut s = String::with_capacity(text.len() * 4 + 6);
+ s.push_str("<FEFF");
+ for unit in text.encode_utf16() {
+ let _ = write!(s, "{unit:04X}");
+ }
+ s.push('>');
+ s
+}
+
+impl PdfDoc {
+ pub fn new() -> PdfDoc {
+ PdfDoc::default()
+ }
+
+ /// Adds a page of `width_pt` × `height_pt` points and returns it for drawing.
+ pub fn add_page(&mut self, width_pt: f32, height_pt: f32) -> &mut Page {
+ let width = if width_pt.is_finite() { width_pt.clamp(3.0, 14_400.0) } else { 612.0 };
+ let height = if height_pt.is_finite() { height_pt.clamp(3.0, 14_400.0) } else { 792.0 };
+ self.pages.push(Page { width, height, content: String::new(), fonts: [false; FONT_SLOTS], embedded: Default::default(), images: Vec::new(), links: Vec::new(), depth: 0 });
+ let i = self.pages.len() - 1;
+ &mut self.pages[i]
+ }
+
+ pub fn page_count(&self) -> usize {
+ self.pages.len()
+ }
+
+ /// The page at `i`, to keep drawing on it.
+ pub fn page_mut(&mut self, i: usize) -> Option<&mut Page> {
+ self.pages.get_mut(i)
+ }
+
+ /// Serializes the document. A document without pages gets one blank Letter page.
+ pub fn finish(mut self) -> Vec<u8> {
+ if self.pages.is_empty() {
+ self.add_page(612.0, 792.0);
+ }
+ // Object numbering: 1 catalog, 2 page tree, 3 info, then fonts, then per page.
+ let mut used = [false; FONT_SLOTS];
+ for p in &self.pages {
+ for (u, f) in used.iter_mut().zip(p.fonts.iter()) {
+ *u |= *f;
+ }
+ }
+ let mut next = 4u32;
+ let mut font_ids = [0u32; FONT_SLOTS];
+ for (i, u) in used.iter().enumerate() {
+ if *u {
+ font_ids[i] = next;
+ // The CID font also needs its descendant font and font descriptor.
+ next += if i == CID_FONT { 3 } else { 1 };
+ }
+ }
+ // Artefact patch: embedded faces (six objects each) over every page's glyphs.
+ let mut embedded: embed::Used = Default::default();
+ for p in &self.pages {
+ for (all, page) in embedded.iter_mut().zip(p.embedded.iter()) {
+ all.extend(page.iter().map(|(g, c)| (*g, *c)));
+ }
+ }
+ let mut embed_ids = [0u32; 3];
+ for face in embed::FACES {
+ if !embedded[face.index()].is_empty() {
+ embed_ids[face.index()] = next;
+ next += 6;
+ }
+ }
+ let mut objects: Vec<(u32, Vec<u8>)> = Vec::new();
+ for face in embed::FACES {
+ let id = embed_ids[face.index()];
+ if id != 0 {
+ match embed::objects(face, id, &embedded[face.index()]) {
+ Some(objs) => objects.extend(objs),
+ None => embed_ids[face.index()] = 0,
+ }
+ }
+ }
+ let mut kids = Vec::new();
+ let mut annotations = Vec::new();
+ let page_count = self.pages.len();
+ let mut font_dict = String::new();
+ for face in embed::FACES {
+ let id = embed_ids[face.index()];
+ if id != 0 {
+ let _ = write!(font_dict, "/FE{} {} 0 R ", face.index() + 1, id);
+ }
+ }
+ for (i, id) in font_ids.iter().enumerate() {
+ if *id != 0 {
+ let _ = write!(font_dict, "/F{} {} 0 R ", i + 1, id);
+ if i == CID_FONT {
+ let (cid_id, desc_id) = (id + 1, id + 2);
+ objects.push((
+ *id,
+ format!(
+ "<< /Type /Font /Subtype /Type0 /BaseFont /{CID_BASE_FONT} /Encoding /UniGB-UTF16-H /DescendantFonts [{cid_id} 0 R] >>"
+ )
+ .into_bytes(),
+ ));
+ objects.push((
+ cid_id,
+ format!(
+ "<< /Type /Font /Subtype /CIDFontType0 /BaseFont /{CID_BASE_FONT} /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 4 >> /FontDescriptor {desc_id} 0 R /DW {CID_WIDTH} >>"
+ )
+ .into_bytes(),
+ ));
+ objects.push((
+ desc_id,
+ format!(
+ "<< /Type /FontDescriptor /FontName /{CID_BASE_FONT} /Flags 6 /FontBBox [-25 -254 1000 880] /ItalicAngle 0 /Ascent 880 /Descent -120 /CapHeight 880 /StemV 93 >>"
+ )
+ .into_bytes(),
+ ));
+ continue;
+ }
+ let name = Font::ALL.get(i).copied().unwrap_or_default().base_name();
+ let enc = if name.starts_with("Symbol") { "" } else { " /Encoding /WinAnsiEncoding" };
+ objects.push((*id, format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name}{enc} >>").into_bytes()));
+ }
+ }
+ for page in &mut self.pages {
+ while page.depth > 0 {
+ page.restore();
+ }
+ let mut xobjects = String::new();
+ for (k, img) in page.images.iter().enumerate() {
+ let img_id = next;
+ next += 1;
+ let smask = match &img.alpha {
+ Some(a) => {
+ let id = next;
+ next += 1;
+ let data = run_length(a);
+ let mut o = format!(
+ "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /RunLengthDecode /Length {} >>\nstream\n",
+ img.width,
+ img.height,
+ data.len()
+ )
+ .into_bytes();
+ o.extend_from_slice(&data);
+ o.extend_from_slice(b"\nendstream");
+ objects.push((id, o));
+ format!(" /SMask {id} 0 R")
+ }
+ None => String::new(),
+ };
+ let data = run_length(&img.rgb);
+ let mut o = format!(
+ "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceRGB /BitsPerComponent 8{} /Filter /RunLengthDecode /Length {} >>\nstream\n",
+ img.width,
+ img.height,
+ smask,
+ data.len()
+ )
+ .into_bytes();
+ o.extend_from_slice(&data);
+ o.extend_from_slice(b"\nendstream");
+ objects.push((img_id, o));
+ let _ = write!(xobjects, "/Im{} {} 0 R ", k + 1, img_id);
+ }
+ let content_id = next;
+ let page_id = next + 1;
+ next += 2;
+ let body = std::mem::take(&mut page.content);
+ let mut o = format!("<< /Length {} >>\nstream\n", body.len()).into_bytes();
+ o.extend_from_slice(body.as_bytes());
+ o.extend_from_slice(b"endstream");
+ objects.push((content_id, o));
+ let xo = if xobjects.is_empty() { String::new() } else { format!(" /XObject << {xobjects}>>") };
+ let mut link_refs = String::new();
+ for link in std::mem::take(&mut page.links) {
+ if matches!(&link.target, LinkTarget::Page { index, .. } if *index >= page_count) {
+ continue;
+ }
+ let id = next;
+ next += 1;
+ let _ = write!(link_refs, "{id} 0 R ");
+ annotations.push((id, link));
+ }
+ let annots = if link_refs.is_empty() { String::new() } else { format!(" /Annots [{link_refs}]") };
+ objects.push((
+ page_id,
+ format!(
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources << /ProcSet [/PDF /Text /ImageB /ImageC] /Font << {}>>{} >> /Contents {} 0 R{} >>",
+ n(page.width),
+ n(page.height),
+ font_dict,
+ xo,
+ content_id,
+ annots
+ )
+ .into_bytes(),
+ ));
+ kids.push(page_id);
+ }
+ for (id, link) in annotations {
+ let [x0, y0, x1, y1] = link.rect;
+ let action = match link.target {
+ LinkTarget::Uri(uri) => format!("/A << /S /URI /URI {} >>", pdf_uri_string(&uri)),
+ LinkTarget::Page { index, x, y } => {
+ let Some(&page_id) = kids.get(index) else { continue };
+ let height = self.pages.get(index).map_or(0.0, |p| p.height);
+ format!("/Dest [{page_id} 0 R /XYZ {} {} null]", n(x), n(height - y))
+ }
+ };
+ objects.push((
+ id,
+ format!("<< /Type /Annot /Subtype /Link /Rect [{} {} {} {}] /Border [0 0 0] {action} >>", n(x0), n(y0), n(x1), n(y1)).into_bytes(),
+ ));
+ }
+ objects.push((1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()));
+ let kids_s: Vec<String> = kids.iter().map(|k| format!("{k} 0 R")).collect();
+ objects.push((2, format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids_s.join(" "), kids.len()).into_bytes()));
+ let creator = if self.info.creator.is_empty() { "GridCraft" } else { &self.info.creator };
+ let mut info = format!("<< /Producer {} /Creator {}", pdf_text_string("GridCraft PDF"), pdf_text_string(creator));
+ if !self.info.title.is_empty() {
+ let _ = write!(info, " /Title {}", pdf_text_string(&self.info.title));
+ }
+ if !self.info.author.is_empty() {
+ let _ = write!(info, " /Author {}", pdf_text_string(&self.info.author));
+ }
+ info.push_str(" >>");
+ objects.push((3, info.into_bytes()));
+ objects.sort_by_key(|(id, _)| *id);
+
+ let mut out: Vec<u8> = Vec::new();
+ out.extend_from_slice(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
+ let mut offsets = vec![0usize; next as usize];
+ for (id, body) in &objects {
+ if let Some(slot) = offsets.get_mut(*id as usize) {
+ *slot = out.len();
+ }
+ out.extend_from_slice(format!("{id} 0 obj\n").as_bytes());
+ out.extend_from_slice(body);
+ out.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = out.len();
+ let mut x = format!("xref\n0 {}\n0000000000 65535 f \n", next);
+ for off in offsets.iter().skip(1) {
+ let _ = writeln!(x, "{off:010} 00000 n ");
+ }
+ let _ = write!(x, "trailer\n<< /Size {} /Root 1 0 R /Info 3 0 R >>\nstartxref\n{}\n%%EOF\n", next, xref);
+ out.extend_from_slice(x.as_bytes());
+ out
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/engine/vendor/gridcraft-pdf/src/metrics.rs b/engine/vendor/gridcraft-pdf/src/metrics.rs
new file mode 100644
index 0000000..09fbbfb
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/src/metrics.rs
@@ -0,0 +1,114 @@
+//! Advance widths of the standard 14 PDF fonts, in 1/1000 em, for the printable ASCII range.
+//!
+//! Source: the glyph advance widths ("WX" values) of Adobe's Core 14 AFM font metrics files
+//! (Helvetica, Helvetica-Bold, Times-Roman, Times-Bold, Courier). Adobe distributes those metrics
+//! files with permission to use, copy and distribute them for any purpose ("This file and the 14
+//! PostScript(R) AFM files it accompanies may be used, copied, and distributed for any purpose and
+//! without charge, with or without modification, provided that all copyright notices are retained;
+//! that the AFM files are not distributed without this file; that all modifications to this file
+//! or any of the AFM files are prominently noted in the modified file(s); and that this paragraph
+//! is not modified."). Only the numeric widths are reproduced here, typed in from the public
+//! metrics; no AFM file is included. Oblique/italic faces reuse the upright widths (an
+//! approximation that is exact for Helvetica and close for Times), and characters outside ASCII
+//! are approximated by their base letter.
+
+/// Helvetica and Helvetica-Oblique, chars 32..=126.
+pub(crate) const HELVETICA: [u16; 95] = [
+ 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, // ' '..'/'
+ 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, // '0'..'9'
+ 278, 278, 584, 584, 584, 556, 1015, // ':'..'@'
+ 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, // 'A'..'M'
+ 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, // 'N'..'Z'
+ 278, 278, 278, 469, 556, 333, // '['..'`'
+ 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, // 'a'..'m'
+ 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, // 'n'..'z'
+ 334, 260, 334, 584, // '{'..'~'
+];
+
+/// Helvetica-Bold and Helvetica-BoldOblique, chars 32..=126.
+pub(crate) const HELVETICA_BOLD: [u16; 95] = [
+ 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, // ' '..'/'
+ 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, // '0'..'9'
+ 333, 333, 584, 584, 584, 611, 975, // ':'..'@'
+ 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, // 'A'..'M'
+ 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, // 'N'..'Z'
+ 333, 278, 333, 584, 556, 333, // '['..'`'
+ 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, // 'a'..'m'
+ 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, // 'n'..'z'
+ 389, 280, 389, 584, // '{'..'~'
+];
+
+/// Times-Roman and Times-Italic (approximation), chars 32..=126.
+pub(crate) const TIMES: [u16; 95] = [
+ 250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278, // ' '..'/'
+ 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, // '0'..'9'
+ 278, 278, 564, 564, 564, 444, 921, // ':'..'@'
+ 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, // 'A'..'M'
+ 722, 722, 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, // 'N'..'Z'
+ 333, 278, 333, 469, 500, 333, // '['..'`'
+ 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, // 'a'..'m'
+ 500, 500, 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, // 'n'..'z'
+ 480, 200, 480, 541, // '{'..'~'
+];
+
+/// Times-Bold and Times-BoldItalic (approximation), chars 32..=126.
+pub(crate) const TIMES_BOLD: [u16; 95] = [
+ 250, 333, 555, 500, 500, 1000, 833, 278, 333, 333, 500, 570, 250, 333, 250, 278, // ' '..'/'
+ 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, // '0'..'9'
+ 333, 333, 570, 570, 570, 500, 930, // ':'..'@'
+ 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944, // 'A'..'M'
+ 722, 778, 611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, // 'N'..'Z'
+ 333, 278, 333, 581, 500, 333, // '['..'`'
+ 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833, // 'a'..'m'
+ 556, 500, 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, // 'n'..'z'
+ 394, 220, 394, 520, // '{'..'~'
+];
+
+/// Maps a non-ASCII character to an ASCII character of similar width, or `None` to use the
+/// font's default width.
+pub(crate) fn fold(c: char) -> Option<char> {
+ Some(match c {
+ 'À'..='Å' => 'A',
+ 'Æ' => 'W',
+ 'Ç' => 'C',
+ 'È'..='Ë' => 'E',
+ 'Ì'..='Ï' => 'I',
+ 'Ð' => 'D',
+ 'Ñ' => 'N',
+ 'Ò'..='Ö' | 'Ø' => 'O',
+ '×' => '+',
+ 'Ù'..='Ü' => 'U',
+ 'Ý' | 'Ÿ' => 'Y',
+ 'Þ' => 'P',
+ 'ß' => 'b',
+ 'à'..='å' => 'a',
+ 'æ' => 'm',
+ 'ç' => 'c',
+ 'è'..='ë' => 'e',
+ 'ì'..='ï' => 'i',
+ 'ð' => 'o',
+ 'ñ' => 'n',
+ 'ò'..='ö' | 'ø' => 'o',
+ '÷' => '+',
+ 'ù'..='ü' => 'u',
+ 'ý' | 'ÿ' => 'y',
+ 'þ' => 'p',
+ 'Š' => 'S',
+ 'š' => 's',
+ 'Ž' => 'Z',
+ 'ž' => 'z',
+ 'Œ' => 'W',
+ 'œ' => 'm',
+ '‘'..='‚' => '\'',
+ '“'..='„' => '"',
+ '–' | '€' | '£' | '¥' | '¢' | '¤' => '0',
+ '\u{a0}' => ' ',
+ '·' | '•' => '.',
+ '«' | '»' | '‹' | '›' => '<',
+ '¡' => '!',
+ '¿' => '?',
+ '¦' => '|',
+ '°' | '¹' | '²' | '³' | 'ª' | 'º' => '*',
+ _ => return None,
+ })
+}
diff --git a/engine/vendor/gridcraft-pdf/src/symbol.rs b/engine/vendor/gridcraft-pdf/src/symbol.rs
new file mode 100644
index 0000000..c8a1eda
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/src/symbol.rs
@@ -0,0 +1,239 @@
+//! The standard Symbol font: its built-in encoding and advance widths.
+//!
+//! Source: the character codes and glyph advance widths ("C" and "WX" values) of Adobe's Core 14
+//! AFM metrics file for Symbol (`Symbol.afm`, version 001.008), and the Unicode values of its glyph
+//! names from Unicode, Inc.'s `symbol.txt` ("Adobe Symbol Encoding to Unicode", table version
+//! 1.0). Adobe distributes the Core 14 metrics with permission to use, copy and distribute them
+//! for any purpose (the notice is quoted in `metrics.rs`); Unicode, Inc. grants the right to use
+//! the information in its file in products supporting the Unicode Standard (its notice is
+//! recorded in `ATTRIBUTION.md`). Only the numbers are reproduced here, typed in from the public
+//! tables; neither file is included. The stretchable
+//! bracket, brace and integral pieces (codes 0xE6 to 0xEF and 0xF3 to 0xFE) and the sans-serif
+//! duplicates of the registered, copyright and trademark signs are left out of the Unicode map:
+//! they have no Unicode counterpart of their own.
+
+/// The Symbol-encoding code for `c`, or `None` when Symbol has no such glyph.
+pub fn symbol_code(c: char) -> Option<u8> {
+ let u = c as u32;
+ // Characters Symbol encodes at their ASCII code.
+ if matches!(
+ c,
+ ' ' | '!' | '#' | '%' | '&' | '(' | ')' | '+' | ',' | '.' | '/' | '0'
+ ..='9' | ':' | ';' | '<' | '=' | '>' | '?' | '[' | ']' | '_' | '{' | '|' | '}'
+ ) {
+ return Some(u as u8);
+ }
+ Some(match c {
+ '\u{2200}' => 0x22, // for all
+ '\u{2203}' => 0x24, // there exists
+ '\u{220B}' => 0x27, // such that (contains as member)
+ '\u{2217}' | '*' => 0x2A,
+ '\u{2212}' | '-' => 0x2D, // minus
+ '\u{2245}' => 0x40, // approximately equal (congruent)
+ '\u{0391}' => 0x41,
+ '\u{0392}' => 0x42,
+ '\u{03A7}' => 0x43,
+ '\u{0394}' | '\u{2206}' => 0x44,
+ '\u{0395}' => 0x45,
+ '\u{03A6}' => 0x46,
+ '\u{0393}' => 0x47,
+ '\u{0397}' => 0x48,
+ '\u{0399}' => 0x49,
+ '\u{03D1}' => 0x4A, // theta1
+ '\u{039A}' => 0x4B,
+ '\u{039B}' => 0x4C,
+ '\u{039C}' => 0x4D,
+ '\u{039D}' => 0x4E,
+ '\u{039F}' => 0x4F,
+ '\u{03A0}' => 0x50,
+ '\u{0398}' => 0x51,
+ '\u{03A1}' => 0x52,
+ '\u{03A3}' => 0x53,
+ '\u{03A4}' => 0x54,
+ '\u{03A5}' => 0x55,
+ '\u{03C2}' => 0x56, // final sigma (sigma1)
+ '\u{03A9}' | '\u{2126}' => 0x57,
+ '\u{039E}' => 0x58,
+ '\u{03A8}' => 0x59,
+ '\u{0396}' => 0x5A,
+ '\u{2234}' => 0x5C, // therefore
+ '\u{22A5}' => 0x5E, // perpendicular
+ '\u{03B1}' => 0x61,
+ '\u{03B2}' => 0x62,
+ '\u{03C7}' => 0x63,
+ '\u{03B4}' => 0x64,
+ '\u{03B5}' | '\u{03F5}' => 0x65,
+ '\u{03C6}' => 0x66,
+ '\u{03B3}' => 0x67,
+ '\u{03B7}' => 0x68,
+ '\u{03B9}' => 0x69,
+ '\u{03D5}' => 0x6A, // phi1
+ '\u{03BA}' => 0x6B,
+ '\u{03BB}' => 0x6C,
+ '\u{03BC}' | '\u{00B5}' => 0x6D,
+ '\u{03BD}' => 0x6E,
+ '\u{03BF}' => 0x6F,
+ '\u{03C0}' => 0x70,
+ '\u{03B8}' => 0x71,
+ '\u{03C1}' => 0x72,
+ '\u{03C3}' => 0x73,
+ '\u{03C4}' => 0x74,
+ '\u{03C5}' => 0x75,
+ '\u{03D6}' => 0x76, // omega1 (pi symbol)
+ '\u{03C9}' => 0x77,
+ '\u{03BE}' => 0x78,
+ '\u{03C8}' => 0x79,
+ '\u{03B6}' => 0x7A,
+ '\u{223C}' | '~' => 0x7E, // similar
+ '\u{20AC}' => 0xA0, // euro
+ '\u{03D2}' => 0xA1, // Upsilon1
+ '\u{2032}' => 0xA2, // minute (prime)
+ '\u{2264}' => 0xA3,
+ '\u{2044}' => 0xA4, // fraction slash
+ '\u{221E}' => 0xA5,
+ '\u{0192}' => 0xA6,
+ '\u{2663}' => 0xA7,
+ '\u{2666}' => 0xA8,
+ '\u{2665}' => 0xA9,
+ '\u{2660}' => 0xAA,
+ '\u{2194}' => 0xAB,
+ '\u{2190}' => 0xAC,
+ '\u{2191}' => 0xAD,
+ '\u{2192}' => 0xAE,
+ '\u{2193}' => 0xAF,
+ '\u{00B0}' => 0xB0,
+ '\u{00B1}' => 0xB1,
+ '\u{2033}' => 0xB2, // second (double prime)
+ '\u{2265}' => 0xB3,
+ '\u{00D7}' => 0xB4,
+ '\u{221D}' => 0xB5,
+ '\u{2202}' => 0xB6,
+ '\u{2022}' | '\u{2219}' => 0xB7,
+ '\u{00F7}' => 0xB8,
+ '\u{2260}' => 0xB9,
+ '\u{2261}' => 0xBA,
+ '\u{2248}' => 0xBB,
+ '\u{2026}' => 0xBC,
+ '\u{21B5}' => 0xBF,
+ '\u{2135}' => 0xC0,
+ '\u{2111}' => 0xC1,
+ '\u{211C}' => 0xC2,
+ '\u{2118}' => 0xC3,
+ '\u{2297}' => 0xC4,
+ '\u{2295}' => 0xC5,
+ '\u{2205}' => 0xC6,
+ '\u{2229}' => 0xC7,
+ '\u{222A}' => 0xC8,
+ '\u{2283}' => 0xC9,
+ '\u{2287}' => 0xCA,
+ '\u{2284}' => 0xCB,
+ '\u{2282}' => 0xCC,
+ '\u{2286}' => 0xCD,
+ '\u{2208}' => 0xCE,
+ '\u{2209}' => 0xCF,
+ '\u{2220}' => 0xD0,
+ '\u{2207}' => 0xD1,
+ '\u{00AE}' => 0xD2,
+ '\u{00A9}' => 0xD3,
+ '\u{2122}' => 0xD4,
+ '\u{220F}' => 0xD5,
+ '\u{221A}' => 0xD6,
+ '\u{22C5}' | '\u{00B7}' => 0xD7, // dot operator
+ '\u{00AC}' => 0xD8,
+ '\u{2227}' => 0xD9,
+ '\u{2228}' => 0xDA,
+ '\u{21D4}' => 0xDB,
+ '\u{21D0}' => 0xDC,
+ '\u{21D1}' => 0xDD,
+ '\u{21D2}' => 0xDE,
+ '\u{21D3}' => 0xDF,
+ '\u{25CA}' => 0xE0,
+ '\u{2329}' | '\u{27E8}' => 0xE1, // angle bracket left
+ '\u{2211}' => 0xE5,
+ '\u{232A}' | '\u{27E9}' => 0xF1, // angle bracket right
+ '\u{222B}' => 0xF2,
+ _ => return None,
+ })
+}
+
+/// Advance widths in 1/1000 em for codes 0x20..=0xFF (0 where Symbol has no glyph).
+const WIDTHS: [u16; 224] = [
+ // 0x20
+ 250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549, 250, 278, //
+ // 0x30
+ 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 549, 549, 549, 444, //
+ // 0x40
+ 549, 722, 667, 722, 612, 611, 763, 603, 722, 333, 631, 722, 686, 889, 722, 722, //
+ // 0x50
+ 768, 741, 556, 592, 611, 690, 439, 768, 645, 795, 611, 333, 863, 333, 658, 500, //
+ // 0x60
+ 500, 631, 549, 549, 494, 439, 521, 411, 603, 329, 603, 549, 549, 576, 521, 549, //
+ // 0x70
+ 549, 521, 549, 603, 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 0, //
+ // 0x80
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
+ // 0x90
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
+ // 0xA0
+ 750, 620, 247, 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603, //
+ // 0xB0
+ 400, 549, 411, 549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000, 658, //
+ // 0xC0
+ 823, 686, 795, 987, 768, 768, 823, 768, 768, 713, 713, 713, 713, 713, 713, 713, //
+ // 0xD0
+ 768, 713, 790, 790, 890, 823, 549, 250, 713, 603, 603, 1042, 987, 603, 987, 603, //
+ // 0xE0
+ 494, 329, 790, 790, 786, 713, 384, 384, 384, 384, 384, 384, 494, 494, 494, 494, //
+ // 0xF0
+ 0, 329, 274, 686, 686, 686, 384, 384, 384, 384, 384, 384, 494, 494, 494, 0, //
+];
+
+/// The advance width of code `code` in 1/1000 em, or `None` for an empty slot.
+pub fn symbol_width(code: u8) -> Option<u16> {
+ let w = *WIDTHS.get(usize::from(code).checked_sub(0x20)?)?;
+ (w > 0).then_some(w)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn maths_symbols_are_encoded_with_their_widths() {
+ for (c, code, w) in [
+ ('α', 0x61, 631),
+ ('π', 0x70, 549),
+ ('Σ', 0x53, 592),
+ ('∑', 0xE5, 713),
+ ('∫', 0xF2, 274),
+ ('√', 0xD6, 549),
+ ('≤', 0xA3, 549),
+ ('≥', 0xB3, 549),
+ ('±', 0xB1, 549),
+ ('×', 0xB4, 549),
+ ('÷', 0xB8, 549),
+ ('∞', 0xA5, 713),
+ ('∂', 0xB6, 494),
+ ('−', 0x2D, 549),
+ ('=', 0x3D, 549),
+ ('2', 0x32, 500),
+ ] {
+ assert_eq!(symbol_code(c), Some(code), "{c}");
+ assert_eq!(symbol_width(code), Some(w), "{c}");
+ }
+ assert_eq!(symbol_code('A'), None, "Latin letters belong to the text faces");
+ assert_eq!(symbol_code('ℝ'), None);
+ assert_eq!(symbol_width(0x7F), None);
+ assert_eq!(symbol_width(0x10), None);
+ assert_eq!(symbol_width(0xFF), None);
+ }
+
+ #[test]
+ fn every_encoded_character_has_a_width() {
+ for u in 0..0x3000u32 {
+ if let Some(code) = char::from_u32(u).and_then(symbol_code) {
+ assert!(symbol_width(code).is_some(), "U+{u:04X} -> {code:#x}");
+ }
+ }
+ }
+}
diff --git a/engine/vendor/gridcraft-pdf/src/tests.rs b/engine/vendor/gridcraft-pdf/src/tests.rs
new file mode 100644
index 0000000..9a8521a
--- /dev/null
+++ b/engine/vendor/gridcraft-pdf/src/tests.rs
@@ -0,0 +1,376 @@
+use super::*;
+use std::error::Error;
+use std::io;
+
+fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
+ hay.windows(needle.len()).position(|w| w == needle)
+}
+fn rfind(hay: &[u8], needle: &[u8]) -> Option<usize> {
+ hay.windows(needle.len()).rposition(|w| w == needle)
+}
+
+/// Parses the xref table back and checks each in-use entry points at `N 0 obj`.
+fn check_xref(pdf: &[u8]) -> Result<usize, Box<dyn Error>> {
+ let sx = rfind(pdf, b"startxref\n").ok_or_else(|| io::Error::other("missing startxref"))?;
+ let rest = std::str::from_utf8(&pdf[sx + 10..])?;
+ let off: usize = rest.lines().next().ok_or_else(|| io::Error::other("missing xref offset"))?.trim().parse()?;
+ assert!(pdf[off..].starts_with(b"xref\n"), "startxref points at xref");
+ let table = std::str::from_utf8(&pdf[off..sx])?;
+ let mut lines = table.lines();
+ assert_eq!(lines.next(), Some("xref"));
+ let hdr: Vec<usize> =
+ lines.next().ok_or_else(|| io::Error::other("missing xref header"))?.split(' ').map(str::parse).collect::<Result<_, _>>()?;
+ assert_eq!(hdr.first(), Some(&0));
+ let count = *hdr.get(1).ok_or_else(|| io::Error::other("missing xref count"))?;
+ let mut checked = 0;
+ for i in 0..count {
+ let e = lines.next().ok_or_else(|| io::Error::other("missing xref entry"))?;
+ assert_eq!(e.len(), 19, "entry `{e}` (20 bytes with newline)");
+ let o: usize = e.get(..10).ok_or_else(|| io::Error::other("short xref offset"))?.parse()?;
+ if e.trim_end().ends_with('n') {
+ let want = format!("{i} 0 obj");
+ assert!(pdf[o..].starts_with(want.as_bytes()), "object {i} at {o}");
+ checked += 1;
+ }
+ }
+ assert!(table.contains("trailer"));
+ assert!(table.contains(&format!("/Size {count}")));
+ Ok(checked)
+}
+
+#[test]
+fn minimal_document() -> Result<(), Box<dyn Error>> {
+ let pdf = PdfDoc::new().finish();
+ assert!(pdf.starts_with(b"%PDF-1.7"));
+ assert!(pdf.ends_with(b"%%EOF\n"));
+ assert!(check_xref(&pdf)? >= 5);
+ Ok(())
+}
+
+#[test]
+fn drawing_and_text() -> Result<(), Box<dyn Error>> {
+ let mut d = PdfDoc::new();
+ d.info.title = "Report (Q1)".into();
+ let p = d.add_page(612.0, 792.0);
+ p.fill_rect(10.0, 10.0, 100.0, 20.0, [255, 255, 0]);
+ p.rect_stroke(10.0, 10.0, 100.0, 20.0, 0.5, [0, 0, 0]);
+ p.stroke_line(0.0, 0.0, 612.0, 792.0, 1.0, [255, 0, 0]);
+ p.stroke_line_dashed(Point::new(0.0, 5.0), Point::new(100.0, 5.0), 1.0, [0, 0, 0], &[3.0, 2.0]);
+ p.polygon(&[[0.0, 0.0], [10.0, 0.0], [5.0, 8.0]], Some([0, 0, 255]), Some(([0, 0, 0], 1.0)));
+ p.circle(300.0, 300.0, 20.0, Some([0, 128, 0]), None);
+ p.save();
+ p.clip_rect(0.0, 0.0, 50.0, 50.0);
+ p.text(72.0, 72.0, 12.0, Font::Helvetica, [0, 0, 0], "Hello (world) \\ café €5");
+ p.restore();
+ p.text_rotated(Point::new(100.0, 100.0), 9.0, Font::TimesBold, [0, 0, 0], "Up", -std::f32::consts::FRAC_PI_2);
+ let p2 = d.add_page(842.0, 595.0);
+ p2.text(10.0, 20.0, 10.0, Font::CourierBold, [0, 0, 0], "Second");
+ assert_eq!(d.page_count(), 2);
+ let pdf = d.finish();
+ check_xref(&pdf)?;
+ assert!(find(&pdf, b"(Hello \\(world\\) \\\\ caf\\351 \\2005) Tj").is_some());
+ assert!(find(&pdf, b"(Second) Tj").is_some());
+ assert!(find(&pdf, b"/BaseFont /Helvetica /Encoding /WinAnsiEncoding").is_some());
+ assert!(find(&pdf, b"/BaseFont /Courier-Bold").is_some());
+ assert!(find(&pdf, b"/BaseFont /Times-Bold").is_some());
+ assert!(find(&pdf, b"/Count 2").is_some());
+ assert!(find(&pdf, b"/MediaBox [0 0 842 595]").is_some());
+ assert!(find(&pdf, b"/Title (Report \\(Q1\\))").is_some());
+ // Top-left origin: a line from (0,0) starts at the top of the page.
+ assert!(find(&pdf, b"0 792 m 612 0 l S").is_some());
+ Ok(())
+}
+
+#[test]
+fn uri_and_page_links_are_real_pdf_annotations() -> Result<(), Box<dyn Error>> {
+ let mut d = PdfDoc::new();
+ let first = d.add_page(200.0, 300.0);
+ first.link_uri(10.0, 20.0, 80.0, 30.0, "https://example.org/a(b)?q=£");
+ first.link_page(Rect::new(100.0, 40.0, 50.0, 20.0), 1, Point::new(35.0, 60.0));
+ first.link_uri(-20.0, -20.0, 40.0, 40.0, "mailto:[email protected]");
+ first.link_uri(0.0, 0.0, f32::NAN, 10.0, "https://bad.example");
+ first.link_uri(0.0, 0.0, 10.0, 10.0, "javascript:alert(1)");
+ let second = d.add_page(100.0, 200.0);
+ second.link_page(Rect::new(0.0, 0.0, 10.0, 10.0), 99, Point::new(0.0, 0.0));
+ let pdf = d.finish();
+ check_xref(&pdf)?;
+ let s = String::from_utf8_lossy(&pdf);
+ assert_eq!(s.matches("/Subtype /Link").count(), 3);
+ assert!(s.contains("/Annots ["));
+ assert!(s.contains("/Rect [10 250 90 280]"));
+ assert!(s.contains("/Rect [0 280 20 300]"));
+ assert!(s.contains("/URI (https://example.org/a\\(b\\)?q=%C2%A3)"));
+ assert!(s.contains("/XYZ 35 140 null"));
+ assert!(!s.contains("https://bad.example"));
+ Ok(())
+}
+
+#[test]
+fn images_with_alpha() -> Result<(), Box<dyn Error>> {
+ let mut d = PdfDoc::new();
+ let p = d.add_page(200.0, 200.0);
+ let mut px = Vec::new();
+ for i in 0..16u8 {
+ px.extend_from_slice(&[i * 10, 0, 0, if i < 8 { 255 } else { 128 }]);
+ }
+ p.image_rgba(Rect::new(10.0, 10.0, 40.0, 40.0), &px, [4, 4]);
+ p.image_rgba(Rect::new(10.0, 10.0, 40.0, 40.0), &[255; 16], [2, 2]); // opaque: no mask
+ p.image_rgba(Rect::new(0.0, 0.0, 1.0, 1.0), &[1, 2, 3], [4, 4]); // too short: ignored
+ let pdf = d.finish();
+ check_xref(&pdf)?;
+ assert!(find(&pdf, b"/SMask").is_some());
+ assert!(find(&pdf, b"/Im1 Do").is_some());
+ assert!(find(&pdf, b"/Im2 Do").is_some());
+ assert!(find(&pdf, b"/Im3").is_none());
+ Ok(())
+}
+
+#[test]
+fn run_length_roundtrip() {
+ fn decode(d: &[u8]) -> Vec<u8> {
+ let mut out = Vec::new();
+ let mut i = 0;
+ while i < d.len() {
+ let l = d[i];
+ i += 1;
+ if l == 128 {
+ break;
+ } else if l < 128 {
+ out.extend_from_slice(&d[i..i + l as usize + 1]);
+ i += l as usize + 1;
+ } else {
+ out.extend(std::iter::repeat_n(d[i], 257 - l as usize));
+ i += 1;
+ }
+ }
+ out
+ }
+ let cases: Vec<Vec<u8>> = vec![
+ vec![],
+ vec![1],
+ vec![1, 1],
+ vec![1, 2, 3, 3, 3, 3, 4, 5, 5],
+ (0..1000).map(|i| (i / 7) as u8).collect(),
+ (0..1000).map(|i| (i * 31 % 251) as u8).collect(),
+ vec![9; 300],
+ ];
+ for c in cases {
+ assert_eq!(decode(&run_length(&c)), c);
+ }
+}
+
+#[test]
+fn widths() {
+ assert!((text_width(Font::Helvetica, 10.0, "Hello") - 22.78).abs() < 0.01);
+ assert!(text_width(Font::HelveticaBold, 10.0, "Hello") > text_width(Font::Helvetica, 10.0, "Hello"));
+ assert_eq!(text_width(Font::Courier, 10.0, "abc"), 18.0);
+ assert!(text_width(Font::TimesRoman, 12.0, "é") > 0.0);
+ assert_eq!(text_width(Font::Helvetica, 10.0, ""), 0.0);
+ assert_eq!(Font::family_for("Calibri"), Family::Sans);
+ assert_eq!(Font::family_for("Times New Roman"), Family::Serif);
+ assert_eq!(Font::family_for("Consolas"), Family::Mono);
+ assert_eq!(Font::styled(Family::Serif, true, true), Font::TimesBoldItalic);
+}
+
+#[test]
+fn hostile_inputs_never_panic() -> Result<(), Box<dyn Error>> {
+ let mut d = PdfDoc::new();
+ let p = d.add_page(f32::NAN, -5.0);
+ p.text(f32::INFINITY, f32::NAN, 1e30, Font::Helvetica, [0, 0, 0], "x");
+ p.fill_rect(0.0, 0.0, -1.0, 5.0, [0, 0, 0]);
+ p.polygon(&[], None, None);
+ p.circle(0.0, 0.0, -3.0, Some([0, 0, 0]), None);
+ p.restore();
+ p.restore();
+ p.save();
+ p.image_rgba(Rect::new(0.0, 0.0, 10.0, 10.0), &[], [u32::MAX, u32::MAX]);
+ let pdf = d.finish();
+ check_xref(&pdf)?;
+ Ok(())
+}
+
+fn page_content(d: &PdfDoc) -> &str {
+ &d.pages[0].content
+}
+
+#[test]
+fn text_width_does_not_overflow() {
+ // 8,000,000 x 556 units exceeds u32::MAX: a u32 sum panics in debug builds.
+ let long = "a".repeat(8_000_000);
+ let w = text_width(Font::Helvetica, 10.0, &long);
+ assert!(w.is_finite() && w > 0.0);
+ assert!(w > text_width(Font::Helvetica, 10.0, &"a".repeat(7_000_000)));
+}
+
+#[test]
+fn all_zero_dash_is_drawn_solid() {
+ let mut d = PdfDoc::new();
+ let p = d.add_page(100.0, 100.0);
+ p.stroke_line_dashed(Point::new(0.0, 0.0), Point::new(50.0, 0.0), 1.0, [0, 0, 0], &[0.0, 0.0]);
+ p.polyline(&[[0.0, 0.0], [5.0, 5.0]], 1.0, [0, 0, 0], &[0.0, 0.0001, f32::NAN]);
+ p.stroke_line_dashed(Point::new(0.0, 0.0), Point::new(50.0, 0.0), 1.0, [0, 0, 0], &[3.0, 2.0]);
+ let c = page_content(&d);
+ assert_eq!(c.matches("[] 0 d").count(), 2);
+ assert!(!c.contains("[0 0]"));
+ assert!(c.contains("[3 2] 0 d"));
+}
+
+#[test]
+fn negative_and_nan_stroke_widths_become_zero() {
+ let mut d = PdfDoc::new();
+ let p = d.add_page(100.0, 100.0);
+ p.rect_stroke(1.0, 1.0, 10.0, 10.0, -3.0, [0, 0, 0]);
+ p.stroke_line(0.0, 0.0, 5.0, 5.0, f32::NAN, [0, 0, 0]);
+ p.polygon(&[[0.0, 0.0], [5.0, 0.0], [5.0, 5.0]], None, Some(([0, 0, 0], -1.0)));
+ p.circle(20.0, 20.0, 5.0, None, Some(([0, 0, 0], f32::NEG_INFINITY)));
+ let c = page_content(&d);
+ assert_eq!(c.matches("\n0 w ").count(), 4);
+ assert!(!c.contains("-1 w") && !c.contains("-3 w"));
+}
+
+#[test]
+fn non_finite_image_size_stores_nothing() {
+ let mut d = PdfDoc::new();
+ let p = d.add_page(200.0, 200.0);
+ let px = [255u8; 16];
+ for (w, h) in [(f32::NAN, 10.0), (10.0, f32::NAN), (f32::INFINITY, 10.0), (-1.0, 10.0)] {
+ p.image_rgba(Rect::new(0.0, 0.0, w, h), &px, [2, 2]);
+ }
+ p.image_rgba(Rect::new(f32::NAN, 0.0, 10.0, 10.0), &px, [2, 2]);
+ assert!(p.images.is_empty());
+ assert!(p.content.is_empty());
+}
+
+#[test]
+fn every_draw_method_survives_hostile_numbers() -> Result<(), Box<dyn Error>> {
+ let bad = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -7.0, 0.0, 1.0e30, -1.0e30];
+ let px = [200u8; 16];
+ let mut d = PdfDoc::new();
+ let p = d.add_page(300.0, 300.0);
+ for &a in &bad {
+ for &b in &bad {
+ p.clip_rect(a, b, a, b);
+ p.fill_rect(a, b, b, a, [1, 2, 3]);
+ p.rect_stroke(a, b, a, b, a, [1, 2, 3]);
+ p.stroke_line(a, b, b, a, a, [1, 2, 3]);
+ p.stroke_line_dashed(Point::new(a, b), Point::new(b, a), b, [1, 2, 3], &[a, b, 0.0]);
+ p.polyline(&[[a, b], [b, a], [1.0, 1.0]], a, [1, 2, 3], &[b, a]);
+ p.polygon(&[[a, b], [b, a], [1.0, 1.0]], Some([1, 2, 3]), Some(([4, 5, 6], a)));
+ p.circle(a, b, b, Some([1, 2, 3]), Some(([4, 5, 6], a)));
+ p.text(a, b, a, Font::Helvetica, [0, 0, 0], "x");
+ p.text_rotated(Point::new(a, b), 10.0, Font::TimesRoman, [0, 0, 0], "y", b);
+ p.image_rgba(Rect::new(a, b, b, a), &px, [2, 2]);
+ }
+ }
+ p.stroke_line_dashed(Point::new(0.0, 0.0), Point::new(1.0, 1.0), 1.0, [0, 0, 0], &[0.0; 100]);
+ let c = page_content(&d);
+ assert!(!c.contains("NaN") && !c.contains("inf"));
+ let pdf = d.finish();
+ check_xref(&pdf)?;
+ Ok(())
+}
+
+/// Decodes the `<FEFF…>` hex string following `key` in the file bytes.
+fn utf16_entry(pdf: &[u8], key: &str) -> Result<String, Box<dyn Error>> {
+ let at = find(pdf, key.as_bytes()).ok_or_else(|| io::Error::other("missing PDF info key"))? + key.len();
+ let end = at + 9000.min(pdf.len() - at);
+ let rest = std::str::from_utf8(pdf.get(at..end).ok_or_else(|| io::Error::other("short PDF info value"))?)?;
+ let hex = rest.trim_start().strip_prefix("<FEFF").ok_or_else(|| io::Error::other("missing UTF-16 marker"))?;
+ let end = hex.find('>').ok_or_else(|| io::Error::other("missing UTF-16 terminator"))?;
+ let hex = hex.get(..end).ok_or_else(|| io::Error::other("invalid UTF-16 range"))?;
+ let units: Vec<u16> = (0..hex.len()).step_by(4).map(|i| u16::from_str_radix(hex.get(i..i + 4).unwrap_or(""), 16)).collect::<Result<_, _>>()?;
+ Ok(String::from_utf16(&units)?)
+}
+
+#[test]
+fn info_strings_with_non_ascii_are_utf16be() -> Result<(), Box<dyn Error>> {
+ let mut doc = PdfDoc::new();
+ doc.add_page(200.0, 200.0);
+ doc.info.title = "Übersicht €5 – “Q1” 日本 😀".into();
+ doc.info.author = "Müller & Søn".into();
+ let pdf = doc.finish();
+ assert_eq!(utf16_entry(&pdf, "/Title")?, "Übersicht €5 – “Q1” 日本 😀");
+ assert_eq!(utf16_entry(&pdf, "/Author")?, "Müller & Søn");
+ Ok(())
+}
+
+#[test]
+fn ascii_info_strings_stay_literal_and_escaped() {
+ let mut doc = PdfDoc::new();
+ doc.add_page(200.0, 200.0);
+ doc.info.title = r"Q1 (draft) a\b".into();
+ let pdf = doc.finish();
+ assert!(find(&pdf, br"/Title (Q1 \(draft\) a\\b)").is_some());
+ assert!(find(&pdf, b"/Producer (GridCraft PDF)").is_some());
+}
+
+#[test]
+fn info_strings_are_capped() -> Result<(), Box<dyn Error>> {
+ let mut doc = PdfDoc::new();
+ doc.add_page(200.0, 200.0);
+ doc.info.title = "日".repeat(100_000);
+ let pdf = doc.finish();
+ assert_eq!(utf16_entry(&pdf, "/Title")?.chars().count(), MAX_INFO_CHARS);
+ Ok(())
+}
+
+#[test]
+fn cjk_text_is_not_replaced_by_question_marks() -> Result<(), Box<dyn Error>> {
+ let mut doc = PdfDoc::new();
+ let p = doc.add_page(612.0, 792.0);
+ p.text(10.0, 20.0, 10.0, Font::Helvetica, [0, 0, 0], "签字清单");
+ p.text(10.0, 40.0, 10.0, Font::Helvetica, [0, 0, 0], "No. 编号 2");
+ let pdf = doc.finish();
+ check_xref(&pdf)?;
+ assert!(find(&pdf, b"(????) Tj").is_none(), "CJK text written as question marks");
+ assert!(find(&pdf, b"<7B7E5B576E055355> Tj").is_some());
+ assert!(find(&pdf, b"(No. ) Tj").is_some());
+ assert!(find(&pdf, b"<7F1653F7> Tj").is_some());
+ assert!(find(&pdf, b"( 2) Tj").is_some());
+ assert!(find(&pdf, b"/Encoding /UniGB-UTF16-H").is_some());
+ // Measured as full-width glyphs, matching the CID font's default width.
+ assert_eq!(text_width(Font::Helvetica, 10.0, "签字"), 20.0);
+ Ok(())
+}
+
+#[test]
+fn symbol_font_draws_maths_in_its_own_encoding() {
+ let mut doc = PdfDoc::new();
+ let p = doc.add_page(200.0, 200.0);
+ p.text(10.0, 50.0, 12.0, Font::Symbol, [0, 0, 0], "\u{2211}\u{03B1}\u{2264}\u{221E}x");
+ p.text(10.0, 80.0, 12.0, Font::TimesItalic, [0, 0, 0], "x");
+ let pdf = doc.finish();
+ let s = String::from_utf8_lossy(&pdf);
+ assert!(s.contains("/BaseFont /Symbol >>"), "Symbol has no WinAnsi encoding");
+ assert!(s.contains("/BaseFont /Times-Italic /Encoding /WinAnsiEncoding"));
+ // The sum, alpha, less-or-equal and infinity codes; x is not in Symbol and becomes `?`.
+ assert!(s.contains("(\\345a\\243\\245?) Tj"), "{s}");
+ check_xref(&pdf).unwrap();
+ assert!(Font::Symbol.can_encode('\u{2211}') && !Font::Symbol.can_encode('x'));
+ assert!(Font::TimesRoman.can_encode('x') && !Font::TimesRoman.can_encode('\u{2211}'));
+ assert_eq!(text_width(Font::Symbol, 10.0, "\u{2211}"), 7.13);
+}
+
+#[test]
+fn cyrillic_text_is_embedded_and_measured() {
+ let mut doc = PdfDoc::new();
+ let page = doc.add_page(200.0, 100.0);
+ page.text(10.0, 20.0, 12.0, Font::Helvetica, [0, 0, 0], "Привет мир, abc");
+ let pdf = doc.finish();
+ let s = String::from_utf8_lossy(&pdf);
+ assert!(s.contains("/CIDFontType2"), "an embedded face is written");
+ assert!(s.contains("/FontFile2"), "the face is embedded");
+ assert!(s.contains("/ToUnicode"));
+ assert!(!s.contains("STSong-Light"), "Cyrillic no longer uses the non-embedded CID font");
+ // Source Sans's real widths, not the full-width fallback.
+ let w = text_width(Font::Helvetica, 10.0, "Привет");
+ assert!(w > 20.0 && w < 55.0, "width {w}");
+}
+
+#[test]
+fn cjk_text_still_uses_the_fallback() {
+ let mut doc = PdfDoc::new();
+ doc.add_page(100.0, 100.0).text(10.0, 20.0, 12.0, Font::Helvetica, [0, 0, 0], "漢字");
+ let s = String::from_utf8_lossy(&doc.finish()).into_owned();
+ assert!(s.contains("STSong-Light"));
+}