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
App: one menu glass, adaptive luminance, a faster and truer sheet grid
chethan61610de171256ae
diff --git a/HANDOFF.md b/HANDOFF.mdindex 6ad6719..e645a00 100644--- a/HANDOFF.md+++ b/HANDOFF.md@@ -86,6 +86,32 @@ tf`; an encrypted- Build note: the first release build of wordcraft is long (~20 min on this PC); `assembleFast`compiles the Rust release profile (thin LTO, one codegen unit).+## Glass and office changes (2026-11-11)++The parts a later session needs to know:++- **Adaptive luminance** (Settings ▸ Liquid glass & motion, off by default; `GlassSettings.adaptive`).+ Menus and toasts read their own backdrop (`GlassLuminance` in `ui/glass/AdaptiveGlass.kt`: a small+ second record of the backdrop, read back a few times a second). Every other glass control reads+ the luminance around itself from the window's one `ScreenInkSampler` (`rememberSurroundLuminance`+ in `AdaptiveInk.kt`); `ClearApp` runs that sampler app-wide while the setting is on. In this mode+ the glass presets' frost, colour, brightness and tint are not applied (`GlassStyle.adaptiveBase`).+ Only controls whose ink follows (`GlassCircle`, `GlassPill`, `glassBar`) take the milk/smoke wash;+ chips, panels, sheets and dialogs keep their wash because their text is in the theme's ink.+- **Menus** are all one `MenuCard` (`Overlays.kt`); rows take their ink from `LocalGlassInk` /+ `LocalMenuInk` (`menuInk()` in the viewer). A menu whose anchor is at most 72 dp grows out of that+ button and lies over it (`GlassMotion.grow`); a larger anchor unfolds beside it.+- **Glass springs** take a 0.0005 rest threshold (`GlassMotion`): Compose's default 0.01 cut a menu's+ last swing short. Menus close on `GlassMotion.fold`, not on the screens' curve.+- **Sheets grid** (`ui/sheets/SheetViewer.kt`): cells are made ready once per block (`DrawCell`, with+ its merge and which borders show), text is laid out once at zoom 1 and drawn scaled+ (`SheetTextCache`). Gestures read `top` through `rememberUpdatedState`: the bars over the grid+ change height, and a stale value put taps on the wrong cell.+- **.ppt** (`engine/mobile/src/ppt.rs`) reads each slide's drawing (text boxes, pictures) through the+ persist directory, and falls back to the outline. Only tested on a synthetic file.+- **Releases** build five APKs (`-arm64-v8a`, `-armeabi-v7a`, `-x86`, `-x86_64`, `-universal`); `x86`+ is new (`i686-linux-android`, version-code suffix 4). `ci.yml` builds pull requests.+## Motion rules (2026-11-06)- **Glass things spring, screens glide** (sheets on their own fixed spring, see Gotchas). Glass controls AND glass popovers (menus, dialogs, toasts, hint toasts, the recorder pill) usediff --git a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.ktindex 7054767..fee5805 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt@@ -73,6 +73,7 @@ class MainActivity : ComponentActivity() {private val pickFolder = registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> uri?.let(vm::addLocalFolder) }private val micPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> vm.onMicPermission(granted) }private val pickNotePhoto = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> vm.onNotePhoto(uri) }+ private val pickAudio = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> vm.onAudioPicked(uri) }private val takeNotePhoto = registerForActivityResult(ActivityResultContracts.TakePicture()) { ok -> vm.onNoteCamera(ok) }override fun onCreate(savedInstanceState: Bundle?) {@@ -130,6 +131,7 @@ class MainActivity : ComponentActivity() {lifecycleScope.launch { for (d in vm.imagePicks) launchSafely { pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } }lifecycleScope.launch { for (u in vm.photoPicks) launchSafely { pickPhotos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } }lifecycleScope.launch { for (u in vm.notePhotoPicks) launchSafely { pickNotePhoto.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } }+ lifecycleScope.launch { for (u in vm.audioPicks) launchSafely { pickAudio.launch("audio/*") } }lifecycleScope.launch {for (f in vm.noteCameraShots) {val uri = FileProvider.getUriForFile(this@MainActivity, "$packageName.files", f)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/engine/LocalFiles.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/LocalFiles.ktindex 4bc8f9f..79306b2 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/LocalFiles.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/LocalFiles.kt@@ -165,8 +165,24 @@ class Thumbnails(private val context: Context) {}.getOrNull() ?: return null// a very large file isn't copied just for its first pageif (size > MAX_COPY) return null- return cached(sha("$uri|$modified|$size|$maxSide")) {- val tmp = File.createTempFile("thumb", ".pdf", context.cacheDir)+ // The copy keeps the document's own extension. The engine tells most files by their bytes,+ // but a table of plain text (.csv, .tsv), a text file and a password-protected Office file+ // are known by name alone: copied as "thumb.pdf" they could not be read, so they got no+ // picture and were shown as a blank page with a PDF badge.+ val extension = runCatching {+ resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->+ if (c.moveToFirst() && !c.isNull(0)) c.getString(0) else null+ }+ }.getOrNull()?.substringAfterLast('.', "")?.lowercase()?.takeIf { it.length in 1..8 && it.all(Char::isLetterOrDigit) }+ ?: when (runCatching { resolver.getType(uri) }.getOrNull()) {+ "text/csv", "text/comma-separated-values" -> "csv"+ "text/tab-separated-values" -> "tsv"+ "text/plain" -> "txt"+ "text/markdown", "text/x-markdown" -> "md"+ else -> "pdf"+ }+ return cached(sha("$uri|$modified|$size|$maxSide|$extension")) {+ val tmp = File.createTempFile("thumb", ".$extension", context.cacheDir)try {resolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("unreadable")fileThumbnail(tmp.absolutePath, maxSide.toUInt()).toBitmap()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 b35550f..c45b6f8 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@@ -2167,6 +2167,19 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrdeliver(out, "${doc.title}_protected.pdf")}+ /**+ * A copy of [doc] with its password and restrictions removed for good, saved to Downloads: it+ * opens without asking from then on. Only a document already opened with its password gets+ * here (the engine holds it), so nothing is broken into; a file whose security the engine+ * can't lift (a certificate's, say) says so.+ */+ fun removePassword(doc: OpenDocument) = job(text(R.string.msg_busy_removing_password)) { _ ->+ save(doc)+ val out = unlockedCopy(doc) ?: error(text(R.string.msg_unlock_failed))+ toolScreen = null+ deliver(out, "${doc.title}_unlocked.pdf")+ }+/** Crop [page] (or every page) to [rect] (points from the page's top-left). */fun crop(doc: OpenDocument, page: Int?, rect: FloatArray) {val args = mutableMapOf<String, Any?>("rect" to rect.map { it.toDouble() })@@ -2180,9 +2193,17 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr/** Export [doc] as a Word, RTF, Excel or PowerPoint document. */fun exportDocument(doc: OpenDocument, ext: String) = job(text(R.string.msg_busy_exporting_to, ext.uppercase())) { eng ->val out = tempFile(ext)- eng.tool("doc_export_office", mapOf("doc" to doc.id, "path" to out.absolutePath))+ if (ext == "txt") {+ // the words of every page, in reading order, a blank line between pages+ val pages = (0 until doc.pageCount).map { p -> eng.command { pagePlainText(doc.id, p.toUInt()) }.trim() }+ if (pages.all { it.isEmpty() }) error(text(R.string.msg_no_text_to_export))+ withContext(Dispatchers.IO) { out.writeText(pages.joinToString("\n\n")) }+ } else {+ eng.tool("doc_export_office", mapOf("doc" to doc.id, "path" to out.absolutePath))+ }toolScreen = nullval mime = when (ext) {+ "txt" -> "text/plain""docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document""rtf" -> "application/rtf""xlsx" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"@@ -2622,6 +2643,92 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : AndrnotePhotoPicks.trySend(Unit)}+ /** Asks for an audio file to bring onto the desk as a voice note. */+ val audioPicks = Channel<Unit>(Channel.CONFLATED)++ fun pickAudio() {+ audioPicks.trySend(Unit)+ }++ /**+ * An audio file (m4a, mp3, wav, ogg…) copied into the notes as a voice note of its own: it+ * plays, renames, pins and deletes like one recorded here. Its length is read from the file;+ * its wave is drawn even (the sound isn't analysed).+ */+ fun onAudioPicked(uri: Uri?) {+ uri ?: return+ viewModelScope.launch {+ val note = withContext(Dispatchers.IO) {+ runCatching {+ val resolver = getApplication<Application>().contentResolver+ val name = resolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->+ if (c.moveToFirst() && !c.isNull(0)) c.getString(0) else null+ }.orEmpty()+ val known = setOf("m4a", "mp3", "wav", "aac", "ogg", "opus", "flac", "amr", "3gp", "mp4")+ val ext = name.substringAfterLast('.', "").lowercase().takeIf { it in known } ?: when (resolver.getType(uri)) {+ "audio/mpeg" -> "mp3"+ "audio/wav", "audio/x-wav" -> "wav"+ "audio/ogg" -> "ogg"+ else -> "m4a"+ }+ val f = notes.newMedia(ext)+ resolver.openInputStream(uri)?.use { input -> f.outputStream().use { input.copyTo(it) } } ?: error("unreadable")+ val retriever = android.media.MediaMetadataRetriever()+ val ms = try {+ retriever.setDataSource(f.absolutePath)+ retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L+ } finally {+ runCatching { retriever.release() }+ }+ if (ms <= 0L) {+ f.delete()+ error("not audio")+ }+ com.chethan616.clearpdf.notes.Note(+ java.util.UUID.randomUUID().toString(), com.chethan616.clearpdf.notes.NoteKind.Voice,+ title = name.substringBeforeLast('.').take(80), audio = f.name, durationMs = ms,+ wave = List(48) { i -> 0.35f + 0.3f * kotlin.math.abs(kotlin.math.sin(i * 0.9f)) },+ )+ }.getOrNull()+ }+ if (note == null) tell(text(R.string.common_file_unreadable))+ else {+ notes.add(note)+ tell(text(R.string.voice_imported))+ }+ }+ }++ /** A voice note's recording saved to Downloads under its name, in the format it is kept in. */+ fun exportVoice(note: com.chethan616.clearpdf.notes.Note) {+ val audio = note.audio ?: return+ viewModelScope.launch {+ runCatching {+ val source = notes.file(audio)+ val ext = audio.substringAfterLast('.', "wav").lowercase()+ val mime = when (ext) {+ "wav" -> "audio/wav"+ "mp3" -> "audio/mpeg"+ "ogg", "opus" -> "audio/ogg"+ "flac" -> "audio/flac"+ else -> "audio/mp4"+ }+ val name = (note.title.ifBlank { text(R.string.voice_export_name) }).replace(Regex("""[\\/:*?"<>|]"""), " ").trim() + ".$ext"+ withContext(Dispatchers.IO) {+ // saveToDownloads takes the file it is given: hand it a copy+ val copy = tempFile(ext)+ source.copyTo(copy, overwrite = true)+ try {+ files.saveToDownloads(copy, name, mime)+ } finally {+ copy.delete()+ }+ }+ tell(text(R.string.msg_saved_downloads, name))+ }.onFailure { tell(it.userMessage) }+ }+ }+fun takeNotePhoto() {val f = notes.newMedia("jpg")noteShot = fdiff --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 4f55a44..da1bb5a 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@@ -126,7 +126,10 @@ fun ClearApp(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage: () ->ClearTheme(vm.theme) {PdfcraftTheme(vm.theme) {ProvideGlassHaptics {- CompositionLocalProvider(LocalGlassOverlayHost provides overlays, LocalHomeVm provides vm) { Shell(vm, onBrowse, onPickSignatureImage) }+ // Adaptive luminance: one sampler of the window for every screen's glass+ com.chethan616.clearpdf.ui.glass.ProvideScreenInk(enabled = com.chethan616.clearpdf.ui.glass.GlassSettings.adaptive) {+ CompositionLocalProvider(LocalGlassOverlayHost provides overlays, LocalHomeVm provides vm) { Shell(vm, onBrowse, onPickSignatureImage) }+ }}}}@@ -248,7 +251,8 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:toast?.let { m ->Box(Modifier.align(Alignment.BottomCenter).navigationBarsPadding()- .padding(start = 16.dp, end = 16.dp, bottom = if (onDesk) 100.dp else 20.dp),+ // over a document it rides above the viewer's bottom bar, not on top of its buttons+ .padding(start = 16.dp, end = 16.dp, bottom = if (onDesk) 100.dp else if (doc != null) 92.dp else 20.dp),) { key(m) { GlassToast(m.text, m.actionLabel, { m.action?.invoke(); toast = null }) } }}},diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/ToolScreens.ktindex 6de7d23..87fc4df 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@@ -328,6 +328,20 @@ fun ProtectScreen(vm: AppViewModel, doc: OpenDocument) {}}) {Column(Modifier.verticalScroll(rememberScrollState())) {+ // a protected file: the way back out first, an unlocked copy that never asks again+ if (doc.info.encrypted) {+ Column(+ Modifier.padding(horizontal = 16.dp).padding(bottom = 18.dp).fillMaxWidth()+ .clip(RoundedCornerShape(18.dp)).background(c.label.copy(alpha = 0.06f)).padding(16.dp),+ ) {+ Text(stringResource(R.string.tools_unlock_title), color = c.label, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)+ Text(stringResource(R.string.tools_unlock_body), color = c.text, fontSize = 14.sp, modifier = Modifier.padding(top = 4.dp, bottom = 12.dp))+ com.chethan616.clearpdf.ui.glass.GlassPill(onClick = { vm.removePassword(doc) }, tint = com.chethan616.clearpdf.ui.theme.Candy.Sky, height = 44.dp) {+ Icon(LucideIcons.LockOpen, null, tint = Color.White, modifier = Modifier.size(18.dp))+ Text(stringResource(R.string.tools_unlock_action), color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.SemiBold)+ }+ }+ }Text(stringResource(R.string.tools_protect_intro), color = c.label, fontSize = 16.sp, modifier = Modifier.padding(horizontal = 24.dp))PasswordField(stringResource(R.string.tools_new_password), pw, { pw = it }, visible, { visible = !visible }, bad, focus)if (bad) Text(stringResource(R.string.tools_password_rule), color = c.red, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp))@@ -353,6 +367,7 @@ fun ExportScreen(vm: AppViewModel, doc: OpenDocument) {listOf(stringResource(R.string.tools_format_word) to "docx", stringResource(R.string.tools_format_rtf) to "rtf",stringResource(R.string.tools_format_excel) to "xlsx", stringResource(R.string.tools_format_powerpoint) to "pptx",+ stringResource(R.string.tools_format_text) to "txt",)} else {listOf(stringResource(R.string.tools_format_jpeg) to "jpg", stringResource(R.string.tools_format_png) to "png")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 f2faca7..9daf950 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@@ -103,7 +103,7 @@ object ToolCatalog {* optionally tilted like a sheet dropped on a desk.*/@Composable-fun PaperThumb(vm: AppViewModel, path: String?, width: Dp, height: Dp, modifier: Modifier = Modifier, tilt: Float = 0f, corner: Dp = 8.dp) {+fun PaperThumb(vm: AppViewModel, path: String?, width: Dp, height: Dp, modifier: Modifier = Modifier, tilt: Float = 0f, corner: Dp = 8.dp, name: String? = null) {var img by remember(path) { mutableStateOf<ImageBitmap?>(null) }LaunchedEffect(path) {if (path != null) img = withContext(Dispatchers.IO) { vm.thumbnails.of(path)?.asImageBitmap() }@@ -124,13 +124,30 @@ fun PaperThumb(vm: AppViewModel, path: String?, width: Dp, height: Dp, modifier:Box(Modifier.fillMaxWidth(0.62f).height(height * 0.05f).clip(CircleShape).background(Color(0xFF17141F).copy(alpha = 0.20f)))repeat(4) { k -> Box(Modifier.fillMaxWidth(if (k == 3) 0.5f else 1f).height(height * 0.03f).clip(CircleShape).background(Color(0xFF17141F).copy(alpha = 0.09f))) }}- Box(Modifier.align(Alignment.BottomEnd).padding(width * 0.08f).clip(RoundedRectangle(4.dp)).background(Candy.Tomato).padding(horizontal = 4.dp, vertical = 1.dp)) {- Text("PDF", color = Color.White, fontSize = (width.value * 0.11f).coerceIn(7f, 13f).sp, style = ClearType.Eyebrow.copy(letterSpacing = 0.4.sp))+ // the corner badge says what the file is (a workbook is not a PDF), in its kind's colour+ val (badge, badgeColor) = kindBadge(name ?: path?.takeIf { !it.startsWith("content:") })+ Box(Modifier.align(Alignment.BottomEnd).padding(width * 0.08f).clip(RoundedRectangle(4.dp)).background(badgeColor).padding(horizontal = 4.dp, vertical = 1.dp)) {+ Text(badge, color = Color.White, fontSize = (width.value * 0.11f).coerceIn(7f, 13f).sp, style = ClearType.Eyebrow.copy(letterSpacing = 0.4.sp))}}}}+/**+ * The badge a file without a picture wears: its own extension (XLSX, CSV, DOCX, PPT, TXT) on its+ * kind's colour, as the office suites colour them; PDF on tomato for a PDF or a name that says nothing.+ */+internal fun kindBadge(name: String?): Pair<String, Color> {+ val ext = name?.substringAfterLast('.', "")?.uppercase().orEmpty()+ return when (name?.let { com.chethan616.clearpdf.engine.DocumentTypes.kindOf(it) }) {+ com.chethan616.clearpdf.engine.DocumentTypes.Kind.Sheets -> ext to Color(0xFF1E9E5A)+ com.chethan616.clearpdf.engine.DocumentTypes.Kind.Word -> ext to Color(0xFF2F6FED)+ com.chethan616.clearpdf.engine.DocumentTypes.Kind.Slides -> ext to Color(0xFFE8672C)+ com.chethan616.clearpdf.engine.DocumentTypes.Kind.Text -> ext to Color(0xFF6B7280)+ else -> "PDF" to Candy.Tomato+ }+}+/** Room left under a pushed screen's last row. */val DockClearance = 40.dp@@ -183,7 +200,7 @@ fun FileListItem(vm: AppViewModel, r: FileRow, recent: Boolean, modifier: Modifi.padding(start = 14.dp, end = 6.dp, top = 10.dp, bottom = 10.dp),verticalAlignment = Alignment.CenterVertically,) {- PaperThumb(vm, r.thumbPath, 40.dp, 52.dp, corner = 6.dp)+ PaperThumb(vm, r.thumbPath, 40.dp, 52.dp, corner = 6.dp, name = r.name)Spacer(Modifier.width(14.dp))Column(Modifier.weight(1f)) {Text(displayName(r.name), style = ClearType.BodyStrong, color = c.ink, maxLines = 2, overflow = TextOverflow.Ellipsis)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/GlassMotionSettings.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/GlassMotionSettings.ktindex 47d87ce..7ca31dd 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/GlassMotionSettings.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/GlassMotionSettings.kt@@ -113,7 +113,11 @@ fun GlassMotionPage(onBack: () -> Unit) {item(key = "glass") { Section(stringResource(R.string.gm_glass_look), custom = g !in GlassStyle.Presets) }item(key = "glasstabs") {- PresetTiles(glassPresetNames(), GlassStyle.Presets.indexOf(g), { glass(GlassStyle.Presets[it]) }) { i -> drawGlassSwatch(i) }+ // with Adaptive luminance on, frost, colour, brightness and tint are the glass's own to+ // set: the presets are shown at rest+ Box(Modifier.graphicsLayer { alpha = if (GlassSettings.adaptive) 0.4f else 1f }) {+ PresetTiles(glassPresetNames(), GlassStyle.Presets.indexOf(g), { if (!GlassSettings.adaptive) glass(GlassStyle.Presets[it]) }) { i -> drawGlassSwatch(i) }+ }}item(key = "glassvalues") {FineTune {@@ -129,6 +133,17 @@ fun GlassMotionPage(onBack: () -> Unit) {}}+ // above the presets it rests (they are dimmed while it is on)+ item(key = "adaptive") {+ Spacer(Modifier.height(8.dp))+ Panel {+ ToggleRow(+ LucideIcons.Sparkles, Candy.Lemon, stringResource(R.string.gm_adaptive), stringResource(R.string.gm_adaptive_body),+ GlassSettings.adaptive, first = true,+ ) { GlassSettings.updateAdaptive(context, it) }+ }+ }+item(key = "motion") { Section(stringResource(R.string.settings_motion), custom = m !in MotionStyle.Presets) }item(key = "motiontabs") {PresetTiles(motionPresetNames(), MotionStyle.Presets.indexOf(m), { motion(MotionStyle.Presets[it]) }) { i -> drawSpringSwatch(MotionStyle.Presets[i].bounce) }@@ -175,6 +190,7 @@ fun GlassMotionPage(onBack: () -> Unit) {Panel {SettingRow(LucideIcons.RotateCcw, Candy.Tomato, stringResource(R.string.gm_reset), {glass(GlassStyle.Default)+ GlassSettings.updateAdaptive(context, false)motion(MotionStyle.Default)MotionSettings.updateCurve(context, EaseCurve.Drawer)MotionSettings.updateDuration(context, 1f)@@ -403,7 +419,8 @@ private fun SpringGraph() {val k = MotionSettings.stiffness(420f)val w0 = sqrt(k)val wd = w0 * sqrt(1f - zeta * zeta)- val settle = (ln(100f) / (zeta * w0)).coerceIn(0.3f, 3f)+ // to where the spring is let go (0.05 % from rest, GlassMotion's threshold), as menus now run it+ val settle = (ln(2000f) / (zeta * w0)).coerceIn(0.3f, 4f)fun x(t: Float): Float = 1f - exp(-zeta * w0 * t) * (cos(wd * t) + zeta * w0 / wd * sin(wd * t))val hi = remember(zeta, w0) { (0..160).maxOf { x(settle * it / 160f) }.coerceAtLeast(1f) + 0.08f }val lo = -0.08fdiff --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 5d1b18d..d5580da 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@@ -105,7 +105,7 @@ fun SettingsScreen(vm: AppViewModel) {(androidx.compose.animation.slideOutHorizontally(com.chethan616.clearpdf.ui.glass.Fluid.push()) { -dir * it / 10 } +androidx.compose.animation.fadeOut(com.chethan616.clearpdf.ui.glass.Fluid.fade()))},- label = "settings page",+ label = "settingsPage",) { p ->when (p) {"licences" -> LicencesPage { page = "root" }diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveGlass.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveGlass.ktnew file mode 100644index 0000000..8bc9a16--- /dev/null+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveGlass.kt@@ -0,0 +1,203 @@+package com.chethan616.clearpdf.ui.glass++import android.graphics.Bitmap+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.tween+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.scale+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.rememberGraphicsLayer+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.util.lerp+import com.chethan616.clearpdf.ui.theme.clear+import com.kyant.backdrop.BackdropEffectScope+import com.kyant.backdrop.effects.blur+import com.kyant.backdrop.effects.colorControls+import com.kyant.backdrop.effects.lens+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.withContext+import kotlin.math.sign++/**+ * Adaptive luminance: a glass surface that reads how light or dark the things behind it are and+ * answers them, as AndroidLiquidGlass's "Adaptive luminance glass" does (Kyant0, Apache-2.0; the+ * library our backdrop module is built on). Over a bright page the glass turns milky and bright and+ * takes dark ink; over a dark one it deepens and takes white ink. So a menu reads the same over a+ * white PDF, a black slide or the wallpaper, whatever the app's theme.+ *+ * How: the surface records the backdrop it draws a second time, very small, into [layer]; a few times+ * a second that record is read back and averaged into one luminance, which glides to its new value.+ * The glass's effects read [value] while drawing, so nothing recomposes as it moves; only [onLight]+ * (which ink) is composition state, and it flips with hysteresis so mid-grey never flickers.+ */+@Stable+class GlassLuminance internal constructor(initial: Float, internal val layer: GraphicsLayer) {+ private val anim = Animatable(initial)+ private var recorded = false++ /** 0 (black behind) … 1 (white behind). Read while drawing. */+ val value: Float get() = anim.value++ /** Whether the glass sits over something light, so its ink should be dark. */+ var onLight by mutableStateOf(initial > 0.5f)+ private set++ /** True once the backdrop has really been read (until then [value] is the theme's guess). */+ var measured by mutableStateOf(false)+ private set++ /** Draws the backdrop, and a small copy of it into [layer] for the reading. */+ internal val recorder: DrawScope.(DrawScope.() -> Unit) -> Unit = { drawBackdrop ->+ drawBackdrop()+ val w = (size.width / DOWN).toInt().coerceAtLeast(1)+ val h = (size.height / DOWN).toInt().coerceAtLeast(1)+ layer.record(IntSize(w, h)) {+ scale(1f / DOWN, 1f / DOWN, pivot = Offset.Zero) { drawBackdrop() }+ }+ recorded = true+ }++ internal suspend fun run() {+ val px = IntArray(SAMPLES * SAMPLES)+ var waited = 0+ while (true) {+ if (!recorded) {+ // nothing drawn to read yet: don't hold the surface back for ever+ if (!measured && ++waited > 12) measured = true+ delay(16)+ continue+ }+ val lum = withContext(Dispatchers.Default) {+ runCatching {+ val full = layer.toImageBitmap().asAndroidBitmap()+ // a hardware bitmap can't be read: a small software copy can+ val small = Bitmap.createScaledBitmap(full, SAMPLES, SAMPLES, true).copy(Bitmap.Config.ARGB_8888, false)+ small.getPixels(px, 0, SAMPLES, 0, 0, SAMPLES, SAMPLES)+ var sum = 0.0+ var n = 0+ for (c in px) {+ // what was not drawn (outside every layer) says nothing+ if ((c ushr 24) < 8) continue+ sum += (0.2126 * ((c shr 16) and 0xFF) + 0.7152 * ((c shr 8) and 0xFF) + 0.0722 * (c and 0xFF)) / 255.0+ n+++ }+ if (n == 0) null else (sum / n).toFloat()+ }.getOrNull()+ }+ if (lum == null && !measured && ++waited > 12) measured = true+ if (lum != null) {+ onLight = when {+ !measured -> lum > 0.5f+ lum > 0.56f -> true+ lum < 0.44f -> false+ else -> onLight+ }+ if (!measured) {+ // The first reading is taken as it is, at once. The surface is held unseen until+ // it is in (see [MenuCard]), so a menu opened over a black page is dark from its+ // first visible frame: it used to open in the theme's guess (white in the light+ // theme) and then swing to black.+ anim.snapTo(lum)+ measured = true+ } else if (kotlin.math.abs(lum - anim.targetValue) > 0.07f) {+ // only a real change behind it moves it (a small one, read again and again, made it breathe)+ anim.animateTo(lum, tween(420))+ }+ }+ delay(SAMPLE_INTERVAL_MS)+ }+ }++ private companion object {+ const val DOWN = 8f+ const val SAMPLES = 6+ const val SAMPLE_INTERVAL_MS = 220L+ }+}++/**+ * A luminance reading for one glass surface, or null when [enabled] is false. Pass it to [glass] (or+ * [GlassCard]) and take the ink from [adaptiveInk].+ */+@Composable+fun rememberGlassLuminance(enabled: Boolean = GlassSettings.adaptive): GlassLuminance? {+ if (!enabled) return null+ val layer = rememberGraphicsLayer()+ val dark = clear.dark+ // the first guess: what the screen as a whole looks like now (the window's sampler, running+ // while Adaptive luminance is on), else the theme+ val screen = LocalScreenInk.current+ val state = remember(layer) { GlassLuminance(screen?.frame?.average() ?: if (dark) 0.14f else 0.86f, layer) }+ LaunchedEffect(state) { state.run() }+ return state+}++/**+ * The ink of the menu or popover being composed (unspecified outside one): its rows and glyphs take+ * it, so they follow the glass when it adapts to what is behind it.+ */+val LocalMenuInk = androidx.compose.runtime.compositionLocalOf { Color.Unspecified }++/** Dark ink over light glass, white over dark, gliding between them; [fallback] when there is no reading. */+@Composable+fun adaptiveInk(luminance: GlassLuminance?, fallback: Color): Color {+ if (luminance == null) return fallback+ val target = if (luminance.onLight) InkOnLight else Color.White+ val ink by animateColorAsState(target, tween(220), label = "adaptiveGlassInk")+ return ink+}++/** [luminance] as -1 (dark) … 1 (light), eased so mid-greys stay near neutral. */+private fun signed(luminance: Float): Float = (luminance * 2f - 1f).let { sign(it) * it * it }++/**+ * The adaptive effect stack (after Kyant0's demo): brighter and flatter over light, deeper over dark,+ * the frost growing with the light (a bright busy page needs more of it than a dark one), then the+ * user's lens.+ */+fun BackdropEffectScope.adaptiveGlassEffects(+ style: GlassStyle,+ luminance: Float,+ blurPx: Float,+ refractionHeightPx: Float,+ refractionAmountPx: Float,+) {+ val l = signed(luminance.coerceIn(0f, 1f))+ colorControls(+ brightness = (if (l > 0f) lerp(0.08f, 0.42f, l) else lerp(0.08f, -0.2f, -l)) + style.brightness,+ contrast = if (l > 0f) lerp(1f, 0.25f, l) else 1f,+ saturation = style.saturation,+ )+ blur(blurPx * style.blur * (if (l > 0f) lerp(1f, 1.5f, l) else lerp(1f, 0.6f, -l)))+ lens(+ refractionHeightPx * style.refractionHeight,+ refractionAmountPx * style.refractionAmount,+ depthEffect = style.depthEffect,+ chromaticAberration = style.chromaticAberration,+ )+}++/**+ * The user's glass with its filters set aside: while Adaptive luminance is on, frost, colour,+ * brightness and tint are the luminance's to set, so the presets' values for them are not applied+ * (the lens and rim light, which are shape, stay).+ */+val GlassStyle.adaptiveBase: GlassStyle get() = copy(blur = 1f, saturation = 1.5f, brightness = 0f, tint = 1f)++/** The thin wash over adaptive glass: milk over light, smoke over dark. */+fun adaptiveWash(luminance: Float): Color {+ val l = signed(luminance.coerceIn(0f, 1f))+ return if (l >= 0f) Color.White.copy(alpha = lerp(0.10f, 0.30f, l)) else Color.Black.copy(alpha = lerp(0.10f, 0.34f, -l))+}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveInk.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveInk.ktindex e2c7cab..5c8ad67 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveInk.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveInk.kt@@ -37,6 +37,7 @@ import androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.platform.LocalViewimport androidx.compose.ui.unit.dpimport kotlinx.coroutines.delay+import kotlinx.coroutines.launchimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.suspendCancellableCoroutineimport java.util.concurrent.atomic.AtomicBoolean@@ -118,6 +119,38 @@ internal class InkFrame(return (0.299 * ((c shr 16) and 0xFF) + 0.587 * ((c shr 8) and 0xFF) + 0.114 * (c and 0xFF)) / 255.0}+ /**+ * Luminance just outside [box], [gap] pixels clear of it on every side and corner: what the+ * glass sits on, with none of the glass itself in the reading. (Read at its own rim, a control+ * saw its own light: it brightened, read brighter, brightened again, and so breathed on a page+ * that never changed.)+ */+ fun outsideLuminance(box: Rect, gap: Float): Float {+ val cx = box.center.x+ val cy = box.center.y+ val l = box.left - gap+ val t = box.top - gap+ val r = box.right + gap+ val b = box.bottom + gap+ val sum = luminanceAt(l, cy) + luminanceAt(r, cy) + luminanceAt(cx, t) + luminanceAt(cx, b) ++ luminanceAt(l, t) + luminanceAt(r, t) + luminanceAt(l, b) + luminanceAt(r, b)+ return (sum / 8.0).toFloat()+ }++ /** The whole window's luminance, from a spread of its pixels. */+ fun average(): Float {+ var sum = 0.0+ var n = 0+ var i = 0+ while (i < pixels.size) {+ val c = pixels[i]+ sum += (0.299 * ((c shr 16) and 0xFF) + 0.587 * ((c shr 8) and 0xFF) + 0.114 * (c and 0xFF)) / 255.0+ n+++ i += 37+ }+ return if (n == 0) 0.5f else (sum / n).toFloat()+ }+/*** Luminance around [box]: just inside its four corners (outside the rounded glass), plus, at* double weight, just outside its left and right edges level with its centre, where the icon@@ -135,18 +168,74 @@ internal class InkFrame(val LocalScreenInk = staticCompositionLocalOf<ScreenInkSampler?> { null }-/** Runs one [ScreenInkSampler] for this window (Android 8+); the viewers' controls read from it. */+/**+ * Runs one [ScreenInkSampler] for this window (Android 8+); the controls under it read from it. One+ * already running above is used as it is (the app runs one for every screen while Adaptive luminance+ * is on; the viewers always ask for one). [enabled] false provides none, without changing what is composed.+ */@Composable-fun ProvideScreenInk(content: @Composable () -> Unit) {+fun ProvideScreenInk(enabled: Boolean = true, content: @Composable () -> Unit) {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {content()return}+ val above = LocalScreenInk.currentval view = LocalView.currentval window = remember(view) { view.context.findActivity()?.window }val sampler = remember { ScreenInkSampler() }- if (window != null) LaunchedEffect(window, view) { sampler.run(window, view) }- CompositionLocalProvider(LocalScreenInk provides if (window != null) sampler else null, content = content)+ val runs = enabled && above == null && window != null+ if (runs && window != null) LaunchedEffect(window, view) { sampler.run(window, view) }+ CompositionLocalProvider(LocalScreenInk provides (above ?: if (runs) sampler else null), content = content)+}++/**+ * How light the screen is around one glass control, from the window's sampler: what the control's+ * glass adapts to while Adaptive luminance is on. One copy of the window serves every control, so a+ * screenful of glass buttons costs no more than one.+ */+@Stable+class SurroundLuminance internal constructor(initial: Float) {+ internal val anim = androidx.compose.animation.core.Animatable(initial)+ internal val box = arrayOfNulls<Rect>(1)++ /** 0 (dark around) … 1 (light around). Read while drawing. */+ val value: Float get() = anim.value++ /** Put on the control (first, so it measures the resting box). */+ val modifier: Modifier = Modifier.onGloballyPositioned { box[0] = it.boundsInWindow() }+}++/** The luminance around the control being composed, or null while Adaptive luminance is off. */+@Composable+fun rememberSurroundLuminance(): SurroundLuminance? {+ val sampler = LocalScreenInk.current+ if (!GlassSettings.adaptive || sampler == null) return null+ val dark = com.chethan616.clearpdf.ui.theme.clear.dark+ val state = remember { SurroundLuminance(sampler.frame?.average() ?: if (dark) 0.14f else 0.86f) }+ val gap = with(LocalDensity.current) { 7.dp.toPx() }+ val overlays = LocalGlassOverlayHost.current+ DisposableEffect(sampler) {+ sampler.users+++ onDispose { sampler.users-- }+ }+ LaunchedEffect(sampler) {+ var first = true+ snapshotFlow { sampler.frame }.collect { frame ->+ val b = state.box[0]+ if (frame == null || b == null || b.width <= 0f || b.height <= 0f) return@collect+ // a menu or sheet over the screen is not the screen: the glass under it holds as it was+ if (!first && overlays != null && overlays.entries.isNotEmpty()) return@collect+ val lum = frame.outsideLuminance(b, gap)+ if (first) {+ state.anim.snapTo(lum)+ first = false+ } else if (kotlin.math.abs(lum - state.anim.targetValue) > 0.1f) {+ // only a real change of what it is over moves it: a neighbour's glint does not+ launch { state.anim.animateTo(lum, tween(360)) }+ }+ }+ }+ return state}/** One control's ink: put [modifier] on the control (first, so it measures the resting box). */@@ -171,6 +260,7 @@ fun rememberAdaptiveInk(fallback: Color): InkProbe {val box = remember { arrayOfNulls<Rect>(1) }val currentFallback by rememberUpdatedState(fallbackOnLight)val inset = with(LocalDensity.current) { 5.dp.toPx() }+ val overlays = LocalGlassOverlayHost.currentif (sampler != null) {DisposableEffect(sampler) {sampler.users++@@ -180,6 +270,8 @@ fun rememberAdaptiveInk(fallback: Color): InkProbe {snapshotFlow { sampler.frame }.collect { frame ->val b = box[0]if (frame == null || b == null || b.width <= 0f || b.height <= 0f) return@collect+ // a menu lying over a button is not what the button stands on: its ink holds+ if (measured && overlays != null && overlays.entries.isNotEmpty()) return@collectval lum = frame.cornerLuminance(b, inset)// Hysteresis, so a control over a mid-grey picture doesn't flicker.onLight = when {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 32c8f39..2f23093 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@@ -64,8 +64,13 @@ private fun Modifier.glassControl(bloom: Boolean = true,tintAt: (() -> Color)? = null,candyBase: Boolean = true,+ adaptWash: Boolean = true,): 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()val scope = rememberCoroutineScope()val haptics = LocalHaptics.currentval currentHaptics by rememberUpdatedState(haptics)@@ -92,13 +97,17 @@ private fun Modifier.glassControl(}}}- val style = GlassSettings.style+ val style = if (around != null) GlassSettings.style.adaptiveBase else GlassSettings.stylereturn this+ .then(around?.modifier ?: Modifier).drawBackdrop(backdrop = backdrop,shape = { shape },shadow = null,- effects = { glassEffects(style, blur.toPx(), 12f.dp.toPx(), 24f.dp.toPx()) },+ effects = {+ if (around != null) adaptiveGlassEffects(style, around.value, blur.toPx(), 12f.dp.toPx(), 24f.dp.toPx())+ else glassEffects(style, blur.toPx(), 12f.dp.toPx(), 24f.dp.toPx())+ },highlight = { glassHighlight(style) },layerBlock = { liquidPressTransform(highlight) },onDrawSurface = {@@ -109,6 +118,8 @@ private fun Modifier.glassControl(if (candyBase) drawRect(Color.White.copy(alpha = 0.42f))drawRect(t, blendMode = BlendMode.Hue)drawRect(t.copy(alpha = if (candyBase) 0.8f else 0.75f))+ } else if (around != null && adaptWash) {+ drawRect(adaptiveWash(around.value).let { it.copy(alpha = it.alpha * 0.7f) })}if (surface.isSpecified) drawRect(surface.glassTint(style))// read here, while drawing, so a colour animating in changes pixels and recomposes nothing@@ -165,16 +176,24 @@ fun Modifier.glassBar(shape: Shape = ChromeCapsule, surface: Color = Color.Unspeval backdrop = LocalBackdrop.currentval scope = rememberCoroutineScope()val highlight = remember(scope) { InteractiveHighlight(scope) }- val style = GlassSettings.style+ val around = rememberSurroundLuminance()+ val style = if (around != null) GlassSettings.style.adaptiveBase else GlassSettings.stylereturn this+ .then(around?.modifier ?: Modifier).drawBackdrop(backdrop = backdrop,shape = { shape },shadow = null,- effects = { glassEffects(style, blur.toPx(), 12f.dp.toPx(), 24f.dp.toPx()) },+ effects = {+ if (around != null) adaptiveGlassEffects(style, around.value, blur.toPx(), 12f.dp.toPx(), 24f.dp.toPx())+ else glassEffects(style, blur.toPx(), 12f.dp.toPx(), 24f.dp.toPx())+ },highlight = { glassHighlight(style) },layerBlock = { liquidPressTransform(highlight) },- onDrawSurface = { if (surface.isSpecified) drawRect(surface.glassTint(style)) },+ onDrawSurface = {+ if (around != null) drawRect(adaptiveWash(around.value).let { it.copy(alpha = it.alpha * 0.7f) })+ if (surface.isSpecified) drawRect(surface.glassTint(style))+ },).then(highlight.modifier).then(highlight.gestureModifier)@@ -242,7 +261,7 @@ fun GlassChip(CompositionLocalProvider(LocalGlassInk provides ink) {Row(modifier- .glassControl(Capsule, onClick, onLongClick, Color.Unspecified, surface, blur, label, fill, tap, bloom)+ .glassControl(Capsule, onClick, onLongClick, Color.Unspecified, surface, blur, label, fill, tap, bloom, adaptWash = false).height(height).padding(contentPadding),horizontalArrangement = horizontalArrangement,diff --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 6df802a..4424741 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@@ -193,23 +193,49 @@ object GlassMotion {/** Alpha and colour. Never bounces. */fun <T> settle(): SpringSpec<T> = spring(dampingRatio = 1f, stiffness = Spring.StiffnessMedium)+ /**+ * How close to rest a glass spring runs before it is let go. The platform's default (1 % of the+ * way) cut a menu's last swing short: on a tall menu that is a jump of ten pixels or more, seen+ * as the bounce stiffening before it had finished. At a twentieth of that nothing is left to see.+ */+ private const val Rest = 0.0005f+/** A menu unfolding: its width leads and settles with a soft overshoot (the one every entrance is judged against). */- fun <T> unfold(): SpringSpec<T> = spring(MotionSettings.damping(0.68f), MotionSettings.stiffness(420f))+ fun unfold(): SpringSpec<Float> = spring(MotionSettings.damping(0.68f), MotionSettings.stiffness(420f), Rest)/** The menu's height, a beat behind its width. */- fun <T> unfoldLag(): SpringSpec<T> = spring(MotionSettings.damping(0.6f), MotionSettings.stiffness(340f))+ fun unfoldLag(): SpringSpec<Float> = spring(MotionSettings.damping(0.6f), MotionSettings.stiffness(340f), Rest)/** Springs open: capsules, chevrons, thumbs, dialogs, toasts. */- fun <T> morph(): SpringSpec<T> = spring(MotionSettings.damping(0.58f), MotionSettings.stiffness(420f))+ fun morph(): SpringSpec<Float> = spring(MotionSettings.damping(0.58f), MotionSettings.stiffness(420f), Rest)/** A small thing popping into place: fan chips, the + glyph. */- fun <T> pop(): SpringSpec<T> = spring(MotionSettings.damping(0.45f), MotionSettings.stiffness(500f))+ fun pop(): SpringSpec<Float> = spring(MotionSettings.damping(0.45f), MotionSettings.stiffness(500f), Rest)++ /**+ * A menu growing out of the button that opens it, as iOS 26's menus do: slower and heavier than+ * [unfold] (a spring of about 0.42 s response, 0.8 damping at the Normal setting), so the eye+ * follows the button becoming the menu; its height runs a touch softer behind ([growLag]).+ */+ fun grow(): SpringSpec<Float> = spring(MotionSettings.damping(0.82f), MotionSettings.stiffness(230f), Rest)++ fun growLag(): SpringSpec<Float> = spring(MotionSettings.damping(0.76f), MotionSettings.stiffness(190f), Rest)++ /**+ * The menu going back into its button, the same way it came: the glass draws in to the+ * button's box on the same slow spring, without the swing (a menu that bounced on its way out+ * would hold the screen while it settled).+ */+ fun shrink(): SpringSpec<Float> = spring(1f, MotionSettings.stiffness(230f), Rest)++ /** A glass popover folding back into its button: quick, critically damped, so it lands without a step. */+ fun fold(): SpringSpec<Float> = spring(1f, MotionSettings.stiffness(900f), Rest)/** The recorder pill growing: slow and soft, with a floor on damping so Jelly cannot ring on. */- fun <T> shape(): SpringSpec<T> = spring(maxOf(MotionSettings.damping(0.6f), ShapeMinDamping), MotionSettings.stiffness(105f))+ fun shape(): SpringSpec<Float> = spring(maxOf(MotionSettings.damping(0.6f), ShapeMinDamping), MotionSettings.stiffness(105f), Rest)/** The recorder pill shrinking back. */- fun <T> shapeBack(): SpringSpec<T> = spring(maxOf(MotionSettings.damping(0.62f), ShapeMinDamping), MotionSettings.stiffness(125f))+ fun shapeBack(): SpringSpec<Float> = spring(maxOf(MotionSettings.damping(0.62f), ShapeMinDamping), MotionSettings.stiffness(125f), Rest)private const val ShapeMinDamping = 0.46fdiff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Overlays.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Overlays.ktindex 7fc0ab6..b125dbe 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Overlays.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Overlays.kt@@ -52,6 +52,7 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.geometry.Rectimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.CompositingStrategy@@ -323,9 +324,35 @@ private const val MenuGoneMillis = 220L// Menus are their own glass material. A neutral wash lets a PDF, picture, or wallpaper supply the// reflected colour instead of imposing the app theme's blue frost over every context.-private val MenuLightWash = Color.White.copy(alpha = 0.72f)-private val MenuDarkWash = Color(0xFF0D0D10).copy(alpha = 0.58f)-private val MenuGlassStyle = GlassStyle.MaximumFrost.copy(saturation = 1f)+// Lighter than before (0.72 / 0.58 over a ×3 blur read as a painted card): the menu is glass again,+// what is behind it showing through as soft colour, in both themes.+private val MenuLightWash = Color.White.copy(alpha = 0.50f)+private val MenuDarkWash = Color(0xFF101014).copy(alpha = 0.54f)++/**+ * The card every menu and popover is made of (the desk's menus, the viewer's selection and page+ * menus, More tools): one frosted glass, whatever the user's glass preset, so no menu comes out+ * clear, prismatic or painted where the others are frosted. With Settings ▸ Liquid glass ▸ Adaptive+ * luminance it reads what is behind it and takes light glass and dark ink, or dark glass and white+ * ink, to suit; its rows take their ink from [LocalGlassInk] / [LocalMenuInk].+ */+@Composable+fun MenuCard(modifier: Modifier = Modifier, shape: androidx.compose.ui.graphics.Shape = RoundedRectangle(24.dp), content: @Composable ColumnScope.() -> Unit) {+ val c = clear+ val luminance = rememberGlassLuminance()+ GlassCard(+ // unseen for the frame or two it takes to read what is behind it (see [GlassLuminance])+ modifier.graphicsLayer { alpha = if (luminance == null || luminance.measured) 1f else 0f },+ shape = shape,+ wash = if (c.dark) MenuDarkWash else MenuLightWash,+ blur = 16.dp,+ styleOverride = if (c.dark) GlassStyle.MenuFrostDark else GlassStyle.MenuFrost,+ luminance = luminance,+ ) {+ val ink = adaptiveInk(luminance, c.ink)+ CompositionLocalProvider(LocalGlassInk provides ink, LocalMenuInk provides ink) { content() }+ }+}@Composablefun GlassMenu(anchor: Rect, onDismiss: () -> Unit, items: List<GlassMenuItem>) {@@ -381,11 +408,27 @@ private fun GlassMenuLayoutContent(// unfolds out of its button like a drop of gel: width first, the height a beat behind, each on// a glass spring (Settings ▸ Motion) that swells a little past rest and settles;// folding back into the button is quick and never bounces- val appear = rememberOverlayAppear(enter = GlassMotion.unfold(), exit = Fluid.dismiss())+ // (a spring both ways: closed mid-swing it carries its speed on instead of starting a new+ // curve from a standstill, and the screens' curve from Settings no longer reaches the glass)+ //+ // Opened from a single button (⋯, More tools, a bar's glyph), the menu is that button grown:+ // it starts as the button's own box, at the button's place, and springs out to its size, over+ // the button, then folds back into it. Opened from anything larger (a card held down on the+ // desk) it unfolds beside its anchor as before.+ val buttonSide = with(LocalDensity.current) { 72.dp.toPx() }+ val morph = anchor.width > 0f && anchor.height > 0f && maxOf(anchor.width, anchor.height) <= buttonSide+ val appear = rememberOverlayAppear(+ enter = if (morph) GlassMotion.grow() else GlassMotion.unfold(),+ exit = if (morph) GlassMotion.shrink() else GlassMotion.fold(),+ )val lag = remember { Animatable(0f) }LaunchedEffect(leaving) {- if (!leaving) lag.animateTo(1f, GlassMotion.unfoldLag()) else lag.animateTo(0f, Fluid.dismiss())+ if (!leaving) lag.animateTo(1f, if (morph) GlassMotion.growLag() else GlassMotion.unfoldLag())+ else lag.animateTo(0f, if (morph) GlassMotion.shrink() else GlassMotion.fold())}+ // where the card was put (the portal's space): the button's box inside it follows from this+ var placedAt by remember { mutableStateOf(Offset.Zero) }+ val menuCorner = with(LocalDensity.current) { 24.dp.toPx() }Box(Modifier.fillMaxSize().clickable(remember { MutableInteractionSource() }, null, onClick = onDismiss))val local = Rect(host.windowToLocal(anchor.topLeft), host.windowToLocal(anchor.bottomRight))val margin = with(LocalDensity.current) { 12.dp.toPx() }@@ -393,25 +436,64 @@ private fun GlassMenuLayoutContent(var fromBelow by remember { mutableStateOf(true) }Layout(content = {- GlassCard(+ MenuCard(Modifier.width(width).floatingLayer {val p = appear.value- scaleX = lerp(0.5f, 1f, p).coerceAtLeast(0.2f)- scaleY = lerp(0.35f, 1f, lag.value).coerceAtLeast(0.2f)- transformOrigin = TransformOrigin(if (fromRight) 1f else 0f, if (fromBelow) 0f else 1f)- alpha = (p * 1.6f).coerceIn(0f, 1f)+ if (morph && size.width > 0f && size.height > 0f) {+ // The glass itself grows: the card lies where it will rest, and what+ // shows of it is an outline that starts as the button's own box (its+ // place, its size, its roundness) and opens out to the card's, the+ // height a beat behind the width. Nothing is stretched, so the corners+ // stay true and the rows don't squash; only an outline on a finished+ // texture moves, which costs nothing.+ val px = p.coerceIn(0f, 1f)+ val py = lag.value.coerceIn(0f, 1f)+ val bl = (local.left - placedAt.x).coerceIn(0f, size.width)+ val bt = (local.top - placedAt.y).coerceIn(0f, size.height)+ val br = (local.right - placedAt.x).coerceIn(bl, size.width)+ val bb = (local.bottom - placedAt.y).coerceIn(bt, size.height)+ shape = GrownShape(+ lerp(bl, 0f, px), lerp(bt, 0f, py), lerp(br, size.width, px), lerp(bb, size.height, py),+ lerp(minOf(br - bl, bb - bt) / 2f, menuCorner, px),+ )+ clip = true+ // the swing past rest is the whole card swelling a little about the button+ scaleX = 1f + (p - px)+ scaleY = 1f + (lag.value - py)+ transformOrigin = TransformOrigin(+ if (size.width > 0f) ((bl + br) / 2f / size.width) else 0.5f,+ if (size.height > 0f) ((bt + bb) / 2f / size.height) else 0.5f,+ )+ // over the button within the first few frames (and off it in the last),+ // so the two glasses cross rather than swap+ alpha = (px * 5f).coerceIn(0f, 1f)+ } else {+ scaleX = lerp(0.5f, 1f, p).coerceAtLeast(0.2f)+ scaleY = lerp(0.35f, 1f, lag.value).coerceAtLeast(0.2f)+ alpha = (p * 1.6f).coerceIn(0f, 1f)+ transformOrigin = TransformOrigin(if (fromRight) 1f else 0f, if (fromBelow) 0f else 1f)+ }},- shape = RoundedRectangle(24.dp),- // Keep menus fully frosted even when the global glass setting is Lite or Crystal.- wash = if (c.dark) MenuDarkWash else MenuLightWash,- blur = 16.dp,- styleOverride = MenuGlassStyle,) {- CompositionLocalProvider(LocalGlassInk provides c.ink) {- Column(Modifier.heightIn(max = maxHeight).verticalScroll(rememberScrollState()), content = content)- }+ Column(+ Modifier+ .then(+ // what is written on the menu comes up out of the button as the glass+ // opens, and goes back first on the way in+ if (morph) Modifier.graphicsLayer {+ val px = appear.value.coerceIn(0f, 1f)+ alpha = ((px - 0.22f) / 0.5f).coerceIn(0f, 1f)+ val s = lerp(0.9f, 1f, px)+ scaleX = s+ scaleY = s+ transformOrigin = TransformOrigin(if (fromRight) 1f else 0f, if (fromBelow) 0f else 1f)+ } else Modifier,+ )+ .heightIn(max = maxHeight).verticalScroll(rememberScrollState()),+ content = content,+ )}},modifier = Modifier.fillMaxSize(),@@ -429,19 +511,32 @@ private fun GlassMenuLayoutContent(val right = local.center.x > constraints.maxWidth / 2ffromRight = rightval x = if (right) (local.right - p.width) else local.left- val below = local.bottom + 6f + p.height < constraints.maxHeight - barBottom - margin+ // grown from a button, the menu lies over it (from its top edge down, or its bottom+ // edge up); beside anything else, a little clear of it+ val gap = if (morph) -local.height else 6f+ val below = local.bottom + gap + p.height < constraints.maxHeight - barBottom - marginfromBelow = below- val y = if (below) local.bottom + 6f else local.top - 6f - p.height+ val y = if (below) local.bottom + gap else local.top - gap - p.heightval minX = barLeft + marginval maxX = (constraints.maxWidth - barRight - p.width - margin).coerceAtLeast(minX)val minY = barTop + marginval maxY = (constraints.maxHeight - barBottom - p.height - margin).coerceAtLeast(minY)- p.place(IntOffset(x.coerceIn(minX, maxX).roundToInt(), y.coerceIn(minY, maxY).roundToInt()))+ val at = IntOffset(x.coerceIn(minX, maxX).roundToInt(), y.coerceIn(minY, maxY).roundToInt())+ placedAt = Offset(at.x.toFloat(), at.y.toFloat())+ p.place(at)}}}}+/** What shows of a menu as it grows out of its button: a rounded box, in the card's own space. */+private class GrownShape(val left: Float, val top: Float, val right: Float, val bottom: Float, val radius: Float) : androidx.compose.ui.graphics.Shape {+ override fun createOutline(size: androidx.compose.ui.geometry.Size, layoutDirection: androidx.compose.ui.unit.LayoutDirection, density: androidx.compose.ui.unit.Density) =+ androidx.compose.ui.graphics.Outline.Rounded(+ androidx.compose.ui.geometry.RoundRect(left, top, right, bottom, androidx.compose.ui.geometry.CornerRadius(radius.coerceAtLeast(0f))),+ )+}+/** A text field on glass: a rounded frosted well, a quiet [placeholder], the theme's ink. */@Composablefun GlassTextField(@@ -481,12 +576,21 @@ fun GlassTextField()}-/** A toast: a glass capsule that rises in above the dock, with an optional candy action. */+/**+ * A toast: a glass capsule that rises in above the dock, with an optional candy action.+ *+ * A toast lands on anything (the wallpaper, a white page, a black slide), so it always reads what is+ * behind it and takes light glass with dark ink or dark glass with white ink, whatever the theme and+ * the Adaptive luminance setting: the theme's frost over a black page came out a grey slab. Its lens+ * is the buttons' own (Back, More), so it bends its edges as they do.+ */@Composablefun GlassToast(text: String, action: String?, onAction: () -> Unit, modifier: Modifier = Modifier) {val c = clearval appear = remember { Animatable(0f) }LaunchedEffect(Unit) { appear.animateTo(1f, GlassMotion.morph()) }+ val luminance = rememberGlassLuminance(enabled = true)+ val ink = adaptiveInk(luminance, c.ink)Row(modifier.floatingLayer {@@ -495,11 +599,11 @@ fun GlassToast(text: String, action: String?, onAction: () -> Unit, modifier: Moalpha = p.coerceIn(0f, 1f)}.widthIn(max = 520.dp)- .glass(Capsule, c.frost, blur = 12.dp)+ .glass(Capsule, c.frost, blur = 12.dp, lensHeight = 12.dp, lensAmount = 24.dp, luminance = luminance).padding(start = 20.dp, end = if (action != null) 6.dp else 20.dp, top = 6.dp, bottom = 6.dp),verticalAlignment = Alignment.CenterVertically,) {- Text(text, style = ClearType.Label, color = c.ink, modifier = Modifier.weight(1f, fill = false).padding(vertical = 8.dp), maxLines = 3)+ Text(text, style = ClearType.Label, color = ink, modifier = Modifier.weight(1f, fill = false).padding(vertical = 8.dp), maxLines = 3)if (action != null) {Spacer(Modifier.width(10.dp))GlassPill(onClick = onAction, tint = Candy.Sky, height = 38.dp, horizontalPadding = 14.dp) {diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Style.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Style.ktindex 8a60a37..2240dc1 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Style.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Style.kt@@ -34,8 +34,18 @@ data class GlassStyle(val Default = GlassStyle()/** Heavier frost and wash: text stays legible over busy pages. */val Frosted = GlassStyle(blur = 2.4f, tint = 1.8f, refractionAmount = 0.7f, saturation = 1.3f)- /** Menu frost stays at the top of the app's blur range, independent of the user's glass preset. */- val MaximumFrost = Frosted.copy(blur = 3f, refractionHeight = 0f, refractionAmount = 0f, tint = 1f)+ /**+ * A menu's own frost, independent of the user's glass preset (a Lite or Crystal menu would not+ * read). Lighter than it was (blur ×3 hid everything behind): what is under the menu now shows+ * through as soft shapes, as a sheet of frosted glass lets it.+ */+ val MenuFrost = GlassStyle(blur = 1.5f, refractionHeight = 0f, refractionAmount = 0f, tint = 1f, saturation = 1.2f, brightness = 0.08f)++ /**+ * The same in the dark theme: what is behind is dimmed a little, so white ink still reads when+ * a dark menu opens over a white page.+ */+ val MenuFrostDark = MenuFrost.copy(brightness = -0.3f)/** Clear, strongly bent glass with a prismatic rim. */val Crystal = GlassStyle(blur = 0.3f, refractionHeight = 1.5f, refractionAmount = 1.6f, depthEffect = true, chromaticAberration = true, tint = 0.6f, saturation = 1.7f)/** No blur or lens at all, for slower phones. */@@ -99,6 +109,18 @@ object GlassSettings {var style: GlassStyle by mutableStateOf(GlassStyle.Default)var haptics: Boolean by mutableStateOf(true)+ /**+ * Adaptive luminance (Settings ▸ Liquid glass): menus, popovers and toasts read how light what is+ * behind them is, and turn light with dark ink or dark with white ink to suit (see [GlassLuminance]).+ */+ var adaptive: Boolean by mutableStateOf(false)+ private set++ fun updateAdaptive(context: Context, on: Boolean) {+ adaptive = on+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("adaptive", on).apply()+ }+fun load(context: Context) {val p = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)val d = GlassStyle.Default@@ -114,6 +136,7 @@ object GlassSettings {highlight = p.getFloat("highlight", d.highlight),)haptics = p.getBoolean("haptics", true)+ adaptive = p.getBoolean("adaptive", false)wallpaper = runCatching { Wallpaper.valueOf(p.getString("wallpaper", null) ?: "Aurora") }.getOrDefault(Wallpaper.Aurora)if (wallpaper == Wallpaper.Custom) loadCustom(context)if (wallpaper == Wallpaper.Custom && customWallpaper == null) wallpaper = Wallpaper.Auroradiff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Surfaces.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Surfaces.ktindex fed79a6..d4ecb3c 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Surfaces.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Surfaces.kt@@ -44,9 +44,34 @@ fun Modifier.glass(lensHeight: Dp = 16.dp,lensAmount: Dp = 24.dp,styleOverride: GlassStyle? = null,+ luminance: GlassLuminance? = null,): Modifier {val backdrop = LocalBackdrop.currentval style = styleOverride ?: GlassSettings.style+ // adaptive: the glass answers what is behind it instead of wearing the theme's wash+ if (luminance != null) return drawBackdrop(+ backdrop = backdrop,+ shape = { shape },+ shadow = null,+ effects = { adaptiveGlassEffects(style, luminance.value, blur.toPx(), lensHeight.toPx(), lensAmount.toPx()) },+ highlight = { glassHighlight(style) },+ onDrawBackdrop = luminance.recorder,+ onDrawSurface = { drawRect(adaptiveWash(luminance.value).glassTint(style)) },+ )+ // Adaptive luminance on: a still surface (a bar, a panel, a sheet) takes its frost and light+ // from what is around it. It keeps its own wash: what is written on it is in the theme's ink.+ val around = rememberSurroundLuminance()+ if (around != null && styleOverride == null) {+ val base = style.adaptiveBase+ return then(around.modifier).drawBackdrop(+ backdrop = backdrop,+ shape = { shape },+ shadow = null,+ effects = { adaptiveGlassEffects(base, around.value, blur.toPx(), lensHeight.toPx(), lensAmount.toPx()) },+ highlight = { glassHighlight(base) },+ onDrawSurface = { if (wash.isSpecified) drawRect(wash) },+ )+ }return drawBackdrop(backdrop = backdrop,shape = { shape },@@ -68,13 +93,14 @@ fun GlassCard(wash: Color = clear.glass,blur: Dp = 8.dp,styleOverride: GlassStyle? = null,+ luminance: GlassLuminance? = null,content: @Composable ColumnScope.() -> Unit,) {val below = LocalBackdrop.currentval layer = rememberLayerBackdrop()val combined = rememberCombinedBackdrop(below, layer)Box(modifier) {- Box(Modifier.matchParentSize().layerBackdrop(layer).glass(shape, wash, blur, styleOverride = styleOverride))+ Box(Modifier.matchParentSize().layerBackdrop(layer).glass(shape, wash, blur, styleOverride = styleOverride, luminance = luminance))CompositionLocalProvider(LocalBackdrop provides combined) { Column(content = content) }}}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Tabs.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Tabs.ktindex 275bd3c..b745ff7 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Tabs.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Tabs.kt@@ -95,7 +95,7 @@ fun GlassTabs(val count = tabs.sizeval container = c.glassval inner = (height - 8.dp).coerceAtLeast(0.dp)- val accent by animateColorAsState(tabs.getOrNull(selected)?.accent ?: c.ink, GlassMotion.settle(), label = "tab accent")+ val accent by animateColorAsState(tabs.getOrNull(selected)?.accent ?: c.ink, GlassMotion.settle(), label = "tabAccent")val tabsLayer = rememberLayerBackdrop()val select by rememberUpdatedState(onSelect)val selectedNow by rememberUpdatedState(selected)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 bbcdfb2..5ddf33d 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@@ -198,7 +198,7 @@ fun CheckPill(item: CheckItem, tone: CardTone, onToggle: () -> Unit) {// ticked: a deeper wash over the glass (the tone's ink on light cards, shade on dark ones)val doneWash = if (dark) Color.Black.copy(alpha = 0.34f) else tone.ink.copy(alpha = 0.58f)val wash by animateColorAsState(if (done) doneWash else Color.Transparent, com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "pill")- val ink by animateColorAsState(if (done) Color.White else tone.ink, com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "pill ink")+ val ink by animateColorAsState(if (done) Color.White else tone.ink, com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "pillInk")val tick by animateFloatAsState(if (done) 1f else 0f, com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "tick")GlassChip(onClick = { haptics?.play(if (done) com.chethan616.clearpdf.ui.glass.Feel.ToggleOff else com.chethan616.clearpdf.ui.glass.Feel.ToggleOn); onToggle() },@@ -554,7 +554,7 @@ fun RecentCard(vm: AppViewModel, rows: List<FileRow>, onAll: () -> Unit, modifieval tilt = listOf(-4f, 7f, -12f)[i]val dx = listOf(0, 26, -22)[i]PaperThumb(- vm, r.thumbPath, 84.dp, 110.dp, tilt = tilt, corner = 7.dp,+ vm, r.thumbPath, 84.dp, 110.dp, tilt = tilt, corner = 7.dp, name = r.name,modifier = Modifier.align(Alignment.Center).offset(x = dx.dp, y = (i * 4).dp),)}@@ -577,7 +577,7 @@ fun RecentCard(vm: AppViewModel, rows: List<FileRow>, onAll: () -> Unit, modifiefun DocCard(vm: AppViewModel, r: FileRow, tone: CardTone, tilt: Float, onLong: () -> Unit, modifier: Modifier = Modifier) {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, modifier = Modifier.graphicsLayer { shadowElevation = 10.dp.toPx(); shape = RoundedRectangle(8.dp) })+ 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) {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/HomeScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/HomeScreen.ktindex 7d1b861..ddb6fe9 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@@ -286,6 +286,7 @@ private fun DeskHeader(vm: AppViewModel) {GlassMenu(anchor, { menu = false }, listOf(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() },GlassMenuItem(stringResource(R.string.home_settings), LucideIcons.Settings) { vm.settingsOpen = true },))}@@ -329,7 +330,7 @@ private fun DeskTitle(filter: DeskFilter) {(slideInVertically(com.chethan616.clearpdf.ui.glass.Fluid.push()) { it / 3 } + fadeIn(com.chethan616.clearpdf.ui.glass.Fluid.quick())) togetherWith(slideOutVertically(com.chethan616.clearpdf.ui.glass.Fluid.quick()) { -it / 4 } + fadeOut(com.chethan616.clearpdf.ui.glass.Fluid.fade()))},- label = "desk title",+ label = "deskTitle",modifier = Modifier.fillMaxWidth().height(height),) { f ->BasicText(@@ -443,8 +444,10 @@ private fun NoteActions(vm: AppViewModel, n: Note, anchor: Rect, onRename: () ->val openLabel = stringResource(R.string.notes_open)val photoLabel = stringResource(R.string.photo_edit)val deleteLabel = stringResource(R.string.common_delete)+ val exportLabel = stringResource(R.string.voice_export)GlassMenu(anchor, onDismiss, buildList {if (voice) add(GlassMenuItem(renameLabel, LucideIcons.PenLine) { onDismiss(); onRename() })+ if (voice && n.audio != null) add(GlassMenuItem(exportLabel, LucideIcons.SaveAs) { vm.exportVoice(n); onDismiss() })add(GlassMenuItem(pinLabel, LucideIcons.Pin) { vm.notes.put(n.copy(pinned = !n.pinned)); onDismiss() })if (!voice) add(GlassMenuItem(openLabel, LucideIcons.SquarePen) { vm.openNote = n.id; onDismiss() })n.images.firstOrNull()?.let { pic -> add(GlassMenuItem(photoLabel, LucideIcons.SlidersHorizontal) { onDismiss(); vm.editingPhoto = n.id to pic }) }diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.ktindex 894a469..a19a27c 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/notes/PhotoEditor.kt@@ -60,6 +60,10 @@ import com.chethan616.clearpdf.core.PhotoEditorimport com.chethan616.clearpdf.engine.toBitmapimport com.chethan616.clearpdf.ui.AppViewModelimport com.chethan616.clearpdf.ui.LucideIcons+import androidx.compose.material.icons.rounded.Details+import androidx.compose.material.icons.rounded.Straighten+import androidx.compose.material.icons.rounded.Vignette+import androidx.compose.material.icons.rounded.WbSunnyimport com.chethan616.clearpdf.ui.glass.ChromeCapsuleimport com.chethan616.clearpdf.ui.glass.Fluidimport com.chethan616.clearpdf.ui.glass.GlassCircle@@ -102,6 +106,13 @@ private enum class Adjust(Shadows("light", "shadows", R.string.photo_shadows, LucideIcons.Shadows, -100f, 100f, 0),Vibrance("color", "vibrance", R.string.photo_vibrance, LucideIcons.Palette, -100f, 100f, 0),Saturation("color", "saturation", R.string.photo_saturation, LucideIcons.Droplet, -100f, 100f, 0),+ // LightCraft's geometry, tone, presence and detail (names as its settings spell them)+ Straighten("geometry", "rotate", R.string.photo_straighten, androidx.compose.material.icons.Icons.Rounded.Straighten, -10f, 10f, 1),+ Whites("light", "whites", R.string.photo_whites, androidx.compose.material.icons.Icons.Rounded.WbSunny, -100f, 100f, 0),+ Blacks("light", "blacks", R.string.photo_blacks, LucideIcons.Moon, -100f, 100f, 0),+ Clarity("effects", "clarity", R.string.photo_clarity, LucideIcons.Sparkles, -100f, 100f, 0),+ Sharpen("detail", "sharpen_amount", R.string.photo_sharpen, androidx.compose.material.icons.Icons.Rounded.Details, 0f, 150f, 0),+ Vignette("vignette", "amount", R.string.photo_vignette, androidx.compose.material.icons.Icons.Rounded.Vignette, -100f, 100f, 0),}private val TURNS = listOf("Normal", "Rotate90", "Rotate180", "Rotate270")@@ -318,9 +329,22 @@ private fun PhotoControls(Text(stringResource(selected.label), style = ClearType.Label, color = ink.color.copy(alpha = 0.66f), maxLines = 1, overflow = TextOverflow.Ellipsis)Text(shown(selected, value), style = ClearType.Title.copy(fontSize = 22.sp), color = if (value == 0f) ink.color else Candy.Lemon)}+ // felt under the thumb: a light tick every fortieth of the way, a firm one through zero+ val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()+ val notch = remember(selected) { intArrayOf(Int.MIN_VALUE) }Slider(value = value,- onValueChange = onValueChange,+ onValueChange = { v ->+ val at = Math.round((v - selected.min) / (selected.max - selected.min).coerceAtLeast(0.0001f) * 40f)+ if (at != notch[0]) {+ if (notch[0] != Int.MIN_VALUE) {+ val throughZero = selected.min < 0f && ((value < 0f) != (v < 0f) || v == 0f)+ feel(if (throughZero) com.chethan616.clearpdf.ui.glass.Feel.Tap else com.chethan616.clearpdf.ui.glass.Feel.Tick)+ }+ notch[0] = at+ }+ onValueChange(v)+ },valueRange = selected.min..selected.max,modifier = Modifier.weight(1f),colors = SliderDefaults.colors(diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.ktindex 670f374..081e3cd 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt@@ -39,6 +39,8 @@ import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.drawscope.DrawScopeimport androidx.compose.ui.graphics.drawscope.clipRectimport androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.graphics.drawscope.withTransform+import androidx.compose.ui.graphics.asImageBitmapimport androidx.compose.ui.graphics.luminanceimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.platform.LocalDensity@@ -136,11 +138,34 @@ private const val SPARE_COLS = 8private const val HEAD_H = 20fprivate const val HEAD_W = 36f-/** One sheet's layout: where every row and column starts (points from A1), its merges and freeze. */+/** One row-and-column pair as a map key. */+private fun cellKey(row: Int, col: Int): Long = (row.toLong() shl 24) or col.toLong()++/**+ * One sheet's layout: where every row and column starts (points from A1), its merges and freeze.+ * A cell's merge is looked up in a map (a form can hold hundreds of merges, and every cell drawn+ * asks for its own on every frame); only the few very large ones are searched.+ */internal class SheetLayout(val info: SheetInfo, val colX: FloatArray, val rowY: FloatArray, val merges: List<CellSpan>) {val cols get() = colX.size - 1val rows get() = rowY.size - 1+ private val mergeOf = HashMap<Long, CellSpan>()+ private val bigMerges = ArrayList<CellSpan>()++ init {+ for (m in merges) {+ val h = (m.row1 - m.row0).toLong() + 1+ val w = (m.col1 - m.col0).toLong() + 1+ if (h * w > 4096 || mergeOf.size > 400_000) bigMerges += m+ else for (r in m.row0.toInt()..m.row1.toInt()) for (c in m.col0.toInt()..m.col1.toInt()) mergeOf[cellKey(r, c)] = m+ }+ }++ /** The merged area [row], [col] is part of, if it is. */+ fun spanAt(row: Int, col: Int): CellSpan? =+ mergeOf[cellKey(row, col)] ?: bigMerges.firstOrNull { row.toUInt() in it.row0..it.row1 && col.toUInt() in it.col0..it.col1 }+/** The first index whose start is past [v] in [edges], less one: the line [v] falls in. */fun indexAt(edges: FloatArray, v: Float): Int {var lo = 0@@ -167,6 +192,27 @@ private fun columnName(c: Int): String {private fun rgb(c: UInt): Color = Color(0xFF000000.toInt() or c.toInt())+/**+ * A cell made ready to draw, once, when its block arrives: the area its fill and text take (its+ * merge, or itself), which of its own edges show (inside a merge only those on the merge's rim),+ * and its colours. [covered] cells lie inside a merge but are not its first cell: they draw no fill+ * or text of their own.+ */+internal class DrawCell(val v: CellView, val row: Int, val col: Int, val r0: Int, val c0: Int, val r1: Int, val c1: Int, val covered: Boolean, val edges: Int) {+ val fill: Color? = v.fill?.let(::rgb)+ val merged: Boolean get() = r0 != r1 || c0 != c1++ companion object {+ const val LEFT = 1+ const val TOP = 2+ const val RIGHT = 4+ const val BOTTOM = 8+ }+}++/** A picture floating over the sheet, decoded. */+internal class SheetImage(val x: Float, val y: Float, val width: Float, val height: Float, val image: androidx.compose.ui.graphics.ImageBitmap)+/*** One workbook's grid as the screen holds it: the sheets, the one shown, its layout and the cells* fetched so far (in blocks), the zoom and scroll, the chosen cell and the search hits.@@ -177,7 +223,10 @@ class SheetGridState internal constructor(private val eng: Engine, private val dinternal setvar current by mutableIntStateOf(0)internal var layout by mutableStateOf<SheetLayout?>(null)- internal val blocks = mutableStateMapOf<Triple<Int, Int, Int>, List<CellView>>()+ internal val blocks = mutableStateMapOf<Triple<Int, Int, Int>, List<DrawCell>>()+ /** The cells holding text, of the blocks fetched: a long text may run on over its empty neighbours, not over these. */+ internal val texted = HashSet<Long>()+ internal var pictures by mutableStateOf<List<SheetImage>>(emptyList())var scale by mutableStateOf(1f)var pan by mutableStateOf(Offset.Zero)/** The chosen cell, if one is. */@@ -199,6 +248,7 @@ class SheetGridState internal constructor(private val eng: Engine, private val dselected = nullhits = emptyList()pan = Offset.Zero+ pictures = emptyList()current = index}@@ -216,21 +266,63 @@ class SheetGridState internal constructor(private val eng: Engine, private val d}}.getOrNull()// a sheet chosen meanwhile wins- if (sheet == current) layout = loaded+ if (sheet != current) return+ // the cells were made ready against the old layout's merges: they are fetched again+ blocks.clear()+ texted.clear()+ layout = loaded+ pictures = runCatching {+ eng.command {+ sheetPictures(docId, sheet.toUInt()).mapNotNull { p ->+ val bounds = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }+ android.graphics.BitmapFactory.decodeByteArray(p.data, 0, p.data.size, bounds)+ // a photo is drawn a few hundred pixels wide: no need for all of it+ var sample = 1+ while (maxOf(bounds.outWidth, bounds.outHeight) / sample > 1600) sample *= 2+ val bitmap = android.graphics.BitmapFactory.decodeByteArray(p.data, 0, p.data.size, android.graphics.BitmapFactory.Options().apply { inSampleSize = sample })+ bitmap?.let { SheetImage(p.x, p.y, p.width, p.height, it.asImageBitmap()) }+ }+ }+ }.getOrDefault(emptyList()).takeIf { sheet == current }.orEmpty()}internal suspend fun loadBlock(br: Int, bc: Int) {- val key = Triple(current, br, bc)+ val l = layout ?: return+ val sheet = current+ val key = Triple(sheet, br, bc)if (key in blocks) returnblocks[key] = emptyList()- blocks[key] = runCatching {- eng.command { sheetCells(docId, current.toUInt(), (br * BLOCK_ROWS).toUInt(), BLOCK_ROWS.toUInt(), (bc * BLOCK_COLS).toUInt(), BLOCK_COLS.toUInt()) }+ val cells = runCatching {+ eng.command {+ sheetCells(docId, sheet.toUInt(), (br * BLOCK_ROWS).toUInt(), BLOCK_ROWS.toUInt(), (bc * BLOCK_COLS).toUInt(), BLOCK_COLS.toUInt()).mapNotNull { v ->+ val row = v.row.toInt()+ val col = v.col.toInt()+ if (row >= l.rows || col >= l.cols) return@mapNotNull null+ val m = l.spanAt(row, col)+ if (m == null) DrawCell(v, row, col, row, col, row, col, false, DrawCell.LEFT or DrawCell.TOP or DrawCell.RIGHT or DrawCell.BOTTOM)+ else {+ val r0 = m.row0.toInt()+ val c0 = m.col0.toInt()+ val r1 = min(m.row1.toInt(), l.rows - 1)+ val c1 = min(m.col1.toInt(), l.cols - 1)+ // inside a merge a cell keeps only the borders on the merge's rim+ val edges = (if (col == c0) DrawCell.LEFT else 0) or (if (row == r0) DrawCell.TOP else 0) or+ (if (col == c1) DrawCell.RIGHT else 0) or (if (row == r1) DrawCell.BOTTOM else 0)+ DrawCell(v, row, col, r0, c0, r1, c1, covered = row != r0 || col != c0, edges = edges)+ }+ }+ }}.getOrDefault(emptyList())+ if (layout !== l || sheet != current) return+ for (c in cells) if (c.v.text.isNotEmpty() && !c.covered) texted += cellKey(c.row, c.col)+ blocks[key] = cells}- /** After an edit: everything shown is fetched again (sizes and values may all have moved). */+ /**+ * After an edit: the layout and cells are fetched again (sizes and values may all have moved).+ * What is shown stays until the new layout is in, so the grid doesn't blink empty on every edit.+ */fun changed() {- blocks.clear()version++}}@@ -247,9 +339,49 @@ fun rememberSheetGrid(eng: Engine, docId: ULong): SheetGridState {}/**- * The grid itself: pans and pinch-zooms, a tap chooses a cell ([onCell]; [onDoubleTapCell] for- * the editor), the heading strips and frozen panes held in place. [top] and [bottom] are the- * room the bars over it take (pixels): the grid runs on beneath them for their glass to refract.+ * Text laid out once per cell and kept: at the size it has at zoom 1, drawn scaled, so neither a+ * scroll nor a pinch measures anything again (measuring every cell in view on every frame was what+ * made a full sheet lag). The least recently drawn go first when it is full.+ */+internal class SheetTextCache(private val measurer: TextMeasurer) {+ private class Entry(val text: String, val style: Int, val width: Int, val layout: androidx.compose.ui.text.TextLayoutResult)++ private val cells = object : LinkedHashMap<Long, Entry>(512, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, Entry>?): Boolean = size > 6000+ }+ private val labels = HashMap<String, androidx.compose.ui.text.TextLayoutResult>()++ /** [c]'s text set in [style], wrapped at [wrapWidth] pixels (0: one line). */+ fun cell(c: DrawCell, style: TextStyle, styleKey: Int, wrapWidth: Int): androidx.compose.ui.text.TextLayoutResult {+ val key = cellKey(c.row, c.col)+ cells[key]?.let { if (it.text == c.v.text && it.style == styleKey && it.width == wrapWidth) return it.layout }+ val wrap = wrapWidth > 0+ val layout = measurer.measure(+ c.v.text, style,+ overflow = TextOverflow.Clip,+ softWrap = wrap, maxLines = if (wrap) Int.MAX_VALUE else 1,+ constraints = Constraints(maxWidth = if (wrap) wrapWidth else Constraints.Infinity),+ )+ cells[key] = Entry(c.v.text, styleKey, wrapWidth, layout)+ return layout+ }++ /** A heading's letters or number. */+ fun label(text: String, style: TextStyle): androidx.compose.ui.text.TextLayoutResult {+ if (labels.size > 4000) labels.clear()+ return labels.getOrPut(text) { measurer.measure(text, style) }+ }++ fun clear() {+ cells.clear()+ labels.clear()+ }+}++/**+ * The grid itself: pans and pinch-zooms, a tap chooses a cell ([onCell]), the heading strips and+ * frozen panes held in place. [top] is the room the bars over it take (pixels): the grid runs on+ * beneath them for their glass to refract.*/@Composablefun SheetGrid(@@ -257,12 +389,11 @@ fun SheetGrid(modifier: Modifier = Modifier,top: Float = 0f,onCell: ((CellSpan?) -> Unit)? = null,- onDoubleTapCell: ((CellSpan) -> Unit)? = null,) {val c = pdfColorsval sheetSurface = if (c.dark) Color(0xFF18192F) else Color.Whiteval density = LocalDensity.current- val measurer = rememberTextMeasurer(cacheSize = 256)+ val measurer = rememberTextMeasurer(cacheSize = 8)val l = state.layoutBox(modifier.fillMaxSize().background(c.surface)) {if (l == null) {@@ -270,13 +401,16 @@ fun SheetGrid(return@Box}val px = density.density+ val texts = remember(l, measurer, c.dark, density.fontScale) { SheetTextCache(measurer) }// the blocks in view, asked for as the grid movesLaunchedEffect(l) {snapshotFlow { Triple(state.pan, state.scale, l) }.distinctUntilChanged().collect { (p, s, lay) ->val k = px * sval c0 = lay.indexAt(lay.colX, (-p.x / k).coerceAtLeast(0f)) / BLOCK_COLSval r0 = lay.indexAt(lay.rowY, (-p.y / k).coerceAtLeast(0f)) / BLOCK_ROWS- for (br in r0..r0 + 1) for (bc in c0..c0 + 1) {+ // zoomed out, a screen holds more than two blocks each way+ val across = if (s < 0.75f) 2 else 1+ for (br in r0..r0 + across) for (bc in c0..c0 + across) {if (br * BLOCK_ROWS < lay.rows && bc * BLOCK_COLS < lay.cols) state.loadBlock(br, bc)}}@@ -294,11 +428,26 @@ fun SheetGrid(state.pan = Offset(x.coerceAtMost(0f), y.coerceAtMost(0f))state.selected = h}+ // The bars over the grid grow and shrink (the formula bar comes with a chosen cell, the search+ // field with Find), moving where the grid starts. The gestures below live as long as the+ // layout does, so they read the room as it is now, not as it was when they began: a tap used+ // to be measured against the old room, and chose a cell a few rows off the one touched.+ val room = androidx.compose.runtime.rememberUpdatedState(top)+ val tapped = androidx.compose.runtime.rememberUpdatedState(onCell)+ // ... and the cells stay where they were on the screen while the bars change over them+ val lastTop = remember(l) { floatArrayOf(top) }+ androidx.compose.runtime.SideEffect {+ val d = top - lastTop[0]+ if (d != 0f) {+ lastTop[0] = top+ state.pan = Offset(state.pan.x, (state.pan.y - d).coerceAtMost(0f))+ }+ }// the cell under a point of the canvas (null: a heading strip)fun cellAt(p: Offset): CellSpan? {val k = px * state.scaleval head = Offset(HEAD_W * k.coerceAtMost(px * 1.5f), HEAD_H * k.coerceAtMost(px * 1.5f))- val y = p.y - top+ val y = p.y - room.valueif (p.x < head.x || y < head.y) return nullval fr = minOf(l.info.frozenRows.toInt(), l.rows)val fc = minOf(l.info.frozenCols.toInt(), l.cols)@@ -306,31 +455,24 @@ fun SheetGrid(val gy = y - head.yval col = if (gx < l.colX[fc] * k) l.indexAt(l.colX, gx / k) else l.indexAt(l.colX, (gx - state.pan.x) / k)val row = if (gy < l.rowY[fr] * k) l.indexAt(l.rowY, gy / k) else l.indexAt(l.rowY, (gy - state.pan.y) / k)- val m = l.merges.firstOrNull { row.toUInt() in it.row0..it.row1 && col.toUInt() in it.col0..it.col1 }- return m ?: CellSpan(row.toUInt(), col.toUInt(), row.toUInt(), col.toUInt())+ return l.spanAt(row, col) ?: CellSpan(row.toUInt(), col.toUInt(), row.toUInt(), col.toUInt())}val flinger = remember { arrayOfNulls<kotlinx.coroutines.Job>(1) }Canvas(Modifier.fillMaxSize().panZoomFling(state, l, px, flinger)- .pointerInput(l, onCell, onDoubleTapCell) {+ .pointerInput(l) {+ // no double tap is waited for: a tap chooses at once (a second tap on the chosen+ // cell edits it), where waiting made every tap land a third of a second latedetectTapGestures(onPress = { flinger[0]?.cancel() },- onTap = { p -> onCell?.invoke(cellAt(p)) },- onDoubleTap = { p ->- val cell = cellAt(p)- if (cell != null && onDoubleTapCell != null) onDoubleTapCell(cell)- else {- state.scale = if (state.scale > 1.2f) 1f else 2f- state.pan = Offset.Zero- }- },+ onTap = { p -> tapped.value?.invoke(cellAt(p)) },)},) {translate(top = top) {- drawSheet(l, state.blocks, state.current, px * state.scale, state.pan, measurer, sheetSurface, c.text, c.dark, state.hits.getOrNull(state.hit), state.selected)+ drawSheet(l, state, px * state.scale, texts, sheetSurface, c.text, c.dark)}}}@@ -351,6 +493,7 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {val grid = rememberSheetGrid(eng, doc.id)val scope = rememberCoroutineScope()val density = LocalDensity.current+ val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()var searching by remember { mutableStateOf(false) }var query by remember { mutableStateOf("") }var editing by remember { mutableStateOf(false) }@@ -407,13 +550,14 @@ fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {SheetGrid(grid, top = topPx,onCell = { cell ->+ // a tap chooses the cell; a tap on the chosen cell opens it for typingif (cell != null && cell == grid.selected) editing = trueelse {+ if (cell != null) feel(com.chethan616.clearpdf.ui.glass.Feel.Tick)grid.selected = cellediting = false}},- onDoubleTapCell = { cell -> grid.selected = cell; editing = true },)}CompositionLocalProvider(LocalBackdrop provides backdrop, LocalGlassInk provides chrome.color) {@@ -707,22 +851,25 @@ private fun DockKey(icon: ImageVector, label: String, enabled: Boolean = true, m}/**- * The sheet at [k] pixels per point, moved by [pan]: the body, then the frozen rows and columns- * held still on their axis, then the heading strips, each clipped to its own region.+ * The sheet at [k] pixels per point: the body, then the frozen rows and columns held still on their+ * axis, then the heading strips, each clipped to its own region. In each region, in Excel's order:+ * grid lines, merged areas cleared of them, fills and data bars, borders, pictures, the chosen cell+ * and the search hit, then the text.*/private fun DrawScope.drawSheet(l: SheetLayout,- blocks: Map<Triple<Int, Int, Int>, List<CellView>>,- sheet: Int,+ state: SheetGridState,k: Float,- pan: Offset,- measurer: TextMeasurer,+ texts: SheetTextCache,sheetSurface: Color,ink: Color,dark: Boolean,- found: CellSpan?,- selected: CellSpan?,) {+ val pan = state.pan+ val sheet = state.current+ val blocks = state.blocks+ val found = state.hits.getOrNull(state.hit)+ val selected = state.selecteddrawRect(sheetSurface)val head = Offset(HEAD_W * k.coerceAtMost(density * 1.5f), HEAD_H * k.coerceAtMost(density * 1.5f))val fr = min(l.info.frozenRows.toInt(), l.rows)@@ -730,6 +877,13 @@ private fun DrawScope.drawSheet(val frozenW = l.colX[fc] * kval frozenH = l.rowY[fr] * kval body = Rect(head.x + frozenW, head.y + frozenH, size.width, size.height)+ // text is laid out at zoom 1 and drawn scaled+ val zoom = k / density+ val accent = Color(0xFF0A84FF)+ val gridLine = if (dark) Color(0xFF343650) else Color(0xFFE1E4EA)+ val dashes = androidx.compose.ui.graphics.PathEffect.dashPathEffect(floatArrayOf(3f * k, 2f * k))+ val dots = androidx.compose.ui.graphics.PathEffect.dashPathEffect(floatArrayOf(1f * k, 1.2f * k))+ val shown = ArrayList<DrawCell>(512)// a region of the sheet: rows/columns from the given starts, drawn from [origin]fun region(clip: Rect, origin: Offset, rowsFrom: Int, rowsTo: Int, colsFrom: Int, colsTo: Int, scrollX: Boolean, scrollY: Boolean) {if (clip.width <= 0f || clip.height <= 0f) return@@ -742,46 +896,95 @@ private fun DrawScope.drawSheet(val r1 = min(rowsTo, l.indexAt(l.rowY, (clip.bottom - oy) / k) + 1)if (c0 >= c1 || r0 >= r1) returnclipRect(clip.left, clip.top, clip.right, clip.bottom) {- val cell = { r: Int, c: Int -> Rect(ox + l.colX[c] * k, oy + l.rowY[r] * k, ox + l.colX[c + 1] * k, oy + l.rowY[r + 1] * k) }+ fun x(c: Int) = ox + l.colX[c] * k+ fun y(r: Int) = oy + l.rowY[r] * k+ fun area(a: DrawCell) = Rect(x(a.c0), y(a.r0), x(a.c1 + 1), y(a.r1 + 1))// grid linesif (l.info.gridlines) {- val line = if (dark) Color(0xFF343650) else Color(0xFFE1E4EA)- for (c in c0..c1) drawLine(line, Offset(ox + l.colX[c] * k, clip.top), Offset(ox + l.colX[c] * k, clip.bottom), 1f)- for (r in r0..r1) drawLine(line, Offset(clip.left, oy + l.rowY[r] * k), Offset(clip.right, oy + l.rowY[r] * k), 1f)- }- // the cells of the blocks in view: fills, then borders, then text- val shown = ArrayList<CellView>()- for (br in r0 / BLOCK_ROWS..(r1 - 1) / BLOCK_ROWS) for (bc in c0 / BLOCK_COLS..(c1 - 1) / BLOCK_COLS) {- blocks[Triple(sheet, br, bc)]?.forEach { v -> if (v.row.toInt() in r0 until r1 && v.col.toInt() in c0 until c1) shown += v }+ for (c in c0..c1) drawLine(gridLine, Offset(x(c), clip.top), Offset(x(c), clip.bottom), 1f)+ for (r in r0..r1) drawLine(gridLine, Offset(clip.left, y(r)), Offset(clip.right, y(r)), 1f)+ // a merged area is one cell: no grid lines run through it+ if (l.merges.size <= 4000) for (m in l.merges) {+ val mr0 = m.row0.toInt()+ val mc0 = m.col0.toInt()+ val mr1 = min(m.row1.toInt(), l.rows - 1)+ val mc1 = min(m.col1.toInt(), l.cols - 1)+ if (mr1 < r0 || mr0 >= r1 || mc1 < c0 || mc0 >= c1) continue+ val a = Rect(x(mc0), y(mr0), x(mc1 + 1), y(mr1 + 1))+ if (a.width > 2f && a.height > 2f) drawRect(sheetSurface, Offset(a.left + 0.5f, a.top + 0.5f), Size(a.width - 1f, a.height - 1f))+ }}- fun spanOf(v: CellView): Rect {- val m = l.merges.firstOrNull { it.row0 == v.row && it.col0 == v.col }- return if (m == null) cell(v.row.toInt(), v.col.toInt())- else cell(m.row0.toInt(), m.col0.toInt()).let { a ->- val b = cell(min(m.row1.toInt(), l.rows - 1), min(m.col1.toInt(), l.cols - 1))- Rect(a.left, a.top, b.right, b.bottom)+ // the cells in view, from the blocks in view and the ones before them (a merge that+ // begins above or left of the screen still shows its fill and text)+ shown.clear()+ val br0 = max(0, r0 / BLOCK_ROWS - 1)+ val bc0 = max(0, c0 / BLOCK_COLS - 1)+ for (br in br0..(r1 - 1) / BLOCK_ROWS) for (bc in bc0..(c1 - 1) / BLOCK_COLS) {+ val cells = blocks[Triple(sheet, br, bc)] ?: continue+ for (cell in cells) {+ if (cell.covered) {+ if (cell.row in r0 until r1 && cell.col in c0 until c1) shown += cell+ } else if (cell.r1 >= r0 && cell.r0 < r1 && cell.c1 >= c0 && cell.c0 < c1) shown += cell}}- for (v in shown) v.fill?.let { drawRect(rgb(it), spanOf(v).topLeft, spanOf(v).size) }- for (v in shown) {- val r = spanOf(v)- fun edge(e: com.chethan616.clearpdf.core.CellEdge, a: Offset, b: Offset) {- if (e.weight > 0u) drawLine(rgb(e.color), a, b, e.weight.toFloat() * density * 0.6f)+ // fills, then data bars+ for (cell in shown) {+ if (cell.covered) continue+ val a = area(cell)+ cell.fill?.let { drawRect(it, a.topLeft, a.size) }+ if (cell.v.bar > 0f) drawRect(rgb(cell.v.barColor).copy(alpha = 0.55f), Offset(a.left + k, a.top + k), Size(((a.width - 2 * k) * cell.v.bar).coerceAtLeast(0f), (a.height - 2 * k).coerceAtLeast(0f)))+ }+ // borders: each cell's own, on its own box (inside a merge only those on the merge's rim)+ for (cell in shown) {+ if (cell.edges == 0) continue+ val left = x(cell.col)+ val top = y(cell.row)+ val right = x(cell.col + 1)+ val bottom = y(cell.row + 1)+ fun edge(e: com.chethan616.clearpdf.core.CellEdge, bit: Int, a: Offset, b: Offset, nx: Float, ny: Float) {+ val weight = e.weight.toInt()+ if (weight == 0 || cell.edges and bit == 0) return+ // automatic (black) lines take the sheet's ink in the dark theme, where black would vanish+ val color = if (e.color == 0u && dark && cell.fill == null) ink.copy(alpha = 0.85f) else rgb(e.color)+ val line = e.line.toInt()+ val width = if (line == 4) 1f else max(1f, weight * 0.5f * k)+ when (line) {+ // double: two thin lines either side of the edge+ 3 -> {+ val d = max(1f, 0.6f * k)+ val w = max(1f, 0.35f * k)+ drawLine(color, Offset(a.x + nx * d, a.y + ny * d), Offset(b.x + nx * d, b.y + ny * d), w)+ drawLine(color, Offset(a.x - nx * d, a.y - ny * d), Offset(b.x - nx * d, b.y - ny * d), w)+ }+ 1 -> drawLine(color, a, b, width, pathEffect = dashes)+ 2 -> drawLine(color, a, b, width, pathEffect = dots)+ else -> drawLine(color, a, b, width)+ }}- edge(v.left, r.topLeft, r.bottomLeft)- edge(v.top, r.topLeft, r.topRight)- edge(v.right, r.topRight, r.bottomRight)- edge(v.bottom, r.bottomLeft, r.bottomRight)+ edge(cell.v.left, DrawCell.LEFT, Offset(left, top), Offset(left, bottom), 1f, 0f)+ edge(cell.v.top, DrawCell.TOP, Offset(left, top), Offset(right, top), 0f, 1f)+ edge(cell.v.right, DrawCell.RIGHT, Offset(right, top), Offset(right, bottom), 1f, 0f)+ edge(cell.v.bottom, DrawCell.BOTTOM, Offset(left, bottom), Offset(right, bottom), 0f, 1f)+ }+ // pictures float over the cells (in the part that scrolls both ways)+ if (scrollX && scrollY) for (p in state.pictures) {+ val w = (p.width * k).toInt()+ val h = (p.height * k).toInt()+ val left = ox + p.x * k+ val top = oy + p.y * k+ if (w <= 0 || h <= 0 || left > clip.right || top > clip.bottom || left + w < clip.left || top + h < clip.top) continue+ drawImage(p.image, dstOffset = androidx.compose.ui.unit.IntOffset(left.toInt(), top.toInt()), dstSize = androidx.compose.ui.unit.IntSize(w, h))}// the chosen cell (or its merged area): a ring in the accent, as a spreadsheet marks itselected?.let { f ->val r = f.row0.toInt()val col = f.col0.toInt()- if (r in r0 until r1 && col in c0 until c1) {- val a = cell(r, col)- val b = cell(minOf(f.row1.toInt(), l.rows - 1), minOf(f.col1.toInt(), l.cols - 1))- val box = Rect(a.left, a.top, b.right, b.bottom)- drawRect(Color(0xFF0A84FF), box.topLeft, box.size, style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.5f * density))+ val rEnd = minOf(f.row1.toInt(), l.rows - 1)+ val cEnd = minOf(f.col1.toInt(), l.cols - 1)+ if (rEnd >= r0 && r < r1 && cEnd >= c0 && col < c1) {+ val box = Rect(x(col), y(r), x(cEnd + 1), y(rEnd + 1))+ drawRect(accent.copy(alpha = 0.08f), box.topLeft, box.size)+ drawRect(accent, box.topLeft, box.size, style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.5f * density))}}// the search hit in this region: an accent ring round its cell@@ -789,25 +992,44 @@ private fun DrawScope.drawSheet(val r = f.row0.toInt()val col = f.col0.toInt()if (r in r0 until r1 && col in c0 until c1) {- val box = cell(r, col)- drawRect(Color(0x330A84FF), box.topLeft, box.size)- drawRect(Color(0xFF0A84FF), box.topLeft, box.size, style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.5f * density))+ val box = Rect(x(col), y(r), x(col + 1), y(r + 1))+ drawRect(accent.copy(alpha = 0.2f), box.topLeft, box.size)+ drawRect(accent, box.topLeft, box.size, style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.5f * density))}}- for (v in shown) {- if (v.text.isEmpty()) continue- val r = spanOf(v)- val pad = 2f * k- val maxW = (r.width - 2 * pad).toInt()- if (maxW <= 0) continue+ // text+ for (cell in shown) {+ val v = cell.v+ if (cell.covered || v.text.isEmpty()) continue+ val a = area(cell)+ if (a.width < 2f || a.height < 2f) continue+ val turned = v.rotation.toInt() != 0 && v.rotation.toInt() in -90..90+ // the room the text has, at zoom 1 (pixels): the cell less its padding and indent+ val pad0 = 2f * density+ val indent0 = v.indent.toInt() * 7f * density+ val cellW0 = a.width / zoom+ val cellH0 = a.height / zoom+ val wrapWidth = if (v.wrap && !turned) (cellW0 - 2 * pad0 - indent0).toInt().coerceAtLeast(1) else 0+ val auto = v.ink == 0u+ val surface = cell.fill ?: sheetSurface+ val color = when {+ auto -> if (surface.luminance() > 0.5f) Color(0xFF15171C) else ink+ // a dark colour chosen for a white sheet, on the dark theme's ground: lifted so it reads+ cell.fill == null && dark && rgb(v.ink).luminance() < 0.22f -> androidx.compose.ui.graphics.lerp(rgb(v.ink), Color.White, 0.62f)+ else -> rgb(v.ink)+ }+ val styleKey = (color.hashCode() * 31 + (v.size * 4).toInt()) * 31 ++ ((if (v.bold) 1 else 0) or (if (v.italic) 2 else 0) or (if (v.underline) 4 else 0) or (if (v.strike) 8 else 0) or (v.face.toInt() shl 4))val style = TextStyle(- color = if (v.ink == 0u) {- val cellSurface = v.fill?.let(::rgb) ?: sheetSurface- if (cellSurface.luminance() > 0.5f) Color(0xFF15171C) else ink- } else rgb(v.ink),- fontSize = (v.size * k / density / fontScale).sp,+ color = color,+ fontSize = (v.size / fontScale).sp,fontWeight = if (v.bold) FontWeight.Bold else FontWeight.Normal,fontStyle = if (v.italic) FontStyle.Italic else FontStyle.Normal,+ fontFamily = when (v.face.toInt()) {+ 1 -> androidx.compose.ui.text.font.FontFamily.Serif+ 2 -> androidx.compose.ui.text.font.FontFamily.Monospace+ else -> androidx.compose.ui.text.font.FontFamily.SansSerif+ },textDecoration = when {v.underline && v.strike -> TextDecoration.combine(listOf(TextDecoration.Underline, TextDecoration.LineThrough))v.underline -> TextDecoration.Underline@@ -815,25 +1037,58 @@ private fun DrawScope.drawSheet(else -> null},)- val t = measurer.measure(- v.text, style,- overflow = TextOverflow.Clip,- softWrap = v.wrap, maxLines = if (v.wrap) Int.MAX_VALUE else 1,- constraints = Constraints(maxWidth = if (v.wrap) maxW else Constraints.Infinity, maxHeight = max(1, r.height.toInt())),- )- val w = t.size.width.toFloat()- val x = when (v.align) {- "c" -> r.left + (r.width - w) / 2f- "r" -> r.right - pad - w- else -> r.left + pad+ val t = texts.cell(cell, style, styleKey, wrapWidth)+ val tw = t.size.width.toFloat()+ val th = t.size.height.toFloat()+ if (turned) {+ // turned text: about the middle of its cell, kept inside it+ clipRect(a.left, a.top, a.right, a.bottom) {+ withTransform({+ translate(a.center.x, a.center.y)+ rotate(-v.rotation.toFloat(), Offset.Zero)+ scale(zoom, zoom, Offset.Zero)+ }) { drawText(t, topLeft = Offset(-tw / 2f, -th / 2f)) }+ }+ continue}- val y = when (v.valign) {- "t" -> r.top + pad / 2- "c" -> r.top + (r.height - t.size.height) / 2f- else -> r.bottom - pad / 2 - t.size.height+ val x0 = when (v.align) {+ "c" -> (cellW0 - tw) / 2f+ "r" -> cellW0 - pad0 - indent0 - tw+ else -> pad0 + indent0+ }+ val y0 = when (v.valign) {+ "t" -> pad0 / 2+ "c" -> (cellH0 - th) / 2f+ else -> cellH0 - pad0 / 2 - th+ }+ // One line too long for its cell runs on over the empty cells beside it, as Excel+ // shows it (a title typed in A1 reads across the row), and stops at the first cell+ // that holds something. Wrapped and merged text keeps to its own area.+ var clipLeft = a.left+ var clipRight = a.right+ if (wrapWidth == 0 && !cell.merged && tw > cellW0 - 2 * pad0) {+ val need = tw * zoom+ if (v.align != "r") {+ var cEnd = cell.col+ while (cEnd + 1 < c1 + 8 && cEnd + 1 < l.cols && x(cEnd + 1) - a.left < need + pad0 * zoom * 2 &&+ cellKey(cell.row, cEnd + 1) !in state.texted && l.spanAt(cell.row, cEnd + 1) == null+ ) cEnd+++ clipRight = x(cEnd + 1)+ }+ if (v.align != "l") {+ var cStart = cell.col+ while (cStart - 1 >= 0 && a.right - x(cStart) < need + pad0 * zoom * 2 &&+ cellKey(cell.row, cStart - 1) !in state.texted && l.spanAt(cell.row, cStart - 1) == null+ ) cStart--+ clipLeft = x(cStart)+ }+ }+ clipRect(clipLeft, a.top, clipRight, a.bottom) {+ withTransform({+ translate(a.left, a.top)+ scale(zoom, zoom, Offset.Zero)+ }) { drawText(t, topLeft = Offset(x0, y0)) }}- // text stays within its cell (a neighbour's text would overlap it otherwise)- clipRect(r.left, r.top, r.right, r.bottom) { drawText(t, topLeft = Offset(x, y)) }}}}@@ -845,31 +1100,57 @@ private fun DrawScope.drawSheet(val frozenDivider = if (dark) Color(0xFF777D9A) else Color(0xFF9AA3B2)if (fr > 0) drawLine(frozenDivider, Offset(head.x, head.y + frozenH), Offset(size.width, head.y + frozenH), density)if (fc > 0) drawLine(frozenDivider, Offset(head.x + frozenW, head.y), Offset(head.x + frozenW, size.height), density)- // the heading strips+ // the heading strips: only the letters and numbers in view, each measured onceval strip = if (dark) Color(0xFF20213B) else Color(0xFFF2F4F8)- val label = TextStyle(color = ink.copy(alpha = 0.6f), fontSize = (11 * min(k / density, 1.5f) / fontScale).sp)+ val chosen = accent.copy(alpha = if (dark) 0.30f else 0.16f)+ val labelZoom = min(zoom, 1.5f)+ val label = TextStyle(color = ink.copy(alpha = 0.6f), fontSize = (11 / fontScale).sp)drawRect(strip, Offset(0f, 0f), Size(size.width, head.y))drawRect(strip, Offset(0f, 0f), Size(head.x, size.height))val lineC = if (dark) Color(0xFF343650) else Color(0xFFD5D9E0)clipRect(head.x, 0f, size.width, head.y) {- for (c in 0 until l.cols) {- val x0 = head.x + l.colX[c] * k + (if (c >= fc) pan.x else 0f)- val x1 = head.x + l.colX[c + 1] * k + (if (c >= fc) pan.x else 0f)- if (x1 < head.x + (if (c >= fc) frozenW else 0f) || x0 > size.width || x1 - x0 < 1f) continue- drawLine(lineC, Offset(x1, 0f), Offset(x1, head.y), 1f)- val t = measurer.measure(columnName(c), label)- if (t.size.width < x1 - x0) drawText(t, topLeft = Offset((x0 + x1 - t.size.width) / 2f, (head.y - t.size.height) / 2f))+ fun columns(from: Int, to: Int, shift: Float, clipFrom: Float) {+ if (from >= to) return+ val first = max(from, l.indexAt(l.colX, (clipFrom - head.x - shift) / k))+ val last = min(to - 1, l.indexAt(l.colX, (size.width - head.x - shift) / k))+ for (c in first..last) {+ val x0 = head.x + l.colX[c] * k + shift+ val x1 = head.x + l.colX[c + 1] * k + shift+ if (x1 - x0 < 1f) continue+ if (selected != null && c.toUInt() in selected.col0..selected.col1) drawRect(chosen, Offset(x0, 0f), Size(x1 - x0, head.y))+ drawLine(lineC, Offset(x1, 0f), Offset(x1, head.y), 1f)+ val t = texts.label(columnName(c), label)+ val w = t.size.width * labelZoom+ if (w < x1 - x0) withTransform({+ translate((x0 + x1 - w) / 2f, (head.y - t.size.height * labelZoom) / 2f)+ scale(labelZoom, labelZoom, Offset.Zero)+ }) { drawText(t) }+ }}+ clipRect(head.x + frozenW, 0f, size.width, head.y) { columns(fc, l.cols, pan.x, head.x + frozenW) }+ columns(0, fc, 0f, head.x)}clipRect(0f, head.y, head.x, size.height) {- for (r in 0 until l.rows) {- val y0 = head.y + l.rowY[r] * k + (if (r >= fr) pan.y else 0f)- val y1 = head.y + l.rowY[r + 1] * k + (if (r >= fr) pan.y else 0f)- if (y1 < head.y + (if (r >= fr) frozenH else 0f) || y0 > size.height || y1 - y0 < 1f) continue- drawLine(lineC, Offset(0f, y1), Offset(head.x, y1), 1f)- val t = measurer.measure((r + 1).toString(), label)- if (t.size.height < y1 - y0 + 2) drawText(t, topLeft = Offset((head.x - t.size.width) / 2f, (y0 + y1 - t.size.height) / 2f))+ fun rows(from: Int, to: Int, shift: Float, clipFrom: Float) {+ if (from >= to) return+ val first = max(from, l.indexAt(l.rowY, (clipFrom - head.y - shift) / k))+ val last = min(to - 1, l.indexAt(l.rowY, (size.height - head.y - shift) / k))+ for (r in first..last) {+ val y0 = head.y + l.rowY[r] * k + shift+ val y1 = head.y + l.rowY[r + 1] * k + shift+ if (y1 - y0 < 1f) continue+ if (selected != null && r.toUInt() in selected.row0..selected.row1) drawRect(chosen, Offset(0f, y0), Size(head.x, y1 - y0))+ drawLine(lineC, Offset(0f, y1), Offset(head.x, y1), 1f)+ val t = texts.label((r + 1).toString(), label)+ val h = t.size.height * labelZoom+ if (h < y1 - y0 + 2) withTransform({+ translate((head.x - t.size.width * labelZoom) / 2f, (y0 + y1 - h) / 2f)+ scale(labelZoom, labelZoom, Offset.Zero)+ }) { drawText(t) }+ }}+ clipRect(0f, head.y + frozenH, head.x, size.height) { rows(fr, l.rows, pan.y, head.y + frozenH) }+ rows(0, fr, 0f, head.y)}drawLine(lineC, Offset(0f, head.y), Offset(size.width, head.y), 1f)drawLine(lineC, Offset(head.x, 0f), Offset(head.x, size.height), 1f)@@ -926,7 +1207,7 @@ private fun Modifier.panZoomFling(val c = event.calculateCentroid()centroid = cif (zoomChange != 1f) {- val newScale = (state.scale * zoomChange).coerceIn(0.4f, 4f)+ val newScale = (state.scale * zoomChange).coerceIn(0.4f, 6f)val factor = newScale / state.scaleval origin = if (c.isSpecified) c else Offset.Zeroval target = (state.pan - origin) * factor + origin + pandiff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DocLayout.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DocLayout.ktindex 7991877..267cd8d 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DocLayout.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/DocLayout.kt@@ -65,16 +65,25 @@ class DocLayout(PageMode.SinglePage -> {val availW = max(1f, viewW - 2 * margin)val availH = max(1f, viewH - padTop - padBottom - 2 * margin)+ // A phone turned on its side: an upright page fitted whole would be a narrow strip+ // in the middle of the screen, too small to read. There the page takes the screen's+ // width, as other readers show it, and is read by scrolling down it; a swipe+ // sideways still turns the page.+ val sideways = viewW > viewH * 1.15f+ var tallest = viewHpages.forEachIndexed { i, p ->- val s = min(availW / p.width.coerceAtLeast(1f), availH / p.height.coerceAtLeast(1f))+ val byWidth = availW / p.width.coerceAtLeast(1f)+ val whole = min(byWidth, availH / p.height.coerceAtLeast(1f))+ val s = if (sideways) byWidth else wholeval w = p.width.coerceAtLeast(1f) * sval h = p.height.coerceAtLeast(1f) * sval x = i * viewW + (viewW - w) / 2f- val y = padTop + margin + (availH - h) / 2f+ val y = padTop + margin + max(0f, (availH - h) / 2f)out.add(LRect(x, y, x + w, y + h))+ tallest = max(tallest, y + h + margin + padBottom)}width = max(viewW, pages.size * viewW)- height = viewH+ height = tallest}}rects = outdiff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageCanvas.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageCanvas.ktindex d457fa1..6e86705 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageCanvas.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageCanvas.kt@@ -292,7 +292,11 @@ private suspend fun settle(state: ViewerState, velocity: Offset, density: Float,if (state.mode == PageMode.SinglePage && state.zoom <= 1.01f) {val target = state.snapTarget(velocity.x)val anim = Animatable(state.scrollX)- anim.animateTo(target, spring(stiffness = 600f), initialVelocity = -velocity.x) { state.setScroll(value, 0f) }+ // where the reader is down the page is kept while it settles; a new page starts from its top+ val page = state.currentPage+ val y = state.scrollY+ anim.animateTo(target, spring(stiffness = 600f), initialVelocity = -velocity.x) { state.setScroll(value, y) }+ if (state.currentPage != page) state.setScroll(state.scrollX, 0f)return}if (velocity.getDistance() < 50f) returndiff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageMenu.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageMenu.ktindex 36f44be..dbf6137 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageMenu.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PageMenu.kt@@ -74,7 +74,7 @@ fun PageMenuView(vm: AppViewModel, menu: PageMenu) {val appear = remember { androidx.compose.animation.core.Animatable(0f) }LaunchedEffect(Unit) { appear.animateTo(1f, com.chethan616.clearpdf.ui.glass.GlassMotion.unfold()) }val opensDown = y > menu.screen.y- com.chethan616.clearpdf.ui.glass.GlassCard(+ com.chethan616.clearpdf.ui.glass.MenuCard(Modifier.offset { IntOffset(x.roundToInt(), y.roundToInt()) }.onSizeChanged { size = it }@@ -87,9 +87,6 @@ fun PageMenuView(vm: AppViewModel, menu: PageMenu) {alpha = (p * 1.6f).coerceIn(0f, 1f)}.pointerInput(Unit) { detectTapGestures { } },- shape = com.chethan616.clearpdf.ui.glass.RoundedRectangle(24.dp),- wash = com.chethan616.clearpdf.ui.theme.clear.frost,- blur = 16.dp,) {Spacer(Modifier.height(6.dp))if (doc.isOffice) {@@ -104,7 +101,7 @@ fun PageMenuView(vm: AppViewModel, menu: PageMenu) {MenuIcon(LucideIcons.Type, stringResource(R.string.page_menu_add_text), annotate) { close(); vm.textPrompt = TextPrompt(doc, menu.at) }if (fill) MenuIcon(LucideIcons.Signature, stringResource(R.string.common_sign), true) { close(); vm.enterTool(doc, ViewerTool.FillSign) }}- Box(Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(1.dp).background(com.chethan616.clearpdf.ui.theme.clear.ink.copy(alpha = 0.12f)))+ Box(Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(1.dp).background(menuInk().copy(alpha = 0.12f)))Spacer(Modifier.height(4.dp))if (!menu.pageHasText) MenuRow(LucideIcons.ScanText, stringResource(R.string.common_tool_recognize_text)) { close(); vm.recognizeText(doc) }MenuRow(LucideIcons.Crop, stringResource(R.string.common_tool_crop)) { close(); vm.openCrop(doc) }diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.ktindex 865b4cd..87e5c46 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt@@ -339,8 +339,10 @@ private fun dockSlots(widthDp: Int): Int = when {}/**- * The floating dock: the tools the reader keeps there, each glyph in its own candy, on a glass- * capsule, and More tools as a grape bubble beside it.+ * The floating dock, in the manner of the tools' own bars (Edit, Comment, Fill & Sign): the tools+ * the reader keeps there as glyphs on one glass capsule, the one just tapped on a blue disc for a+ * moment, and More tools as a blue glass circle beside it (where those bars keep Done). One capsule+ * is one piece of glass to draw, where a row of glass circles was one each.*/@Composablefun QuickToolbar(@@ -356,30 +358,43 @@ fun QuickToolbar(val overflow = remember(tools, moreTools, slots) { (tools.drop(slots) + moreTools).distinct() }var menuAt by remember { mutableStateOf<Rect?>(null) }var moreRect by remember { mutableStateOf(Rect.Zero) }- val turn by androidx.compose.animation.core.animateFloatAsState(if (menuAt != null) 45f else 0f, com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "more")+ val turn by androidx.compose.animation.core.animateFloatAsState(if (menuAt != null) 45f else 0f, GlassMotion.morph(), label = "more")+ // the tool just tapped, lit for a moment+ var lit by remember { mutableStateOf<QuickTool?>(null) }+ LaunchedEffect(lit) {+ if (lit != null) {+ kotlinx.coroutines.delay(420)+ lit = null+ }+ }Row(Modifier.fillMaxWidth().height(BottomBarHeight).padding(horizontal = 12.dp, vertical = 8.dp),verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.spacedBy(10.dp),) {- // Match Back and More tools: every action has its own clear glass circle rather than living- // inside a themed toolbar surface.+ val ink = rememberGlassInk(clear.ink)Row(- Modifier.weight(1f).fillMaxHeight(),+ Modifier.weight(1f).fillMaxHeight().then(ink.modifier).glassBar().padding(horizontal = 6.dp),horizontalArrangement = Arrangement.SpaceEvenly,verticalAlignment = Alignment.CenterVertically,) {- for (t in shown) DockItem(t.icon, stringResource(t.label)) { onTool(t) }+ CompositionLocalProvider(LocalGlassInk provides ink.color) {+ for (t in shown) DockItem(t.icon, stringResource(t.label), lit == t) {+ lit = t+ onTool(t)+ }+ }}// Office documents have their own concise toolbar. PDFs use the menu for the remaining// tools rather than opening the old grid sheet.if (overflow.isNotEmpty() || onCustomize != null) GlassCircle(onClick = { menuAt = moreRect },- size = 60.dp,+ size = 48.dp,+ tint = Candy.Sky,label = stringResource(R.string.common_tool_more_tools),modifier = Modifier.onGloballyPositioned { moreRect = it.boundsInWindow() },) {- GlassIcon(LucideIcons.LayoutGrid, null, Modifier.size(23.dp).androidxRotate(turn))+ GlassIcon(LucideIcons.LayoutGrid, null, Modifier.size(22.dp).androidxRotate(turn))}}menuAt?.let { anchor ->@@ -392,10 +407,18 @@ fun QuickToolbar(private fun Modifier.androidxRotate(degrees: Float) = this.graphicsLayer { rotationZ = degrees }+/** A tool of the dock: its glyph in the bar's ink; [lit], white on a blue disc. */@Composable-private fun DockItem(icon: ImageVector, label: String, onClick: () -> Unit) {- GlassCircle(onClick = onClick, size = 48.dp, label = label) {- GlassIcon(icon, null, Modifier.size(24.dp))+private fun DockItem(icon: ImageVector, label: String, lit: Boolean, onClick: () -> Unit) {+ val disc by animateColorAsState(if (lit) Candy.Sky else Color.Transparent, GlassMotion.settle(), label = "dock")+ val ink = com.chethan616.clearpdf.ui.glass.LocalGlassInk.current.takeIf { it != Color.Unspecified } ?: clear.ink+ val glyph by animateColorAsState(if (lit) Color.White else ink, GlassMotion.settle(), label = "dockInk")+ Box(+ Modifier.width(54.dp).fillMaxHeight().pressable(onClick, pressedScale = 0.86f).semantics { contentDescription = label },+ contentAlignment = Alignment.Center,+ ) {+ Box(Modifier.size(42.dp).clip(CircleShape).background(disc))+ Icon(icon, null, tint = glyph, modifier = Modifier.size(23.dp))}}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 1778a54..0a410af 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@@ -216,7 +216,7 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)val appear = remember { androidx.compose.animation.core.Animatable(0f) }LaunchedEffect(Unit) { appear.animateTo(1f, com.chethan616.clearpdf.ui.glass.GlassMotion.unfold()) }val opensDown = y > top.y- com.chethan616.clearpdf.ui.glass.GlassCard(+ com.chethan616.clearpdf.ui.glass.MenuCard(Modifier.offset { IntOffset(x.roundToInt(), y.roundToInt()) }.onSizeChanged { menuSize = it }@@ -228,9 +228,6 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, if (opensDown) 0f else 1f)alpha = (p * 1.6f).coerceIn(0f, 1f)},- shape = com.chethan616.clearpdf.ui.glass.RoundedRectangle(24.dp),- wash = clear.frost,- blur = 16.dp,) {Spacer(Modifier.height(6.dp))// a Word document or presentation opens for reading: no markup, no Edit text@@ -241,7 +238,7 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)MenuIcon(LucideIcons.Strikethrough, stringResource(R.string.viewer_strikethrough), allowed) { markup(TextMarkup.Strikethrough) }}// an inset divider, then the rows- if (!doc.isOffice) Box(Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(1.dp).background(clear.ink.copy(alpha = 0.12f)))+ if (!doc.isOffice) Box(Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(1.dp).background(menuInk().copy(alpha = 0.12f)))if (!doc.isOffice) Spacer(Modifier.height(4.dp))if (!doc.isOffice && (doc.writable || doc.source == null)) MenuRow(LucideIcons.FilePenLine, stringResource(R.string.viewer_edit_text)) {doc.selection.clear()@@ -257,9 +254,14 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)}}+/** The ink of the menu being composed: the glass's own when it adapts, else the theme's. */+@Composable+internal fun menuInk(): androidx.compose.ui.graphics.Color =+ com.chethan616.clearpdf.ui.glass.LocalMenuInk.current.let { if (it == androidx.compose.ui.graphics.Color.Unspecified) clear.ink else it }+@Composableinternal fun MenuIcon(icon: ImageVector, label: String, enabled: Boolean, onClick: () -> Unit) {- val ink = clear.ink+ val ink = menuInk()Box(Modifier.size(48.dp).clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = label },contentAlignment = Alignment.Center,@@ -270,11 +272,11 @@ internal fun MenuIcon(icon: ImageVector, label: String, enabled: Boolean, onClic@Composableinternal fun MenuRow(icon: ImageVector, label: String, onClick: () -> Unit) {- val c = clear+ val ink = menuInk()// as the desk menu's rows: the label, its glyph at the endRow(Modifier.fillMaxWidth().pressable(onClick).padding(horizontal = 16.dp, vertical = 11.dp), verticalAlignment = Alignment.CenterVertically) {- Text(label, color = c.ink, style = com.chethan616.clearpdf.ui.theme.ClearType.BodyStrong, modifier = Modifier.weight(1f))- Icon(icon, null, tint = c.inkSoft, modifier = Modifier.size(19.dp))+ Text(label, color = ink, style = com.chethan616.clearpdf.ui.theme.ClearType.BodyStrong, modifier = Modifier.weight(1f))+ Icon(icon, null, tint = ink.copy(alpha = 0.65f), modifier = Modifier.size(19.dp))}}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.ktindex 833d4b1..5bf7a4a 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt@@ -190,6 +190,20 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {val search = doc.searchval selection = doc.selection+ // Selecting text is felt, as the system's own selection is: a firm rise when a long press takes+ // a word (or the selection first appears), then a light tick each time a dragged handle takes in+ // or lets go of a character. The haptics drop ticks closer than 35 ms, so a fast drag purrs+ // rather than buzzes. Clearing the selection is silent.+ val feel = com.chethan616.clearpdf.ui.glass.rememberFeel()+ LaunchedEffect(selection) {+ var last: com.chethan616.clearpdf.core.TextRange? = null+ snapshotFlow { selection.selection?.range }.collect { range ->+ if (range != null && range != last) {+ feel(if (last == null) com.chethan616.clearpdf.ui.glass.Feel.Bloom else com.chethan616.clearpdf.ui.glass.Feel.Tick)+ }+ last = range+ }+ }// on a desktop, zoom buttons at the bottom right: with the bars, or for a moment when the mouse// comes near the corner or the wheel zooms, as the reference has themval config = androidx.compose.ui.platform.LocalConfiguration.currentdiff --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 ee40362..216d9fe 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@@ -215,7 +215,7 @@ private fun androidx.compose.foundation.layout.RowScope.LayoutChoice(icon: Imageval c = clearval fill by androidx.compose.animation.animateColorAsState(if (chosen) Candy.Sky.copy(alpha = if (c.dark) 0.30f else 0.16f) else if (c.dark) Color.White.copy(alpha = 0.075f) else Color.White.copy(alpha = 0.66f),- com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "layout choice",+ com.chethan616.clearpdf.ui.glass.Fluid.quick(), label = "layoutChoice",)Column(Modifier.weight(1f).height(96.dp).clip(RoundedRectangle(22.dp)).background(fill)@@ -473,7 +473,7 @@ private fun ToolTile(icon: ImageVector, label: String, tint: Color, modifier: MoIcon(icon, null, tint = Color.White, modifier = Modifier.size(27.dp))}Spacer(Modifier.height(8.dp))- Text(label, style = ClearType.Caption.copy(fontSize = 11.sp, lineHeight = 13.sp), color = clear.ink, textAlign = TextAlign.Center, maxLines = 2, modifier = Modifier.padding(horizontal = 2.dp))+ Text(label, style = ClearType.Caption.copy(fontSize = 11.sp, lineHeight = 13.sp), color = menuInk(), textAlign = TextAlign.Center, maxLines = 2, modifier = Modifier.padding(horizontal = 2.dp))}}@@ -521,7 +521,7 @@ fun MoreToolsSheet(vm: AppViewModel, doc: OpenDocument, anchor: Rect) {} else {Spacer(Modifier.height(6.dp))Row(Modifier.fillMaxWidth().padding(start = 18.dp, end = 14.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {- Text(stringResource(R.string.common_tool_more_tools), style = ClearType.Title.copy(fontSize = 18.sp), color = clear.ink, modifier = Modifier.weight(1f))+ Text(stringResource(R.string.common_tool_more_tools), style = ClearType.Title.copy(fontSize = 18.sp), color = menuInk(), modifier = Modifier.weight(1f))com.chethan616.clearpdf.ui.glass.GlassCircle(onClick = { ctl.sheet = ViewerSheet.None }, size = 36.dp, label = stringResource(R.string.ui_close_sheet)) {com.chethan616.clearpdf.ui.glass.GlassIcon(LucideIcons.X, null, Modifier.size(18.dp))}@@ -548,8 +548,8 @@ fun MoreToolsSheet(vm: AppViewModel, doc: OpenDocument, anchor: Rect) {onClick = { customizing = true }, modifier = Modifier.padding(horizontal = 16.dp).fillMaxWidth(), height = 48.dp,label = stringResource(R.string.sheet_customize_toolbar),) {- Icon(LucideIcons.SlidersHorizontal, null, tint = clear.ink, modifier = Modifier.size(18.dp))- Text(stringResource(R.string.sheet_customize_toolbar), style = ClearType.BodyStrong, color = clear.ink)+ Icon(LucideIcons.SlidersHorizontal, null, tint = menuInk(), modifier = Modifier.size(18.dp))+ Text(stringResource(R.string.sheet_customize_toolbar), style = ClearType.BodyStrong, color = menuInk())}Spacer(Modifier.height(12.dp))}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerState.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerState.ktindex 625d614..0e5cf79 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerState.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerState.kt@@ -216,7 +216,8 @@ class ViewerState(pages: List<PageSize>) {val ch = l.height * zoomscrollX = if (cw <= viewW) -(viewW - cw) / 2f else scrollX.coerceIn(0f, cw - viewW)scrollY = if (ch <= viewH) -(viewH - ch) / 2f else scrollY.coerceIn(0f, ch - viewH)- if (mode == PageMode.SinglePage && zoom <= 1.001f) scrollY = 0f+ // a single page that fits stays put; one taller than the screen (a phone on its side) scrolls+ if (mode == PageMode.SinglePage && zoom <= 1.001f && l.height <= viewH + 0.5f) scrollY = 0f}/** Page [i]'s rectangle on screen. */diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 2dc1157..9c6c00d 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -226,6 +226,9 @@<!-- Tool screens: Set password --><string name="tools_about_passwords">About passwords</string><string name="tools_protect_intro">A protected copy of this file is saved.</string>+ <string name="tools_unlock_title">This PDF is password-protected</string>+ <string name="tools_unlock_body">Save a copy that opens without its password, for good. Its restrictions on printing, copying and editing are lifted too.</string>+ <string name="tools_unlock_action">Remove password</string><!-- The * marks a field that must be filled in --><string name="tools_new_password">New password *</string><!-- The * marks a field that must be filled in -->@@ -247,6 +250,8 @@<string name="tools_format_rtf">Rich Text Format (rtf)</string><string name="tools_format_excel">Excel (xlsx)</string><string name="tools_format_powerpoint">PowerPoint (pptx)</string>+ <string name="tools_format_text">Plain text (txt)</string>+ <string name="msg_no_text_to_export">This PDF has no text to export. Recognize its text first.</string><string name="tools_format_jpeg">JPEG (jpeg)</string><string name="tools_format_png">PNG (png)</string>@@ -1027,6 +1032,12 @@<string name="photo_shadows">Shadows</string><string name="photo_vibrance">Vibrance</string><string name="photo_saturation">Saturation</string>+ <string name="photo_straighten">Straighten</string>+ <string name="photo_whites">Whites</string>+ <string name="photo_blacks">Blacks</string>+ <string name="photo_clarity">Clarity</string>+ <string name="photo_sharpen">Sharpen</string>+ <string name="photo_vignette">Vignette</string><string name="photo_rotate">Rotate</string><string name="photo_edit">Edit picture</string><string name="msg_ppt_text_only">This PowerPoint 97–2003 file shows its slides\' text. Saved as .pptx, it opens with its pictures and layout.</string>@@ -1138,6 +1149,8 @@<string name="msg_compress_no_gain">This file is already as small as it can be.</string><string name="msg_busy_combining">Combining…</string><string name="msg_busy_setting_password">Setting password…</string>+ <string name="msg_busy_removing_password">Removing password…</string>+ <string name="msg_unlock_failed">This file\'s protection can\'t be removed</string><string name="msg_crop_all">Every page is cropped.</string><string name="msg_crop_page">The page is cropped.</string><!-- %1$s is a file format, for example DOCX. -->@@ -1274,6 +1287,8 @@<string name="gm_highlight">Rim light</string><string name="gm_depth">Depth</string><string name="gm_chromatic">Prism edge</string>+ <string name="gm_adaptive">Adaptive luminance</string>+ <string name="gm_adaptive_body">Glass turns light or dark to suit what is behind it. The presets above rest while it is on</string><string name="gm_spring">Glass spring</string><string name="gm_spring_body">How glass swells, springs past and settles. Tap the graph to pause it.</string><string name="gm_spring_stats">Damping %1$s · stiffness %2$s · settles in %3$s s</string>@@ -1368,6 +1383,10 @@<string name="create_photo_note">Photo note</string><string name="create_voice">Record a voice note</string><string name="voice_saved">Voice note saved</string>+ <string name="voice_import">Import audio</string>+ <string name="voice_imported">Audio added to your desk</string>+ <string name="voice_export">Save to Downloads</string>+ <string name="voice_export_name">Voice note</string><string name="voice_too_short">Too short to keep. Hold on a little longer.</string><!-- Notes -->