Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
Instant widgets, a file menu that morphs, stars that stick, Outfit and two new desk pages
chethan61602a786edf4ce
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.mdindex e007130..ff0e27d 100644--- a/ATTRIBUTION.md+++ b/ATTRIBUTION.md@@ -267,6 +267,7 @@ Every asset Artefact includes, bundles or uses to build its published material,| `engine/assets/icons/pilcrow.svg` | Lucide icon "pilcrow" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pilcrow.svg) | UI icon, embedded via engine/crates/ui-egui/src/icon_data.rs || `engine/assets/icons/move-horizontal.svg` | Lucide icon "move-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-horizontal.svg) | UI icon, embedded via engine/crates/ui-egui/src/icon_data.rs |+| `android/app/src/main/res/font/outfit.ttf` | Outfit | The Outfit Project Authors | OFL-1.1 | https://github.com/Outfitio/Outfit-Fonts | Android app UI typeface; source and license are also listed in the app Licences screen || `android/app/src/main/res/font/jakarta.ttf` | Plus Jakarta Sans Regular | The Plus Jakarta Sans Project Authors | OFL-1.1 | https://github.com/tokotype/PlusJakartaSans | Android app UI typeface; source and license are also listed in the app Licences screen || `android/app/src/main/res/font/jakarta_italic.ttf` | Plus Jakarta Sans Italic | The Plus Jakarta Sans Project Authors | OFL-1.1 | https://github.com/tokotype/PlusJakartaSans | Android app UI typeface; source and license are also listed in the app Licences screen || `android/app/src/main/res/font/bricolage.ttf` | Bricolage Grotesque Variable | The Bricolage Grotesque Project Authors | OFL-1.1 | https://github.com/ateliertriay/bricolage | Android app UI typeface; source and license are also listed in the app Licences screen |diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.tomlindex 3bf495c..b706acf 100644--- a/ATTRIBUTION.toml+++ b/ATTRIBUTION.toml@@ -3196,6 +3196,17 @@ licence_file = "engine/assets/icons/LICENSE-lucide.txt"kind = "icon"usage = "UI icon, embedded via engine/crates/ui-egui/src/icon_data.rs"sha256 = "864ab2f19254e6ac7240bc6a98323197332e8f714d4d3f94831f41309e5ef2f7"+[[asset]]+path = "android/app/src/main/res/font/outfit.ttf"+title = "Outfit"+author = "The Outfit Project Authors"+source = "https://github.com/Outfitio/Outfit-Fonts"+licence = "OFL-1.1"+licence_file = "android/app/src/main/assets/licences/OFL-Outfit.txt"+kind = "font"+usage = "Android app UI typeface; source and license are also listed in the app's Licences screen"+sha256 = "fc7287273e66929776e2ba54f144fe699080bec29f61bf649d70d871468aeade"+[[asset]]path = "android/app/src/main/res/font/jakarta.ttf"title = "Plus Jakarta Sans Regular"diff --git a/DESIGN.md b/DESIGN.mdindex f116a76..b29902c 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -120,6 +120,7 @@ Springs and curves come from `glass/Motion.kt`, scaled by the user's Settings| --- | --- || `GlassMotion.unfold()` / `fold()` | A menu or popover opening and closing || `GlassMotion.morph()` | A dialog popping in |+| `GlassMotion.morphOpen()` / `morphClose()` | A round button's glass becoming its menu, and back || `GlassMotion.pop()` | A small bouncy reaction || `GlassMotion.shape()` / `shapeBack()` | A shape changing (a pressed button, a thumb) || `Fluid.quick()`, `Fluid.fade()`, `Fluid.dismiss()` | Fades and quick tweens |@@ -129,7 +130,12 @@ Rules:- No `tween(300)` or `spring(0.8f, 400f)` in a screen. Use a named spec so Settings applies.- Leaving is faster than arriving, and never bounces.-- Menus unfold beside the button that opened them. There is no morph from the button.+- A menu opened from a round glass button (or a file's ⋯) is that button's glass: it morphs out of+ it (`MorphButtonSurface`: circle, tall drop, wide, menu) on `GlassMotion.morphOpen()`, which+ bounces at the user's setting (Calm barely, Jelly most) as the menu's own stretch and squash, and+ folds back without a bounce. Other menus unfold beside the button that opened them.+- A long press on a card opens its menu the same way, from a drop over the card's corner+ (`FileMenuAt(ghost = true)`).- Animate state the user caused. A static page does not breathe or shimmer.## Hapticsdiff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex d2cc5c7..0bc6e2d 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -71,6 +71,17 @@android:name="android.appwidget.provider"android:resource="@xml/widget_recent_info" /></receiver>+ <receiver+ android:name=".widget.StarredWidget"+ android:exported="false"+ android:label="@string/widget_starred_name">+ <intent-filter>+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />+ </intent-filter>+ <meta-data+ android:name="android.appwidget.provider"+ android:resource="@xml/widget_starred_info" />+ </receiver><receiverandroid:name=".widget.NoteWidget"android:exported="false"diff --git a/android/app/src/main/assets/licences/OFL-Outfit.txt b/android/app/src/main/assets/licences/OFL-Outfit.txtnew file mode 100644index 0000000..723cd44--- /dev/null+++ b/android/app/src/main/assets/licences/OFL-Outfit.txt@@ -0,0 +1,93 @@+Copyright 2021 The Outfit Project Authors (https://github.com/Outfitio/Outfit-Fonts)++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:+https://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.diff --git a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.ktindex 704345b..bcf9341 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt@@ -207,7 +207,14 @@ class MainActivity : ComponentActivity() {val fromPreview = intent?.getBooleanExtra(EXTRA_FROM_PREVIEW, false) == trueintent?.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+ if (intent?.getBooleanExtra(com.chethan616.clearpdf.widget.EXTRA_OPEN_FILES, false) == true) {+ vm.filesShowRecent = true+ vm.homeTab = com.chethan616.clearpdf.ui.home.HomeTab.Files+ }+ if (intent?.getBooleanExtra(com.chethan616.clearpdf.widget.EXTRA_OPEN_STARRED, false) == true) {+ vm.filesShowStarred = 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/engine/RecentFiles.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/RecentFiles.ktindex 6aa5b70..b8181d6 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/RecentFiles.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/RecentFiles.kt@@ -22,6 +22,8 @@ data class RecentFile(val lastX: Float = -1f,val lastY: Float = -1f,val lastZoom: Float = 1f,+ /** Starred from Files without being opened: kept for its star, not shown as read lately. */+ val starOnly: Boolean = false,)/**@@ -46,6 +48,25 @@ class RecentFiles(private val file: File) {write(read().map { if (it.uri == uri) f(it) else it })}+ /**+ * Star or unstar a file: the entry for [entry]'s uri, or failing that the same file known by another+ * address (its name and size: a file opened from another app and found again on the phone), else+ * a new entry for it, set in among the others by [RecentFile.opened] (starring a file on the phone+ * does not make it the newest thing read).+ */+ fun star(entry: RecentFile, starred: Boolean) = synchronized(lock) {+ val list = read()+ val same = list.filter { it.uri == entry.uri || (it.name == entry.name && it.size == entry.size && entry.size > 0) }+ if (same.isNotEmpty()) {+ val keys = same.map { it.uri }.toSet()+ // a file kept only for its star goes once unstarred+ write(list.mapNotNull { if (it.uri in keys) it.copy(starred = starred).takeIf { r -> starred || !r.starOnly } else it })+ } else if (starred) {+ val at = list.indexOfFirst { it.opened < entry.opened }.let { if (it < 0) list.size else it }+ write(list.take(at) + entry.copy(starred = true, starOnly = true) + list.drop(at))+ }+ }+fun remove(uris: Set<String>) = synchronized(lock) { write(read().filter { it.uri !in uris }) }fun clear() = synchronized(lock) { write(emptyList()) }@@ -68,6 +89,7 @@ class RecentFiles(private val file: File) {lastX = o.optDouble("lastX", -1.0).toFloat(),lastY = o.optDouble("lastY", -1.0).toFloat(),lastZoom = o.optDouble("lastZoom", 1.0).toFloat(),+ starOnly = o.optBoolean("starOnly"),)}}.getOrDefault(emptyList())@@ -75,11 +97,13 @@ class RecentFiles(private val file: File) {private fun write(list: List<RecentFile>) {val a = JSONArray()- for (r in list.take(MAX)) {+ // at most MAX, but a starred file is never let go: its star lives here+ for (r in list.filterIndexed { i, it -> i < MAX || it.starred }) {a.put(JSONObject().put("uri", r.uri).put("name", r.name).put("opened", r.opened).put("pages", r.pages).put("size", r.size).put("lastPage", r.lastPage).put("starred", r.starred).put("reading", r.reading)- .put("lastX", r.lastX.toDouble()).put("lastY", r.lastY.toDouble()).put("lastZoom", r.lastZoom.toDouble()),+ .put("lastX", r.lastX.toDouble()).put("lastY", r.lastY.toDouble()).put("lastZoom", r.lastZoom.toDouble())+ .put("starOnly", r.starOnly),)}val tmp = File(file.parentFile, file.name + ".tmp")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.ktindex b76f21f..693c99f 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@@ -112,6 +112,8 @@ class Notes(private val context: Context, private val scope: CoroutineScope) {fun toggle(noteId: String, itemId: String) {val n = get(noteId) ?: returnput(n.copy(items = n.items.map { if (it.id == itemId) it.copy(done = !it.done) else it }))+ // the home screen's list widgets tick it too, at once (their pill flipped, nothing redrawn)+ runCatching { com.chethan616.clearpdf.widget.TodoWidget.flipNow(context, noteId, itemId) }}fun delete(id: String) {@@ -259,12 +261,15 @@ object NoteFile {}/** Tick or untick [itemId] of [noteId]; false when either is gone. */+ fun toggle(c: Context, noteId: String, itemId: String): Boolean = change(c, noteId, itemId) { !it }+@Synchronized- fun toggle(c: Context, noteId: String, itemId: String): Boolean {+ private fun change(c: Context, noteId: String, itemId: String, done: (Boolean) -> Boolean): 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 item = n.items.firstOrNull { it.id == itemId } ?: return false+ if (item.done == done(item.done)) return true+ val changed = n.copy(items = n.items.map { if (it.id == itemId) it.copy(done = 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")diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.ktindex 89e26a1..20bdb9f 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt@@ -3,7 +3,9 @@ package com.chethan616.clearpdf.uiimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.rounded.*import androidx.compose.material.icons.rounded.*+import androidx.compose.material.icons.outlined.Editimport androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.unit.dp/*** The app's icons: Material Symbols, Rounded (the old ClearPDF's set), under the names the code has@@ -84,7 +86,11 @@ object LucideIcons {val GripVertical: ImageVector get() = Icons.Rounded.DragIndicatorval Hash: ImageVector get() = Icons.Rounded.Tagval Heading: ImageVector get() = Icons.Rounded.Title- val Highlighter: ImageVector get() = Icons.Rounded.Highlight+ /**+ * A highlighter pen laid at a slant over its stroke, centred in its square as the other markup+ * glyphs are (Material's Highlight is a torch drawn low in its box, so it sat below its row).+ */+ val Highlighter: ImageVector get() = HighlighterGlyphval ImagePlus: ImageVector get() = Icons.Rounded.AddPhotoAlternateval Images: ImageVector get() = Icons.Rounded.PhotoLibraryval Info: ImageVector get() = Icons.Rounded.Info@@ -114,6 +120,7 @@ object LucideIcons {val Pause: ImageVector get() = Icons.Rounded.Pauseval PenLine: ImageVector get() = Icons.Rounded.Drawval Pencil: ImageVector get() = Icons.Rounded.Edit+ val PencilOutline: ImageVector get() = Icons.Outlined.Editval Pin: ImageVector get() = Icons.Rounded.PushPinval Play: ImageVector get() = Icons.Rounded.PlayArrowval Plus: ImageVector get() = Icons.Rounded.Add@@ -132,6 +139,7 @@ object LucideIcons {val Share2: ImageVector get() = Icons.Rounded.Shareval ShieldCheck: ImageVector get() = Icons.Rounded.VerifiedUserval Signature: ImageVector get() = Icons.Rounded.Gesture+ val Accessibility: ImageVector get() = Icons.Rounded.Accessibilityval SlidersHorizontal: ImageVector get() = Icons.Rounded.Tuneval Smartphone: ImageVector get() = Icons.Rounded.Smartphoneval Sparkles: ImageVector get() = Icons.Rounded.AutoAwesome@@ -139,6 +147,7 @@ object LucideIcons {val SquarePen: ImageVector get() = Icons.Rounded.EditNoteval SquareTerminal: ImageVector get() = Icons.Rounded.Terminalval Star: ImageVector get() = Icons.Rounded.Star+ val StarOutline: ImageVector get() = Icons.Rounded.StarBorderval Strikethrough: ImageVector get() = Icons.Rounded.FormatStrikethroughval Sun: ImageVector get() = Icons.Rounded.LightModeval TextCursorInput: ImageVector get() = Icons.Rounded.TextFields@@ -152,3 +161,24 @@ object LucideIcons {val Wrench: ImageVector get() = Icons.Rounded.Buildval X: ImageVector get() = Icons.Rounded.Close}++private val HighlighterGlyph: ImageVector by lazy {+ ImageVector.Builder("Highlighter", 24.dp, 24.dp, 24f, 24f).apply {+ // the pen's body and nib (Lucide's highlighter, ISC), then the ink line under it+ addPath(+ androidx.compose.ui.graphics.vector.PathParser().parsePathString("M9.5,10.5L4.5,15.5V18.5H11.5L14.5,15.5M20.5,10.6L16.6,14.5A1.8,1.8 0,0 1,14.1 14.5L9.6,10A1.8,1.8 0,0 1,9.6 7.5L13.5,3.6").toNodes(),+ fill = null,+ stroke = androidx.compose.ui.graphics.SolidColor(androidx.compose.ui.graphics.Color.Black),+ strokeLineWidth = 2.1f,+ strokeLineCap = androidx.compose.ui.graphics.StrokeCap.Round,+ strokeLineJoin = androidx.compose.ui.graphics.StrokeJoin.Round,+ )+ addPath(+ androidx.compose.ui.graphics.vector.PathParser().parsePathString("M14,21.5H21").toNodes(),+ fill = null,+ stroke = androidx.compose.ui.graphics.SolidColor(androidx.compose.ui.graphics.Color.Black),+ strokeLineWidth = 2.1f,+ strokeLineCap = androidx.compose.ui.graphics.StrokeCap.Round,+ )+ }.build()+}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.ktindex b6ea4a1..cd8e73c 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@@ -3,6 +3,7 @@ package com.chethan616.clearpdf.uiimport android.app.ActivityManagerimport com.chethan616.clearpdf.ui.home.FileToolimport com.chethan616.clearpdf.ui.viewer.FillElement+import androidx.compose.ui.graphics.asAndroidBitmapimport androidx.compose.ui.graphics.asImageBitmapimport com.chethan616.clearpdf.engine.toBitmapimport com.chethan616.clearpdf.engine.UserBookmark@@ -120,7 +121,13 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : AndrrunCatching { files.pruneCopies(list.map { it.uri }, open) }}}- // the home screen's Recent widget is the desk's Recent card+ // the stars the lists showed at once that the file now agrees with+ val list = recentList+ starNow = starNow.filterNot { (k, v) ->+ val same = list.filter { it.uri == k || sameFile(it.name, it.size) == k }+ if (v) same.any { it.starred } else same.none { it.starred }+ }+ // the home screen's Recent and Starred widgets are the desk's Recent cardrunCatching { com.chethan616.clearpdf.widget.Widgets.refreshRecent(this@AppViewModel) }}}@@ -861,6 +868,32 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr}}+ /**+ * Star or unstar a file wherever it is listed (Recent, Starred, On this device): one never opened+ * gets an entry of its own, so its star stays. The list shows it at once (before the file is written).+ */+ fun setStarred(row: com.chethan616.clearpdf.ui.home.FileRow, starred: Boolean) {+ val key = sameFile(row.name, row.size)+ // at once on screen: the stars the lists read follow this set until the file catches up+ starNow = starNow + (row.key to starred) + (key to starred)+ viewModelScope.launch {+ withContext(Dispatchers.IO) {+ recents.star(com.chethan616.clearpdf.engine.RecentFile(row.key, row.name, row.date, 0, row.size), starred)+ }+ refreshRecents()+ }+ }++ /** Stars just set and not yet read back from the file, by uri and by name and size. */+ private var starNow by mutableStateOf<Map<String, Boolean>>(emptyMap())++ /** Whether [row]'s file is starred now (follows a star set a moment ago). */+ fun isStarred(row: com.chethan616.clearpdf.ui.home.FileRow): Boolean {+ starNow[row.key]?.let { return it }+ starNow[sameFile(row.name, row.size)]?.let { return it }+ return row.starred+ }+// ---- View settings ----------------------------------------------------------------------/** Reading Mode (text reflowed to the screen) is showing. Remembered for each file, as the reference does. */@@ -1666,6 +1699,7 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrbold = if (o.has("bold")) o.optBoolean("bold") else font.contains("Bold", true) || font.contains("Black", true) || font.contains("Heavy", true),italic = if (o.has("italic")) o.optBoolean("italic") else font.contains("Italic", true) || font.contains("Oblique", true),color = o.optString("color").takeIf { it.startsWith("#") },+ runs = styleRuns(o),)}editSelection?.takeIf { it.page == page }?.let { sel -> editSelection = paragraphs[page]?.firstOrNull { it.number == sel.number } }@@ -1746,6 +1780,83 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr/** The part of the paragraph being typed in that is selected (null: none, or a bare caret). */var editRange by mutableStateOf<androidx.compose.ui.text.TextRange?>(null)+ /** The bold and italic words of the paragraph being typed in, following the typing (#127). */+ var editRuns by mutableStateOf<List<com.chethan616.clearpdf.ui.viewer.StyleRun>>(emptyList())++ /**+ * A paragraph's style runs from the engine (UTF-8 byte ranges of its editor text) as character+ * ranges of its text. The two differ only where rows break (a newline for a space); anything+ * else (a hyphen joined across rows) and the runs are left out rather than misplaced.+ */+ private fun styleRuns(o: org.json.JSONObject): List<com.chethan616.clearpdf.ui.viewer.StyleRun> {+ val arr = o.optJSONArray("runs") ?: return emptyList()+ if (arr.length() == 0) return emptyList()+ val editor = o.optString("editor_text")+ if (editor.replace('\n', ' ') != o.optString("text")) return emptyList()+ // byte offset to character offset+ val total = editor.toByteArray(Charsets.UTF_8).size+ val charAt = IntArray(total + 1)+ var b = 0+ editor.forEachIndexed { i, ch ->+ val n = ch.toString().toByteArray(Charsets.UTF_8).size+ for (k in 0 until n) charAt[b + k] = i+ b += n+ }+ charAt[total] = editor.length+ return (0 until arr.length()).mapNotNull { i ->+ val r = arr.optJSONObject(i) ?: return@mapNotNull null+ val range = r.optJSONArray("range") ?: return@mapNotNull null+ val s = range.optInt(0).coerceIn(0, total)+ val e = range.optInt(1).coerceIn(s, total)+ com.chethan616.clearpdf.ui.viewer.StyleRun(charAt[s], charAt[e], r.optBoolean("bold"), r.optBoolean("italic"))+ }+ }++ /**+ * Bold (or, when they all are already, un-bold) only the words selected while reading (#127): the+ * paragraph under the selection is found, the selected words in it, and just those characters+ * change face; the rest of the paragraph keeps its own.+ */+ fun boldSelection(doc: OpenDocument, page: Int, rects: List<FloatArray>) {+ viewModelScope.launch {+ val picked = doc.selection.text()?.trim().orEmpty()+ doc.selection.clear()+ if (picked.isEmpty() || rects.isEmpty()) return@launch+ loadParagraphs(doc, page)+ val paras = paragraphs[page].orEmpty()+ val r0 = rects.first()+ val cx = (r0[0] + r0[2]) / 2f+ val cy = (r0[1] + r0[3]) / 2f+ fun inside(p: com.chethan616.clearpdf.ui.viewer.Paragraph) = cx >= p.box[0] - 2f && cx <= p.box[2] + 2f && cy >= p.box[1] - 2f && cy <= p.box[3] + 2f+ // the selected words where they are in the paragraph (lines broken anywhere in between)+ val words = picked.split(Regex("\\s+")).filter { it.isNotEmpty() }+ val pattern = Regex(words.joinToString("\\s+") { Regex.escape(it) })+ val para = paras.filter(::inside).firstOrNull { pattern.containsMatchIn(it.text) }+ ?: paras.firstOrNull { pattern.containsMatchIn(it.text) }+ if (para == null) {+ tell(text(R.string.viewer_bold_not_found))+ return@launch+ }+ // the first place the words are in the paragraph+ val match = pattern.findAll(para.text).firstOrNull() ?: return@launch+ val range = androidx.compose.ui.text.TextRange(match.range.first, match.range.last + 1)+ editing = null+ editRuns = para.runs+ val bold = !rangeStyled(para, range)+ styleRange(doc, para, range, bold = bold, italic = rangeStyled(para, range, italic = true))+ }+ }++ /** Whether every character of [range] in [para] (as being typed) is bold (or, with [italic], slanted). */+ fun rangeStyled(para: com.chethan616.clearpdf.ui.viewer.Paragraph, range: androidx.compose.ui.text.TextRange, italic: Boolean = false): Boolean {+ val words = editDraft?.takeIf { editing != null } ?: para.text+ val chars = com.chethan616.clearpdf.ui.viewer.StyleRun.perChar(editRuns, words.length, para.bold, para.italic)+ val from = range.min.coerceIn(0, words.length)+ val to = range.max.coerceIn(from, words.length)+ if (from == to) return if (italic) para.italic else para.bold+ return (from until to).all { if (italic) chars[it].second else chars[it].first }+ }+/*** Bold or slanted, only the words selected in the paragraph being typed in: the rest keeps its* face. The engine takes the selection as a byte range of the paragraph's text, in one of its@@ -1764,6 +1875,13 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrelse -> "helvetica"}val one = mapOf("range" to listOf(bytes(start), bytes(end)), "font" to family, "bold" to bold, "italic" to italic)+ // the editor shows it at once; the page follows from the engine+ val chars = com.chethan616.clearpdf.ui.viewer.StyleRun.perChar(editRuns, words.length, para.bold, para.italic)+ for (i in start until end) chars[i] = bold to italic+ editRuns = com.chethan616.clearpdf.ui.viewer.StyleRun.of(chars).ifEmpty {+ // all one style now, but maybe not the paragraph's own: say so explicitly+ if (chars.isNotEmpty() && chars[0] != (para.bold to para.italic)) listOf(com.chethan616.clearpdf.ui.viewer.StyleRun(0, chars.size, chars[0].first, chars[0].second)) else emptyList()+ }runTool(doc, "text_edit", paraArgs(para) + mapOf("text" to words, "ranges" to listOf(one)))}@@ -2135,6 +2253,38 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrreturn android.graphics.BitmapFactory.decodeFile(f.absolutePath, opts)?.let { rotateForExif(f, it) }?.asImageBitmap()}+ /**+ * What [page] will look like saved with [filter]: the same straightening and clean-up the save+ * runs (`page_enhance_camera`), on the page's quarter-size picture in a throwaway document, so it+ * takes a moment, not the seconds the full photo would. Null when it couldn't be made.+ */+ suspend fun scanPreview(page: com.chethan616.clearpdf.ui.ScanPage, filter: com.chethan616.clearpdf.ui.ScanFilter): androidx.compose.ui.graphics.ImageBitmap? {+ val eng = engine ?: return null+ return withContext(Dispatchers.IO) {+ runCatching {+ val src = File(getApplication<Application>().cacheDir, "camera/preview-${page.file.nameWithoutExtension}.jpg")+ if (!src.isFile) {+ src.parentFile?.mkdirs()+ src.outputStream().use { page.thumb.asAndroidBitmap().compress(android.graphics.Bitmap.CompressFormat.JPEG, 92, it) }+ }+ val id = eng.tool("doc_create", mapOf("from" to "images", "paths" to listOf(src.absolutePath), "name" to "Preview")).optLong("doc")+ try {+ val size = eng.tool("doc_info", mapOf("doc" to id)).optJSONArray("pages")?.optJSONObject(0) ?: return@runCatching null+ val (w, h) = size.optDouble("width") to size.optDouble("height")+ if (!(filter == com.chethan616.clearpdf.ui.ScanFilter.Original && page.corners.contentEquals(com.chethan616.clearpdf.ui.ScanPage.WHOLE))) {+ val corners = page.corners.mapIndexed { k, v -> v * if (k % 2 == 0) w else h }+ eng.tool("page_enhance_camera", mapOf("doc" to id, "page" to 1, "corners" to corners, "mode" to filter.mode, "level" to filter.level))+ }+ val scale = (900.0 / maxOf(w, h)).toFloat().coerceIn(0.2f, 4f)+ val img = withContext(eng.renders) { eng.session.renderPage(id.toULong(), 0u, scale, null) }+ img.toBitmap().asImageBitmap()+ } finally {+ runCatching { eng.tool("doc_close", mapOf("doc" to id, "discard_changes" to true)) }+ }+ }.getOrNull()+ }+ }+/** Scan's pages go into this document at this (1-based) position instead of a new PDF. */var insertScanAt: Pair<OpenDocument, Int>? = nullprivate var insertFileAt: Pair<OpenDocument, Int>? = null@@ -2556,6 +2706,9 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrbusy = text(R.string.msg_busy_recognizing)runCatching { eng.tool("ocr_recognize", mapOf("doc" to id)) }}+ // the document's own title is its name (not the first photo's file name)+ val title = scanName.trim().ifEmpty { "Scan " + java.text.SimpleDateFormat("yyyy-MM-dd HH.mm.ss", java.util.Locale.US).format(java.util.Date()) }+ runCatching { eng.tool("doc_set_info", mapOf("doc" to id, "key" to "Title", "value" to title)) }val out = tempFile("pdf")eng.tool("doc_save", mapOf("doc" to id, "path" to out.absolutePath, "full" to true))val target = insertScanAt@@ -3009,11 +3162,48 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrvar homeTab by mutableStateOf(com.chethan616.clearpdf.ui.home.HomeTab.Home)var settingsOpen by mutableStateOf(false)- /** The file whose "..." sheet is open, and whether it was opened from Recent. */- var fileSheet by mutableStateOf<Pair<com.chethan616.clearpdf.ui.home.FileRow, Boolean>?>(null)+ /** The file whose menu is open (from its ⋯ or a long press), and where its glass grows from. */+ var fileMenu by mutableStateOf<com.chethan616.clearpdf.ui.desk.FileMenuAt?>(null)++ /** A file being renamed or about to be deleted (asked once its menu has folded away). */+ var fileRenaming by mutableStateOf<com.chethan616.clearpdf.ui.home.FileRow?>(null)+ var fileDeleting by mutableStateOf<com.chethan616.clearpdf.ui.home.FileRow?>(null)var showLicences by mutableStateOf(false)var filesShowLocal by mutableStateOf(false)+ /** Files opens on Starred (the Starred widget asked). */+ var filesShowStarred by mutableStateOf(false)++ /** The owner's name, shown small above Today's greeting (Settings ▸ Your name); empty: none. */+ var ownerName by mutableStateOf(appPrefs.getString("ownerName", "").orEmpty())+ private set++ fun updateOwnerName(name: String) {+ ownerName = name.trim()+ appPrefs.edit().putString("ownerName", ownerName).apply()+ }++ /** The desk's own pages open over it (Today, Thought of the day), the last one showing. */+ val deskPages = androidx.compose.runtime.mutableStateListOf<com.chethan616.clearpdf.ui.home.DeskPage>()++ /** Open desk page [p] over the desk (or bring it forward). */+ fun openDeskPage(p: com.chethan616.clearpdf.ui.home.DeskPage) {+ deskPages.remove(p)+ deskPages.add(p)+ homeTab = com.chethan616.clearpdf.ui.home.HomeTab.Home+ }++ /** Back from the desk page showing. */+ fun closeDeskPage() {+ if (deskPages.isNotEmpty()) deskPages.removeAt(deskPages.lastIndex)+ }++ /** The desk turns to this shelf (asked from a desk page), then forgets it. */+ var deskShelf by mutableStateOf<com.chethan616.clearpdf.ui.home.DeskFilter?>(null)++ /** Files opens on Recent (the Recent card or widget asked). */+ var filesShowRecent by mutableStateOf(false)+/** Lists as a grid instead of rows (remembered). */private var gridViewState by mutableStateOf(appPrefs.getBoolean("gridView", false))var gridView: Boolean@@ -3119,6 +3309,18 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr* on disk and its place, which the desk and Files must not do again on every recomposition.*/fun recentRows(): List<com.chethan616.clearpdf.ui.home.FileRow> {+ val all = knownRows()+ recentOnlyMemo?.let { (from, rows) -> if (from === all) return rows }+ val keep = recentList.filter { !it.starOnly }.map { it.uri }.toHashSet()+ val rows = all.filter { it.key in keep }+ recentOnlyMemo = all to rows+ return rows+ }++ private var recentOnlyMemo: Pair<List<com.chethan616.clearpdf.ui.home.FileRow>, List<com.chethan616.clearpdf.ui.home.FileRow>>? = null++ /** Every file Recent knows: those read lately and those only starred. */+ private fun knownRows(): List<com.chethan616.clearpdf.ui.home.FileRow> {val list = recentListrecentRowsMemo?.let { (from, rows) -> if (from === list) return rows }val rows = list.map { r ->@@ -3130,7 +3332,7 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrprivate var recentRowsMemo: Pair<List<RecentFile>, List<com.chethan616.clearpdf.ui.home.FileRow>>? = null- fun starredRows(): List<com.chethan616.clearpdf.ui.home.FileRow> = recentRows().filter { it.starred }.let { l ->+ fun starredRows(): List<com.chethan616.clearpdf.ui.home.FileRow> = knownRows().filter { it.starred }.let { l ->if (starSort == 1) l.sortedBy { it.name.lowercase() } else l.sortedByDescending { it.date }}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.ktindex 5d0cada..d0d9f53 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt@@ -76,7 +76,6 @@ import androidx.compose.ui.text.withStyleimport androidx.compose.ui.unit.dpimport androidx.core.view.WindowCompatimport com.chethan616.clearpdf.R-import com.chethan616.clearpdf.ui.desk.FileActionsSheetimport com.chethan616.clearpdf.ui.desk.FilesScreenimport com.chethan616.clearpdf.ui.desk.SettingsScreenimport com.chethan616.clearpdf.ui.desk.ToolCatalog@@ -163,14 +162,16 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:BackHandler(enabled = doc != null && vm.toolScreen == null) { vm.closeDocument() }BackHandler(enabled = doc == null && vm.onboarded && !vm.settingsOpen && vm.openNote == null && vm.homeTab != HomeTab.Home && vm.toolScreen == null) { vm.homeTab = HomeTab.Home }BackHandler(enabled = vm.editingPhoto != null) { vm.editingPhoto = null }+ BackHandler(enabled = doc == null && vm.onboarded && !vm.settingsOpen && vm.openNote == null && vm.homeTab == HomeTab.Home && vm.deskPages.isNotEmpty() && vm.toolScreen == null) { vm.closeDeskPage() }val route = when {!vm.onboarded -> "welcome"vm.settingsOpen -> "settings"vm.openNote != null -> "note:" + vm.openNote+ vm.homeTab == HomeTab.Home && vm.deskPages.isNotEmpty() -> "page:" + vm.deskPages.last().nameelse -> vm.homeTab.name}- val onDesk = doc == null && route == HomeTab.Home.name && vm.toolScreen == null && vm.signaturePad == null && vm.certSign == null && !vm.idCreate && vm.editingPhoto == null && vm.presenting == null+ val onDesk = doc == null && (route == HomeTab.Home.name || route == "page:Today") && vm.toolScreen == null && vm.signaturePad == null && vm.certSign == null && !vm.idCreate && vm.editingPhoto == null && vm.presenting == nullval desk = remember { DeskState(scope) }var dockIntoNote by remember { mutableStateOf(false) }var dockFromNote by remember { mutableStateOf(false) }@@ -178,6 +179,8 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:route == "welcome" -> AuroraMoods.Welcomevm.settingsOpen -> AuroraMoods.Settingsvm.openNote != null -> AuroraMoods.Note+ route == "page:Thoughts" -> AuroraMoods.Thoughts+ route == "page:Today" -> AuroraMoods.Todayvm.homeTab == HomeTab.Files -> AuroraMoods.Filesvm.homeTab == HomeTab.Tools -> AuroraMoods.Toolselse -> AuroraMoods.Desk@@ -202,6 +205,8 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:r.startsWith("note:") -> NoteEditor(vm, r.removePrefix("note:"))r == HomeTab.Files.name -> FilesScreen(vm, onBrowse)r == HomeTab.Tools.name -> ToolsScreen(vm)+ r == "page:Today" -> com.chethan616.clearpdf.ui.home.TodayScreen(vm)+ r == "page:Thoughts" -> com.chethan616.clearpdf.ui.home.ThoughtsScreen(vm, desk)else -> HomeScreen(vm, desk)}}@@ -254,8 +259,10 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:if (vm.noteBarHidden != (intoNote || fromNote)) vm.noteBarHidden = intoNote || fromNotelastRoute[0] = route}- if ((onDesk || dockIntoNote) && vm.editingPhoto == null && vm.editingImage == null && vm.previewingMap == null && vm.presenting == null) {- CreateDock(vm, desk, onBrowse, intoNote = !onDesk, fromNote = onDesk && dockFromNote) {+ // a voice memo started from Thought of the day records in the dock there too+ val recordingOnPage = doc == null && route == "page:Thoughts" && desk.recorder != null+ if ((onDesk || dockIntoNote || recordingOnPage) && vm.editingPhoto == null && vm.editingImage == null && vm.previewingMap == null && vm.presenting == null) {+ CreateDock(vm, desk, onBrowse, intoNote = !onDesk && !recordingOnPage, fromNote = onDesk && dockFromNote) {dockIntoNote = falsedockFromNote = falsevm.noteBarHidden = false@@ -271,7 +278,8 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:},)- if (doc == null) vm.fileSheet?.let { (r, recent) -> FileActionsSheet(vm, r, recent) { vm.fileSheet = null } }+ if (doc == null) vm.fileMenu?.let { at -> androidx.compose.runtime.key(at) { com.chethan616.clearpdf.ui.desk.FileMenu(vm, at) { if (vm.fileMenu == at) vm.fileMenu = null } } }+ com.chethan616.clearpdf.ui.desk.FileDialogs(vm)// the loader only for an open that takes a while: a quick one shouldn't flash a spinner firstvar slowOpen by remember { mutableStateOf(false) }LaunchedEffect(vm.opening) {diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/Theme.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/Theme.ktindex 0b20d5e..daafae3 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/Theme.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/Theme.kt@@ -16,8 +16,8 @@ import androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.sp-/** The app's reading face: Plus Jakarta Sans, the same as the glass screens (the old name stays for the viewer's code). */-val Inter: FontFamily get() = com.chethan616.clearpdf.ui.theme.Jakarta+/** The app's reading face: Outfit, the same as the glass screens (the old name stays for the viewer's code). */+val Inter: FontFamily get() = com.chethan616.clearpdf.ui.theme.Outfit/** The colours the screens use beyond Material's roles (measured from the reference app's screens). */@Immutablediff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.ktindex d10af98..1e36ccb 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.kt@@ -804,6 +804,8 @@ fun ScanScreen(vm: AppViewModel) {var current by remember { mutableStateOf(0) }var cropping by remember { mutableStateOf<java.io.File?>(null) }var naming by remember { mutableStateOf(false) }+ // the pages as they will be saved, by page, look and crop+ val previews = remember { HashMap<String, ImageBitmap>() }LaunchedEffect(Unit) { if (pages.isEmpty()) vm.takeScanPhoto() }// a page just taken is the one shownvar seen by remember { mutableStateOf(pages.size) }@@ -841,7 +843,25 @@ fun ScanScreen(vm: AppViewModel) {Box(Modifier.weight(1f).fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp).then(com.chethan616.clearpdf.ui.glass.washPanel()), contentAlignment = Alignment.Center) {val page = pages.getOrNull(current.coerceAtMost(pages.lastIndex))if (page != null) {- ScanPhoto(page.thumb, page.corners, Modifier.fillMaxSize())+ // the page as it will be saved: cropped, straightened and in the chosen look, made+ // as soon as a look or a crop is chosen (the photo with its outline until it is ready)+ val key = "${page.file.name}|${filter.name}|${page.corners.contentHashCode()}"+ var shown by remember { mutableStateOf<Pair<String, ImageBitmap>?>(null) }+ LaunchedEffect(key) {+ previews[key]?.let { shown = key to it; return@LaunchedEffect }+ vm.scanPreview(page, filter)?.let { previews[key] = it; shown = key to it }+ }+ val ready = shown?.takeIf { it.first == key }?.second+ androidx.compose.animation.Crossfade(ready, label = "scanLook") { img ->+ if (img != null) {+ Image(img, null, Modifier.fillMaxSize().padding(16.dp), contentScale = ContentScale.Fit)+ } else {+ Box(Modifier.fillMaxSize()) {+ ScanPhoto(page.thumb, page.corners, Modifier.fillMaxSize())+ com.chethan616.clearpdf.ui.glass.GlassLoader(Modifier.align(Alignment.Center))+ }+ }+ }} else {Text(stringResource(R.string.tools_scan_empty), color = c.textSecondary)}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.ktindex c902256..9ca48d3 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/Common.kt@@ -29,7 +29,10 @@ import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawWithContentimport androidx.compose.ui.draw.rotate+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.ui.layout.onGloballyPositionedimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.ImageBitmap@@ -198,7 +201,10 @@ fun SettingsButton(vm: AppViewModel) {}}-/** A file in a list: its paper, its name, when and how big, a star, and its menu. */+/**+ * A file in a list: its paper, its name, when and how big, its star (a tap stars or unstars it, there+ * and then) and its ⋯, whose glass grows into the file's menu ([FileMenu]).+ */@Composablefun FileListItem(vm: AppViewModel, r: FileRow, recent: Boolean, modifier: Modifier = Modifier) {val c = clear@@ -208,7 +214,7 @@ fun FileListItem(vm: AppViewModel, r: FileRow, recent: Boolean, modifier: Modifimodifier.fillMaxWidth().pressable(onClick = { if (selecting) vm.toggleSelected(r) else r.open() }, onLongClick = { vm.toggleSelected(r) }).background(if (ticked) Candy.Sky.copy(alpha = 0.14f) else Color.Transparent)- .padding(start = 14.dp, end = 6.dp, top = 10.dp, bottom = 10.dp),+ .padding(start = 14.dp, end = 2.dp, top = 10.dp, bottom = 10.dp),verticalAlignment = Alignment.CenterVertically,) {PaperThumb(vm, r.thumbPath, 40.dp, 52.dp, corner = 6.dp, name = r.name)@@ -221,7 +227,6 @@ fun FileListItem(vm: AppViewModel, r: FileRow, recent: Boolean, modifier: Modifistyle = ClearType.Caption, color = c.inkSoft, maxLines = 1,)}- if (r.starred) Icon(LucideIcons.Star, stringResource(R.string.home_starred_description), tint = Candy.Lemon, modifier = Modifier.padding(horizontal = 4.dp).size(16.dp))if (selecting) {Box(Modifier.size(44.dp), contentAlignment = Alignment.Center) {Box(@@ -231,72 +236,23 @@ fun FileListItem(vm: AppViewModel, r: FileRow, recent: Boolean, modifier: Modifi) { if (ticked) Icon(LucideIcons.Check, null, tint = Color.White, modifier = Modifier.size(14.dp)) }}} else {- Box(Modifier.size(44.dp).pressable({ vm.fileSheet = r to recent }), contentAlignment = Alignment.Center) {+ val starred = vm.isStarred(r)+ StarToggle(starred, size = 40.dp) { vm.setStarred(r, !starred) }+ var dots by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }+ Box(+ Modifier.size(44.dp)+ .onGloballyPositioned { dots = it.boundsInWindow() }+ // stepped aside while its glass is the menu (the menu's own ⋯ is drawn there instead)+ .drawWithContent { if (!com.chethan616.clearpdf.ui.glass.MorphAnchors.hides(dots)) drawContent() }+ .pressable({ if (vm.fileMenu == null) vm.fileMenu = FileMenuAt(r, recent, dots) }, pressedScale = 0.85f),+ contentAlignment = Alignment.Center,+ ) {Icon(LucideIcons.EllipsisVertical, stringResource(R.string.home_more_options_for, r.name), tint = c.inkSoft, modifier = Modifier.size(20.dp))}}}}-/** A file's sheet: four big candy actions up top, then its tools and the rest. */-@Composable-fun FileActionsSheet(vm: AppViewModel, r: FileRow, recent: Boolean, onDismiss: () -> Unit) {- var renaming by remember { mutableStateOf(false) }- var deleting by remember { mutableStateOf(false) }- fun act(f: () -> Unit) {- onDismiss()- f()- }- GlassSheet(onDismiss = onDismiss, title = displayName(r.name), subtitle = listOfNotNull(whenLabel(r.date), r.size.takeIf { it > 0 }?.let { formatSize(it) }).joinToString(" · ")) {- Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp), horizontalArrangement = Arrangement.SpaceEvenly) {- BigAction(LucideIcons.Share2, stringResource(R.string.common_share), Candy.Sky) { act { vm.shareFile(r) } }- BigAction(LucideIcons.Star, stringResource(if (r.starred) R.string.home_unstar else R.string.home_star), Candy.Lemon) { act { vm.setStarred(r.key, !r.starred) } }- BigAction(LucideIcons.Pencil, stringResource(R.string.common_rename), Candy.Grape) { renaming = true }- BigAction(LucideIcons.Printer, stringResource(R.string.home_print), Candy.Mint) { act { vm.printFile(r) } }- }- Spacer(Modifier.height(6.dp))- Column(Modifier.verticalScroll(rememberScrollState())) {- GlassRow(stringResource(R.string.common_tool_edit_pdf), { act { vm.openFor(r, FileTool.Edit) } }, icon = LucideIcons.FilePenLine, accent = ToolCatalog.Edit.accent)- GlassRow(stringResource(R.string.common_tool_read_aloud), { act { vm.openFor(r, FileTool.ReadAloud) } }, icon = LucideIcons.Volume2, accent = ToolCatalog.ReadAloud.accent)- GlassRow(stringResource(R.string.home_export_as), { act { vm.openFor(r, FileTool.Export) } }, icon = LucideIcons.FileOutput, accent = ToolCatalog.Export.accent)- GlassRow(stringResource(R.string.common_tool_compress), { act { vm.openFor(r, FileTool.Compress) } }, icon = LucideIcons.FileArchive, accent = ToolCatalog.Compress.accent)- GlassRow(stringResource(R.string.common_tool_set_password), { act { vm.openFor(r, FileTool.Protect) } }, icon = LucideIcons.FileLock2, accent = ToolCatalog.Protect.accent)- GlassRow(stringResource(R.string.home_open_with), { act { vm.openWith(r) } }, icon = LucideIcons.ExternalLink, accent = Candy.Sky)- GlassRow(stringResource(R.string.home_duplicate), { act { vm.duplicateFile(r) } }, icon = LucideIcons.Copy, accent = Candy.Tangerine)- GlassRow(stringResource(R.string.common_save_copy), { act { vm.saveFileCopy(r) } }, icon = LucideIcons.FileDown, accent = Candy.Mint)- if (recent) GlassRow(stringResource(R.string.home_remove_from_recent), { act { vm.removeRecent(r.key) } }, icon = LucideIcons.X, accent = Candy.Grape)- GlassRow(stringResource(R.string.common_delete), { deleting = true }, icon = LucideIcons.Trash2, destructive = true)- }- }- if (renaming) {- var name by remember { mutableStateOf(com.chethan616.clearpdf.engine.DocumentTypes.title(r.name)) }- GlassDialog(- onDismiss = { renaming = false }, title = stringResource(R.string.common_rename), icon = LucideIcons.Pencil, accent = Candy.Grape,- confirm = stringResource(R.string.common_done), confirmEnabled = name.isNotBlank() && !name.startsWith("."),- onConfirm = { renaming = false; onDismiss(); vm.renameFile(r, name) },- dismiss = stringResource(R.string.common_cancel),- ) { GlassTextField(name, { name = it }, stringResource(R.string.home_enter_name)) }- }- if (deleting) {- GlassDialog(- onDismiss = { deleting = false }, title = stringResource(R.string.home_delete_file_title), icon = LucideIcons.Trash2, destructive = true,- confirm = stringResource(R.string.common_delete), onConfirm = { deleting = false; onDismiss(); vm.deleteFile(r) },- dismiss = stringResource(R.string.common_cancel),- ) { Text(stringResource(R.string.home_delete_file_body, r.name), style = ClearType.Body, color = clear.inkSoft) }- }-}--/** A big round candy action with its name under it. */-@Composable-private fun BigAction(icon: ImageVector, label: String, accent: Color, onClick: () -> Unit) {- val c = clear- Column(Modifier.width(76.dp), horizontalAlignment = Alignment.CenterHorizontally) {- GlassCircle(onClick = onClick, size = 56.dp, tint = accent, label = label) { GlassIcon(icon, null, Modifier.size(24.dp)) }- Spacer(Modifier.height(6.dp))- Text(label, style = ClearType.Caption, color = c.inkSoft, maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center)- }-}-/** An empty list, playfully: three tilted papers, a big line and a candy action. */@Composablefun EmptyHero(title: String, body: String, action: String? = null, accent: Color = Candy.Tomato, onAction: (() -> Unit)? = null) {diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FileMenu.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FileMenu.ktnew file mode 100644index 0000000..f033b45--- /dev/null+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FileMenu.kt@@ -0,0 +1,248 @@+package com.chethan616.clearpdf.ui.desk++import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.Animatable+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+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.graphicsLayer+import androidx.compose.ui.graphics.isSpecified+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.chethan616.clearpdf.R+import com.chethan616.clearpdf.ui.AppViewModel+import com.chethan616.clearpdf.ui.LucideIcons+import com.chethan616.clearpdf.ui.glass.Feel+import com.chethan616.clearpdf.ui.glass.GlassDialog+import com.chethan616.clearpdf.ui.glass.GlassMenuItem+import com.chethan616.clearpdf.ui.glass.GlassMotion+import com.chethan616.clearpdf.ui.glass.GlassTextField+import com.chethan616.clearpdf.ui.glass.LocalGlassInk+import com.chethan616.clearpdf.ui.glass.MorphAnchors+import com.chethan616.clearpdf.ui.glass.MorphButtonSurface+import com.chethan616.clearpdf.ui.glass.MorphMenuRow+import com.chethan616.clearpdf.ui.glass.RoundedRectangle+import com.chethan616.clearpdf.ui.glass.pressable+import com.chethan616.clearpdf.ui.glass.rememberFeel+import com.chethan616.clearpdf.ui.home.FileRow+import com.chethan616.clearpdf.ui.home.FileTool+import com.chethan616.clearpdf.ui.home.displayName+import com.chethan616.clearpdf.ui.home.whenLabel+import com.chethan616.clearpdf.ui.theme.Candy+import com.chethan616.clearpdf.ui.theme.ClearType+import com.chethan616.clearpdf.ui.theme.clear+import com.chethan616.clearpdf.ui.viewer.formatSize+import kotlinx.coroutines.launch++/**+ * A file's menu, open: the file, whether it was opened from Recent, and the window bounds of what its+ * glass grows out of. [ghost]: nothing round stands there (a long-pressed card), so the glass starts+ * as a drop over the card's corner and melts away there when it closes.+ */+data class FileMenuAt(val row: FileRow, val recent: Boolean, val anchor: Rect, val ghost: Boolean = false)++/** The corner of a card [bounds] that a long press's menu grows from: a round drop of [side], inset from the top right. */+fun cardMenuAnchor(bounds: Rect, density: androidx.compose.ui.unit.Density, side: Dp = 44.dp, inset: Dp = 10.dp): Rect = with(density) {+ val s = side.toPx()+ val i = inset.toPx()+ Rect(bounds.right - i - s, bounds.top + i, bounds.right - i, bounds.top + i + s)+}++/**+ * A file's menu as liquid glass, the same glass every round button's menu is: it grows out of the+ * file's ⋯ (or the corner of a long-pressed card) in the morph's four states and settles with the+ * user's bounce. The file at the top with its star, one tap to star or unstar right there (the menu+ * stays open and the star pops); four quick actions; then its tools. A row closes the menu, which+ * folds back into the ⋯ before the row's action runs.+ */+@Composable+fun FileMenu(vm: AppViewModel, at: FileMenuAt, onGone: () -> Unit) {+ var open by remember(at) { mutableStateOf(true) }+ val dots: @Composable () -> Unit = {+ val ink = LocalGlassInk.current+ Icon(LucideIcons.EllipsisVertical, null, tint = if (ink.isSpecified) ink else clear.inkSoft, modifier = Modifier.size(20.dp))+ }+ // the ⋯ stands in for a round button: the glass folds back into it, and it steps aside meanwhile+ DisposableEffect(at.anchor, at.ghost) {+ if (!at.ghost) MorphAnchors.register(at.anchor, dots)+ onDispose { if (!at.ghost) MorphAnchors.unregister(at.anchor) }+ }+ MorphButtonSurface(+ anchor = at.anchor,+ open = open,+ onDismiss = { open = false },+ onGone = onGone,+ menuWidth = 292.dp,+ maxHeight = 600.dp,+ icon = dots,+ ghost = at.ghost,+ ) { shut, choose -> FileMenuBody(vm, at.row, at.recent, shut, choose) }+}++@Composable+private fun ColumnScope.FileMenuBody(vm: AppViewModel, r: FileRow, recent: Boolean, shut: Boolean, choose: (() -> Unit) -> Unit) {+ val ink = LocalGlassInk.current.takeIf { it.isSpecified } ?: clear.ink+ val starred = vm.isStarred(r)+ // the file: its first page, its name, when and how big, and its star+ Row(Modifier.fillMaxWidth().padding(start = 14.dp, end = 8.dp, top = 6.dp, bottom = 10.dp), verticalAlignment = Alignment.CenterVertically) {+ PaperThumb(vm, r.thumbPath, 36.dp, 47.dp, corner = 6.dp, name = r.name)+ Spacer(Modifier.width(12.dp))+ Column(Modifier.weight(1f)) {+ Text(displayName(r.name), style = ClearType.BodyStrong, color = ink, maxLines = 2, overflow = TextOverflow.Ellipsis)+ Text(+ listOfNotNull(whenLabel(r.date), r.size.takeIf { it > 0 }?.let { formatSize(it) }).joinToString(" · "),+ style = ClearType.Caption, color = ink.copy(alpha = 0.6f), maxLines = 1,+ )+ }+ Spacer(Modifier.width(6.dp))+ StarToggle(starred, enabled = !shut, size = 44.dp, filled = true) { vm.setStarred(r, !starred) }+ }+ // the four things done most, a tap each+ Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ QuickAction(LucideIcons.Share2, stringResource(R.string.common_share), Candy.Sky, ink, !shut) { choose { vm.shareFile(r) } }+ QuickAction(LucideIcons.Pencil, stringResource(R.string.common_rename), Candy.Grape, ink, !shut) { choose { vm.fileRenaming = r } }+ QuickAction(LucideIcons.Printer, stringResource(R.string.home_print), Candy.Mint, ink, !shut) { choose { vm.printFile(r) } }+ QuickAction(LucideIcons.ExternalLink, stringResource(R.string.home_open_with), Candy.Tangerine, ink, !shut) { choose { vm.openWith(r) } }+ }+ Spacer(Modifier.height(8.dp))+ Box(Modifier.padding(horizontal = 16.dp).fillMaxWidth().height(1.dp).background(ink.copy(alpha = 0.1f)))+ Spacer(Modifier.height(4.dp))+ @Composable+ fun row(label: String, icon: ImageVector, destructive: Boolean = false, action: () -> Unit) {+ MorphMenuRow(GlassMenuItem(label, icon, destructive, action), shut) { choose(action) }+ }+ row(stringResource(R.string.common_tool_edit_pdf), LucideIcons.FilePenLine) { vm.openFor(r, FileTool.Edit) }+ row(stringResource(R.string.common_tool_read_aloud), LucideIcons.Volume2) { vm.openFor(r, FileTool.ReadAloud) }+ row(stringResource(R.string.home_export_as), LucideIcons.FileOutput) { vm.openFor(r, FileTool.Export) }+ row(stringResource(R.string.common_tool_compress), LucideIcons.FileArchive) { vm.openFor(r, FileTool.Compress) }+ row(stringResource(R.string.common_tool_set_password), LucideIcons.FileLock2) { vm.openFor(r, FileTool.Protect) }+ row(stringResource(R.string.home_duplicate), LucideIcons.Copy) { vm.duplicateFile(r) }+ row(stringResource(R.string.common_save_copy), LucideIcons.FileDown) { vm.saveFileCopy(r) }+ if (recent) row(stringResource(R.string.home_remove_from_recent), LucideIcons.CircleMinus) { vm.removeRecent(r.key) }+ row(stringResource(R.string.common_delete), LucideIcons.Trash2, destructive = true) { vm.fileDeleting = r }+}++/** One of the menu's quick actions: a candy blob with its glyph, its name under it. */+@Composable+private fun androidx.compose.foundation.layout.RowScope.QuickAction(icon: ImageVector, label: String, accent: Color, ink: Color, enabled: Boolean, onClick: () -> Unit) {+ val c = clear+ Column(+ Modifier.weight(1f).clip(RoundedRectangle(16.dp)).pressable(onClick, pressedScale = 0.88f, enabled = enabled).padding(vertical = 8.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(Modifier.size(42.dp).clip(CircleShape).background(accent.copy(alpha = if (c.dark) 0.3f else 0.2f)), contentAlignment = Alignment.Center) {+ Icon(icon, null, tint = accent, modifier = Modifier.size(21.dp))+ }+ Spacer(Modifier.height(5.dp))+ Text(label, style = ClearType.Caption, color = ink.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center)+ }+}++/**+ * A star you tap to star or unstar a file: it pops (a quick squash and a bouncy spring back, by+ * Settings ▸ Motion) and ticks. [filled] gives it a round lemon well when starred (the menu's); else it+ * is a bare glyph (a file row's), faint until starred.+ */+@Composable+fun StarToggle(starred: Boolean, modifier: Modifier = Modifier, enabled: Boolean = true, size: Dp = 44.dp, filled: Boolean = false, onToggle: () -> Unit) {+ val c = clear+ val feel = rememberFeel()+ val scope = rememberCoroutineScope()+ val pop = remember { Animatable(1f) }+ val ink = LocalGlassInk.current.takeIf { it.isSpecified } ?: c.ink+ val glyph by animateColorAsState(+ when {+ starred && filled -> Color(0xFF1C2433)+ starred -> Candy.Lemon+ else -> ink.copy(alpha = if (filled) 0.7f else 0.35f)+ },+ GlassMotion.settle(), label = "star",+ )+ val well by animateColorAsState(+ if (filled) (if (starred) Candy.Lemon else ink.copy(alpha = 0.08f)) else Color.Transparent,+ GlassMotion.settle(), label = "starWell",+ )+ val label = stringResource(if (starred) R.string.home_unstar else R.string.home_star)+ Box(+ modifier.size(size)+ .semantics { contentDescription = label }+ .pressable(+ {+ feel(if (starred) Feel.Fall else Feel.Rise)+ onToggle()+ scope.launch {+ pop.snapTo(0.72f)+ pop.animateTo(1f, GlassMotion.pop())+ }+ },+ pressedScale = 0.86f, role = Role.Switch, enabled = enabled, feel = null,+ ),+ contentAlignment = Alignment.Center,+ ) {+ Box(+ Modifier.size(size * 0.82f)+ .graphicsLayer {+ scaleX = pop.value+ scaleY = pop.value+ // a little turn as it pops, the way a sticker is slapped on+ rotationZ = (1f - pop.value) * 70f+ }+ .clip(CircleShape).background(well),+ contentAlignment = Alignment.Center,+ ) {+ Icon(if (starred) LucideIcons.Star else LucideIcons.StarOutline, null, tint = glyph, modifier = Modifier.size(size * 0.46f))+ }+ }+}++/** Renaming and deleting a file, asked once its menu has folded away (they outlive the menu). */+@Composable+fun FileDialogs(vm: AppViewModel) {+ vm.fileRenaming?.let { r ->+ var name by remember(r.key) { mutableStateOf(com.chethan616.clearpdf.engine.DocumentTypes.title(r.name)) }+ GlassDialog(+ onDismiss = { vm.fileRenaming = null }, title = stringResource(R.string.common_rename), icon = LucideIcons.Pencil, accent = Candy.Grape,+ confirm = stringResource(R.string.common_done), confirmEnabled = name.isNotBlank() && !name.startsWith("."),+ onConfirm = { vm.fileRenaming = null; vm.renameFile(r, name) },+ dismiss = stringResource(R.string.common_cancel),+ ) { GlassTextField(name, { name = it }, stringResource(R.string.home_enter_name)) }+ }+ vm.fileDeleting?.let { r ->+ GlassDialog(+ onDismiss = { vm.fileDeleting = null }, title = stringResource(R.string.home_delete_file_title), icon = LucideIcons.Trash2, destructive = true,+ confirm = stringResource(R.string.common_delete), onConfirm = { vm.fileDeleting = null; vm.deleteFile(r) },+ dismiss = stringResource(R.string.common_cancel),+ ) { Text(stringResource(R.string.home_delete_file_body, r.name), style = ClearType.Body, color = clear.inkSoft) }+ }+}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FilesScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FilesScreen.ktindex eebd056..8fa9681 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FilesScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FilesScreen.kt@@ -96,6 +96,18 @@ fun FilesScreen(vm: AppViewModel, onBrowse: () -> Unit) {vm.filesShowLocal = false}}+ LaunchedEffect(vm.filesShowRecent) {+ if (vm.filesShowRecent) {+ tab = 0+ vm.filesShowRecent = false+ }+ }+ LaunchedEffect(vm.filesShowStarred) {+ if (vm.filesShowStarred) {+ tab = 1+ vm.filesShowStarred = false+ }+ }LaunchedEffect(tab) { if (tab == 2) vm.scanLocal() }BackHandler(enabled = vm.selectedFiles.isNotEmpty()) { vm.selectedFiles.clear() }BackHandler(enabled = vm.selectedFiles.isEmpty() && query.isNotEmpty()) { query = "" }diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/SettingsScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/SettingsScreen.ktindex d5580da..814846d 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/SettingsScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/SettingsScreen.kt@@ -134,6 +134,7 @@ private fun SettingsRoot(vm: AppViewModel, openLicences: () -> Unit, openGlass:?: stringResource(R.string.read_aloud_system_default, Locale.getDefault().getDisplayName(Locale.getDefault()))val uri = LocalUriHandler.currentvar leaving by remember { mutableStateOf<String?>(null) }+ var naming by remember { mutableStateOf(false) }var authorDialog by remember { mutableStateOf(false) }LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 32.dp)) {item { Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars)) }@@ -157,7 +158,13 @@ private fun SettingsRoot(vm: AppViewModel, openLicences: () -> Unit, openGlass:}item(key = "personal") { Section(stringResource(R.string.settings_personalization)) }- item(key = "personalpanel") { Panel { WallpaperPicker(context) } }+ item(key = "personalpanel") {+ Panel {+ // the name Today greets (small, above "Good Morning"); empty: none+ SettingRow(LucideIcons.UserRound, Candy.Tangerine, stringResource(R.string.settings_your_name), { naming = true }, value = vm.ownerName.ifBlank { null }, chevron = true, first = true)+ WallpaperPicker(context)+ }+ }item(key = "reading") { Section(stringResource(R.string.settings_reading)) }item(key = "readingpanel") {@@ -196,6 +203,14 @@ private fun SettingsRoot(vm: AppViewModel, openLicences: () -> Unit, openGlass:item(key = "credits") { AppFooter(vm) }item { Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars)) }}+ if (naming) {+ var name by remember { mutableStateOf(vm.ownerName) }+ GlassDialog(+ onDismiss = { naming = false }, title = stringResource(R.string.settings_your_name), icon = LucideIcons.UserRound, accent = Candy.Tangerine,+ confirm = stringResource(R.string.common_done), onConfirm = { vm.updateOwnerName(name); naming = false },+ dismiss = stringResource(R.string.common_cancel),+ ) { com.chethan616.clearpdf.ui.glass.GlassTextField(name, { name = it }, stringResource(R.string.settings_your_name_hint)) }+ }leaving?.let { url ->GlassDialog(onDismiss = { leaving = null }, title = stringResource(R.string.home_leaving_title), icon = LucideIcons.ExternalLink, accent = Candy.Sky,@@ -608,6 +623,7 @@ private fun LicencesPage(onBack: () -> Unit) {Credit("JNA", stringResource(R.string.licences_role_bridge), "Apache-2.0 · the JNA authors", "https://github.com/java-native-access/jna"),)),CreditGroup(R.string.licences_type, listOf(+ Credit("Outfit", stringResource(R.string.licences_role_ui_font), "OFL-1.1 · The Outfit Project Authors", "https://github.com/Outfitio/Outfit-Fonts", "OFL-Outfit.txt"),Credit("Plus Jakarta Sans", stringResource(R.string.licences_role_ui_font), "OFL-1.1 · The Plus Jakarta Sans Project Authors", "https://github.com/tokotype/PlusJakartaSans", "OFL-PlusJakartaSans.txt"),Credit("Bricolage Grotesque", stringResource(R.string.licences_role_titles), "OFL-1.1 · The Bricolage Grotesque Project Authors", "https://github.com/ateliertriay/bricolage", "OFL-BricolageGrotesque.txt"),Credit("Fraunces", stringResource(R.string.licences_role_titles), "OFL-1.1 · The Fraunces Project Authors", "https://github.com/undercasetype/Fraunces", "OFL-Fraunces.txt"),diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Backdrops.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Backdrops.ktindex 00b7edb..41088ed 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Backdrops.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Backdrops.kt@@ -72,12 +72,22 @@ fun GlassLayer(}}-/** A mood of the wallpaper: where its blooms of light sit, as fractions of the screen, and how big they are. */-data class AuroraMood(val blobs: List<Offset>, val radius: Float = 0.62f)+/**+ * A mood of the wallpaper: where its blooms of light sit, as fractions of the screen, and how big they+ * are. [painting]: in the light theme, the sky the design mock gives that screen instead (its gradient+ * sampled from the mock and baked into a small picture, drawn smooth and stretched to the screen).+ */+data class AuroraMood(val blobs: List<Offset>, val radius: Float = 0.62f, val painting: Int? = null)object AuroraMoods {// the blooms, in ClearColors.blooms' order: aqua, lilac, pink, periwinkle, haze- val Desk = AuroraMood(listOf(Offset(0.0f, 0.58f), Offset(0.98f, 0.44f), Offset(1.0f, 0.1f), Offset(0.5f, 1.08f), Offset(0.2f, -0.05f)))+ val Desk = AuroraMood(listOf(Offset(0.0f, 0.58f), Offset(0.98f, 0.44f), Offset(1.0f, 0.1f), Offset(0.5f, 1.08f), Offset(0.2f, -0.05f)), painting = com.chethan616.clearpdf.R.drawable.sky_desk)++ /** Thought of the day: blue at the ends, lilac and pink through the middle (the mock's). */+ val Thoughts = AuroraMood(listOf(Offset(0.05f, 0.85f), Offset(0.6f, 0.35f), Offset(0.95f, 0.2f), Offset(0.4f, 1.1f), Offset(0.1f, 0.0f)), 0.68f, com.chethan616.clearpdf.R.drawable.sky_thoughts)++ /** Today: periwinkle at the top, peach on the left and pink on the right, pale blue below (the mock's). */+ val Today = AuroraMood(listOf(Offset(0.0f, 0.35f), Offset(0.9f, 0.6f), Offset(0.95f, 0.15f), Offset(0.3f, 1.05f), Offset(0.5f, 0.0f)), 0.7f, com.chethan616.clearpdf.R.drawable.sky_today)val Files = AuroraMood(listOf(Offset(0.1f, 0.3f), Offset(0.9f, 0.7f), Offset(0.85f, 0.0f), Offset(0.2f, 1.05f), Offset(0.6f, -0.1f)), 0.58f)val Tools = AuroraMood(listOf(Offset(0.9f, 0.25f), Offset(0.1f, 0.65f), Offset(0.0f, 0.05f), Offset(0.8f, 1.05f), Offset(0.45f, -0.08f)))val Settings = AuroraMood(listOf(Offset(0.15f, 0.15f), Offset(0.95f, 0.85f), Offset(1.0f, 0.3f), Offset(0.1f, 1.0f), Offset(0.6f, 0.0f)), 0.55f)@@ -151,6 +161,16 @@ fun Aurora(mood: AuroraMood, modifier: Modifier = Modifier) {onDrawBehind { drawImage(image, dstSize = IntSize(size.width.toInt(), size.height.toInt()), filterQuality = FilterQuality.Low) }},)+ // the mock's own sky for this screen (light theme), crossfading as the screens change+ val painting = if (!colors.dark) mood.painting else null+ androidx.compose.animation.Crossfade(painting, modifier.fillMaxSize(), animationSpec = androidx.compose.animation.core.tween(700), label = "sky") { id ->+ if (id != null) {+ androidx.compose.foundation.Image(+ androidx.compose.ui.graphics.painter.BitmapPainter(ImageBitmap.imageResource(id), filterQuality = FilterQuality.High),+ null, Modifier.fillMaxSize(), contentScale = androidx.compose.ui.layout.ContentScale.FillBounds,+ )+ }+ }}/**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.ktindex aa5a878..b251f31 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@@ -75,12 +75,15 @@ private fun Modifier.glassControl(tintAt: (() -> Color)? = null,candyBase: Boolean = true,adaptWash: Boolean = true,+ /** Told the control's surround reading (the morph that grows out of a round button carries it on). */+ aroundOut: ((SurroundLuminance?) -> Unit)? = null,): Modifier {val backdrop = LocalBackdrop.current// Adaptive luminance on: the glass reads the screen around it and turns to suit, its frost,// colour and tint set by that instead of the glass preset. [adaptWash] false keeps the milk or// smoke off a control whose ink is the caller's (a chip's label), where only the glass adapts.val around = rememberSurroundLuminance()+ aroundOut?.invoke(around)val scope = rememberCoroutineScope()val haptics = LocalHaptics.currentval currentHaptics by rememberUpdatedState(haptics)@@ -352,13 +355,16 @@ fun GlassCircle(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) {+ // its adaptive reading, for the morph to wear the very same glass at the button's end+ val around = androidx.compose.runtime.remember { arrayOfNulls<SurroundLuminance>(1) }+ androidx.compose.runtime.DisposableEffect(at, GlassSettings.adaptive) {val r = atif (r != null) {MorphAnchors.register(r) { CompositionLocalProvider(LocalGlassInk provides inkNow) { glyph() } }MorphAnchors.setTint(r, tint)+ MorphAnchors.setSurround(r, around[0])}- onDispose { if (r != null) MorphAnchors.unregister(r) }+ onDispose { if (r != null) { MorphAnchors.unregister(r); MorphAnchors.setSurround(r, null) } }}CompositionLocalProvider(LocalGlassInk provides probe.color) {Box(@@ -367,7 +373,7 @@ fun GlassCircle(// 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),+ .size(size).glassControl(CircleShape, onClick, onLongClick, tint, surface, 2.dp, label, tap = tap, bloom = true, candyBase = false, aroundOut = { around[0] = it }),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.ktindex 2c5cab0..c05cfe1 100644--- 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@@ -51,6 +51,8 @@ import androidx.compose.ui.unit.dpimport androidx.compose.ui.util.lerpimport com.chethan616.clearpdf.ui.theme.clearimport com.kyant.backdrop.drawBackdrop+import com.kyant.backdrop.effects.blur+import com.kyant.backdrop.effects.colorControlsimport com.kyant.backdrop.effects.runtimeShaderEffectimport kotlin.math.maximport kotlin.math.min@@ -184,10 +186,11 @@ internal fun LiquidMorphSurface(open: Boolean,onDismiss: () -> Unit,onGone: () -> Unit,- items: List<GlassMenuItem>,menuWidth: Dp,maxHeight: Dp,icon: @Composable () -> Unit,+ ghost: Boolean,+ body: @Composable androidx.compose.foundation.layout.ColumnScope.(shut: Boolean, choose: (() -> Unit) -> Unit) -> Unit,) {val gone by rememberUpdatedState(onGone)GlassOverlay(animatesOut = true) {@@ -210,7 +213,7 @@ internal fun LiquidMorphSurface(// 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.+ // (gated springs read as a machine). Past rest the spring's swing is the menu's own jelly.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)@@ -224,16 +227,18 @@ internal fun LiquidMorphSurface(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))+ // the states and pace the owner liked, now on a spring that bounces at Settings ▸ Motion's+ // bounce: past the menu and back, jelly-like (see geo: the swing is the menu's own stretch)+ p.animateTo(1f, GlassMotion.morphOpen())} 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))+ if (!ghost && 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))+ else if (chosenAction != null) p.animateTo(0f, GlassMotion.morphChosen())+ else p.animateTo(0f, GlassMotion.morphClose())+ // no real button under it (a menu opened by a long press): the drop it folded back into melts away+ if (ghost) fade.animateTo(0f, androidx.compose.animation.core.tween(110))// 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@@ -273,7 +278,8 @@ internal fun LiquidMorphSurface(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)+ // room for the jelly: the menu stretches up to a tenth of its height past rest as it settles+ val swellPx = menuH * JellyStretch * JellyMax + px(6.dp)val radius24 = px(24.dp)val neckPx = px(22.dp)val opening = !shut@@ -286,25 +292,26 @@ internal fun LiquidMorphSurface(/** 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)+ // set once the opening spring has first reached the menu: from then on its swing past and back is+ // the settling of the glass (jelly), not the path running backwards into the drop+ val arrived = remember { booleanArrayOf(false) }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+ if (opening && raw >= 1f) arrived[0] = true+ // the path through the four states (circle, tall drop, wide, menu) runs from 0 to 1; anything+ // past it is jelly, shown as the menu's own stretch below+ val pv = if (opening && arrived[0]) 1f else raw.coerceAtMost(1f)+ val jelly = if (full > 0 && (raw > 1f || (opening && arrived[0]))) (raw - 1f).coerceIn(-JellyMax, JellyMax) else 0fval 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+ val po = if (full > 0) ease((pv - 0.36f) / 0.64f) 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 ownval 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 path = 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) * poRect(rl, min(top, bottom - 1f), rr, max(bottom, top + 1f))@@ -313,17 +320,37 @@ internal fun LiquidMorphSurface(val top = lerp(local.center.y - local.height * 0.25f, local.top - peek, d) - (local.top - peek - endT) * poRect(rl, min(top, bottom - 1f), rr, max(bottom, top + 1f))}+ // jelly: past rest the menu runs on away from its button and draws in at the sides (taller and+ // narrower, a tall ellipse's moment), then swings back squat and wide, settling; it stays held+ // at the button's corner, as a drop of gel hangs from what it is stuck to+ val menu = if (jelly == 0f) path else {+ val h = path.height * (1f + JellyStretch * jelly)+ val w = path.width * (1f - JellySqueeze * jelly)+ val l = if (fromRight) path.right - w else path.left+ val t = if (below) path.top else path.bottom - h+ Rect(l, t, l + w, t + h)+ }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 menuval 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)+ // how lively the lens and frost are: through the morph's path only, easing out as it lands. (Tied to+ // the jelly's swing it pulsed with every wobble, and the page behind (a white title on the dark+ // theme) flickered sharp and blurred, bent and straight, with it.)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)+ // Adaptive luminance on: at the button's end the glass is the button's own adaptive glass (its+ // reading of what is around it, its frost, colour and milk or smoke), so neither the opening nor+ // the landing ever shows a moment of plain glass where the adaptive button was+ val adaptiveOn = GlassSettings.adaptive+ val around = if (adaptiveOn) MorphAnchors.surroundAt(anchor) else null+ val fallbackLum = if (clear.dark) 0.14f else 0.86f+ fun aroundLum(): Float = around?.value ?: luminance?.value ?: fallbackLumval ink = adaptiveInk(luminance, clear.ink)val style = GlassSettings.styleval dark = clear.dark@@ -351,8 +378,10 @@ internal fun LiquidMorphSurface(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)+ // adaptive blur: the button's clear glass frosts to a menu's as it opens, so rows read+ // over a busy page (as MenuCard's), more over a bright page than a dark one, and a+ // touch more while the glass is on the move+ morphEffects(if (adaptiveOn) style.adaptiveBase else style, luminance?.value ?: if (dark) 0.14f else 0.86f, dark, washIn(), g.motion, px(1.dp), if (adaptiveOn) aroundLum() else null)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@@ -373,8 +402,15 @@ internal fun LiquidMorphSurface(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+ // the milk or smoke a menu wears, thicker than a button's, so its rows read+ val menuWash = adaptiveWash(lum).let { it.copy(alpha = (it.alpha * 1.7f).coerceAtMost(0.55f)) }.glassTint(style)+ val plain = menuWash.let { it.copy(alpha = it.alpha * w) }+ val wash = when {+ tint.isSpecified -> androidx.compose.ui.graphics.lerp(tint.copy(alpha = 0.75f), plain, w)+ // the adaptive button's own wash at its end, the menu's as it opens+ adaptiveOn -> androidx.compose.ui.graphics.lerp(adaptiveWash(aroundLum()).let { it.copy(alpha = it.alpha * 0.7f) }, menuWash, w)+ else -> plain+ }surface.setFloatUniform("wash", wash.red, wash.green, wash.blue, wash.alpha)surface.setFloatUniform("rimAlpha", rimAlpha)surface.shapeUniforms(g)@@ -396,14 +432,20 @@ internal fun LiquidMorphSurface(.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) },+ // exactly as GlassCircle draws itself, adaptive or not+ effects = {+ if (adaptiveOn) adaptiveGlassEffects(style.adaptiveBase, aroundLum(), px(2.dp), px(12.dp), px(24.dp))+ else glassEffects(style, px(2.dp), px(12.dp), px(24.dp))+ },+ highlight = { glassHighlight(if (adaptiveOn) style.adaptiveBase else style) },shadow = null,onDrawSurface = {- // as GlassCircle paints a tinted button+ // as GlassCircle paints a tinted button, or its adaptive milk or smokeif (tint.isSpecified) {drawRect(tint, blendMode = androidx.compose.ui.graphics.BlendMode.Hue)drawRect(tint.copy(alpha = 0.75f))+ } else if (adaptiveOn) {+ drawRect(adaptiveWash(aroundLum()).let { it.copy(alpha = it.alpha * 0.7f) })}},),@@ -444,7 +486,7 @@ internal fun LiquidMorphSurface() {Column(Modifier.heightIn(max = maxHeight).verticalScroll(rememberScrollState())) {Spacer(Modifier.height(6.dp))- items.forEach { item -> MorphMenuRow(item, shut) { chosenAction = item.onClick; onDismiss() } }+ body(shut) { action -> if (chosenAction == null) { chosenAction = action; onDismiss() } }Spacer(Modifier.height(6.dp))}}@@ -459,3 +501,40 @@ private class RectClip(private val r: Rect, private val radius: Float) : androidoverride 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)))}++/** How much taller the menu runs per unit of the spring's swing past rest (the jelly). */+private const val JellyStretch = 0.24f++/** How much it draws in at the sides meanwhile (gel keeps its volume). */+private const val JellySqueeze = 0.1f++/** The furthest swing shown, either way (Jelly at its springiest). */+private const val JellyMax = 0.4f++/** [luminance] as -1 (dark) … 1 (light), eased so mid-greys stay near neutral (as AdaptiveGlass's). */+private fun signedLum(luminance: Float): Float = (luminance * 2f - 1f).let { kotlin.math.sign(it) * it * it }++/**+ * The morph's colour and frost: at [open] 0 the button's own glass (the user's style, a light frost),+ * at 1 a menu's frost that answers what is behind it (brighter and more frosted over a light page,+ * deeper over a dark one, as [MenuCard] with Adaptive luminance). [motion] adds a little frost while+ * the glass moves, so it reads as liquid rushing rather than a sharp shape sliding. [dp] is one dp.+ */+private fun com.kyant.backdrop.BackdropEffectScope.morphEffects(style: GlassStyle, luminance: Float, dark: Boolean, open: Float, motion: Float, dp: Float, buttonLuminance: Float? = null) {+ val l = signedLum(luminance.coerceIn(0f, 1f))+ val o = open.coerceIn(0f, 1f)+ val menuBrightness = if (l > 0f) lerp(0.08f, 0.3f, l) else lerp(if (dark) -0.12f else 0.04f, -0.24f, -l)+ // the button's end: plain glass, or (Adaptive luminance) the adaptive button's own colour and frost,+ // as adaptiveGlassEffects sets them from the reading around the button+ val b = buttonLuminance?.let { signedLum(it.coerceIn(0f, 1f)) }+ val buttonBrightness = if (b == null) style.brightness else (if (b > 0f) lerp(0.08f, 0.42f, b) else lerp(0.08f, -0.2f, -b)) + style.brightness+ val buttonContrast = if (b != null && b > 0f) lerp(1f, 0.25f, b) else 1f+ colorControls(+ brightness = lerp(buttonBrightness, menuBrightness, o),+ contrast = lerp(buttonContrast, if (l > 0f) lerp(1f, 0.5f, l) else 1f, o),+ saturation = lerp(style.saturation, 1.25f, o),+ )+ val buttonBlur = 2f * dp * style.blur * (if (b == null) 1f else if (b > 0f) lerp(1f, 1.5f, b) else lerp(1f, 0.6f, -b))+ val menuBlur = 22f * dp * (if (l > 0f) lerp(1f, 1.35f, l) else lerp(1f, 0.75f, -l))+ blur(lerp(buttonBlur, menuBlur, o) + 5f * dp * motion.coerceIn(0f, 1f))+}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.ktindex e6704dd..fc678f5 100644--- 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@@ -86,6 +86,8 @@ fun MorphButton(size: Dp = HeaderButtonSize,menuWidth: Dp = 236.dp,enabled: Boolean = true,+ /** A wash over the button's glass (unspecified: none). */+ surface: Color = Color.Unspecified,icon: @Composable () -> Unit,) {var open by remember { mutableStateOf(false) }@@ -96,6 +98,7 @@ fun MorphButton(modifier = modifier.onGloballyPositioned { anchor = it.boundsInWindow() }.graphicsLayer { alpha = if (up) 0f else 1f },size = size,label = label,+ surface = surface,) { icon() }if (up) MorphButtonSurface(anchor, open, onDismiss = { open = false }, onGone = { up = false }, items = items, menuWidth = menuWidth, icon = icon)}@@ -115,6 +118,27 @@ fun MorphButtonSurface(menuWidth: Dp = 236.dp,maxHeight: Dp = 480.dp,icon: (@Composable () -> Unit)? = null,+) = MorphButtonSurface(anchor, open, onDismiss, onGone, menuWidth, maxHeight, icon) { shut, choose ->+ items.forEach { item -> MorphMenuRow(item, shut) { choose(item.onClick) } }+}++/**+ * [MorphButtonSurface] holding any menu: [body] lays out its rows, and calls `choose(action)` for a+ * row that closes the menu (the glass folds back into the button first, then the action runs);+ * anything else (a star that flips in place) it does itself. [ghost]: no real button sits at+ * [anchor] (a menu a long press opened): the glass folds back into a drop there that melts away.+ */+@Composable+fun MorphButtonSurface(+ anchor: Rect,+ open: Boolean,+ onDismiss: () -> Unit,+ onGone: () -> Unit,+ menuWidth: Dp = 236.dp,+ maxHeight: Dp = 480.dp,+ icon: (@Composable () -> Unit)? = null,+ ghost: Boolean = false,+ body: @Composable androidx.compose.foundation.layout.ColumnScope.(shut: Boolean, choose: (() -> Unit) -> Unit) -> Unit,) {// 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@@ -128,9 +152,9 @@ fun MorphButtonSurface(val glyph: @Composable () -> Unit = icon ?: MorphAnchors.glyphAt(anchor) ?: {}// Android 13+: the liquid version (the glass shaders it needs); before that the plain expansionif (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {- LiquidMorphSurface(anchor, open, onDismiss, gone, items, menuWidth, maxHeight, glyph)+ LiquidMorphSurface(anchor, open, onDismiss, gone, menuWidth, maxHeight, glyph, ghost, body)} else {- RectMorphSurface(anchor, open, onDismiss, gone, items, menuWidth, maxHeight, glyph)+ RectMorphSurface(anchor, open, onDismiss, gone, menuWidth, maxHeight, glyph, ghost, body)}}@@ -166,6 +190,13 @@ object MorphAnchors {internal fun tintAt(r: Rect): Color? = tints[key(r)]+ private val surrounds = HashMap<Long, SurroundLuminance>()++ /** The adaptive reading around the button at [r] (null: Adaptive luminance is off). */+ internal fun setSurround(r: Rect, s: SurroundLuminance?) { if (s != null) surrounds[key(r)] = s else surrounds.remove(key(r)) }++ internal fun surroundAt(r: Rect): SurroundLuminance? = surrounds[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@@ -180,10 +211,11 @@ private fun RectMorphSurface(open: Boolean,onDismiss: () -> Unit,onGone: () -> Unit,- items: List<GlassMenuItem>,- menuWidth: Dp = 236.dp,- maxHeight: Dp = 480.dp,+ menuWidth: Dp,+ maxHeight: Dp,icon: @Composable () -> Unit,+ ghost: Boolean,+ body: @Composable androidx.compose.foundation.layout.ColumnScope.(shut: Boolean, choose: (() -> Unit) -> Unit) -> Unit,) {val gone by rememberUpdatedState(onGone)GlassOverlay(animatesOut = true) {@@ -217,17 +249,19 @@ private fun RectMorphSurface(LaunchedEffect(shut) {if (!shut) {coroutineScope {- launch { drop.animateTo(1f, spring(MotionSettings.damping(0.82f), MotionSettings.stiffness(318f), 0.0005f)) }+ // each on a spring at the user's bounce (Settings ▸ Motion), the next joining before the+ // last has landed, so the glass swings past each state and the swing flows on+ launch { drop.animateTo(1f, spring(maxOf(MotionSettings.damping(0.62f), 0.3f), 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))+ androidx.compose.runtime.snapshotFlow { drop.value >= 0.45f }.first { it }+ wide.animateTo(1f, spring(maxOf(MotionSettings.damping(0.58f), 0.3f), 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))+ androidx.compose.runtime.snapshotFlow { wide.value >= 0.45f }.first { it }+ tall.animateTo(1f, spring(maxOf(MotionSettings.damping(0.6f), 0.3f), MotionSettings.stiffness(181f), 0.0005f))}}- } else if (MorphAnchors.glyphAt(anchor) == null) {+ } else if (!ghost && MorphAnchors.glyphAt(anchor) == null) {fade.animateTo(0f, androidx.compose.animation.core.tween(150))gone()presence?.done()@@ -244,6 +278,7 @@ private fun RectMorphSurface(drop.animateTo(0f, spring(1f, MotionSettings.stiffness(423f), 0.0005f))}}+ if (ghost) fade.animateTo(0f, androidx.compose.animation.core.tween(110))gone()presence?.done()runChosen()@@ -263,7 +298,7 @@ private fun RectMorphSurface(// 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 curveval menuNow = if (full > 0) full.toFloat() else local.height- val curW = lerp(local.width, widthPx, wide.value)+ val curW = lerp(local.width, widthPx, wide.value.coerceAtMost(MaxSwingWide))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)@@ -313,7 +348,7 @@ private fun RectMorphSurface() {Column(Modifier.heightIn(max = maxHeight).verticalScroll(rememberScrollState())) {Spacer(Modifier.height(6.dp))- items.forEach { item -> MorphMenuRow(item, shut) { chosenAction = item.onClick; onDismiss() } }+ body(shut) { action -> if (chosenAction == null) { chosenAction = action; onDismiss() } }Spacer(Modifier.height(6.dp))}}@@ -340,7 +375,7 @@ private fun RectMorphSurface(// the menu grows from the button's own corner and rests over the place the button wasval 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 gw = wide.value.coerceAtMost(MaxSwingWide)val gh = if (full > 0) tall.value else 0fval l = lerp(local.left, endL, gw)val r = lerp(local.right, endL + widthPx, gw)@@ -388,5 +423,9 @@ internal fun MorphMenuRow(item: GlassMenuItem, shut: Boolean, close: () -> Unit)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)+ return (button + first * drop.coerceAtMost(1.15f) + rest * tall.coerceAtMost(MaxSwingTall)).coerceAtLeast(1f)}++/** How far past the menu's width and height the springs may swing the glass (the jelly). */+private const val MaxSwingWide = 1.05f+private const val MaxSwingTall = 1.12fdiff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Motion.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Motion.ktindex 94fe20e..c4bd86e 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Motion.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Motion.kt@@ -223,6 +223,21 @@ object GlassMotion {private const val ShapeMinDamping = 0.46f+ /**+ * A round glass button opening into its menu (`LiquidMorph.kt`): the whole drip, spread and pour on+ * one spring that, at the user's bounce, swings past the menu and back as jelly does (Calm barely,+ * Jelly three or four times). A floor on damping keeps Jelly from ringing on.+ */+ fun morphOpen(): SpringSpec<Float> = spring(maxOf(MotionSettings.damping(0.6f), MorphMinDamping), MotionSettings.stiffness(150f), Rest)++ /** The menu flowing back into its button when dismissed: unhurried, and it lands without a bounce. */+ fun morphClose(): SpringSpec<Float> = spring(1f, MotionSettings.stiffness(150f), 0.01f)++ /** The same after a row was chosen: quicker, done the moment it looks landed (the row's action waits on it). */+ fun morphChosen(): SpringSpec<Float> = spring(1f, MotionSettings.stiffness(300f), 0.03f)++ private const val MorphMinDamping = 0.3f+/** A tap shorter than this still plays the whole press. */const val MinPressMillis = 90L}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.ktindex d7e239c..37387f8 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,6 +1,7 @@package com.chethan616.clearpdf.ui.homeimport androidx.compose.ui.layout.boundsInRoot+import androidx.compose.ui.layout.boundsInWindowimport androidx.compose.ui.layout.onGloballyPositionedimport android.graphics.BitmapFactory@@ -585,7 +586,7 @@ fun StackCard(* and menu buttons (follows Settings ▸ liquid glass and motion), with white ink for the photo behind.*/@Composable-fun PhotoChip(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, icon: ImageVector? = null) {+fun PhotoChip(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, icon: ImageVector? = null, style: androidx.compose.ui.text.TextStyle = ClearType.Label.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)) {// white over a photo; with Adaptive luminance, dark wherever the glass turns lightval ink = com.chethan616.clearpdf.ui.glass.rememberGlassInk(Color.White)GlassChip(@@ -593,7 +594,7 @@ fun PhotoChip(text: String, onClick: () -> Unit, modifier: Modifier = Modifier,horizontalArrangement = Arrangement.spacedBy(6.dp), ink = ink.color,) {if (icon != null) Icon(icon, null, tint = ink.color, modifier = Modifier.size(15.dp))- Text(text, style = ClearType.Label.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold), color = ink.color, maxLines = 1)+ Text(text, style = style, color = ink.color, maxLines = 1)}}@@ -617,10 +618,24 @@ fun RecentCard(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,+ /** The card's word: "Recent", or "Starred" for the Starred widget. */+ title: String = stringResource(R.string.desk_recent),+ /** The card's colour: sky for Recent, lavender for Starred. */+ cardTone: Tone = Tone.Sky,+ /** A star on the card's corner (the Starred widget). */+ starred: Boolean = false,+ /** A long press: the newest document's menu, from where the finger is. */+ onLong: ((androidx.compose.ui.geometry.Rect) -> Unit)? = null,) {- val tone = clear.tone(Tone.Sky)+ val tone = clear.tone(cardTone)val top = rows.first()- Box(modifier.height(226.dp).pressable(top.open, { vm.fileSheet = top to true }, pressedScale = 0.95f)) {+ var bounds by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }+ Box(+ modifier.height(226.dp)+ .onGloballyPositioned { bounds = it.boundsInWindow() }+ // a tap opens Recent in Files (the list, not the newest document by itself)+ .pressable(onAll, onLong?.let { { it(bounds) } }, pressedScale = 0.95f),+ ) {// a blush card peeking out behind, turnedBox(Modifier.fillMaxSize().padding(vertical = 8.dp).graphicsLayer { rotationZ = 5f; translationX = 8.dp.toPx() }.clip(CardShape).background(Brush.verticalGradient(listOf(clear.tone(Tone.Blush).top, clear.tone(Tone.Blush).bottom))))// the card and the pages fanned on it are the layer the chips' glass refracts@@ -629,8 +644,13 @@ fun RecentCard(paint = {Box(Modifier.fillMaxSize().cardPaint(tone, Offset(0.9f, 0.0f)))Column(Modifier.padding(start = 16.dp, top = 14.dp, end = 16.dp)) {- Text(stringResource(R.string.desk_recent), style = ClearType.Title.copy(fontSize = 17.sp), color = tone.ink, maxLines = 1)- Text(whenLabel(top.date), style = ClearType.Caption.copy(fontSize = 10.5.sp), color = tone.ink.copy(alpha = 0.6f), maxLines = 1)+ Text(title, style = ClearType.RecentTitle, color = tone.ink, maxLines = 1)+ Text(whenLabel(top.date), style = ClearType.RecentWhen, color = tone.ink.copy(alpha = 0.6f), maxLines = 1)+ }+ if (starred) {+ Box(Modifier.align(Alignment.TopEnd).padding(12.dp).size(30.dp).clip(CircleShape).background(Color.White), contentAlignment = Alignment.Center) {+ Icon(LucideIcons.Star, null, tint = com.chethan616.clearpdf.ui.theme.Candy.Lemon, modifier = Modifier.size(17.dp))+ }}// up to three first pages, fanned; the newest on topval shown = rows.take(3)@@ -649,15 +669,38 @@ fun RecentCard(opaque = true,) {Row(Modifier.align(Alignment.BottomStart).padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {- if (rows.size > 1) PhotoChip("+${rows.size - 1}", onAll)+ if (rows.size > 1) PhotoChip("+${rows.size - 1}", onAll, style = ClearType.RecentChip)// what the newest is: PDFs, Pictures, Spreadsheets, Mind maps …val kind = com.chethan616.clearpdf.engine.DocumentTypes.kindOf(top.name)- PhotoChip(stringResource(kind.short), onAll, icon = kind.icon)+ PhotoChip(stringResource(kind.short), onAll, icon = kind.icon, style = ClearType.RecentChip)}}}}+/**+ * The Starred widget before anything is starred: the butter card, a big lemon star, and how to star+ * a file.+ */+@Composable+fun StarredEmptyCard(modifier: Modifier = Modifier) {+ // lavender: the one light tone made for white ink, so the glass and words on it read+ val tone = clear.tone(Tone.Lavender)+ Box(modifier.height(226.dp).cardPaint(tone, Offset(0.9f, 0.0f))) {+ Column(Modifier.padding(start = 16.dp, top = 14.dp, end = 16.dp)) {+ Text(stringResource(R.string.home_list_starred), style = ClearType.Title.copy(fontSize = 17.sp), color = tone.ink, maxLines = 1)+ }+ Box(Modifier.align(Alignment.Center).size(78.dp).clip(CircleShape).background(Color.White.copy(alpha = 0.55f)), contentAlignment = Alignment.Center) {+ Icon(LucideIcons.Star, null, tint = com.chethan616.clearpdf.ui.theme.Candy.Lemon, modifier = Modifier.size(40.dp))+ }+ Text(+ stringResource(R.string.widget_starred_empty), style = ClearType.Label, color = tone.ink.copy(alpha = 0.7f),+ textAlign = androidx.compose.ui.text.style.TextAlign.Center,+ modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth().padding(horizontal = 16.dp, vertical = 16.dp),+ )+ }+}+// ---- A single document ---------------------------------------------------------------------------/** One PDF on the desk: its first page tilted on a tinted card, its name under it. */@@ -666,7 +709,7 @@ fun DocCard(vm: AppViewModel, r: FileRow, tone: CardTone, tilt: Float, onLong: (Column(modifier.pressable(r.open, onLong, pressedScale = 0.95f).cardPaint(tone, Offset(0.8f, 0.0f)).padding(14.dp)) {Box(Modifier.fillMaxWidth().height(150.dp), contentAlignment = Alignment.Center) {PaperThumb(vm, r.thumbPath, 104.dp, 136.dp, tilt = tilt, corner = 8.dp, name = r.name, modifier = Modifier.graphicsLayer { shadowElevation = 10.dp.toPx(); shape = RoundedRectangle(8.dp) })- if (r.starred) {+ if (vm.isStarred(r)) {Box(Modifier.align(Alignment.TopEnd).size(26.dp).clip(CircleShape).background(Color.White), contentAlignment = Alignment.Center) {Icon(LucideIcons.Star, null, tint = com.chethan616.clearpdf.ui.theme.Candy.Lemon, modifier = Modifier.size(14.dp))}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/DeskPages.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/DeskPages.ktnew file mode 100644index 0000000..197921b--- /dev/null+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/DeskPages.kt@@ -0,0 +1,691 @@+package com.chethan616.clearpdf.ui.home++import androidx.compose.animation.animateContentSize+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.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.navigationBarsPadding+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBars+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.windowInsetsTopHeight+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+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.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.saveable.rememberSaveable+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.layout.onSizeChanged+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.ui.layout.layout+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.draw.blur+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.chethan616.clearpdf.R+import com.chethan616.clearpdf.notes.Note+import com.chethan616.clearpdf.notes.NoteKind+import com.chethan616.clearpdf.ui.AppViewModel+import com.chethan616.clearpdf.ui.LucideIcons+import com.chethan616.clearpdf.ui.glass.GlassBackButton+import com.chethan616.clearpdf.ui.glass.GlassCircle+import com.chethan616.clearpdf.ui.glass.GlassIcon+import com.chethan616.clearpdf.ui.glass.GlassMenuItem+import com.chethan616.clearpdf.ui.glass.GlassMotion+import com.chethan616.clearpdf.ui.glass.GlassPill+import com.chethan616.clearpdf.ui.glass.MorphButton+import com.chethan616.clearpdf.ui.glass.RoundedRectangle+import com.chethan616.clearpdf.ui.glass.pressable+import com.chethan616.clearpdf.ui.theme.Candy+import com.chethan616.clearpdf.ui.theme.ClearType+import com.chethan616.clearpdf.ui.theme.Tone+import com.chethan616.clearpdf.ui.theme.clear+import com.chethan616.clearpdf.ui.theme.glowing+import kotlinx.coroutines.launch+import java.text.DateFormat+import java.util.Calendar+import java.util.Date++/** A page of the desk's own besides the bento: the day's greeting, and the thoughts as a deck of cards. */+enum class DeskPage { Today, Thoughts }++/** A picture in a note, with the note it is in (the desk's Highlights). */+data class NotePicture(val note: Note, val name: String)++/** Every picture in the notes, the newest note's first. */+fun notePictures(notes: List<Note>): List<NotePicture> =+ notes.filter { it.images.isNotEmpty() }.sortedByDescending { it.updated }.flatMap { n -> n.images.map { NotePicture(n, it) } }++/** The documents made with Scan ("Scan 2026-…"), newest first: the desk's Snapshots. */+fun scanRows(rows: List<FileRow>): List<FileRow> = rows.filter { it.name.startsWith("Scan ", ignoreCase = true) }++// ---- the desk's two picture cards -----------------------------------------------------------------++/** Highlights: the pictures in the notes, the newest filling the card, "+N" and Photos to see them all. */+@Composable+fun HighlightsCard(pictures: List<NotePicture>, onOpen: () -> Unit, onAll: () -> Unit, modifier: Modifier = Modifier) {+ val first = pictures.first()+ StackCard(+ stringResource(R.string.desk_highlights), shortDate(first.note.updated),+ listOf(clear.tone(Tone.Blush), clear.tone(Tone.Peach)), onOpen, modifier, height = 214.dp,+ chips = {+ Row(Modifier.align(Alignment.BottomStart).padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if (pictures.size > 1) PhotoChip("+${pictures.size - 1}", onAll)+ PhotoChip(stringResource(R.string.home_photos), onAll, icon = LucideIcons.Images)+ }+ },+ ) { NoteImage(first.name, Modifier.matchParentSize(), maxPx = 900) }+}++/** Snapshots: the documents made with Scan, the newest page filling the card, "+N" in the corner. */+@Composable+fun SnapshotsCard(vm: AppViewModel, scans: List<FileRow>, onOpen: () -> Unit, modifier: Modifier = Modifier) {+ val first = scans.first()+ StackCard(+ stringResource(R.string.desk_snapshots), whenLabel(first.date),+ listOf(clear.tone(Tone.Butter)), onOpen, modifier, height = 196.dp,+ chips = { if (scans.size > 1) PhotoChip("+${scans.size - 1}", onOpen, Modifier.align(Alignment.BottomEnd).padding(12.dp)) },+ ) { PageFill(vm, first.thumbPath) }+}++// ---- The mock's measures ---------------------------------------------------------------------------++/*+ * Thought of the day and Today are built to the design mock (needed.png) one to one. Every measure+ * below is read off the mock in its own pixels (each phone screen there is 491 px wide, measured+ * from its bezel; positions are from the screen's top-left corner) and scaled to this screen's width,+ * so on the 354 dp phone 1 mock px is 0.721 dp. Type sizes were fitted to the mock's own glyphs with+ * Outfit (its face), weight by weight.+ */++/** Mock pixels to dp on this screen. */+@Composable+private fun mockScale(): Float = androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp / MockWidth++private const val MockWidth = 491f++/** The scale the type sizes below were fitted at (354 dp over 491 mock px). */+private const val FitScale = 354f / MockWidth++/** [px] mock pixels as dp at scale [k]. */+private fun m(px: Number, k: Float): androidx.compose.ui.unit.Dp = (px.toFloat() * k).dp++/** A fitted type size (sp at the fitting scale) at this screen's scale. */+private fun s(sp: Float, k: Float) = (sp * k / FitScale).sp++/** Outfit at [weight], [size], [tracking] (em) and [line] height. */+private fun outfit(weight: Int, size: androidx.compose.ui.unit.TextUnit, tracking: Float = 0f, line: androidx.compose.ui.unit.TextUnit = androidx.compose.ui.unit.TextUnit.Unspecified) =+ androidx.compose.ui.text.TextStyle(+ fontFamily = com.chethan616.clearpdf.ui.theme.Outfit, fontWeight = androidx.compose.ui.text.font.FontWeight(weight), fontSize = size,+ letterSpacing = (tracking * size.value).sp, lineHeight = line,+ lineHeightStyle = androidx.compose.ui.text.style.LineHeightStyle(androidx.compose.ui.text.style.LineHeightStyle.Alignment.Center, androidx.compose.ui.text.style.LineHeightStyle.Trim.None),+ platformStyle = androidx.compose.ui.text.PlatformTextStyle(includeFontPadding = false),+ )++/** Places this text so its first baseline is at [y] (and its left edge at [x], when given) in its parent. */+private fun Modifier.baselineAt(x: androidx.compose.ui.unit.Dp?, y: androidx.compose.ui.unit.Dp) = layout { measurable, c ->+ val p = measurable.measure(c)+ val b = p[androidx.compose.ui.layout.FirstBaseline].takeIf { it != androidx.compose.ui.layout.AlignmentLine.Unspecified } ?: p.height+ layout(p.width, p.height) { p.place(x?.roundToPx() ?: 0, y.roundToPx() - b) }+}++/**+ * Children stacked by baselines, as the mock spaces them: each text's first baseline lands [gaps]`[i]`+ * below the last baseline (or the bottom, for a picture) of the one before; [after] closes it.+ */+@Composable+private fun BaselineStack(gaps: List<androidx.compose.ui.unit.Dp>, after: androidx.compose.ui.unit.Dp, modifier: Modifier = Modifier, content: @Composable () -> Unit) =+ androidx.compose.ui.layout.Layout(content, modifier) { ms, c ->+ val ps = ms.map { it.measure(c.copy(minHeight = 0)) }+ var y = 0+ val ys = IntArray(ps.size)+ ps.forEachIndexed { i, p ->+ val fb = p[androidx.compose.ui.layout.FirstBaseline]+ val lb = p[androidx.compose.ui.layout.LastBaseline]+ val gap = gaps.getOrElse(i) { 0.dp }.roundToPx()+ if (fb != androidx.compose.ui.layout.AlignmentLine.Unspecified) {+ ys[i] = y + gap - fb+ y = ys[i] + lb+ } else {+ ys[i] = y + gap+ y = ys[i] + p.height+ }+ }+ layout(c.maxWidth, y + after.roundToPx()) { ps.forEachIndexed { i, p -> p.place(0, ys[i]) } }+ }++/**+ * The mock's soft fade of a title or a card's last lines into blur: sharp above [from] (a share of its+ * height), more and more blurred below, by [blur] at the bottom.+ */+@Composable+private fun FadeIntoBlur(from: Float, blur: androidx.compose.ui.unit.Dp, modifier: Modifier = Modifier, content: @Composable () -> Unit) {+ Box(modifier) {+ Box(+ Modifier.graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }+ .drawWithContent {+ drawContent()+ drawRect(Brush.verticalGradient(0f to Color.Black, from to Color.Black, 1f to Color.Transparent), blendMode = androidx.compose.ui.graphics.BlendMode.DstIn)+ },+ ) { content() }+ Box(+ Modifier.graphicsLayer {+ val r = blur.toPx()+ renderEffect = androidx.compose.ui.graphics.BlurEffect(r, r, androidx.compose.ui.graphics.TileMode.Decal)+ compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen+ }.drawWithContent {+ drawContent()+ drawRect(Brush.verticalGradient(0f to Color.Transparent, from to Color.Transparent, 1f to Color.Black), blendMode = androidx.compose.ui.graphics.BlendMode.DstIn)+ },+ ) { content() }+ }+}++// ---- Thought of the day -----------------------------------------------------------------------------++/** What the thoughts deck shows: words, pictures or voice. */+private enum class ThoughtShelf(val label: Int) { Text(R.string.desk_text), Images(R.string.desk_filter_images), Audios(R.string.thoughts_audios) }++/**+ * Thought of the day (the mock's second screen): Back and More, the title large and white fading into+ * blur on its second line, Text / Images / Audios in clear glass, and the notes as a deck: the front+ * card pure white over a cream one and a pink one peeking out above it. Swipe the front card away+ * and the next comes forward; tap it, or its pencil, to open it. "Create new" sits on the deck's foot.+ */+@Composable+fun ThoughtsScreen(vm: AppViewModel, desk: DeskState) {+ val k = mockScale()+ var shelf by rememberSaveable { mutableStateOf(ThoughtShelf.Text) }+ val all = vm.notes.all+ val notes = remember(all, shelf) {+ when (shelf) {+ ThoughtShelf.Text -> all.filter { it.kind == NoteKind.Text && !it.isEmpty }+ ThoughtShelf.Images -> all.filter { it.images.isNotEmpty() }+ ThoughtShelf.Audios -> all.filter { it.kind == NoteKind.Voice }+ }.sortedWith(compareByDescending<Note> { it.thought != 0L }.thenByDescending { it.updated })+ }+ var front by rememberSaveable(shelf) { mutableIntStateOf(0) }+ // voice memos play right on the card, as on the desk+ val scope = rememberCoroutineScope()+ val player = remember { com.chethan616.clearpdf.ui.viewer.VoicePlayer(scope) }+ var playing by remember { mutableStateOf<String?>(null) }+ androidx.compose.runtime.DisposableEffect(Unit) { onDispose { player.release() } }+ fun play(n: Note) {+ val f = n.audio?.let(vm.notes::file) ?: return+ if (playing == n.id) player.toggle() else if (player.load(f)) { playing = n.id; player.toggle() }+ }+ // a long press on the card: the desk's own note menu+ var actionsFor by remember { mutableStateOf<Note?>(null) }+ var actionsAnchor by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }+ Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {+ Box(Modifier.fillMaxWidth().height(m(1068, k))) {+ // Back and More: the desk's own header buttons, where the desk's header puts them+ DeskHeaderRow(+ leading = { GlassBackButton({ vm.closeDeskPage() }) },+ trailing = {+ MorphButton(+ items = listOf(+ GlassMenuItem(stringResource(R.string.create_note), LucideIcons.SquarePen) { vm.newNote(NoteKind.Text) },+ GlassMenuItem(stringResource(R.string.create_voice), LucideIcons.Mic) { desk.startRecording(vm) },+ GlassMenuItem(stringResource(R.string.today_title), LucideIcons.Sun) { vm.openDeskPage(DeskPage.Today) },+ GlassMenuItem(stringResource(R.string.home_settings), LucideIcons.Settings) { vm.settingsOpen = true },+ ),+ label = stringResource(R.string.common_more_options),+ ) { GlassIcon(LucideIcons.Ellipsis, null, Modifier.size(20.dp)) }+ },+ )+ // the title: Outfit 500 at 55.5 (fitted), baselines at 239 and 323 px, its second line in blur+ FadeIntoBlur(0.5f, m(3.2f, k), Modifier.fillMaxWidth().baselineAt(null, m(239, k))) {+ Text(+ stringResource(R.string.thought_title),+ style = outfit(500, s(55.5f, k), -0.016f, (84 * k).sp).copy(color = Color.White, textAlign = TextAlign.Center),+ modifier = Modifier.fillMaxWidth().padding(horizontal = m(40, k)),+ )+ }+ // the shelves: the desk's own chips (the chosen one filled), centred on the mock's row (397 px)+ Row(+ Modifier.fillMaxWidth().offset(y = m(397, k) - 23.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.CenterHorizontally),+ ) {+ ThoughtShelf.entries.forEach { sh -> DeskChip(stringResource(sh.label), sh == shelf) { shelf = sh } }+ }+ // the deck from 452 px (the pink card's top), Create new on its foot+ Column(Modifier.fillMaxWidth().offset(y = m(452, k)), horizontalAlignment = Alignment.CenterHorizontally) {+ if (notes.isEmpty()) {+ Text(+ stringResource(R.string.thoughts_empty), style = outfit(400, s(12.9f, k)).copy(color = Color(0xFF2C1E3D), textAlign = TextAlign.Center),+ modifier = Modifier.padding(top = m(60, k), bottom = m(60, k)).padding(horizontal = m(40, k)),+ )+ } else {+ ThoughtDeck(+ vm, notes, front.coerceIn(0, notes.lastIndex), k,+ playing = { n -> playing == n.id && player.playing },+ progress = { n -> if (playing == n.id && player.durationMs > 0) player.positionMs / player.durationMs.toFloat() else -1f },+ onPlay = ::play,+ onLong = { n, at -> actionsAnchor = at; actionsFor = n },+ ) { front = (front + 1) % notes.size }+ }+ CreateNewPill(k, Modifier.offset(y = -m(13, k))) {+ when (shelf) {+ ThoughtShelf.Text -> vm.newNote(NoteKind.Text)+ ThoughtShelf.Images -> { vm.newNote(NoteKind.Text); vm.pickNotePhoto() }+ // records here, in the dock, and the memo joins the deck+ ThoughtShelf.Audios -> desk.startRecording(vm)+ }+ }+ }+ }+ }+ actionsFor?.let { n -> NoteActions(vm, n, actionsAnchor, onRename = { desk.naming = n.id }) { actionsFor = null } }+ desk.naming?.let { id -> vm.notes.get(id)?.let { n -> NameSheet(vm, n) { desk.naming = null } } }+}++/**+ * The desk's header row, as [DeskHeader] lays it out (the grid's 16 dp edge plus its own 6 and 4 dp,+ * 14 dp under the status bar): [leading] on the left, [trailing] on the right, the desk's own sizes.+ */+@Composable+internal fun DeskHeaderRow(leading: @Composable () -> Unit, trailing: @Composable () -> Unit) {+ Column(Modifier.fillMaxWidth()) {+ Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars))+ Row(Modifier.fillMaxWidth().padding(start = 22.dp, top = 14.dp, end = 20.dp), verticalAlignment = Alignment.CenterVertically) {+ leading()+ Spacer(Modifier.weight(1f))+ trailing()+ }+ }+}++/** The mock's "Create new": a white pill (190 × 56 px) in a slate glass ring (212 × 79 px). */+@Composable+private fun CreateNewPill(k: Float, modifier: Modifier, onClick: () -> Unit) {+ Box(+ modifier.size(m(212, k), m(79, k)).clip(androidx.compose.foundation.shape.CircleShape).background(Color(0xFF4E5E78).copy(alpha = 0.94f))+ .pressable(onClick, pressedScale = 0.94f),+ contentAlignment = Alignment.Center,+ ) {+ Box(Modifier.size(m(190, k), m(56, k)).clip(androidx.compose.foundation.shape.CircleShape).background(Color.White)) {+ // the plus: 20 px, 24 px in from the pill's left+ androidx.compose.foundation.Canvas(Modifier.offset(m(24, k), m(18, k)).size(m(20, k))) {+ val w = 2.4f * k.dp.toPx()+ drawLine(Color.Black, Offset(0f, size.height / 2), Offset(size.width, size.height / 2), w, androidx.compose.ui.graphics.StrokeCap.Round)+ drawLine(Color.Black, Offset(size.width / 2, 0f), Offset(size.width / 2, size.height), w, androidx.compose.ui.graphics.StrokeCap.Round)+ }+ Text(+ stringResource(R.string.thoughts_create_new), style = outfit(400, s(15.3f, k), -0.014f).copy(color = Color.Black),+ modifier = Modifier.baselineAt(m(57, k), m(32, k)),+ )+ }+ }+}++/**+ * The deck: the pink card (inset 64 px, its top at 0), the cream card (inset 29 px, 24 px lower) and+ * the white front card (inset 34 px... 457, 60 px lower), as the mock stacks them. The front card+ * follows a sideways drag, leans, and past a third of its width flies off; the next comes forward.+ */+@Composable+private fun ThoughtDeck(+ vm: AppViewModel,+ notes: List<Note>,+ front: Int,+ k: Float,+ playing: (Note) -> Boolean,+ progress: (Note) -> Float,+ onPlay: (Note) -> Unit,+ onLong: (Note, androidx.compose.ui.geometry.Rect) -> Unit,+ onNext: () -> Unit,+) {+ // the deck as the mock stacks it: up to three of the notes themselves (never a blank card), the+ // front one white, the next a step back (36 px up, 29 px in from each side) in cream, the one after+ // two steps back (60 px up, 64 px in) in pink, each further back softer and more blurred+ val shown = (0 until minOf(3, notes.size)).map { notes[(front + it) % notes.size] }+ var frontHeight by remember { mutableIntStateOf(0) }+ // the deck's height follows the front card's on a spring, so Create new glides as cards change+ BoxWithConstraints(Modifier.fillMaxWidth().animateContentSize(androidx.compose.animation.core.spring(1f, 500f)).padding(top = m(60, k))) {+ val width = constraints.maxWidth.toFloat()+ // back to front, so the front card is drawn last; each card keeps its own place (keyed by its+ // note) as it moves from depth to depth, so a card swiped away tucks in behind the others+ for (depth in shown.indices.reversed()) {+ val n = shown[depth]+ androidx.compose.runtime.key(n.id) {+ DeckCard(+ vm, n, depth, shown.size, k, width, frontHeight,+ playing(n), { progress(n) }, { onPlay(n) }, { at -> onLong(n, at) },+ onMeasured = { if (depth == 0) frontHeight = it },+ onSwipedAway = onNext,+ )+ }+ }+ }+}++/**+ * One card of the deck at [depth] (0 front). The front card follows a sideways drag and leans; let go+ * past a quarter of the width (or flung), it slides aside and goes to the back of the deck while the+ * next one comes forward, both on springs; short of that it springs back.+ */+@Composable+private fun DeckCard(+ vm: AppViewModel,+ n: Note,+ depth: Int,+ count: Int,+ k: Float,+ width: Float,+ frontHeight: Int,+ isPlaying: Boolean,+ progress: () -> Float,+ onPlay: () -> Unit,+ onLong: (androidx.compose.ui.geometry.Rect) -> Unit,+ onMeasured: (Int) -> Unit,+ onSwipedAway: () -> Unit,+) {+ val scope = rememberCoroutineScope()+ val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()+ // where in the deck it is, gliding between depths (0 front … 2 back)+ // (no overshoot: a bounce here read as the card wobbling between places)+ val d by animateFloatAsState(depth.toFloat(), androidx.compose.animation.core.spring(0.9f, 420f), label = "deckDepth")+ // its own sideways travel: the drag, then the slide aside and home again behind the others+ val x = remember { Animatable(0f) }+ var bounds by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }+ val density = androidx.compose.ui.platform.LocalDensity.current+ val inset = m(34, k)+ val front = depth == 0+ // a card behind takes the front card's height, so nothing of it shows below the front one+ val sized = if (!front && frontHeight > 0) Modifier.height(with(density) { frontHeight.toDp() }) else Modifier+ Box(+ Modifier.padding(horizontal = inset).fillMaxWidth().then(sized)+ .graphicsLayer {+ // depth 0 → 1 → 2: 0 → 36 → 60 px up; full width → 365 / 423 → 295 / 423 of it+ val up = if (d <= 1f) 36f * d else 36f + 24f * (d - 1f)+ val sc = if (d <= 1f) 1f - 0.137f * d else 0.863f - 0.166f * (d - 1f)+ translationY = -up * k * density.density+ scaleX = sc+ scaleY = sc+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, 0f)+ translationX = x.value+ rotationZ = x.value / width * 9f+ }+ .onGloballyPositioned { bounds = it.boundsInWindow() }+ .then(+ if (front && count > 1) Modifier.pointerInput(n.id) {+ val tracker = androidx.compose.ui.input.pointer.util.VelocityTracker()+ detectHorizontalDragGestures(+ onDragStart = { tracker.resetTracking() },+ onDragEnd = {+ val v = tracker.calculateVelocity().x+ scope.launch {+ // the side it goes to is the side it was dragged to (a flick only decides+ // when the card has hardly moved), so it never crosses over to the other side+ val dragged = kotlin.math.abs(x.value) > 12f * density.density+ val side = if (dragged) kotlin.math.sign(x.value) else kotlin.math.sign(v)+ val flung = kotlin.math.abs(v) > 1400f && kotlin.math.sign(v) == side+ if (side != 0f && (kotlin.math.abs(x.value) > width / 4f || flung)) {+ feel(com.chethan616.clearpdf.ui.glass.Feel.Tick)+ // one throw, no stop: flung out to that side, a single spring carries it out and+ // straight back home; at the far point (where it turns) it goes to the back of the+ // deck, so it comes home behind the others with no pause at the edge+ var tucked = false+ val throwV = side * maxOf(kotlin.math.abs(v), 9000f)+ x.animateTo(0f, androidx.compose.animation.core.spring(1f, 140f, 1f), initialVelocity = throwV) {+ if (!tucked && kotlin.math.sign(velocity) != side) {+ tucked = true+ onSwipedAway()+ }+ }+ if (!tucked) onSwipedAway()+ } else {+ // not far enough: back to the front, settling without swinging past+ x.animateTo(0f, androidx.compose.animation.core.spring(1f, 500f))+ }+ }+ },+ onDragCancel = { scope.launch { x.animateTo(0f, GlassMotion.morph()) } },+ ) { change, dx ->+ change.consume()+ tracker.addPosition(change.uptimeMillis, change.position)+ scope.launch { x.snapTo(x.value + dx) }+ }+ } else Modifier,+ )+ .onSizeChanged { if (front) onMeasured(it.height) },+ ) {+ if (n.kind == NoteKind.Voice) {+ // a voice memo is the desk's own voice card: its periwinkle, its play mark, its glowing bars+ VoiceCard(n, isPlaying, { progress().let { if (it < 0f) 0f else it } }, onPlay, { onLong(bounds) }, Modifier.fillMaxWidth())+ } else {+ FrontCard(vm, n, k, isPlaying, progress, onPlay, { onLong(bounds) }, Modifier.fillMaxWidth(), active = front)+ }+ // a card behind only shows: a touch on the part of it that peeks out does nothing+ if (!front) Box(Modifier.matchParentSize().pointerInput(Unit) { detectTapGestures { } })+ // further back: tinted (cream, then pink) and blurred, as the mock's cards behind+ if (d > 0.01f) {+ val tint = if (d <= 1f) Color(0xFFFBFCF0) else androidx.compose.ui.graphics.lerp(Color(0xFFFBFCF0), Color(0xFFFCEEFD), (d - 1f).coerceIn(0f, 1f))+ Box(+ Modifier.matchParentSize().clip(RoundedRectangle(m(28, k)))+ .background(tint.copy(alpha = (0.62f * d).coerceAtMost(0.8f))),+ )+ }+ }+}++private fun titleOf(n: Note): String =+ n.title.ifBlank { n.body.lineSequence().firstOrNull { it.isNotBlank() }?.trim()?.removePrefix("# ").orEmpty() }++/** A note's words split as the mock's card sets them: a line or sentence to lead in blue, the rest under it. */+private fun leadAndRest(n: Note): Pair<String?, String> {+ val text = n.body.lineSequence().map { it.trim().removePrefix("# ").replace("**", "") }.filter { it.isNotBlank() }.toList()+ val lines = if (n.title.isBlank()) text.drop(1) else text+ if (lines.isEmpty()) return null to ""+ if (lines.size > 1) return lines.first() to lines.drop(1).joinToString(" ")+ // one paragraph: its first sentence leads+ val one = lines.first()+ val end = Regex("[.!?](\\s|$)").find(one)?.range?.first+ return if (end != null && end + 1 < one.length) one.substring(0, end + 1) to one.substring(end + 1).trim() else one to ""+}++/**+ * The front card, as the mock's "Morning Reflection": white, 28 px corners; its name (Outfit 600,+ * 13.7) on a baseline 47 px down and 25 px in, when (9.2, grey) 22 px under it, the pencil on the+ * right; the lead in blue (600, 18.9, lines 31 px apart) 56 px under that, the rest (400, 12.9, lines+ * 25 px apart) 43 px under the lead, then its pictures (129 px tall) 31 px under the text, 26 px of card below.+ */+@Composable+private fun FrontCard(+ vm: AppViewModel,+ n: Note,+ k: Float,+ isPlaying: Boolean,+ progress: () -> Float,+ onPlay: () -> Unit,+ onLong: () -> Unit,+ modifier: Modifier,+ /** The front card: it takes taps; the ones behind only show. */+ active: Boolean = true,+) {+ // a voice memo plays (or pauses) on a tap; anything else opens+ val open = { if (n.kind == NoteKind.Voice) onPlay() else vm.openNote = n.id }+ val (lead, rest) = leadAndRest(n)+ Box(modifier.clip(RoundedRectangle(m(28, k))).background(Color.White).pressable(open, onLong, pressedScale = 0.98f, enabled = active)) {+ val gaps = buildList {+ add(m(47, k)); add(m(22, k))+ if (lead != null) add(m(56, k))+ if (rest.isNotBlank()) add(m(if (lead != null) 43 else 56, k))+ if (n.images.isNotEmpty()) add(m(31, k))+ }+ BaselineStack(gaps, m(26, k), Modifier.padding(horizontal = m(25, k))) {+ Text(titleOf(n).ifBlank { stringResource(R.string.notes_untitled_note) }, style = outfit(600, s(13.7f, k), -0.03f).copy(color = Color.Black), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(end = m(60, k)))+ Text(+ DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(n.updated)) ++ (if (n.kind == NoteKind.Voice && n.durationMs > 0) " · " + com.chethan616.clearpdf.ui.viewer.clock(n.durationMs) else ""),+ style = outfit(400, s(9.2f, k), -0.02f).copy(color = Color(0xFF525658)),+ )+ if (lead != null) Text(lead, style = outfit(600, s(18.9f, k), -0.005f, (31 * k).sp).copy(color = Color(0xFF2B649B)), maxLines = 3, overflow = TextOverflow.Ellipsis)+ if (rest.isNotBlank()) Text(rest, style = outfit(400, s(12.9f, k), 0f, (25 * k).sp).copy(color = Color.Black), maxLines = 5, overflow = TextOverflow.Ellipsis)+ if (n.images.isNotEmpty()) {+ Row(horizontalArrangement = Arrangement.spacedBy(m(16, k))) {+ NoteImage(n.images[0], Modifier.weight(if (n.images.size > 1) 226f else 1f).height(m(129, k)).clip(RoundedRectangle(m(20, k))))+ if (n.images.size > 1) NoteImage(n.images[1], Modifier.weight(136f).height(m(129, k)).clip(RoundedRectangle(m(20, k))))+ }+ }+ }+ // the pencil: a 54 px white button with a soft shadow, 16 px in from the right, 28 px down+ if (n.kind != NoteKind.Voice) {+ Box(+ Modifier.align(Alignment.TopEnd).padding(top = m(28, k), end = m(16, k)).size(m(54, k))+ .graphicsLayer { shadowElevation = 6.dp.toPx(); shape = androidx.compose.foundation.shape.CircleShape; clip = true; ambientShadowColor = Color(0x22000000); spotShadowColor = Color(0x22000000) }+ .background(Color.White).pressable(open, pressedScale = 0.9f, enabled = active),+ contentAlignment = Alignment.Center,+ ) { Icon(LucideIcons.PencilOutline, stringResource(R.string.notes_open), tint = Color(0xFF1A1A1A), modifier = Modifier.size(m(26, k))) }+ }+ }+}++// ---- Today ------------------------------------------------------------------------------------------------++/**+ * Today (the mock's third screen): the mark and the menu, the owner's name small above "Good Morning"+ * (afternoon, evening, night) large, translucent white and fading into blur, and three cards laid over+ * it: the day's thought turned left, the latest picture (Highlights) turned right over it, and the date+ * on frosted glass over that.+ */+@Composable+fun TodayScreen(vm: AppViewModel) {+ val k = mockScale()+ val notes = vm.notes.all+ val pictures = remember(notes) { notePictures(notes) }+ val res = androidx.compose.ui.platform.LocalContext.current.resources+ val thought = remember(res) { com.chethan616.clearpdf.notes.thoughtFor(res) }+ val hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+ val greeting = stringResource(+ when (hour) {+ in 5..11 -> R.string.today_morning+ in 12..16 -> R.string.today_afternoon+ in 17..21 -> R.string.today_evening+ else -> R.string.today_night+ },+ )+ val name = vm.ownerName+ Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {+ Box(Modifier.fillMaxWidth().height(m(1068, k))) {+ // the desk's own header: its mark (a tap goes back to the desk) and its menu button+ DeskHeaderRow(+ leading = {+ androidx.compose.foundation.Image(+ androidx.compose.ui.res.painterResource(R.drawable.artefact_mark), stringResource(R.string.app_name),+ colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(clear.hero),+ modifier = Modifier.height(50.dp).width(56.dp).pressable({ vm.closeDeskPage() }, pressedScale = 0.94f),+ )+ },+ trailing = {+ MorphButton(+ items = listOf(+ GlassMenuItem(stringResource(R.string.thought_title), LucideIcons.Sparkles) { vm.openDeskPage(DeskPage.Thoughts) },+ GlassMenuItem(stringResource(R.string.home_tab_files), LucideIcons.FolderOpen) { vm.closeDeskPage(); vm.homeTab = HomeTab.Files },+ GlassMenuItem(stringResource(R.string.home_tab_tools), LucideIcons.LayoutGrid) { vm.closeDeskPage(); vm.homeTab = HomeTab.Tools },+ GlassMenuItem(stringResource(R.string.home_settings), LucideIcons.Settings) { vm.settingsOpen = true },+ ),+ label = stringResource(R.string.common_more_options),+ ) { FourDots(Color.Unspecified) }+ },+ )+ // the name: Outfit 300 at 15, its baseline at 178 px+ if (name.isNotBlank()) Text(+ name.uppercase(), style = outfit(300, s(15f, k), 0.01f).copy(color = Color.White, textAlign = TextAlign.Center),+ modifier = Modifier.fillMaxWidth().baselineAt(null, m(178, k)),+ )+ // the greeting: Outfit 500 at 73, baselines 264 and 354 px, white at 62 %, fading into blur+ FadeIntoBlur(0.55f, m(2.6f, k), Modifier.fillMaxWidth().baselineAt(null, m(264, k)).graphicsLayer { alpha = 0.62f }) {+ Text(+ greeting, style = outfit(500, s(73f, k), 0f, (90 * k).sp).copy(color = Color.White, textAlign = TextAlign.Center),+ modifier = Modifier.fillMaxWidth().padding(horizontal = m(20, k)),+ )+ }+ // the day's thought: a 205 × 200 px frosted card centred at (152, 440), turned 6° left+ Box(+ Modifier.offset(m(152 - 102.5f, k), m(440 - 100, k)).size(m(205, k), m(200, k))+ .graphicsLayer { rotationZ = -6f }+ .clip(RoundedRectangle(m(22, k))).background(Color(0xFFFFF6F6).copy(alpha = 0.86f))+ .pressable({ vm.openDeskPage(DeskPage.Thoughts) }, pressedScale = 0.96f),+ ) {+ Text(stringResource(R.string.thought_title), style = outfit(500, s(13.4f, k), -0.01f).copy(color = Color(0xFF3B6593)), modifier = Modifier.baselineAt(m(17, k), m(42, k)))+ Text(shortDate(System.currentTimeMillis()), style = outfit(400, s(10f, k)).copy(color = Color(0xFF9D9591)), modifier = Modifier.baselineAt(m(17, k), m(66, k)))+ FadeIntoBlur(0.48f, m(3.5f, k), Modifier.padding(start = m(17, k), end = m(14, k)).baselineAt(null, m(112, k))) {+ Text(+ (thought.quote + " " + thought.reflection).replace("**", ""), style = outfit(400, s(11.1f, k), 0f, (16 * k).sp).copy(color = Color(0xFF1E1515)),+ maxLines = 5, overflow = TextOverflow.Clip,+ )+ }+ }+ // the latest picture: 222 × 272 px centred at (343, 605), turned 2° right, over the thought+ val pic = pictures.firstOrNull()+ val scan = if (pic == null) scanRows(vm.recentRows()).firstOrNull() else null+ Box(+ Modifier.offset(m(343 - 111, k), m(605 - 136, k)).size(m(222, k), m(272, k))+ .graphicsLayer { rotationZ = 2f; shadowElevation = 4.dp.toPx(); shape = RoundedRectangle(m(28, k)); clip = true }+ .background(Color(0xFF9CCDE4))+ .pressable({ vm.deskPages.clear(); vm.deskShelf = DeskFilter.Images }, pressedScale = 0.96f),+ ) {+ if (pic != null) NoteImage(pic.name, Modifier.matchParentSize(), maxPx = 900)+ else if (scan != null) PageFill(vm, scan.thumbPath)+ else Icon(LucideIcons.Images, null, tint = Color.White.copy(alpha = 0.7f), modifier = Modifier.align(Alignment.Center).size(m(56, k)))+ // a scanned page is white: a soft shade under the label so it still reads+ if (pic == null && scan != null) Box(Modifier.fillMaxWidth().height(m(90, k)).background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.32f), Color.Transparent))))+ Text(stringResource(R.string.desk_highlights), style = outfit(500, s(13.4f, k), -0.01f).copy(color = Color.White), modifier = Modifier.baselineAt(m(25, k), m(37, k)))+ Text(shortDate(pic?.note?.updated ?: scan?.date ?: System.currentTimeMillis()), style = outfit(500, s(10.6f, k)).copy(color = Color.White), modifier = Modifier.baselineAt(m(25, k), m(61, k)))+ }+ // the date: frosted glass, 220 × 202 px at (55, 700), 30 px corners+ val now = Date()+ Box(+ Modifier.offset(m(55, k), m(700, k)).size(m(220, k), m(202, k))+ .graphicsLayer { shadowElevation = 3.dp.toPx(); shape = RoundedRectangle(m(30, k)); clip = true; ambientShadowColor = Color(0x22000000); spotShadowColor = Color(0x22000000) }+ .background(Color(0xFFF4F8FF).copy(alpha = 0.78f))+ .pressable({ vm.closeDeskPage() }, pressedScale = 0.96f),+ ) {+ Text(java.text.SimpleDateFormat("EEEE", java.util.Locale.getDefault()).format(now), style = outfit(700, s(37.6f, k), -0.035f).copy(color = Color.Black), maxLines = 1, modifier = Modifier.baselineAt(m(22, k), m(52, k)))+ Text(+ java.text.SimpleDateFormat(android.text.format.DateFormat.getBestDateTimePattern(java.util.Locale.getDefault(), "MMMd"), java.util.Locale.getDefault()).format(now),+ style = outfit(300, s(32f, k)).copy(color = Color(0xFF737D87)), maxLines = 1, modifier = Modifier.baselineAt(m(22, k), m(96, k)),+ )+ Text(stringResource(R.string.today_overview), style = outfit(400, s(11.1f, k)).copy(color = Color(0xFF84909C)), modifier = Modifier.baselineAt(m(22, k), m(177, k)))+ }+ }+ }+}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.ktindex e44a6e7..28342c3 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.kt@@ -129,6 +129,16 @@ sealed interface DeskItem {data class Doc(val row: FileRow) : DeskItem {override val key get() = "d-" + row.key}++ /** The pictures in the notes. */+ data class Highlights(val pictures: List<NotePicture>) : DeskItem {+ override val key get() = "highlights"+ }++ /** The documents made with Scan. */+ data class Snapshots(val scans: List<FileRow>) : DeskItem {+ override val key get() = "snapshots"+ }}/** The desk's cards for [filter]: notes newest first, with the collections set in among them. */@@ -139,6 +149,9 @@ fun deskItems(filter: DeskFilter, notes: List<Note>, recents: List<FileRow>): Lival out = sorted.map<Note, DeskItem> { DeskItem.Of(it) }.toMutableList()if (recents.isNotEmpty()) out.add(minOf(1, out.size), DeskItem.Recent(recents))out.add(minOf(3, out.size), DeskItem.Files)+ // the notes' pictures and the scans, as the mock's Highlights and Snapshots+ notePictures(notes).takeIf { it.isNotEmpty() }?.let { out.add(minOf(4, out.size), DeskItem.Highlights(it)) }+ scanRows(recents).takeIf { it.isNotEmpty() }?.let { out.add(minOf(5, out.size), DeskItem.Snapshots(it)) }out.add(minOf(6, out.size), DeskItem.Pdfs(recents.size))out}@@ -163,12 +176,18 @@ val DeskDockClearance = 128.dp@Composablefun HomeScreen(vm: AppViewModel, desk: DeskState) {var filter by rememberSaveable { mutableStateOf(DeskFilter.All) }+ val thoughtTitle = stringResource(R.string.thought_title)+ // a desk page asked for a shelf (Today's picture: Images)+ LaunchedEffect(vm.deskShelf) { vm.deskShelf?.let { filter = it; vm.deskShelf = null } }val scope = rememberCoroutineScope()val player = remember { VoicePlayer(scope) }var playing by remember { mutableStateOf<String?>(null) }DisposableEffect(Unit) { onDispose { player.release() } }var actionsFor by remember { mutableStateOf<Note?>(null) }var actionsAnchor by remember { mutableStateOf(Rect.Zero) }+ // where each card is (window bounds, by its key): a long press's menu grows from its own card+ val bounds = remember { HashMap<String, Rect>() }+ val density = LocalDensity.currentval notes = vm.notes.allval recents = vm.recentRows()val fresh = remember(filter, notes, vm.recentList) { deskItems(filter, notes, recents) }@@ -220,18 +239,20 @@ fun HomeScreen(vm: AppViewModel, desk: DeskState) {FilterChips(filter) { filter = it }}itemsIndexed(items, key = { _, it -> it.key }) { i, item ->- val m = Modifier.fillMaxWidth().riseIn(i, active = intro).onGloballyPositioned { actionsAnchor = it.boundsInWindow() }+ val m = Modifier.fillMaxWidth().riseIn(i, active = intro).onGloballyPositioned { bounds[item.key] = it.boundsInWindow() }+ val long: (Note) -> Unit = { n -> actionsAnchor = bounds[item.key] ?: Rect.Zero; actionsFor = n }when (item) {is DeskItem.Of -> when (item.note.kind) {- NoteKind.List -> ListCard(item.note, { vm.openNote = item.note.id }, { actionsFor = item.note }, { vm.notes.toggle(item.note.id, it.id) }, m)+ NoteKind.List -> ListCard(item.note, { vm.openNote = item.note.id }, { long(item.note) }, { vm.notes.toggle(item.note.id, it.id) }, m)NoteKind.Voice -> VoiceCard(item.note, playing == item.note.id && player.playing,// read while drawing: the position ticking never recomposes the desk{ if (playing == item.note.id && player.durationMs > 0) player.positionMs / player.durationMs.toFloat() else 0f },- { play(item.note) }, { actionsFor = item.note }, m,+ { play(item.note) }, { long(item.note) }, m,)- NoteKind.Text -> NoteCard(item.note, { vm.openNote = item.note.id }, { actionsFor = item.note }, m)- NoteKind.Map -> MapCard(item.note, { vm.openNote = item.note.id }, { actionsFor = item.note }, m)+ // the thought of the day opens its own page: the thoughts as a deck+ NoteKind.Text -> NoteCard(item.note, { if (item.note.thought != 0L || item.note.title == thoughtTitle) vm.openDeskPage(DeskPage.Thoughts) else vm.openNote = item.note.id }, { long(item.note) }, m)+ NoteKind.Map -> MapCard(item.note, { vm.openNote = item.note.id }, { long(item.note) }, m)}is DeskItem.Picture -> {val n = item.note@@ -239,7 +260,7 @@ fun HomeScreen(vm: AppViewModel, desk: DeskState) {val open = if (filter == DeskFilter.Images) ({ vm.editingPhoto = n.id to n.images.first() }) else ({ vm.openNote = n.id })StackCard(n.title.ifBlank { stringResource(R.string.desk_filter_images) }, shortDate(n.updated),- listOf(clear.tone(Tone.Blush), clear.tone(Tone.Peach)), open, m, onLong = { actionsFor = n },+ listOf(clear.tone(Tone.Blush), clear.tone(Tone.Peach)), open, m, onLong = { long(n) },chips = {if (n.images.size > 1) PhotoChip("+${n.images.size - 1}", { vm.openNote = n.id }, Modifier.align(Alignment.BottomEnd).padding(12.dp))},@@ -247,10 +268,20 @@ fun HomeScreen(vm: AppViewModel, desk: DeskState) {}DeskItem.Files -> CollectionCard(stringResource(R.string.desk_word_files), clear.tone(Tone.Butter), { vm.filesShowLocal = true; vm.homeTab = HomeTab.Files }, m)is DeskItem.Pdfs -> CollectionCard(stringResource(R.string.desk_word_pdf), clear.tone(Tone.Orchid), { vm.homeTab = HomeTab.Files }, m, height = 136.dp)- is DeskItem.Recent -> RecentCard(vm, item.rows, { vm.homeTab = HomeTab.Files }, m)+ // a long press: the newest document's menu, its glass growing out of the card's corner+ is DeskItem.Highlights -> HighlightsCard(item.pictures, { filter = DeskFilter.Images }, { filter = DeskFilter.Images }, m)+ is DeskItem.Snapshots -> SnapshotsCard(vm, item.scans, { vm.filesShowRecent = true; vm.homeTab = HomeTab.Files }, m)+ is DeskItem.Recent -> RecentCard(+ vm, item.rows, { vm.filesShowRecent = true; vm.homeTab = HomeTab.Files }, m,+ onLong = { b -> vm.fileMenu = com.chethan616.clearpdf.ui.desk.FileMenuAt(item.rows.first(), true, com.chethan616.clearpdf.ui.desk.cardMenuAnchor(b, density), ghost = true) },+ )is DeskItem.Doc -> DocCard(vm, item.row, clear.tone(listOf(Tone.Sky, Tone.Peach, Tone.Sage, Tone.Butter)[i % 4]), listOf(-3f, 4f, -2f, 3f)[i % 4],- { vm.fileSheet = item.row to true }, m,+ {+ val b = bounds[item.key] ?: Rect.Zero+ vm.fileMenu = com.chethan616.clearpdf.ui.desk.FileMenuAt(item.row, true, com.chethan616.clearpdf.ui.desk.cardMenuAnchor(b, density), ghost = true)+ },+ m,)}}@@ -285,6 +316,8 @@ private fun DeskHeader(vm: AppViewModel) {}if (menu) {GlassMenu(anchor, { menu = false }, listOf(+ GlassMenuItem(stringResource(R.string.today_title), LucideIcons.Sun) { vm.openDeskPage(DeskPage.Today) },+ GlassMenuItem(stringResource(R.string.thought_title), LucideIcons.Sparkles) { vm.openDeskPage(DeskPage.Thoughts) },GlassMenuItem(stringResource(R.string.home_tab_files), LucideIcons.FolderOpen) { vm.homeTab = HomeTab.Files },GlassMenuItem(stringResource(R.string.home_tab_tools), LucideIcons.LayoutGrid) { vm.homeTab = HomeTab.Tools },GlassMenuItem(stringResource(R.string.voice_import), LucideIcons.Mic) { vm.pickAudio() },@@ -437,7 +470,7 @@ private fun DeskEmpty(vm: AppViewModel, filter: DeskFilter, desk: DeskState) {/** A long press on a note: name it (a voice memo), pin it, open it, or delete it. */@Composable-private fun NoteActions(vm: AppViewModel, n: Note, anchor: Rect, onRename: () -> Unit, onDismiss: () -> Unit) {+internal fun NoteActions(vm: AppViewModel, n: Note, anchor: Rect, onRename: () -> Unit, onDismiss: () -> Unit) {val voice = n.kind == NoteKind.Voiceval feel = com.chethan616.clearpdf.ui.glass.rememberFeel()val renameLabel = stringResource(R.string.notes_rename)@@ -461,7 +494,7 @@ private fun NoteActions(vm: AppViewModel, n: Note, anchor: Rect, onRename: () ->* selected, so typing replaces it; Done or Save keeps it, an empty name clears it.*/@Composable-private fun NameSheet(vm: AppViewModel, n: Note, onDismiss: () -> Unit) {+internal fun NameSheet(vm: AppViewModel, n: Note, onDismiss: () -> Unit) {var name by remember(n.id) { mutableStateOf(androidx.compose.ui.text.input.TextFieldValue(n.title, androidx.compose.ui.text.TextRange(0, n.title.length))) }val focus = remember { androidx.compose.ui.focus.FocusRequester() }val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.ktindex 84c4e97..8010077 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/MindMap.kt@@ -370,7 +370,7 @@ internal object MapType {val loaded: Boolean get() = base != nullfun load(context: android.content.Context) {- if (base == null) base = runCatching { androidx.core.content.res.ResourcesCompat.getFont(context, R.font.jakarta) }.getOrNull()+ if (base == null) base = runCatching { androidx.core.content.res.ResourcesCompat.getFont(context, R.font.outfit) }.getOrNull()}fun face(weight: Int): Typeface = Typeface.create(base ?: Typeface.DEFAULT, weight, false)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/theme/ClearTheme.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/theme/ClearTheme.ktindex 6da7b80..3f093d0 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/theme/ClearTheme.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/theme/ClearTheme.kt@@ -175,6 +175,18 @@ private fun jakarta(weight: Int, italic: Boolean = false) = FontFamily(),)+/** Outfit (OFL), the interface's face (the mock's): a geometric sans at one weight of its variable axis. */+private fun outfit(weight: Int) = FontFamily(+ Font(R.font.outfit, FontWeight(weight), FontStyle.Normal, variationSettings = FontVariation.Settings(FontVariation.weight(weight))),+)++/** The whole Outfit family, every weight the text styles ask for (it has no italic: slants are synthesized). */+val Outfit: FontFamily = FontFamily(+ listOf(300, 400, 500, 600, 700, 800).map { w ->+ Font(R.font.outfit, FontWeight(w), FontStyle.Normal, variationSettings = FontVariation.Settings(FontVariation.weight(w)))+ },+)+/** The whole Jakarta family, every weight the text styles ask for. */val Jakarta: FontFamily = FontFamily(listOf(300, 400, 500, 600, 700, 800).flatMap { w ->@@ -223,19 +235,19 @@ private fun display(family: FontFamily, size: TextUnit, line: TextUnit, trackingTextStyle(fontFamily = family, fontSize = size, lineHeight = line, letterSpacing = tracking, lineHeightStyle = Trim)/**- * The type scale, all Plus Jakarta Sans: heavy and tight for heroes and titles (Apple's display+ * The type scale, all Outfit (the mock's face): heavy and tight for heroes and titles (Apple's display* sizes, a touch rounder), plain for reading. [Serif] and [Doto] are the playful accents on cards.*/object ClearType {- val Hero = display(jakarta(700), 54.sp, 56.sp, (-1.4).sp)- val Display = display(jakarta(600), 42.sp, 46.sp, (-1.0).sp)- val Headline = display(jakarta(700), 26.sp, 30.sp, (-0.5).sp)- val Title = display(jakarta(700), 18.sp, 22.sp, (-0.2).sp)- val Tile = display(jakarta(700), 17.sp, 20.sp, (-0.2).sp)- val Number = display(jakarta(700), 22.sp, 24.sp, 0.sp).copy(fontFeatureSettings = "tnum")+ val Hero = display(outfit(700), 54.sp, 56.sp, (-1.4).sp)+ val Display = display(outfit(600), 42.sp, 46.sp, (-1.0).sp)+ val Headline = display(outfit(700), 26.sp, 30.sp, (-0.5).sp)+ val Title = display(outfit(700), 18.sp, 22.sp, (-0.2).sp)+ val Tile = display(outfit(700), 17.sp, 20.sp, (-0.2).sp)+ val Number = display(outfit(700), 22.sp, 24.sp, 0.sp).copy(fontFeatureSettings = "tnum")/** A note card's title: bold, tight, in the note's blue. */- val CardTitle = display(jakarta(800), 27.sp, 29.sp, (-0.6).sp)+ val CardTitle = display(outfit(800), 27.sp, 29.sp, (-0.6).sp)/** A collection card's word ("Files"). */val SerifWord = display(Serif, 52.sp, 52.sp, (-1.2).sp)/** A list card's title. */@@ -248,7 +260,7 @@ object ClearType {// title; the desk shrinks that one size (for every title alike) only if a translation is too wide.val DeskTitleSize = 44.spval DeskTitleLine = 50.sp- val DeskAll = display(bricolage(700, 100f, 96.sp), DeskTitleSize, DeskTitleLine, (-1.4).sp)+ val DeskAll = display(outfit(500), DeskTitleSize, DeskTitleLine, (-1.0).sp)val DeskNotes = display(fraunces(600, 50f, 72.sp), DeskTitleSize, DeskTitleLine, (-0.8).sp)val DeskTodo = display(Doto, DeskTitleSize, DeskTitleLine, 0.sp)val DeskPdfs = display(Serif, DeskTitleSize, DeskTitleLine, (-0.8).sp)@@ -260,11 +272,17 @@ object ClearType {/** A tool tile's name, set like the desk's "Files" and "Pdf" words. */val ToolWord = display(Serif, 31.sp, 33.sp, (-0.6).sp)- val Eyebrow = TextStyle(fontFamily = Jakarta, fontWeight = FontWeight.SemiBold, fontSize = 11.5.sp, lineHeight = 14.sp, letterSpacing = 1.4.sp)- val Body = TextStyle(fontFamily = Jakarta, fontWeight = FontWeight.Normal, fontSize = 15.sp, lineHeight = 22.sp)+ val Eyebrow = TextStyle(fontFamily = Outfit, fontWeight = FontWeight.SemiBold, fontSize = 11.5.sp, lineHeight = 14.sp, letterSpacing = 1.4.sp)+ val Body = TextStyle(fontFamily = Outfit, fontWeight = FontWeight.Normal, fontSize = 15.sp, lineHeight = 22.sp)val BodyStrong = Body.copy(fontWeight = FontWeight.SemiBold)- val Label = TextStyle(fontFamily = Jakarta, fontWeight = FontWeight.Medium, fontSize = 13.sp, lineHeight = 18.sp)- val Caption = TextStyle(fontFamily = Jakarta, fontWeight = FontWeight.Normal, fontSize = 11.5.sp, lineHeight = 15.sp)+ val Label = TextStyle(fontFamily = Outfit, fontWeight = FontWeight.Medium, fontSize = 13.sp, lineHeight = 18.sp)+ val Caption = TextStyle(fontFamily = Outfit, fontWeight = FontWeight.Normal, fontSize = 11.5.sp, lineHeight = 15.sp)++ // The Recent card keeps its own Plus Jakarta Sans (its title, when, and chips), set exactly as+ // before the interface moved to Outfit: the owner's chosen look for that card.+ val RecentTitle = display(jakarta(700), 17.sp, 22.sp, (-0.2).sp)+ val RecentWhen = TextStyle(fontFamily = Jakarta, fontWeight = FontWeight.Normal, fontSize = 10.5.sp, lineHeight = 15.sp)+ val RecentChip = TextStyle(fontFamily = Jakarta, fontWeight = FontWeight.SemiBold, fontSize = 13.sp, lineHeight = 18.sp)}/** A hero title's soft glow, so white type reads on the pale sky. */diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.ktindex a0fd4ff..11f2a8e 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt@@ -97,8 +97,57 @@ data class Paragraph(val bold: Boolean,val italic: Boolean,val color: String?,+ /** Where its weight or slant changes (a bold word in a plain line), in characters of [text]; empty: all one style. */+ val runs: List<StyleRun> = emptyList(),)+/** Characters [start] until [end] of a paragraph's text, set [bold] and [italic]. */+data class StyleRun(val start: Int, val end: Int, val bold: Boolean, val italic: Boolean) {+ companion object {+ /** Each character's (bold, italic) in a text of [length], [runs] over a [bold]/[italic] base. */+ fun perChar(runs: List<StyleRun>, length: Int, bold: Boolean, italic: Boolean): Array<Pair<Boolean, Boolean>> {+ val out = Array(length) { bold to italic }+ for (r in runs) for (i in r.start.coerceAtLeast(0) until r.end.coerceAtMost(length)) out[i] = r.bold to r.italic+ return out+ }++ /** [chars] back into runs (adjacent characters of one style joined). */+ fun of(chars: Array<Pair<Boolean, Boolean>>): List<StyleRun> {+ val out = ArrayList<StyleRun>()+ var i = 0+ while (i < chars.size) {+ var j = i+ while (j < chars.size && chars[j] == chars[i]) j+++ out.add(StyleRun(i, j, chars[i].first, chars[i].second))+ i = j+ }+ return if (out.size <= 1) emptyList() else out+ }++ /**+ * [runs] after the text changed from [old] to [new]: what is before and after the change keeps+ * its style; typed characters take the style of the one before them (as a word processor does).+ */+ fun shift(runs: List<StyleRun>, old: String, new: String, bold: Boolean, italic: Boolean): List<StyleRun> {+ if (runs.isEmpty() || old == new) return runs+ val before = perChar(runs, old.length, bold, italic)+ var p = 0+ while (p < old.length && p < new.length && old[p] == new[p]) p+++ var s = 0+ while (s < old.length - p && s < new.length - p && old[old.length - 1 - s] == new[new.length - 1 - s]) s+++ val inherit = if (p > 0) before[p - 1] else before.getOrElse(old.length - s) { bold to italic }+ val after = Array(new.length) { i ->+ when {+ i < p -> before[i]+ i >= new.length - s -> before[old.length - (new.length - i)]+ else -> inherit+ }+ }+ return of(after)+ }+ }+}+/** A picture Edit PDF has selected: its number on the page and where it sits (points). */data class EditImage(val page: Int, val number: Int, val rect: FloatArray)@@ -200,14 +249,16 @@ private fun EditFormatBar(vm: AppViewModel, doc: OpenDocument, para: Paragraph)val underline = vm.editUnderline[para.page to para.number] == true// the reference draws these as serif T's: heavy, slanted, underlined, and a small t beside a big one// with words selected in the paragraph, Bold and Italic change only those; else all of it- LetterButton("T", stringResource(R.string.edit_bold), para.bold, weight = FontWeight.Black) {- val picked = vm.editRange?.takeIf { vm.editing != null }- if (picked != null) vm.styleRange(doc, para, picked, bold = !para.bold, italic = para.italic)+ // lit for what is selected: the selected words' own weight and slant (#127), else the paragraph's+ val picked = vm.editRange?.takeIf { vm.editing != null }+ val boldNow = if (picked != null) vm.rangeStyled(para, picked) else para.bold+ val italicNow = if (picked != null) vm.rangeStyled(para, picked, italic = true) else para.italic+ LetterButton("T", stringResource(R.string.edit_bold), boldNow, weight = FontWeight.Black) {+ if (picked != null) vm.styleRange(doc, para, picked, bold = !boldNow, italic = italicNow)else vm.styleParagraph(doc, para, mapOf("bold" to !para.bold))}- LetterButton("T", stringResource(R.string.edit_italic), para.italic, italic = true) {- val picked = vm.editRange?.takeIf { vm.editing != null }- if (picked != null) vm.styleRange(doc, para, picked, bold = para.bold, italic = !para.italic)+ LetterButton("T", stringResource(R.string.edit_italic), italicNow, italic = true) {+ if (picked != null) vm.styleRange(doc, para, picked, bold = boldNow, italic = !italicNow)else vm.styleParagraph(doc, para, mapOf("italic" to !para.italic))}LetterButton("T", stringResource(R.string.edit_underline), underline, underline = true) {@@ -533,6 +584,22 @@ private fun BoxScope.InlineEditor(vm: AppViewModel, doc: OpenDocument, para: Parif (b.y > clear) v.setScroll(v.scrollX, v.scrollY + (b.y - clear))}LaunchedEffect(value.text) { vm.editDraft = value.text }+ // the paragraph's bold and italic words, drawn as they are on the page and kept on the words as+ // they are typed around (#127: a bold word stays the only bold one)+ LaunchedEffect(para) { vm.editRuns = para.runs }+ val runs = vm.editRuns+ val styled = remember(runs) {+ androidx.compose.ui.text.input.VisualTransformation { t ->+ if (runs.isEmpty()) return@VisualTransformation androidx.compose.ui.text.input.TransformedText(t, androidx.compose.ui.text.input.OffsetMapping.Identity)+ val b = androidx.compose.ui.text.AnnotatedString.Builder(t)+ for (r in runs) {+ val s = r.start.coerceIn(0, t.length)+ val e = r.end.coerceIn(s, t.length)+ if (s < e) b.addStyle(androidx.compose.ui.text.SpanStyle(fontWeight = if (r.bold) FontWeight.Bold else FontWeight.Normal, fontStyle = if (r.italic) FontStyle.Italic else FontStyle.Normal), s, e)+ }+ androidx.compose.ui.text.input.TransformedText(b.toAnnotatedString(), androidx.compose.ui.text.input.OffsetMapping.Identity)+ }+ }// what is selected in the paragraph, for Bold and Italic to take only thatLaunchedEffect(value.selection) { vm.editRange = value.selection.takeIf { !it.collapsed } }androidx.compose.runtime.DisposableEffect(para) { onDispose { vm.editRange = null } }@@ -563,7 +630,11 @@ private fun BoxScope.InlineEditor(vm: AppViewModel, doc: OpenDocument, para: Par) {BasicTextField(value = value,- onValueChange = { value = it },+ onValueChange = {+ if (it.text != value.text) vm.editRuns = StyleRun.shift(vm.editRuns, value.text, it.text, para.bold, para.italic)+ value = it+ },+ visualTransformation = styled,textStyle = TextStyle(color = parseHex(para.color ?: "#000000"), fontSize = sp, lineHeight = sp * 1.2f, fontFamily = family,fontWeight = if (para.bold) FontWeight.Bold else FontWeight.Normal,diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.ktindex e939c24..295cdd6 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt@@ -238,6 +238,10 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)// a Word document or presentation opens for reading: no markup, no Edit textif (!doc.isOffice) Row(Modifier.fillMaxWidth().height(61.dp), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {MenuIcon(LucideIcons.MessageSquarePlus, stringResource(R.string.viewer_add_comment), allowed) { vm.notePrompt = NotePrompt(doc, null, sel) }+ // only the selected words, made bold in the page's own text (#127)+ if (doc.writable || doc.source == null) MenuIcon(LucideIcons.Bold, stringResource(R.string.edit_bold), true) {+ vm.boldSelection(doc, page, sel.rects)+ }MenuIcon(LucideIcons.Highlighter, stringResource(R.string.common_tool_highlight), allowed) { markup(TextMarkup.Highlight) }MenuIcon(LucideIcons.Underline, stringResource(R.string.common_tool_underline), allowed) { markup(TextMarkup.Underline) }MenuIcon(LucideIcons.Strikethrough, stringResource(R.string.viewer_strikethrough), allowed) { markup(TextMarkup.Strikethrough) }@@ -269,7 +273,7 @@ internal fun menuInk(): androidx.compose.ui.graphics.Color =internal fun MenuIcon(icon: ImageVector, label: String, enabled: Boolean, onClick: () -> Unit) {val ink = menuInk()Box(- Modifier.size(48.dp).clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = label },+ Modifier.size(44.dp).clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = label },contentAlignment = Alignment.Center,) {Icon(icon, null, tint = if (enabled) ink else ink.copy(alpha = 0.35f), modifier = Modifier.size(24.dp))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.ktindex b2200af..5dd55bb 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@@ -582,7 +582,11 @@ 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. */+/**+ * What the document is, as a card about it: its first page and name up top with what kind of file it+ * is; four tiles for pages, size, page size and where it lives; what it says about itself (title,+ * author, what made it); and three badges for its password, signature and accessibility.+ */@Composablefun DocumentInfoSheet(vm: AppViewModel, doc: OpenDocument) {val ctl = doc.controller@@ -590,53 +594,149 @@ fun DocumentInfoSheet(vm: AppViewModel, doc: OpenDocument) {val info = doc.infoval context = androidx.compose.ui.platform.LocalContext.currentval location = remember(doc.source) { doc.source?.toString()?.let { vm.locationOfDocument(it) } }- val kind = stringResource(com.chethan616.clearpdf.engine.DocumentTypes.kindOf(info.name).short)+ // "PDF 1.7", "DOCX": the file's own kind, never the shelf's plural+ val (badge, badgeColor) = com.chethan616.clearpdf.ui.desk.kindBadge(info.name)+ val kind = badge.ifBlank { "PDF" } + (if (info.pdfVersion.isNotBlank() && !doc.isOffice) " " + info.pdfVersion else "")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)- }+ val thumb = remember(doc.source) {+ doc.source?.let { u -> if (u.scheme == "file") u.path else u.toString() }}- PdfSheet(onDismiss = { ctl.sheet = ViewerSheet.None }, maxHeightFraction = 0.8f) {- SheetHeader(doc.title, subtitle = kind)+ PdfSheet(onDismiss = { ctl.sheet = ViewerSheet.None }, maxHeightFraction = 0.86f) {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)+ // the document: its first page, a little turned, its name and kind+ Row(Modifier.fillMaxWidth().padding(start = 20.dp, end = 12.dp, top = 6.dp, bottom = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ com.chethan616.clearpdf.ui.desk.PaperThumb(vm, thumb, 66.dp, 86.dp, tilt = -3f, corner = 8.dp, name = info.name)+ Spacer(Modifier.width(16.dp))+ Column(Modifier.weight(1f)) {+ Text(doc.title, style = ClearType.Title.copy(fontSize = 19.sp, lineHeight = 24.sp), color = c.text, maxLines = 3, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)+ Spacer(Modifier.height(8.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ InfoChip(kind, badgeColor)+ if (info.encrypted) InfoChip(stringResource(R.string.info_protected), Candy.Grape)+ }+ }+ com.chethan616.clearpdf.ui.glass.GlassCircle(onClick = { ctl.sheet = ViewerSheet.None }, size = 38.dp, label = stringResource(R.string.ui_close_sheet)) {+ com.chethan616.clearpdf.ui.glass.GlassIcon(LucideIcons.X, null, Modifier.size(18.dp))}}- 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)+ // the numbers, as tiles+ val tiles = buildList {+ add(Triple(LucideIcons.FileText, stringResource(if (doc.isSlides) R.string.info_slides else R.string.info_pages), doc.pageCount.toString()))+ add(Triple(LucideIcons.FileArchive, stringResource(R.string.info_size), android.text.format.Formatter.formatShortFileSize(context, info.fileSize.toLong())))+ if (first != null && !doc.isSheets) add(Triple(LucideIcons.Crop, stringResource(R.string.info_page_size), pageSizeName(first.width, first.height)))+ if (!location.isNullOrBlank()) add(Triple(LucideIcons.FolderOpen, stringResource(R.string.info_where), location))+ }+ Column(Modifier.padding(horizontal = 14.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ tiles.chunked(2).forEach { pair ->+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ pair.forEach { (icon, label, value) -> InfoTile(icon, label, value, Modifier.weight(1f)) }+ if (pair.size == 1) Spacer(Modifier.weight(1f))+ }}}- 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())+ // what the file says about itself+ val about = listOf(+ stringResource(R.string.info_title) to info.title,+ stringResource(R.string.info_author) to info.author,+ stringResource(R.string.info_subject) to info.subject,+ stringResource(R.string.info_keywords) to info.keywords,+ stringResource(R.string.info_creator) to info.creator,+ stringResource(R.string.info_producer) to info.producer?.let(::madeBy),+ ).filter { !it.second.isNullOrBlank() }+ if (about.isNotEmpty()) {+ Spacer(Modifier.height(18.dp))+ Text(stringResource(R.string.info_about).uppercase(), style = ClearType.Eyebrow, color = c.textSecondary, modifier = Modifier.padding(horizontal = 22.dp))+ Spacer(Modifier.height(6.dp))+ Column(Modifier.padding(horizontal = 14.dp).fillMaxWidth().clip(com.chethan616.clearpdf.ui.glass.RoundedRectangle(20.dp)).background(c.text.copy(alpha = 0.05f))) {+ about.forEachIndexed { i, (label, value) ->+ if (i > 0) Box(Modifier.padding(start = 16.dp).fillMaxWidth().height(1.dp).background(c.text.copy(alpha = 0.07f)))+ Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.Top) {+ Text(label, style = ClearType.Label, color = c.textSecondary, modifier = Modifier.weight(0.38f))+ Text(value.orEmpty(), style = ClearType.Body, color = c.text, modifier = Modifier.weight(0.62f), textAlign = TextAlign.End)+ }}}}- Spacer(Modifier.height(10.dp))+ // three yes / no facts as badges+ Spacer(Modifier.height(16.dp))+ Row(Modifier.padding(horizontal = 14.dp).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ FactBadge(LucideIcons.FileLock2, stringResource(R.string.info_protected), info.encrypted, Modifier.weight(1f))+ if (!doc.isOffice) {+ FactBadge(LucideIcons.Signature, stringResource(R.string.info_signed), info.signed, Modifier.weight(1f))+ FactBadge(LucideIcons.Accessibility, stringResource(R.string.info_tagged_short), info.tagged, Modifier.weight(1f))+ }+ }+ if (!doc.isOffice && (info.fields > 0u || info.attachments > 0u)) {+ Spacer(Modifier.height(8.dp))+ Row(Modifier.padding(horizontal = 14.dp).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if (info.fields > 0u) InfoTile(LucideIcons.FilePenLine, stringResource(R.string.info_fields), info.fields.toString(), Modifier.weight(1f))+ if (info.attachments > 0u) InfoTile(LucideIcons.Paperclip, stringResource(R.string.info_attachments), info.attachments.toString(), Modifier.weight(1f))+ }+ }+ Spacer(Modifier.height(18.dp))+ }+ }+}++/** What made a file, as people know it: files the app made before it was renamed say PdfCraft. */+private fun madeBy(producer: String): String = if (producer.trim().equals("PdfCraft", ignoreCase = true)) "Artefact" else producer++/** A page size by its paper name when it is one (A4, Letter …), else in millimetres. */+private fun pageSizeName(w: Float, h: Float): String {+ val (a, b) = if (w <= h) w to h else h to w+ fun near(x: Float, y: Float) = kotlin.math.abs(a - x) < 3f && kotlin.math.abs(b - y) < 3f+ val paper = when {+ near(595f, 842f) -> "A4"+ near(420f, 595f) -> "A5"+ near(842f, 1191f) -> "A3"+ near(612f, 792f) -> "Letter"+ near(612f, 1008f) -> "Legal"+ else -> null+ }+ val mm = "%.0f × %.0f mm".format(w / 72f * 25.4f, h / 72f * 25.4f)+ return if (paper != null) "$paper · $mm" else mm+}++/** A small coloured capsule with a word (the file's kind). */+@Composable+private fun InfoChip(text: String, color: Color) {+ Box(Modifier.clip(com.chethan616.clearpdf.ui.glass.Capsule).background(color.copy(alpha = 0.16f)).padding(horizontal = 10.dp, vertical = 4.dp)) {+ Text(text, style = ClearType.Label.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold), color = color)+ }+}++/** A number about the document: a glyph, what it is, and its value large. */+@Composable+private fun InfoTile(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, value: String, modifier: Modifier) {+ val c = pdfColors+ Column(modifier.clip(com.chethan616.clearpdf.ui.glass.RoundedRectangle(20.dp)).background(c.text.copy(alpha = 0.05f)).padding(14.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Icon(icon, null, tint = c.textSecondary, modifier = Modifier.size(15.dp))+ Spacer(Modifier.width(6.dp))+ Text(label, style = ClearType.Caption, color = c.textSecondary, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)+ }+ Spacer(Modifier.height(6.dp))+ Text(value, style = ClearType.BodyStrong.copy(fontSize = 17.sp), color = c.text, maxLines = 2, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)+ }+}++/** A yes / no fact: lit mint with a tick when it holds, faint with a dash when it doesn't. */+@Composable+private fun FactBadge(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, on: Boolean, modifier: Modifier) {+ val c = pdfColors+ val tint = if (on) Candy.Mint else c.textSecondary+ Column(+ modifier.clip(com.chethan616.clearpdf.ui.glass.RoundedRectangle(18.dp)).background(if (on) Candy.Mint.copy(alpha = 0.14f) else c.text.copy(alpha = 0.04f)).padding(vertical = 12.dp, horizontal = 6.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(contentAlignment = Alignment.BottomEnd) {+ Icon(icon, null, tint = tint, modifier = Modifier.size(22.dp))+ Box(Modifier.offset(x = 6.dp, y = 4.dp).size(14.dp).clip(androidx.compose.foundation.shape.CircleShape).background(if (on) Candy.Mint else c.textSecondary.copy(alpha = 0.5f)), contentAlignment = Alignment.Center) {+ Icon(if (on) LucideIcons.Check else LucideIcons.Minus, null, tint = Color.White, modifier = Modifier.size(10.dp))+ }}+ Spacer(Modifier.height(8.dp))+ Text(label, style = ClearType.Caption, color = if (on) c.text else c.textSecondary, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, textAlign = TextAlign.Center)}}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.ktindex a376a16..44d4088 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/widget/ArtefactWidgets.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/widget/ArtefactWidgets.kt@@ -19,12 +19,9 @@ import androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.width-import androidx.compose.ui.layout.SubcomposeLayout-import androidx.compose.ui.unit.Constraintsimport androidx.compose.foundation.layout.wrapContentHeightimport androidx.compose.runtime.Composableimport androidx.compose.runtime.CompositionLocalProvider@@ -47,12 +44,13 @@ import com.chethan616.clearpdf.ui.glass.Feelimport com.chethan616.clearpdf.ui.glass.GlassSettingsimport com.chethan616.clearpdf.ui.glass.Hapticsimport com.chethan616.clearpdf.ui.home.CardShape-import com.chethan616.clearpdf.ui.home.cardPaintimport com.chethan616.clearpdf.ui.home.ListCardimport com.chethan616.clearpdf.ui.home.LocalHomeVmimport com.chethan616.clearpdf.ui.home.NoteCardimport com.chethan616.clearpdf.ui.home.RecentCard+import com.chethan616.clearpdf.ui.home.StarredEmptyCardimport com.chethan616.clearpdf.ui.theme.ClearTheme+import com.chethan616.clearpdf.ui.theme.Toneimport com.chethan616.clearpdf.ui.theme.clearimport java.io.File@@ -65,29 +63,35 @@ 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"+/** A widget tap that asks for Files ▸ Starred. */+const val EXTRA_OPEN_STARRED = "com.chethan616.clearpdf.OPEN_STARRED"+/**- * 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.)+ * The home screen widgets. Notes, Recent and Starred are the desk's very cards (`NoteCard`,+ * `RecentCard`), liquid glass and all, rendered off screen ([ComposeSnapshot]) and kept as pictures.+ * The To-Do list on Android 12+ is the card's picture with real check boxes over it: the home screen+ * flips a tick itself the moment it is tapped and only tells the app, so nothing is redrawn on the tap.+ *+ * Speed rules: a picture is drawn only when what it shows changed (a signature per widget); a resize+ * shows the last picture scaled whole (never stretched) and redraws once the size has settled; a+ * render that a newer one replaces is dropped before it starts.*/object Widgets {private val main = Handler(Looper.getMainLooper())- private val queue = ArrayDeque<() -> Unit>()++ private class Job(val key: String, val run: (next: () -> Unit) -> Unit)++ private val queue = ArrayDeque<Job>()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) {+ /**+ * Runs the renders one after another on the main thread (one virtual display at a time). A job+ * queued under [key] replaces one of the same key still waiting: only the newest picture is drawn.+ */+ internal fun enqueue(key: String, job: (next: () -> Unit) -> Unit) {main.post {- queue.addLast {- job {- main.post {- busy = false- drain()- }- }- }+ queue.removeAll { it.key == key }+ queue.addLast(Job(key) { next -> job(next) })drain()}}@@ -96,42 +100,68 @@ object Widgets {if (busy) returnval job = queue.removeFirstOrNull() ?: returnbusy = true- job()+ job.run {+ main.post {+ busy = false+ drain()+ }+ }}- private val soon = Runnable { pendingCtx?.let { refreshAll(it) }; pendingCtx = null }+ /** What each widget shows now (by widget id): it is drawn again only when this changes. */+ private val shown = java.util.concurrent.ConcurrentHashMap<Int, String>()++ internal fun isShowing(id: Int, sig: String) = shown[id] == sig++ internal fun showing(id: Int, sig: String) { shown[id] = sig }++ internal fun forget(id: Int) { shown.remove(id) }++ private val todoSoon = Runnable { pendingCtx?.let { TodoWidget.syncAll(it) } }+ private val notesSoon = Runnable { pendingCtx?.let { NoteWidget.refreshChanged(it) } }@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.+ * The notes changed in the app: the lists follow at once (they cost nothing to redraw), the note+ * cards once the notes have been still for a moment, and only those whose note really changed.+ * Any thread.*/fun refreshSoon(ctx: Context) {val app = ctx.applicationContextval mgr = AppWidgetManager.getInstance(app)- if (mgr.getAppWidgetIds(ComponentName(app, TodoWidget::class.java)).isEmpty() &&- mgr.getAppWidgetIds(ComponentName(app, NoteWidget::class.java)).isEmpty()) return+ val lists = ids(app, mgr, TodoWidget::class.java)+ val notes = ids(app, mgr, NoteWidget::class.java)+ if (lists.isEmpty() && notes.isEmpty()) returnpendingCtx = app- main.removeCallbacks(soon)- main.postDelayed(soon, 1500L)+ if (lists.isNotEmpty()) {+ main.removeCallbacks(todoSoon)+ main.postDelayed(todoSoon, 1200L)+ }+ if (notes.isNotEmpty()) {+ main.removeCallbacks(notesSoon)+ main.postDelayed(notesSoon, 1200L)+ }}- /** Redraw the notes widgets (the notes changed). Any thread. */+ /** Redraw every list and note widget (a widget was set to show another one). Any thread. */fun refreshAll(ctx: Context, then: (() -> Unit)? = null) {val app = ctx.applicationContextval mgr = AppWidgetManager.getInstance(app)- val todo = mgr.getAppWidgetIds(ComponentName(app, TodoWidget::class.java))- val notes = mgr.getAppWidgetIds(ComponentName(app, NoteWidget::class.java))+ val todo = ids(app, mgr, TodoWidget::class.java)+ val notes = ids(app, mgr, NoteWidget::class.java)var left = todo.size + notes.sizeif (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) }+ todo.forEach { id -> forget(id); TodoWidget.update(app, mgr, id, one) }+ notes.forEach { id -> forget(id); NoteWidget.update(app, mgr, id, one) }}+ internal fun ids(ctx: Context, mgr: AppWidgetManager, provider: Class<*>): IntArray =+ mgr.getAppWidgetIds(ComponentName(ctx, provider))+/** 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@@ -163,6 +193,14 @@ object Widgets {internal fun open(ctx: Context, noteId: String?, requestKey: String): PendingIntent =activity(ctx, requestKey) { if (noteId != null) putExtra(EXTRA_OPEN_NOTE, noteId) }+ /** A broadcast to [provider] with [action] for widget [id]. */+ internal fun broadcast(ctx: Context, provider: Class<*>, action: String, id: Int): PendingIntent {+ val intent = Intent(ctx, provider).setAction(action)+ .setData(Uri.parse("artefact://widget/$action/$id"))+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)+ return PendingIntent.getBroadcast(ctx, "$action/$id".hashCode(), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)+ }+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)@@ -175,12 +213,6 @@ object Widgets {/** 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.@@ -230,6 +262,20 @@ object Widgets {views.setViewLayoutMargin(R.id.card_open, RemoteViews.MARGIN_TOP, f.dy, TypedValue.COMPLEX_UNIT_PX)}+ /** The round "next" button in the fitted card's top right corner, or hidden. */+ internal fun placeNext(ctx: Context, views: RemoteViews, f: Fit?, cardW: Int, onTap: PendingIntent?) {+ if (f == null || onTap == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {+ views.setViewVisibility(R.id.card_next, android.view.View.GONE)+ return+ }+ val inset = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, ctx.resources.displayMetrics)+ val side = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34f, ctx.resources.displayMetrics)+ views.setViewVisibility(R.id.card_next, android.view.View.VISIBLE)+ views.setViewLayoutMargin(R.id.card_next, RemoteViews.MARGIN_LEFT, f.dx + cardW * f.scale - inset - side, TypedValue.COMPLEX_UNIT_PX)+ views.setViewLayoutMargin(R.id.card_next, RemoteViews.MARGIN_TOP, f.dy + inset, TypedValue.COMPLEX_UNIT_PX)+ views.setOnClickPendingIntent(R.id.card_next, onTap)+ }+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. */@@ -241,208 +287,472 @@ object Widgets {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 ------+ // ---- Recent and Starred: drawn by the app (its thumbnails live there), kept for when it is away ----++ /** One of the two document widgets: which files it shows and where its picture is kept. */+ internal enum class Shelf(val provider: Class<out AppWidgetProvider>, val file: String) {+ Recent(RecentWidget::class.java, "widget_recent"),+ Starred(StarredWidget::class.java, "widget_starred"),+ }- private fun recentFile(ctx: Context) = File(ctx.cacheDir, "widget_recent.png")+ private fun picture(ctx: Context, shelf: Shelf) = File(ctx.cacheDir, "${shelf.file}.png")- private fun recentTopFile(ctx: Context) = File(ctx.cacheDir, "widget_recent_top.txt")+ private fun topFile(ctx: Context, shelf: Shelf) = File(ctx.cacheDir, "${shelf.file}_top.txt")- /** The app's view model while it runs: Recent's thumbnails come from it. */+ /** The app's view model while it runs: the document widgets' thumbnails come from it. */@Volatileinternal 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. */+ private val shelfSig = java.util.concurrent.ConcurrentHashMap<Shelf, String>()++ private fun rowsOf(vm: AppViewModel, shelf: Shelf) = when (shelf) {+ Shelf.Recent -> vm.recentRows()+ Shelf.Starred -> vm.starredRows()+ }++ /** The app's documents changed (or a Recent / Starred widget was resized): draw those widgets again if what they show changed. */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)+ for (shelf in Shelf.entries) {+ val ids = ids(app, mgr, shelf.provider)+ if (ids.isEmpty()) continue+ // only when its 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 rows = rowsOf(vm, shelf)+ val sig = rows.take(3).joinToString("|") { it.key + it.date } + "#" + rows.size + "#" + ids.joinToString(",") { id -> size(app, mgr.getAppWidgetOptions(id)).toString() }+ if (!force && sig == shelfSig[shelf]) continue+ shelfSig[shelf] = sig+ val job = shelfJobs.getOrPut(shelf) { Runnable { liveVm?.get()?.let { draw(it, shelf) } } }+ main.removeCallbacks(job)+ main.postDelayed(job, if (force) 450L else 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 val shelfJobs = java.util.concurrent.ConcurrentHashMap<Shelf, Runnable>()- private fun drawRecent(vm: AppViewModel) {+ private fun draw(vm: AppViewModel, shelf: Shelf) {val app = vm.getApplication<android.app.Application>()val mgr = AppWidgetManager.getInstance(app)- val ids = mgr.getAppWidgetIds(ComponentName(app, RecentWidget::class.java))+ val ids = ids(app, mgr, shelf.provider)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) }+ val rows = rowsOf(vm, shelf)+ val top = rows.firstOrNull()?.key+ if (rows.isEmpty() && shelf == Shelf.Recent) {+ picture(app, shelf).delete()+ ids.forEach { showDoc(app, mgr, it, shelf, 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))+ // one picture serves every widget of the shelf: the desk's card at its desk size, fitted to each+ enqueue(shelf.name) { next ->+ GlassSettings.load(app)+ val choice = themeChoice(app)+ val dm = app.resources.displayMetrics+ val pad = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12f, dm).toInt()+ val deskW = deskWidth(app)+ val deskWPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, deskW.value, dm).toInt()+ val deskHPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 226f, dm).toInt()+ val starredTitle = app.getString(R.string.home_list_starred)+ ComposeSnapshot.render(+ app, deskWPx + 2 * pad, deskHPx + 2 * pad, 0f, settleMs = 900,+ content = {+ ClearTheme(choice) {+ CompositionLocalProvider(LocalHomeVm provides vm) {+ Box(Modifier.fillMaxSize().padding(toDp(app, pad))) {+ when {+ shelf == Shelf.Recent -> RecentCard(vm, rows, onAll = {}, modifier = Modifier.width(deskW))+ rows.isEmpty() -> StarredEmptyCard(Modifier.width(deskW))+ else -> RecentCard(vm, rows, onAll = {}, modifier = Modifier.width(deskW), title = starredTitle, cardTone = Tone.Lavender)}}}- },- ) { 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()+ }+ },+ ) { frame ->+ if (frame != null) {+ runCatching { picture(app, shelf).outputStream().use { frame.compress(Bitmap.CompressFormat.PNG, 100, it) } }+ runCatching { if (top != null) topFile(app, shelf).writeText(top) else topFile(app, shelf).delete() }+ ids(app, mgr, shelf.provider).forEach { showDoc(app, mgr, it, shelf, frame, top) }}+ next()}}}- internal fun savedRecent(ctx: Context): Pair<Bitmap?, String?> =- (runCatching { BitmapFactory.decodeFile(recentFile(ctx).path) }.getOrNull()) to runCatching { recentTopFile(ctx).readText() }.getOrNull()+ internal fun saved(ctx: Context, shelf: Shelf): Pair<Bitmap?, String?> =+ (runCatching { BitmapFactory.decodeFile(picture(ctx, shelf).path) }.getOrNull()) to runCatching { topFile(ctx, shelf).readText() }.getOrNull()?.ifBlank { null }++ /** A Recent or Starred widget showing [bitmap]: a tap opens Files on Recent or Starred. */+ internal fun showDoc(ctx: Context, mgr: AppWidgetManager, id: Int, shelf: Shelf, bitmap: Bitmap?, top: String?) {+ val app = ctx.applicationContext+ val views = RemoteViews(app.packageName, R.layout.widget_card)+ val (w, h) = size(app, mgr.getAppWidgetOptions(id))+ if (bitmap != null) {+ views.setImageViewBitmap(R.id.card_image, onBox(bitmap, w, h))+ placeCardTarget(views, fit(w, h, bitmap.width, bitmap.height), bitmap.width, bitmap.height)+ }+ views.setContentDescription(R.id.card_image, app.getString(if (shelf == Shelf.Recent) R.string.desk_recent else R.string.home_list_starred))+ views.setOnClickPendingIntent(+ R.id.card_open,+ // the card opens its own list in Files (Recent or Starred), never a document by itself+ activity(app, "${shelf.file}/$id") { if (shelf == Shelf.Starred) putExtra(EXTRA_OPEN_STARRED, true) else putExtra(EXTRA_OPEN_FILES, true) },+ )+ placeNext(app, views, null, 0, null)+ ROWS.forEach { views.setViewVisibility(it, android.view.View.GONE) }+ runCatching { mgr.updateAppWidget(id, views) }+ }}-/** The most recent list (pinned first), its first items ticked right on the home screen. */+/**+ * A list of the user's (the one chosen for it, else the latest), the desk's own `ListCard`, true+ * liquid glass and all, its items ticked right on the home screen. With more than one list, the round+ * button in its corner turns to the next.+ *+ * A tick is instant without a native copy of the card: every render draws the card twice, as it is+ * and with every item flipped, and keeps where each pill lies. A tap copies that one pill from the+ * flipped picture into the shown one (a few milliseconds of canvas work) and shows it; the two+ * pictures are then each other's flip again, exactly what a new render would draw, so nothing is+ * rendered after a tap at all. They are kept on disk too, so a tap is as quick when the app is gone.+ */class TodoWidget : AppWidgetProvider() {override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {val pending = goAsync()var left = ids.sizeif (left == 0) return pending.finish()- ids.forEach { update(context, manager, it) { if (--left == 0) pending.finish() } }+ ids.forEach { Widgets.forget(it); 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() }+ // at once: the card as it is, scaled whole to the new size; drawn anew once the size settles+ val app = context.applicationContext+ drawn(app, id)?.let { show(app, manager, id, it) }+ val job = resizes.getOrPut(id) { Runnable { update(app, AppWidgetManager.getInstance(app), id) } }+ main.removeCallbacks(job)+ main.postDelayed(job, 350L)+ }++ override fun onDeleted(context: Context, appWidgetIds: IntArray) {+ appWidgetIds.forEach { id ->+ WidgetPicks.set(context, id, null)+ Widgets.forget(id)+ cache.remove(id)+ files(context, id).forEach { it.delete() }+ }}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+ val app = context.applicationContext+ when (intent.action) {+ ACTION_TOGGLE -> {+ val note = intent.getStringExtra(EXTRA_NOTE) ?: return+ val item = intent.getStringExtra(EXTRA_ITEM) ?: return+ GlassSettings.load(app)+ val wasDone = drawnShowing(app, note).firstOrNull()?.note?.items?.firstOrNull { it.id == item }?.done+ ?: (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) }+ // first what is seen: the pill flips on the home screen now+ val flipped = flipNow(app, note, item)+ // then the truth: the file, and the app's own notes if it runs (so it 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() } }+ if (!flipped) {+ // no picture to flip in (a first tap after an update): drawn anew+ val mgr = AppWidgetManager.getInstance(app)+ Widgets.ids(app, mgr, TodoWidget::class.java).filter { WidgetPicks.resolve(app, it, NoteKind.List)?.id == note }.forEach { update(app, mgr, it) }+ }+ return+ }+ ACTION_NEXT -> {+ val id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)+ if (id == AppWidgetManager.INVALID_APPWIDGET_ID) return+ GlassSettings.load(app)+ runCatching { Haptics(app, android.view.View(app)).play(Feel.Tick) }+ WidgetPicks.next(app, id, NoteKind.List)+ val pending = goAsync()+ update(app, AppWidgetManager.getInstance(app), id) { pending.finish() }+ return+ }}super.onReceive(context, intent)}+ /** The card as last drawn for a widget: the picture shown, its every-item-flipped twin, and where each pill is. */+ internal class Drawn(val note: Note, val shown: Bitmap, val twin: Bitmap?, val spots: Map<String, android.graphics.RectF>)+companion object {const val ACTION_TOGGLE = "com.chethan616.clearpdf.widget.TOGGLE"+ const val ACTION_NEXT = "com.chethan616.clearpdf.widget.NEXT_LIST"private const val EXTRA_NOTE = "note"private const val EXTRA_ITEM = "item"+ private val main = Handler(Looper.getMainLooper())+ private val resizes = HashMap<Int, Runnable>()+ private val cache = java.util.concurrent.ConcurrentHashMap<Int, Drawn>()++ /** Bring every list widget in line with the notes (after a change in the app): only those whose list changed are drawn. */+ fun syncAll(ctx: Context) {+ val app = ctx.applicationContext+ val mgr = AppWidgetManager.getInstance(app)+ Widgets.ids(app, mgr, TodoWidget::class.java).forEach { update(app, mgr, it) }+ }++ private fun signature(app: Context, mgr: AppWidgetManager, id: Int, note: Note?): String =+ "${Widgets.size(app, mgr.getAppWidgetOptions(id))}|${WidgetCards.isDark(app)}|${note?.id}|${note?.title}|" ++ note?.items?.joinToString(",") { "${it.id}:${it.text.hashCode()}:${it.done}" } + "|" + WidgetPicks.count(app, NoteKind.List)++ private fun files(ctx: Context, id: Int) = listOf("shown.png", "twin.png", "spots.json").map { File(ctx.cacheDir, "widget_list_${id}_$it") }++ /** The card last drawn for widget [id]: from memory, else from the cache folder (the app was away). */+ private fun drawn(app: Context, id: Int): Drawn? = cache[id] ?: runCatching {+ val (shownF, twinF, spotsF) = files(app, id)+ if (!shownF.isFile || !spotsF.isFile) return null+ val o = org.json.JSONObject(spotsF.readText())+ val note = NoteFile.read(app).firstOrNull { it.id == o.optString("note") } ?: return null+ val spots = HashMap<String, android.graphics.RectF>()+ o.optJSONObject("spots")?.let { s ->+ s.keys().forEach { k -> s.optJSONArray(k)?.let { a -> spots[k] = android.graphics.RectF(a.optDouble(0).toFloat(), a.optDouble(1).toFloat(), a.optDouble(2).toFloat(), a.optDouble(3).toFloat()) } }+ }+ val shown = BitmapFactory.decodeFile(shownF.path)?.copy(Bitmap.Config.ARGB_8888, true) ?: return null+ val twin = BitmapFactory.decodeFile(twinF.path)?.copy(Bitmap.Config.ARGB_8888, true)+ // only while the file still says what the picture shows (a change in the app since then: no)+ val doneNow = note.items.associate { it.id to it.done }+ val doneThen = o.optJSONObject("done")+ if (doneThen == null || doneNow.any { (k, v) -> doneThen.has(k) && doneThen.optBoolean(k) != v }) return null+ Drawn(note, shown, twin, spots).also { cache[id] = it }+ }.getOrNull()++ private fun drawnShowing(app: Context, noteId: String): List<Drawn> {+ val mgr = AppWidgetManager.getInstance(app)+ return Widgets.ids(app, mgr, TodoWidget::class.java).toList().mapNotNull { id -> drawn(app, id)?.takeIf { it.note.id == noteId } }+ }++ private fun save(app: Context, id: Int, d: Drawn) {+ Thread {+ runCatching {+ val (shownF, twinF, spotsF) = files(app, id)+ shownF.outputStream().use { d.shown.compress(Bitmap.CompressFormat.PNG, 100, it) }+ if (d.twin != null) twinF.outputStream().use { d.twin.compress(Bitmap.CompressFormat.PNG, 100, it) } else twinF.delete()+ val spots = org.json.JSONObject()+ d.spots.forEach { (k, r) -> spots.put(k, org.json.JSONArray(listOf(r.left, r.top, r.right, r.bottom))) }+ val done = org.json.JSONObject()+ d.note.items.forEach { done.put(it.id, it.done) }+ spotsF.writeText(org.json.JSONObject().put("note", d.note.id).put("spots", spots).put("done", done).toString())+ }+ }.start()+ }++ /**+ * Item [itemId] of list [noteId] ticked or unticked on every widget showing it, at once: its pill+ * taken from the flipped picture (and the old one put in the flipped picture's place). False when+ * no widget had pictures to do it with.+ */+ fun flipNow(ctx: Context, noteId: String, itemId: String): Boolean {+ val app = ctx.applicationContext+ val mgr = AppWidgetManager.getInstance(app)+ var any = false+ Widgets.ids(app, mgr, TodoWidget::class.java).forEach { id ->+ val d = drawn(app, id)?.takeIf { it.note.id == noteId } ?: return@forEach+ val twin = d.twin ?: return@forEach+ val note = d.note.copy(items = d.note.items.map { if (it.id == itemId) it.copy(done = !it.done) else it })+ val spot = d.spots[itemId]+ val (shown, other) = if (spot == null) d.shown to twin else {+ // a pixel or two round the pill: its rim and the shade it casts on the card+ val r = android.graphics.Rect(spot.left.toInt() - 2, spot.top.toInt() - 2, spot.right.toInt() + 3, spot.bottom.toInt() + 3)+ .apply { intersect(0, 0, d.shown.width, d.shown.height) }+ val newShown = d.shown.copy(Bitmap.Config.ARGB_8888, true)+ val newTwin = twin.copy(Bitmap.Config.ARGB_8888, true)+ val plain = android.graphics.Paint().apply { xfermode = android.graphics.PorterDuffXfermode(android.graphics.PorterDuff.Mode.SRC) }+ android.graphics.Canvas(newShown).drawBitmap(twin, r, r, plain)+ android.graphics.Canvas(newTwin).drawBitmap(d.shown, r, r, plain)+ newShown to newTwin+ }+ val next = Drawn(note, shown, other, d.spots)+ cache[id] = next+ show(app, mgr, id, next)+ // what the widget shows is now this list as it will be: no render needed when the notes catch up+ Widgets.showing(id, signature(app, mgr, id, note))+ save(app, id, next)+ any = true+ }+ return any+ }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 latestval list = WidgetPicks.resolve(app, id, NoteKind.List)+ val sig = signature(app, mgr, id, list)+ if (Widgets.isShowing(id, sig)) return done()val res = app.resourcesval shown = list ?: Note("", NoteKind.List)- Widgets.enqueue { next ->+ val flipped = shown.copy(items = shown.items.map { it.copy(done = !it.done) })+ Widgets.enqueue("list/$id") { 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+ // 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 sizeval 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 })+ fun draw(note: Note, then: (Bitmap?, Map<String, android.graphics.RectF>) -> Unit) {+ 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(note, onOpen = {}, onLong = {}, onToggle = {}, modifier = Modifier.width(deskW), onItemPlaced = { item, r -> placed[item.id] = r })+ }+ }) { frame ->+ val top = card?.top ?: 0+ then(frame, placed.mapValues { (_, r) -> android.graphics.RectF(r.left, r.top - top, r.right, r.bottom - top) })}- }) { 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+ }+ draw(shown) { frame, spots ->+ if (frame == null) {+ // a render that did not come back keeps the card already there+ drawn(app, id)?.let { show(app, mgr, id, it) } ?: run {+ val (w, h) = Widgets.size(app, mgr.getAppWidgetOptions(id))+ val bitmap = 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+ show(app, mgr, id, Drawn(shown, bitmap, null, emptyMap()))}- 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),- )+ next()+ done()+ return@draw+ }+ // shown at once; its flipped twin is drawn after, for the taps+ val d = Drawn(shown, frame.copy(Bitmap.Config.ARGB_8888, true), null, if (list != null) spots else emptyMap())+ cache[id] = d+ show(app, mgr, id, d)+ Widgets.showing(id, sig)+ if (list == null || shown.items.none { it.text.isNotBlank() }) {+ next()+ done()+ return@draw+ }+ draw(flipped) { twin, _ ->+ if (twin != null && twin.width == frame.width && twin.height == frame.height) {+ val full = Drawn(shown, d.shown, twin.copy(Bitmap.Config.ARGB_8888, true), d.spots)+ if (cache[id] === d) cache[id] = full+ save(app, id, full)+ }+ next()+ done()}- runCatching { mgr.updateAppWidget(id, views) }- next()- done()}}}++ /** Widget [id] showing [d]: the card fitted to the widget, a tap target over each of its pills. */+ private fun show(app: Context, mgr: AppWidgetManager, id: Int, d: Drawn) {+ val res = app.resources+ val (w, h) = Widgets.size(app, mgr.getAppWidgetOptions(id))+ val bitmap = d.shown+ 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, d.note.title.ifBlank { res.getString(R.string.notes_untitled_list) })+ views.setOnClickPendingIntent(R.id.card_open, Widgets.open(app, d.note.id.ifEmpty { null }, "list/$id"))+ Widgets.placeCardTarget(views, f, bitmap.width, bitmap.height)+ val spots = d.note.items.filter { it.id in d.spots }.map { it.id to d.spots.getValue(it.id) }+ Widgets.ROWS.forEachIndexed { i, rowId ->+ val spot = spots.getOrNull(i)+ if (spot == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {+ // before Android 12 the targets can't be placed: the whole card opens the list+ 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/${d.note.id}/$itemId"))+ .putExtra(EXTRA_NOTE, d.note.id).putExtra(EXTRA_ITEM, itemId)+ views.setOnClickPendingIntent(+ rowId,+ PendingIntent.getBroadcast(app, "${d.note.id}/$itemId".hashCode(), toggle, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT),+ )+ }+ // more than one list: the round button in the corner turns to the next+ val many = WidgetPicks.count(app, NoteKind.List) > 1+ Widgets.placeNext(app, views, f, bitmap.width, if (many) Widgets.broadcast(app, TodoWidget::class.java, ACTION_NEXT, id) else null)+ if (many) {+ views.setContentDescription(R.id.card_next, res.getString(R.string.widget_next_list))+ views.setInt(R.id.card_next, "setColorFilter", if (WidgetCards.isDark(app)) 0xF0FFFFFF.toInt() else 0xCC12302B.toInt())+ }+ runCatching { mgr.updateAppWidget(id, views) }+ }}}-/** The most recent text note (pinned first) as the desk's paper card: the starter "Thought of the day" on a fresh install. */+/**+ * A note as the desk's paper card (the one chosen for it, else the latest; the starter "Thought of the+ * day" on a fresh install). With more than one note, the round button in its corner turns to the next.+ */class NoteWidget : AppWidgetProvider() {override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {val pending = goAsync()var left = ids.sizeif (left == 0) return pending.finish()- ids.forEach { update(context, manager, it) { if (--left == 0) pending.finish() } }+ ids.forEach { Widgets.forget(it); 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() }+ // at once: the last picture, scaled whole to the new size; the card itself once the size settles+ val app = context.applicationContext+ last[id]?.let { show(app, manager, id, it.first, it.second) }+ val job = resizes.getOrPut(id) { Runnable { update(app, AppWidgetManager.getInstance(app), id) } }+ main.removeCallbacks(job)+ main.postDelayed(job, 350L)+ }++ override fun onDeleted(context: Context, appWidgetIds: IntArray) {+ appWidgetIds.forEach { WidgetPicks.set(context, it, null); Widgets.forget(it); last.remove(it) }+ }++ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action == ACTION_NEXT) {+ val app = context.applicationContext+ val id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)+ if (id == AppWidgetManager.INVALID_APPWIDGET_ID) return+ GlassSettings.load(app)+ runCatching { Haptics(app, android.view.View(app)).play(Feel.Tick) }+ WidgetPicks.next(app, id, NoteKind.Text)+ val pending = goAsync()+ update(app, AppWidgetManager.getInstance(app), id) { pending.finish() }+ return+ }+ super.onReceive(context, intent)}companion object {+ const val ACTION_NEXT = "com.chethan616.clearpdf.widget.NEXT_NOTE"+ private val main = Handler(Looper.getMainLooper())+ private val resizes = HashMap<Int, Runnable>()++ /** The last picture each widget showed and the note it opens: shown at once while a new one draws. */+ private val last = java.util.concurrent.ConcurrentHashMap<Int, Pair<Bitmap, String?>>()++ private fun signature(app: Context, mgr: AppWidgetManager, id: Int, note: Note?): String =+ "${Widgets.size(app, mgr.getAppWidgetOptions(id))}|${WidgetCards.isDark(app)}|${note?.id}|${note?.title}|${note?.body?.hashCode()}|${note?.images}|${note?.updated}|" ++ WidgetPicks.count(app, NoteKind.Text)++ /** Redraw the note widgets whose note changed (after a change in the app). */+ fun refreshChanged(ctx: Context) {+ val app = ctx.applicationContext+ val mgr = AppWidgetManager.getInstance(app)+ Widgets.ids(app, mgr, NoteWidget::class.java).forEach { update(app, mgr, it) }+ }+fun update(ctx: Context, mgr: AppWidgetManager, id: Int, done: () -> Unit = {}) {val app = ctx.applicationContextval (w, h) = Widgets.size(app, mgr.getAppWidgetOptions(id))// the note chosen for this widget, else the latestval note = WidgetPicks.resolve(app, id, NoteKind.Text)+ val sig = signature(app, mgr, id, note)+ if (Widgets.isShowing(id, sig)) return done()val res = app.resourcesval shown = note ?: Note("", NoteKind.Text, title = res.getString(R.string.thought_title), body = res.getString(R.string.seed_note_body))- Widgets.enqueue { next ->+ Widgets.enqueue("note/$id") { next ->GlassSettings.load(app)val choice = Widgets.themeChoice(app)val side = minOf(w, h)@@ -454,81 +764,63 @@ class NoteWidget : AppWidgetProvider() {}}}) { 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) }+ // a render that did not come back keeps the picture already there (never a different-looking stand-in)+ val bitmap = frame ?: last[id]?.first ?: WidgetCards(app, w, h).note(shown, res.getString(R.string.notes_untitled_note)) { Widgets.mediaFile(app, it) }+ last[id] = bitmap to note?.id+ show(app, mgr, id, bitmap, note?.id)+ if (frame != null) Widgets.showing(id, sig)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)+ private fun show(app: Context, mgr: AppWidgetManager, id: Int, bitmap: Bitmap, noteId: String?) {+ val res = app.resourcesval (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) },- )+ 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, res.getString(R.string.widget_note_name))+ views.setOnClickPendingIntent(R.id.card_open, Widgets.open(app, noteId, "note/$id"))+ Widgets.placeCardTarget(views, f, bitmap.width, bitmap.height)+ val many = WidgetPicks.count(app, NoteKind.Text) > 1+ Widgets.placeNext(app, views, f, bitmap.width, if (many) Widgets.broadcast(app, NoteWidget::class.java, ACTION_NEXT, id) else null)+ if (many) {+ views.setContentDescription(R.id.card_next, res.getString(R.string.widget_next_note))+ // the paper card's own ink: dark on the light card, white on the dark one+ views.setInt(R.id.card_next, "setColorFilter", if (WidgetCards.isDark(app)) 0xF0FFFFFF.toInt() else 0xCC3A3420.toInt())+ }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) }- }+/** The desk's Recent card: the newest documents' first pages fanned, opening Files ▸ Recent. */+class RecentWidget : AppWidgetProvider() {+ override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) = docUpdate(context, manager, ids, Widgets.Shelf.Recent)++ override fun onAppWidgetOptionsChanged(context: Context, manager: AppWidgetManager, id: Int, newOptions: Bundle) =+ docResized(context, manager, id, Widgets.Shelf.Recent)+}++/** Starred: the starred documents as the Recent card shows its own, opening Files ▸ Starred. */+class StarredWidget : AppWidgetProvider() {+ override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) = docUpdate(context, manager, ids, Widgets.Shelf.Starred)++ override fun onAppWidgetOptionsChanged(context: Context, manager: AppWidgetManager, id: Int, newOptions: Bundle) =+ docResized(context, manager, id, Widgets.Shelf.Starred)+}++private fun docUpdate(context: Context, manager: AppWidgetManager, ids: IntArray, shelf: Widgets.Shelf) {+ val (bitmap, top) = Widgets.saved(context, shelf)+ ids.forEach { Widgets.showDoc(context, manager, it, shelf, bitmap, top) }+ Widgets.liveVm?.get()?.let { vm -> Handler(Looper.getMainLooper()).post { Widgets.refreshRecent(vm, force = true) } }+}++private fun docResized(context: Context, manager: AppWidgetManager, id: Int, shelf: Widgets.Shelf) {+ // at once: the last picture scaled whole to the new size (the same card at every size)+ val (bitmap, top) = Widgets.saved(context, shelf)+ Widgets.showDoc(context, manager, id, shelf, bitmap, top)}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.ktindex 3d0131a..5e4e54f 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetCards.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetCards.kt@@ -155,14 +155,14 @@ internal class WidgetCards(private val ctx: Context, private val w: Int, private}val more = items.size - spots.sizeif (more > 0) {- val p = paint(R.font.jakarta, 11.5f, tone.ink.argb(0.6f), "'wght' 400")+ val p = paint(R.font.outfit, 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")+ val p = paint(R.font.outfit, 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)@@ -225,7 +225,7 @@ internal class WidgetCards(private val ctx: Context, private val w: Int, private})}val textX = left + dp(8f) + dp(24f) + dp(10f)- val tp = paint(R.font.jakarta, 14.5f, ink.toArgb(), "'wght' 400")+ val tp = paint(R.font.outfit, 14.5f, ink.toArgb(), "'wght' 400")val room = (right - dp(12f) - textX).toInt()val line = layout(item.text, tp, room, 22f, 1)c.save()@@ -247,15 +247,15 @@ internal class WidgetCards(private val ctx: Context, private val w: Int, privateval titleText = title.ifBlank { untitled }val variation = "'wght' 800"- val base = paint(R.font.jakarta, 27f, tone.accent.toArgb(), variation, -0.6f)+ val base = paint(R.font.outfit, 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 tp = paint(R.font.outfit, 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.heightval date = shortDate(note.updated)- val dp0 = paint(R.font.jakarta, 10.5f, tone.ink.argb(0.55f), "'wght' 400")+ val dp0 = paint(R.font.outfit, 10.5f, tone.ink.argb(0.55f), "'wght' 400")val dateH = dp0.fontMetrics.let { it.descent - it.ascent }val dateTop = h - pad - dateHif (body.isNotBlank() && title.length < 40) {@@ -263,7 +263,7 @@ internal class WidgetCards(private val ctx: Context, private val w: Int, privateval 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 bp = paint(R.font.outfit, 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.heightdiff --git a/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetPickActivity.kt b/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetPickActivity.ktindex 6686d51..4d08e57 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetPickActivity.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/widget/WidgetPickActivity.kt@@ -49,12 +49,32 @@ internal object WidgetPicks {}.apply()}+ /** The notes of [kind] a widget can show, in the desk's order (pinned first, then the newest). */+ fun candidates(ctx: Context, kind: NoteKind): List<Note> =+ NoteFile.read(ctx).filter { it.kind == kind && if (kind == NoteKind.List) it.items.any { i -> i.text.isNotBlank() } else !it.isEmpty }+ .sortedWith(compareByDescending<Note> { it.pinned }.thenByDescending { it.created })++ /** How many notes of [kind] there are to turn through. */+ fun count(ctx: Context, kind: NoteKind): Int = candidates(ctx, kind).size+/** 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()}++ /**+ * Turn widget [widgetId] to the next note of [kind] (the widget's round button), wrapping round.+ * The order is by creation, so ticking an item never reshuffles which list comes next.+ */+ fun next(ctx: Context, widgetId: Int, kind: NoteKind) {+ val all = candidates(ctx, kind)+ if (all.size < 2) return+ val now = resolve(ctx, widgetId, kind)?.id+ val i = all.indexOfFirst { it.id == now }+ set(ctx, widgetId, all[(i + 1).mod(all.size)].id)+ }}/**diff --git a/android/app/src/main/res/drawable-nodpi/sky_desk.png b/android/app/src/main/res/drawable-nodpi/sky_desk.pngnew file mode 100644index 0000000..6b3c04dBinary files /dev/null and b/android/app/src/main/res/drawable-nodpi/sky_desk.png differdiff --git a/android/app/src/main/res/drawable-nodpi/sky_thoughts.png b/android/app/src/main/res/drawable-nodpi/sky_thoughts.pngnew file mode 100644index 0000000..4cfaadfBinary files /dev/null and b/android/app/src/main/res/drawable-nodpi/sky_thoughts.png differdiff --git a/android/app/src/main/res/drawable-nodpi/sky_today.png b/android/app/src/main/res/drawable-nodpi/sky_today.pngnew file mode 100644index 0000000..3627dabBinary files /dev/null and b/android/app/src/main/res/drawable-nodpi/sky_today.png differdiff --git a/android/app/src/main/res/drawable/widget_next.xml b/android/app/src/main/res/drawable/widget_next.xmlnew file mode 100644index 0000000..bf6929a--- /dev/null+++ b/android/app/src/main/res/drawable/widget_next.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- The next list or note: two curved arrows going round. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">+ <path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="2.2"+ android:strokeLineCap="round" android:strokeLineJoin="round"+ android:pathData="M4,11A8,8 0,0 1,18.5 7M20,13A8,8 0,0 1,5.5 17M18.5,3V7H14.5M5.5,21V17H9.5" />+</vector>diff --git a/android/app/src/main/res/drawable/widget_round_button.xml b/android/app/src/main/res/drawable/widget_round_button.xmlnew file mode 100644index 0000000..a536410--- /dev/null+++ b/android/app/src/main/res/drawable/widget_round_button.xml@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- A small round glass button on a widget card: a lift of light, a bright rim, a soft press. -->+<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="#40FFFFFF">+ <item>+ <shape android:shape="oval">+ <solid android:color="#38FFFFFF" />+ <stroke android:width="1dp" android:color="#8CFFFFFF" />+ </shape>+ </item>+</ripple>diff --git a/android/app/src/main/res/font/outfit.ttf b/android/app/src/main/res/font/outfit.ttfnew file mode 100644index 0000000..466d624Binary files /dev/null and b/android/app/src/main/res/font/outfit.ttf differdiff --git a/android/app/src/main/res/layout/widget_card.xml b/android/app/src/main/res/layout/widget_card.xmlindex d2069e5..af0ae81 100644--- a/android/app/src/main/res/layout/widget_card.xml+++ b/android/app/src/main/res/layout/widget_card.xml@@ -11,7 +11,7 @@android:layout_width="match_parent"android:layout_height="match_parent"android:importantForAccessibility="yes"- android:scaleType="fitXY" />+ android:scaleType="fitCenter" /><FrameLayoutandroid:id="@+id/card_open"@@ -20,6 +20,18 @@android:layout_gravity="top|start"android:background="@drawable/widget_card_ripple" />+ <!-- The next note (Notes widget, when there is more than one): laid in the card's corner. -->+ <ImageView+ android:id="@+id/card_next"+ android:layout_width="34dp"+ android:layout_height="34dp"+ android:layout_gravity="top|start"+ android:background="@drawable/widget_round_button"+ android:padding="8dp"+ android:src="@drawable/widget_next"+ android:tint="#99000000"+ android:visibility="gone" />+<FrameLayoutandroid:id="@+id/row0"android:layout_width="match_parent"diff --git a/android/app/src/main/res/values-ar/strings.xml b/android/app/src/main/res/values-ar/strings.xmlindex d9a077f..d7f9735 100644--- a/android/app/src/main/res/values-ar/strings.xml+++ b/android/app/src/main/res/values-ar/strings.xml@@ -1243,4 +1243,34 @@<string name="kind_short_text">نص</string><string name="kind_short_images">صور</string><string name="kind_short_maps">خرائط</string>+ <string name="widget_starred_name">المميّزة بنجمة</string>+ <string name="widget_starred_description">مستنداتك المميّزة بنجمة، وأحدثها على بُعد لمسة.</string>+ <string name="widget_starred_empty">ميّز ملفًا بنجمة ليظهر هنا</string>+ <string name="widget_next_list">القائمة التالية</string>+ <string name="widget_next_note">الملاحظة التالية</string>+ <string name="info_about">حول</string>+ <string name="info_tagged_short">قابل للوصول</string>+ <string name="viewer_bold_not_found">تعذّر جعل هذه الكلمات عريضة هنا</string>+ <string name="desk_highlights">أبرز اللحظات</string>+ <string name="desk_snapshots">لقطات</string>+ <string name="desk_text">نص</string>+ <string name="thoughts_create_new">إنشاء جديد</string>+ <string name="thoughts_empty">لا شيء هنا بعد. أنشئ واحدًا بالأسفل.</string>+ <string name="today_title">اليوم</string>+ <string name="today_morning">صباح الخير</string>+ <string name="today_afternoon">مساء الخير</string>+ <string name="today_evening">مساء الخير</string>+ <string name="today_night">تصبح على خير</string>+ <string name="today_overview">نظرة على اليوم</string>+ <plurals name="today_left">+ <item quantity="one">%d مهمة متبقية</item>+ <item quantity="other">%d مهام متبقية</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d ملاحظة اليوم</item>+ <item quantity="other">%d ملاحظات اليوم</item>+ </plurals>+ <string name="settings_your_name">اسمك</string>+ <string name="settings_your_name_hint">يظهر فوق تحية اليوم</string>+ <string name="thoughts_audios">صوتيات</string></resources>diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xmlindex 0928e0d..f91a6de 100644--- a/android/app/src/main/res/values-de/strings.xml+++ b/android/app/src/main/res/values-de/strings.xml@@ -1589,4 +1589,34 @@<string name="kind_short_text">Text</string><string name="kind_short_images">Bilder</string><string name="kind_short_maps">Mindmaps</string>+ <string name="widget_starred_name">Favoriten</string>+ <string name="widget_starred_description">Deine Favoriten, der neueste nur einen Tipp entfernt.</string>+ <string name="widget_starred_empty">Markiere eine Datei mit einem Stern, dann erscheint sie hier</string>+ <string name="widget_next_list">Nächste Liste</string>+ <string name="widget_next_note">Nächste Notiz</string>+ <string name="info_about">Über</string>+ <string name="info_tagged_short">Barrierefrei</string>+ <string name="viewer_bold_not_found">Diese Wörter können hier nicht fett werden</string>+ <string name="desk_highlights">Highlights</string>+ <string name="desk_snapshots">Schnappschüsse</string>+ <string name="desk_text">Text</string>+ <string name="thoughts_create_new">Neu erstellen</string>+ <string name="thoughts_empty">Noch nichts hier. Erstelle unten etwas.</string>+ <string name="today_title">Heute</string>+ <string name="today_morning">Guten Morgen</string>+ <string name="today_afternoon">Guten Tag</string>+ <string name="today_evening">Guten Abend</string>+ <string name="today_night">Gute Nacht</string>+ <string name="today_overview">Tagesüberblick</string>+ <plurals name="today_left">+ <item quantity="one">%d Aufgabe offen</item>+ <item quantity="other">%d Aufgaben offen</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d Notiz heute</item>+ <item quantity="other">%d Notizen heute</item>+ </plurals>+ <string name="settings_your_name">Dein Name</string>+ <string name="settings_your_name_hint">Steht über dem Gruß in Heute</string>+ <string name="thoughts_audios">Audios</string></resources>diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xmlindex 4d18ba4..b8684cd 100644--- a/android/app/src/main/res/values-es/strings.xml+++ b/android/app/src/main/res/values-es/strings.xml@@ -1597,4 +1597,34 @@<string name="kind_short_text">Texto</string><string name="kind_short_images">Fotos</string><string name="kind_short_maps">Mapas</string>+ <string name="widget_starred_name">Destacados</string>+ <string name="widget_starred_description">Tus documentos destacados, el más reciente a un toque.</string>+ <string name="widget_starred_empty">Destaca un archivo y aparecerá aquí</string>+ <string name="widget_next_list">Lista siguiente</string>+ <string name="widget_next_note">Nota siguiente</string>+ <string name="info_about">Acerca de</string>+ <string name="info_tagged_short">Accesible</string>+ <string name="viewer_bold_not_found">Esas palabras no se pueden poner en negrita aquí</string>+ <string name="desk_highlights">Destacados</string>+ <string name="desk_snapshots">Instantáneas</string>+ <string name="desk_text">Texto</string>+ <string name="thoughts_create_new">Crear nuevo</string>+ <string name="thoughts_empty">Aún no hay nada. Crea uno abajo.</string>+ <string name="today_title">Hoy</string>+ <string name="today_morning">Buenos días</string>+ <string name="today_afternoon">Buenas tardes</string>+ <string name="today_evening">Buenas noches</string>+ <string name="today_night">Buenas noches</string>+ <string name="today_overview">Resumen del día</string>+ <plurals name="today_left">+ <item quantity="one">%d tarea pendiente</item>+ <item quantity="other">%d tareas pendientes</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d nota hoy</item>+ <item quantity="other">%d notas hoy</item>+ </plurals>+ <string name="settings_your_name">Tu nombre</string>+ <string name="settings_your_name_hint">Se muestra sobre el saludo de Hoy</string>+ <string name="thoughts_audios">Audios</string></resources>diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xmlindex 621efbc..a8dc2f5 100644--- a/android/app/src/main/res/values-fr/strings.xml+++ b/android/app/src/main/res/values-fr/strings.xml@@ -1469,4 +1469,34 @@<string name="kind_short_text">Texte</string><string name="kind_short_images">Images</string><string name="kind_short_maps">Cartes</string>+ <string name="widget_starred_name">Favoris</string>+ <string name="widget_starred_description">Vos documents favoris, le plus récent à portée de doigt.</string>+ <string name="widget_starred_empty">Ajoutez un fichier aux favoris pour le voir ici</string>+ <string name="widget_next_list">Liste suivante</string>+ <string name="widget_next_note">Note suivante</string>+ <string name="info_about">À propos</string>+ <string name="info_tagged_short">Accessible</string>+ <string name="viewer_bold_not_found">Impossible de mettre ces mots en gras ici</string>+ <string name="desk_highlights">Moments forts</string>+ <string name="desk_snapshots">Instantanés</string>+ <string name="desk_text">Texte</string>+ <string name="thoughts_create_new">Créer</string>+ <string name="thoughts_empty">Rien pour l’instant. Créez-en un ci-dessous.</string>+ <string name="today_title">Aujourd’hui</string>+ <string name="today_morning">Bonjour</string>+ <string name="today_afternoon">Bon après-midi</string>+ <string name="today_evening">Bonsoir</string>+ <string name="today_night">Bonne nuit</string>+ <string name="today_overview">Aperçu du jour</string>+ <plurals name="today_left">+ <item quantity="one">%d tâche restante</item>+ <item quantity="other">%d tâches restantes</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d note aujourd’hui</item>+ <item quantity="other">%d notes aujourd’hui</item>+ </plurals>+ <string name="settings_your_name">Votre nom</string>+ <string name="settings_your_name_hint">Affiché au-dessus du message d’Aujourd’hui</string>+ <string name="thoughts_audios">Audios</string></resources>diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xmlindex f34d2b3..018046b 100644--- a/android/app/src/main/res/values-it/strings.xml+++ b/android/app/src/main/res/values-it/strings.xml@@ -1579,4 +1579,34 @@<string name="kind_short_text">Testo</string><string name="kind_short_images">Foto</string><string name="kind_short_maps">Mappe</string>+ <string name="widget_starred_name">Preferiti</string>+ <string name="widget_starred_description">I tuoi documenti preferiti, il più recente a un tocco.</string>+ <string name="widget_starred_empty">Aggiungi una stella a un file e apparirà qui</string>+ <string name="widget_next_list">Elenco successivo</string>+ <string name="widget_next_note">Nota successiva</string>+ <string name="info_about">Informazioni</string>+ <string name="info_tagged_short">Accessibile</string>+ <string name="viewer_bold_not_found">Queste parole non si possono mettere in grassetto qui</string>+ <string name="desk_highlights">In evidenza</string>+ <string name="desk_snapshots">Istantanee</string>+ <string name="desk_text">Testo</string>+ <string name="thoughts_create_new">Crea nuovo</string>+ <string name="thoughts_empty">Ancora niente. Creane uno qui sotto.</string>+ <string name="today_title">Oggi</string>+ <string name="today_morning">Buongiorno</string>+ <string name="today_afternoon">Buon pomeriggio</string>+ <string name="today_evening">Buonasera</string>+ <string name="today_night">Buonanotte</string>+ <string name="today_overview">Panoramica del giorno</string>+ <plurals name="today_left">+ <item quantity="one">%d attività da fare</item>+ <item quantity="other">%d attività da fare</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d nota oggi</item>+ <item quantity="other">%d note oggi</item>+ </plurals>+ <string name="settings_your_name">Il tuo nome</string>+ <string name="settings_your_name_hint">Mostrato sopra il saluto di Oggi</string>+ <string name="thoughts_audios">Audio</string></resources>diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xmlindex d2e34ae..961738e 100644--- a/android/app/src/main/res/values-pt-rBR/strings.xml+++ b/android/app/src/main/res/values-pt-rBR/strings.xml@@ -1174,4 +1174,34 @@<string name="kind_short_text">Texto</string><string name="kind_short_images">Fotos</string><string name="kind_short_maps">Mapas</string>+ <string name="widget_starred_name">Com estrela</string>+ <string name="widget_starred_description">Seus documentos com estrela, o mais recente a um toque.</string>+ <string name="widget_starred_empty">Marque um arquivo com estrela e ele aparece aqui</string>+ <string name="widget_next_list">Próxima lista</string>+ <string name="widget_next_note">Próxima nota</string>+ <string name="info_about">Sobre</string>+ <string name="info_tagged_short">Acessível</string>+ <string name="viewer_bold_not_found">Não é possível deixar essas palavras em negrito aqui</string>+ <string name="desk_highlights">Destaques</string>+ <string name="desk_snapshots">Instantâneos</string>+ <string name="desk_text">Texto</string>+ <string name="thoughts_create_new">Criar novo</string>+ <string name="thoughts_empty">Ainda nada aqui. Crie um abaixo.</string>+ <string name="today_title">Hoje</string>+ <string name="today_morning">Bom dia</string>+ <string name="today_afternoon">Boa tarde</string>+ <string name="today_evening">Boa noite</string>+ <string name="today_night">Boa noite</string>+ <string name="today_overview">Resumo do dia</string>+ <plurals name="today_left">+ <item quantity="one">%d tarefa pendente</item>+ <item quantity="other">%d tarefas pendentes</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d nota hoje</item>+ <item quantity="other">%d notas hoje</item>+ </plurals>+ <string name="settings_your_name">Seu nome</string>+ <string name="settings_your_name_hint">Mostrado acima da saudação de Hoje</string>+ <string name="thoughts_audios">Áudios</string></resources>diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xmlindex 1fae10b..0056ea8 100644--- a/android/app/src/main/res/values-pt/strings.xml+++ b/android/app/src/main/res/values-pt/strings.xml@@ -1174,4 +1174,34 @@<string name="kind_short_text">Texto</string><string name="kind_short_images">Fotos</string><string name="kind_short_maps">Mapas</string>+ <string name="widget_starred_name">Com estrela</string>+ <string name="widget_starred_description">Os seus documentos com estrela, o mais recente a um toque.</string>+ <string name="widget_starred_empty">Marque um ficheiro com estrela e ele aparece aqui</string>+ <string name="widget_next_list">Lista seguinte</string>+ <string name="widget_next_note">Nota seguinte</string>+ <string name="info_about">Sobre</string>+ <string name="info_tagged_short">Acessível</string>+ <string name="viewer_bold_not_found">Não é possível pôr estas palavras em negrito aqui</string>+ <string name="desk_highlights">Destaques</string>+ <string name="desk_snapshots">Instantâneos</string>+ <string name="desk_text">Texto</string>+ <string name="thoughts_create_new">Criar novo</string>+ <string name="thoughts_empty">Ainda nada aqui. Crie um abaixo.</string>+ <string name="today_title">Hoje</string>+ <string name="today_morning">Bom dia</string>+ <string name="today_afternoon">Boa tarde</string>+ <string name="today_evening">Boa noite</string>+ <string name="today_night">Boa noite</string>+ <string name="today_overview">Resumo do dia</string>+ <plurals name="today_left">+ <item quantity="one">%d tarefa por fazer</item>+ <item quantity="other">%d tarefas por fazer</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d nota hoje</item>+ <item quantity="other">%d notas hoje</item>+ </plurals>+ <string name="settings_your_name">O seu nome</string>+ <string name="settings_your_name_hint">Mostrado acima da saudação de Hoje</string>+ <string name="thoughts_audios">Áudios</string></resources>diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xmlindex ad16fa2..6eea0b1 100644--- a/android/app/src/main/res/values-ru/strings.xml+++ b/android/app/src/main/res/values-ru/strings.xml@@ -1206,4 +1206,34 @@<string name="kind_short_text">Текст</string><string name="kind_short_images">Фото</string><string name="kind_short_maps">Карты</string>+ <string name="widget_starred_name">Избранное</string>+ <string name="widget_starred_description">Избранные документы, самый новый в одно касание.</string>+ <string name="widget_starred_empty">Отметьте файл звёздочкой, и он появится здесь</string>+ <string name="widget_next_list">Следующий список</string>+ <string name="widget_next_note">Следующая заметка</string>+ <string name="info_about">Сведения</string>+ <string name="info_tagged_short">Доступный</string>+ <string name="viewer_bold_not_found">Эти слова здесь нельзя сделать жирными</string>+ <string name="desk_highlights">Лучшее</string>+ <string name="desk_snapshots">Снимки</string>+ <string name="desk_text">Текст</string>+ <string name="thoughts_create_new">Создать</string>+ <string name="thoughts_empty">Здесь пока пусто. Создайте ниже.</string>+ <string name="today_title">Сегодня</string>+ <string name="today_morning">Доброе утро</string>+ <string name="today_afternoon">Добрый день</string>+ <string name="today_evening">Добрый вечер</string>+ <string name="today_night">Доброй ночи</string>+ <string name="today_overview">Обзор дня</string>+ <plurals name="today_left">+ <item quantity="one">%d дело осталось</item>+ <item quantity="other">Осталось дел: %d</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d заметка сегодня</item>+ <item quantity="other">Заметок сегодня: %d</item>+ </plurals>+ <string name="settings_your_name">Ваше имя</string>+ <string name="settings_your_name_hint">Показывается над приветствием «Сегодня»</string>+ <string name="thoughts_audios">Аудио</string></resources>diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 74ad4d3..8d313ed 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -1648,4 +1648,34 @@<string name="kind_short_text">Text</string><string name="kind_short_images">Photos</string><string name="kind_short_maps">Maps</string>+ <string name="widget_starred_name">Starred</string>+ <string name="widget_starred_description">Your starred documents, the newest one a tap away.</string>+ <string name="widget_starred_empty">Star a file and it shows here</string>+ <string name="widget_next_list">Next list</string>+ <string name="widget_next_note">Next note</string>+ <string name="info_about">About</string>+ <string name="info_tagged_short">Accessible</string>+ <string name="viewer_bold_not_found">Those words can\'t be made bold here</string>+ <string name="desk_highlights">Highlights</string>+ <string name="desk_snapshots">Snapshots</string>+ <string name="desk_text">Text</string>+ <string name="thoughts_create_new">Create new</string>+ <string name="thoughts_empty">Nothing here yet. Create one below.</string>+ <string name="today_title">Today</string>+ <string name="today_morning">Good Morning</string>+ <string name="today_afternoon">Good Afternoon</string>+ <string name="today_evening">Good Evening</string>+ <string name="today_night">Good Night</string>+ <string name="today_overview">Daily Overview</string>+ <plurals name="today_left">+ <item quantity="one">%d to-do left</item>+ <item quantity="other">%d to-dos left</item>+ </plurals>+ <plurals name="today_notes">+ <item quantity="one">%d note today</item>+ <item quantity="other">%d notes today</item>+ </plurals>+ <string name="settings_your_name">Your name</string>+ <string name="settings_your_name_hint">Shown above Today\'s greeting</string>+ <string name="thoughts_audios">Audios</string></resources>diff --git a/android/app/src/main/res/xml/widget_starred_info.xml b/android/app/src/main/res/xml/widget_starred_info.xmlnew file mode 100644index 0000000..27bda31--- /dev/null+++ b/android/app/src/main/res/xml/widget_starred_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_starred_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/engine/crates/automation/src/lib.rs b/engine/crates/automation/src/lib.rsindex 83de1d7..31dec9e 100644--- a/engine/crates/automation/src/lib.rs+++ b/engine/crates/automation/src/lib.rs@@ -603,10 +603,17 @@ impl Automation {let r = |x: f32| (x as f64 * 100.0).round() / 100.0;let current = doc.text_blocks(page);let id = doc.id;+ // the page's lines, read only when a paragraph mixes lines (its runs' styles come from them)+ let lines = if current.iter().any(|b| b.spans.iter().any(|(_, l)| Some(*l) != b.spans.first().map(|(_, f)| *f))) {+ doc.text_lines(page)+ } else {+ Vec::new()+ };let blocks: Vec<Value> = current.iter().enumerate().map(|(i, b)| {+ let runs = style_runs(b, &lines);let (u, v) = (info.user_to_view(b.rect[0] as f32, b.rect[1] as f32), info.user_to_view(b.rect[2] as f32, b.rect[3] as f32));json!({"paragraph": i + 1,@@ -619,6 +626,9 @@ impl Automation {"size": (b.size * 100.0).round() / 100.0,"bold": b.bold,"italic": b.italic,+ // Where the paragraph's weight or slant changes (a bold word in a plain+ // line): UTF-8 byte ranges of editor_text; empty when it is all one style.+ "runs": runs,// Passing this back as text_edit's color keeps the source's own colour// operators (any colour space)."color": format!("#{:02x}{:02x}{:02x}", (b.color[0] * 255.0).round() as u8, (b.color[1] * 255.0).round() as u8, (b.color[2] * 255.0).round() as u8),@@ -2893,6 +2903,26 @@ fn write_atomic_synced(.map_err(|e| failed(format!("{}: {e}", path.display())))}+/// A paragraph's bold and italic runs over its `editor_text` (byte ranges), adjacent runs of one+/// style merged; empty when the whole paragraph is one style (or its lines were not read).+fn style_runs(b: &pdfcraft_engine::TextBlock, lines: &[pdfcraft_engine::TextLine]) -> Vec<Value> {+ if lines.is_empty() {+ return Vec::new();+ }+ let mut runs: Vec<(usize, usize, bool, bool)> = Vec::new();+ for (range, line) in &b.spans {+ let (bold, italic) = lines.get(*line).map(|l| (l.bold, l.italic)).unwrap_or((b.bold, b.italic));+ match runs.last_mut() {+ Some(last) if last.2 == bold && last.3 == italic && last.1 <= range.start => last.1 = range.end,+ _ => runs.push((range.start, range.end, bold, italic)),+ }+ }+ if runs.iter().all(|r| r.2 == runs[0].2 && r.3 == runs[0].3) {+ return Vec::new();+ }+ runs.into_iter().map(|(s, e, bold, italic)| json!({ "range": [s, e], "bold": bold, "italic": italic })).collect()+}+#[cfg(test)]mod tests {use super::*;diff --git a/engine/crates/automation/tests/it/automation.rs b/engine/crates/automation/tests/it/automation.rsindex 3bcdabb..3b1435b 100644--- a/engine/crates/automation/tests/it/automation.rs+++ b/engine/crates/automation/tests/it/automation.rs@@ -9278,3 +9278,28 @@ fn page_render_draws_stamps_without_an_appearance() {let grey = custom.iter().filter(|p| p[0].abs_diff(p[1]) < 24 && p[1].abs_diff(p[2]) < 24).count();assert!(grey > 100 && grey == custom.len(), "an unknown name is a grey placeholder: {grey} of {}", custom.len());}++/// #127: bolding one word bolds that word only, and the paragraph listing says where the bold is.+#[test]+fn bold_range_is_one_word_and_listed_as_a_run() {+ let dir = workdir("bold-range");+ let mut a = auto(&dir);+ let id = ok(&mut a, "doc_open", json!({"path":"a.pdf"}))["doc"].as_u64().unwrap();+ ok(+ &mut a,+ "text_edit",+ json!({"doc":id,"page":1,"paragraph":1,"text":"Bold word stays plain","ranges":[{"range":[0,4],"font":"helvetica","bold":true}]}),+ );+ let listed = ok(&mut a, "text_paragraphs", json!({"doc":id,"page":1}));+ let p = &listed["paragraphs"][0];+ let runs = p["runs"].as_array().unwrap();+ assert!(runs.len() >= 2, "{listed}");+ let editor = p["editor_text"].as_str().unwrap();+ let bold: String = runs+ .iter()+ .filter(|r| r["bold"] == true)+ .map(|r| &editor[r["range"][0].as_u64().unwrap() as usize..r["range"][1].as_u64().unwrap() as usize])+ .collect();+ assert_eq!(bold.trim(), "Bold", "{listed}");+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/engine/crates/create/src/lib.rs b/engine/crates/create/src/lib.rsindex 163c5bd..726a425 100644--- a/engine/crates/create/src/lib.rs+++ b/engine/crates/create/src/lib.rs@@ -56,7 +56,7 @@ fn add_page(doc: &mut Document, w: f64, h: f64, resources: Dict, content: Optionfn set_title(doc: &mut Document, title: &str) {let mut info = Dict::new();info.set(b"Title".to_vec(), PdfString::text(title));- info.set(b"Producer".to_vec(), PdfString::text("PdfCraft"));+ info.set(b"Producer".to_vec(), PdfString::text("Artefact"));let r = doc.add(info);doc.trailer_mut().set(b"Info".to_vec(), Object::Ref(r));}diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rsindex 949f049..9792330 100644--- a/engine/mobile/src/tests.rs+++ b/engine/mobile/src/tests.rs@@ -673,10 +673,19 @@ 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+ let id = s+ .open(+ word_file(+ "OverviewSome body text here.Details-More body text.", "Outline.docx"), None).unwrap().id;+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();@@ -698,9 +707,12 @@ 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("Привет,мир+ let path = book_file(+ "Привет,мирΓειά,Hello-", "Cyr.xlsx");+",+ "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();diff --git a/engine/mobile/src/word.rs b/engine/mobile/src/word.rsindex aaf23ea..dfd728d 100644--- a/engine/mobile/src/word.rs+++ b/engine/mobile/src/word.rs@@ -308,12 +308,7 @@ fn headings_of(doc: &Document, layout: &DocLayout) -> Vec<crate::OutlineEntry> {.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),- }+ crate::OutlineEntry { title: title.clone(), level: u32::from(level - top), page, children: u32::try_from(children).unwrap_or(u32::MAX) }}).collect()}