diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 01f8c8ed..dd774645 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -499,6 +499,36 @@ jobs: done exit $found + # The exact set, not only "no INTERNET": a library that starts asking for a permission, or a new + # in the app, must be a decision. Change the list below on purpose, in the same commit. + - name: Check merged manifest permission set + run: | + set -euo pipefail + manifests=$(find app/build/intermediates/merged_manifest app/build/intermediates/merged_manifests \ + -name AndroidManifest.xml -path '*fdroidRelease*' 2>/dev/null || true) + if [ -z "$manifests" ]; then + echo "::error::No merged fdroidRelease manifest found to check" + exit 1 + fi + expected=$(printf '%s\n' \ + android.permission.HIDE_OVERLAY_WINDOWS \ + android.permission.USE_BIOMETRIC \ + android.permission.USE_FINGERPRINT \ + com.pasich.encly.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION | sort) + status=0 + for m in $manifests; do + actual=$(grep -oE ']*android:name="[^"]+"' "$m" \ + | sed -E 's/.*android:name="([^"]+)"/\1/' | sort -u) + echo "Permissions in $m:" + echo "$actual" + if [ "$actual" != "$expected" ]; then + echo "::error file=$m::Merged release permissions differ from the pinned set" + diff <(echo "$expected") <(echo "$actual") || true + status=1 + fi + done + exit $status + - name: Upload reports on failure if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b31a4c8..201979c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,27 @@ IzzyOnDroid) and used as the GitHub Release notes. - Encly for Windows, macOS and Linux (MSI, DMG, DEB and a Flatpak bundle): the same vault, notes and security as on the phone, with list and note side by side, note tabs, several windows, keyboard shortcuts and a menu bar, export to PDF and print, and the PIN's device key in the system's secret store ([#85](https://github.com/pasichDev/Encly/issues/85), [#106](https://github.com/pasichDev/Encly/issues/106)). - Encly for iPhone: each PIN attempt needs the Secure Enclave, Face ID and Touch ID unlock, the vault locks when the app leaves the screen, and the app is hidden in the app switcher ([#107](https://github.com/pasichDev/Encly/issues/107)). +## [3.0.1] - 2026-11-20 + +versionCode 30001. + +### Security + +- Lengthening the auto-lock delay, turning strict keyboard privacy off, showing note previews and turning biometric unlock on now ask for your PIN first, so someone holding your unlocked phone cannot weaken your protection. Changes that make it stricter still apply at once ([#133](https://github.com/pasichDev/Encly/issues/133)). + +### Added + +- After an update from a version before 3.0.0, a one-time notice tells you that the trash now deletes notes 28 days after they were moved there, how many notes are in it, and opens the trash for you ([#126](https://github.com/pasichDev/Encly/issues/126)). + +### Changed + +- The note's long-press sheet is easier to use with TalkBack and a finger: TalkBack announces "Tap again to delete", tag chips have a larger touch target, and hidden tags are marked so you can tell that tapping one hides the note from the main list ([#124](https://github.com/pasichDev/Encly/issues/124)). + +### Fixed + +- The gap between a checkbox or bullet and its text no longer gets wider once a list reaches ten items, and tighter again when it drops below ([#129](https://github.com/pasichDev/Encly/issues/129)). +- Ukrainian: tags are called «мітки» everywhere; some screens and the backup text said «теги». + ## [3.0.0] - 2026-11-19 versionCode 30000. @@ -70,6 +91,12 @@ versionCode 30000. - The decoy vault no longer shows the date of the real vault's last backup. - A temporary failure of the device's key storage no longer offers to erase the vault, and the lock screen says the key storage did not respond instead of that the database could not be opened. +### ⚠️ Compatibility + +- The database moves to version 8 (the trash date, then several tags per note), migrated in place. Installing an older Encly over this version is not supported: it cannot open the newer database. Export a backup first if you might go back. +- A backup made with this version is schema 6 (it carries your settings and several tags per note). Older Encly versions refuse it with "This backup was made by a newer version of Encly. Update the app and try again." +- A note with a table or a code block opens read-only in versions before 3.0.0. + ## [2.3.1] - 2026-10-27 versionCode 20301. @@ -409,7 +436,10 @@ The last release of the old storage format (versionCode 30): the SQLCipher key w Keystore-sealed seed hash, with an optional 4-digit PIN. It had no public users; superseded by 2.0.0. -[Unreleased]: https://github.com/pasichDev/Encly/compare/v2.3.0...HEAD +[Unreleased]: https://github.com/pasichDev/Encly/compare/v3.0.1...HEAD +[3.0.1]: https://github.com/pasichDev/Encly/compare/v3.0.0...v3.0.1 +[3.0.0]: https://github.com/pasichDev/Encly/compare/v2.3.1...v3.0.0 +[2.3.1]: https://github.com/pasichDev/Encly/compare/v2.3.0...v2.3.1 [2.3.0]: https://github.com/pasichDev/Encly/compare/v2.2.1...v2.3.0 [2.2.1]: https://github.com/pasichDev/Encly/compare/v2.2.0...v2.2.1 [2.2.0]: https://github.com/pasichDev/Encly/releases/tag/v2.2.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9d1c5f87..62537fde 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -244,7 +244,9 @@ upload this key instead of letting Google generate one). those platforms ship. Add the version to `` in `desktopApp/packaging/flatpak/io.github.pasichdev.Encly.metainfo.xml` too; the Flatpak build in CI refuses a version that is not listed there. -4. Test the release APK on a device. +4. Test the release APK on a device. If a dependency or the app added or dropped a permission, the + "Check merged manifest permission set" step of CI fails: update its list on purpose and say why + in the pull request. 5. Merge to `main`, then tag the merge commit `vX.Y.Z` and push the tag. The [release workflow](.github/workflows/release.yml) refuses a tag that does not match `version.properties`, fails when a signing secret or `ENCLY_CERT_SHA256` is missing, builds diff --git a/SECURITY.md b/SECURITY.md index 7403007a..403cbab5 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -616,6 +616,26 @@ generic Markdown/TXT (Obsidian, Markor). - **Limits.** Like the editor and the backup import, parsed text passes through JVM strings that cannot be zeroized. +## Settings that ask for re-authentication + +A phone left unlocked for a moment must not be able to weaken the protection of the vault. These +changes on Settings → Security ask for the PIN first (or a Class 3 biometric confirmation when +biometric unlock is on), through the same re-authentication as export and import: + +- lengthening the auto-lock delay; +- turning strict keyboard privacy off; +- turning "Show note previews" on; +- turning biometric unlock on (the PIN is asked before the enrolment; turning it off keeps its + own strong-biometric confirmation); +- "Allow screenshots until the app locks". + +Changes that strengthen protection (a shorter or equal delay, strict keyboard on, previews off, +screenshots blocked again) never ask. The switch keeps its old value until the change is applied, +so a cancel or a wrong PIN leaves it. The change is held in memory only and is discarded, not +applied, by a cancel and by any lock between the request and the PIN, as for the screenshots +allowance. A full backup restore applies the stored settings without asking: it already needs +the recovery phrase and the same re-authentication. + ## Session lifecycle - The database is not considered committed until mandatory PIN setup succeeds. diff --git a/app/src/main/java/com/pasich/encly/ImportFromMyNotesActivity.kt b/app/src/main/java/com/pasich/encly/ImportFromMyNotesActivity.kt index 5ed0389b..4d890518 100644 --- a/app/src/main/java/com/pasich/encly/ImportFromMyNotesActivity.kt +++ b/app/src/main/java/com/pasich/encly/ImportFromMyNotesActivity.kt @@ -15,11 +15,11 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.material3.MaterialTheme -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope import com.pasich.encly.core.di.appGraph import com.pasich.encly.core.locale.AppLocales @@ -118,7 +118,7 @@ class ImportFromMyNotesActivity : AppCompatActivity() { setContent { if (!themeReady) return@setContent - val strictKeyboard by keyboardPrivacy.strict.collectAsState() + val strictKeyboard by keyboardPrivacy.strict.collectAsStateWithLifecycle() hostServices.Provide(this, strictKeyboard) { AppTheme { Box( diff --git a/app/src/main/java/com/pasich/encly/MainActivity.kt b/app/src/main/java/com/pasich/encly/MainActivity.kt index 5ad43862..8f1ab8f0 100644 --- a/app/src/main/java/com/pasich/encly/MainActivity.kt +++ b/app/src/main/java/com/pasich/encly/MainActivity.kt @@ -7,13 +7,13 @@ import android.view.WindowManager import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope import com.pasich.encly.core.di.appGraph import com.pasich.encly.core.locale.AppLocales @@ -103,7 +103,7 @@ class MainActivity : AppCompatActivity() { setContent { // Auto re-lock and the navigation guards live in the shared UI (EnclyApp). - val strictKeyboard by keyboardPrivacy.strict.collectAsState() + val strictKeyboard by keyboardPrivacy.strict.collectAsStateWithLifecycle() hostServices.Provide(this, strictKeyboard) { EnclyApp( startStatus = initialStatus, diff --git a/app/src/main/java/com/pasich/encly/core/security/BiometricTexts.kt b/app/src/main/java/com/pasich/encly/core/security/BiometricTexts.kt index dbd207d7..5a0250a4 100644 --- a/app/src/main/java/com/pasich/encly/core/security/BiometricTexts.kt +++ b/app/src/main/java/com/pasich/encly/core/security/BiometricTexts.kt @@ -16,8 +16,12 @@ import com.pasich.encly.core.security.BiometricManager.PromptConfig import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.Inject import dev.zacsweers.metro.SingleIn -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch import org.jetbrains.compose.resources.getString +import java.util.concurrent.atomic.AtomicBoolean /** The texts of the system biometric prompts, as plain strings in the in-app language. */ class BiometricTexts( @@ -27,7 +31,29 @@ class BiometricTexts( val masterKey: PromptConfig, val settings: PromptConfig, val general: PromptConfig, -) +) { + companion object { + /** + * English texts, shown only while the real ones (in the in-app language) are still being read: a prompt + * must never open with an empty title or button. + */ + val Default = BiometricTexts( + unavailable = "Biometric authentication is unavailable", + cancel = "Cancel", + unlock = PromptConfig( + title = "Unlock Encly", + subtitle = "Confirm your biometrics to access the encrypted key", + negativeButtonText = "Use PIN", + ), + masterKey = PromptConfig(title = "Key access", subtitle = "Confirm your biometrics"), + settings = PromptConfig( + title = "Security confirmation", + subtitle = "Confirm your biometrics to change protection", + ), + general = PromptConfig(title = "Authentication", subtitle = "Confirm your identity"), + ) + } +} /** * Holds the [BiometricTexts] for [KeystoreBiometricManager], which builds the system prompt outside any @@ -40,40 +66,56 @@ class BiometricTextSource { @Volatile private var texts: BiometricTexts? = null + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val loading = AtomicBoolean(false) + /** Reads the texts in the current language. */ suspend fun refresh() { - texts = BiometricTexts( - unavailable = getString(Res.string.biometric_unavailable), - cancel = getString(Res.string.cancel), - unlock = PromptConfig( - title = getString(Res.string.biometric_prompt_unlock_title), - subtitle = getString(Res.string.biometric_prompt_unlock_subtitle), - negativeButtonText = getString(Res.string.biometric_prompt_use_pin), - ), - masterKey = PromptConfig( - title = getString(Res.string.biometric_prompt_key_title), - subtitle = getString(Res.string.biometric_prompt_key_subtitle), - ), - settings = PromptConfig( - title = getString(Res.string.biometric_prompt_settings_title), - subtitle = getString(Res.string.biometric_prompt_settings_subtitle), - ), - general = PromptConfig( - title = getString(Res.string.biometric_prompt_general_title), - subtitle = getString(Res.string.biometric_prompt_general_subtitle), - ), - ) + texts = read() } + private suspend fun read() = BiometricTexts( + unavailable = getString(Res.string.biometric_unavailable), + cancel = getString(Res.string.cancel), + unlock = PromptConfig( + title = getString(Res.string.biometric_prompt_unlock_title), + subtitle = getString(Res.string.biometric_prompt_unlock_subtitle), + negativeButtonText = getString(Res.string.biometric_prompt_use_pin), + ), + masterKey = PromptConfig( + title = getString(Res.string.biometric_prompt_key_title), + subtitle = getString(Res.string.biometric_prompt_key_subtitle), + ), + settings = PromptConfig( + title = getString(Res.string.biometric_prompt_settings_title), + subtitle = getString(Res.string.biometric_prompt_settings_subtitle), + ), + general = PromptConfig( + title = getString(Res.string.biometric_prompt_general_title), + subtitle = getString(Res.string.biometric_prompt_general_subtitle), + ), + ) + /** Uses [texts] as they are (tests, or a caller that resolved them itself). */ fun set(texts: BiometricTexts) { this.texts = texts } /** - * The texts of the last [refresh]. A process started by another entry point than MainActivity - * (the My Notes hand-off) may reach a prompt before any refresh: then they are read here, once, - * so the unlock never fails over a missing title. + * The texts of the last [refresh], without ever blocking the caller (it may be the main thread). A process + * started by another entry point than MainActivity (the My Notes hand-off) may reach a prompt before any + * refresh: the first such call starts reading them in the background and answers with + * [BiometricTexts.Default] until they are ready, so the unlock never fails over a missing title. */ - fun current(): BiometricTexts = texts ?: runBlocking { refresh() }.let { checkNotNull(texts) } + fun current(): BiometricTexts { + texts?.let { return it } + if (loading.compareAndSet(false, true)) { + scope.launch { + runCatching { read() } + .onSuccess { loaded -> if (texts == null) texts = loaded } + loading.set(false) + } + } + return texts ?: BiometricTexts.Default + } } diff --git a/app/src/test/java/com/pasich/encly/core/security/BiometricKeyGenerationTest.kt b/app/src/test/java/com/pasich/encly/core/security/BiometricKeyGenerationTest.kt new file mode 100644 index 00000000..9043a6fb --- /dev/null +++ b/app/src/test/java/com/pasich/encly/core/security/BiometricKeyGenerationTest.kt @@ -0,0 +1,66 @@ +package com.pasich.encly.core.security + +import android.app.Application +import android.content.Context +import android.security.keystore.KeyProperties +import androidx.fragment.app.FragmentActivity +import androidx.test.core.app.ApplicationProvider +import com.pasich.encly.testutil.FakeAndroidKeyStore +import com.pasich.encly.testutil.tempVaultStore +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.shadow.api.Shadow +import org.robolectric.shadows.ShadowBiometricManager +import android.hardware.biometrics.BiometricManager as PlatformBiometricManager + +/** + * The biometric slot's Keystore key is made per use, and from Android 11 (R) its parameters name the strong class. + * The prompt itself needs a device, so what is checked is the spec the key was asked for. The branch below R + * (validity duration -1) is not reached here: Robolectric's androidx.biometric reports no strong biometrics on + * Android 10, so the enrolment stops before a key is made; that branch is left to the device smoke test (issue #17). + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [30, 35], application = Application::class) +class BiometricKeyGenerationTest { + private val context: Application get() = ApplicationProvider.getApplicationContext() + private val store = tempVaultStore() + private val texts = BiometricTextSource().apply { + val prompt = BiometricManager.PromptConfig("title", "subtitle") + set(BiometricTexts("unavailable", "cancel", prompt, prompt, prompt, prompt)) + } + private lateinit var manager: KeystoreBiometricManager + + @Before + fun setUp() { + FakeAndroidKeyStore.install() + manager = KeystoreBiometricManager(context, store, texts) + val platform = context.getSystemService(Context.BIOMETRIC_SERVICE) as PlatformBiometricManager + Shadow.extract(platform).setCanAuthenticate(true) + } + + @After + fun tearDown() = FakeAndroidKeyStore.uninstall() + + @Test + fun enrollingAsksForAPerUseStrongBiometricAesKey() { + val activity = Robolectric.buildActivity(FragmentActivity::class.java).setup().get() + + // The prompt cannot be answered here; the key is made before it is shown. + manager.enroll(ActivityBiometricHost(activity), ByteArray(32)) { } + + val spec = FakeAndroidKeyStore.specs.single() + assertEquals(256, spec.keySize) + assertEquals(KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, spec.purposes) + assertTrue(spec.isUserAuthenticationRequired) + assertTrue(spec.isInvalidatedByBiometricEnrollment) + assertEquals(0, spec.userAuthenticationValidityDurationSeconds) + assertEquals(KeyProperties.AUTH_BIOMETRIC_STRONG, spec.userAuthenticationType) + } +} diff --git a/app/src/test/java/com/pasich/encly/core/security/BiometricTextSourceTest.kt b/app/src/test/java/com/pasich/encly/core/security/BiometricTextSourceTest.kt new file mode 100644 index 00000000..9e4d603a --- /dev/null +++ b/app/src/test/java/com/pasich/encly/core/security/BiometricTextSourceTest.kt @@ -0,0 +1,49 @@ +package com.pasich.encly.core.security + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The prompt texts are never read on the caller's thread, and never empty. */ +class BiometricTextSourceTest { + private fun BiometricTexts.allTexts() = listOf( + unavailable, + cancel, + unlock.title, + unlock.subtitle, + unlock.negativeButtonText.orEmpty(), + masterKey.title, + masterKey.subtitle, + settings.title, + settings.subtitle, + general.title, + general.subtitle, + ) + + @Test + fun theDefaultTextsHaveATitleAndButtonsForEveryPrompt() { + assertTrue(BiometricTexts.Default.allTexts().all { it.isNotBlank() }) + } + + @Test + fun beforeAnyRefreshACallerGetsUsableTextsAtOnce() { + val source = BiometricTextSource() + + val texts = source.current() + + assertTrue(texts.allTexts().all { it.isNotBlank() }) + } + + @Test + fun textsSetByTheCallerAreReturnedAsTheyAre() { + val source = BiometricTextSource() + val prompt = BiometricManager.PromptConfig("title", "subtitle") + val own = BiometricTexts("unavailable", "cancel", prompt, prompt, prompt, prompt) + + source.set(own) + + assertSame(own, source.current()) + assertEquals("cancel", source.current().cancel) + } +} diff --git a/app/src/test/java/com/pasich/encly/core/security/KeystorePinFactorTest.kt b/app/src/test/java/com/pasich/encly/core/security/KeystorePinFactorTest.kt index 11f511c6..a4a33feb 100644 --- a/app/src/test/java/com/pasich/encly/core/security/KeystorePinFactorTest.kt +++ b/app/src/test/java/com/pasich/encly/core/security/KeystorePinFactorTest.kt @@ -21,10 +21,11 @@ import java.security.UnrecoverableKeyException /** * The Keystore-backed PIN factor against an in-memory Keystore that fails on demand: what it * generates, which failures mean "the key is gone for good" and which may pass, and that a - * failed generation never leaves a half-made key behind. + * failed generation never leaves a half-made key behind. Runs on Android 9 (the first with StrongBox and the + * unlocked-device requirement) and on 15; the case below Android 9 is [beforeAndroid9NoStrongBoxIsAskedFor]. */ @RunWith(RobolectricTestRunner::class) -@Config(sdk = [35]) +@Config(sdk = [28, 35]) class KeystorePinFactorTest { private val factor = KeystorePinFactor() private val aliasA = "encly_pin_factor_v3" @@ -104,6 +105,18 @@ class KeystorePinFactorTest { assertEquals(android.security.keystore.KeyProperties.PURPOSE_SIGN, spec.purposes) } + @Test + @Config(sdk = [26]) + fun beforeAndroid9NoStrongBoxIsAskedForAndTheKeyIsStillMade() { + // StrongBox and the unlocked-device flag do not exist on Android 8: the spec is built without them. + assertTrue(factor.ensureKey(PinKeySlot.A)) + + assertEquals(1, FakeAndroidKeyStore.specs.size) + assertEquals(256, FakeAndroidKeyStore.specs.single().keySize) + assertTrue(FakeAndroidKeyStore.has(aliasA)) + assertEquals(32, factor.mac(PinKeySlot.A, byteArrayOf(1)).size) + } + @Test fun aDeviceWithoutStrongBoxFallsBackToTheTeeStillRequiringAnUnlockedDevice() { FakeAndroidKeyStore.onGenerate = { if (it.isStrongBoxBacked) throw ProviderException("no StrongBox") } diff --git a/app/src/test/java/com/pasich/encly/platform/RecentsScreenshotTest.kt b/app/src/test/java/com/pasich/encly/platform/RecentsScreenshotTest.kt new file mode 100644 index 00000000..c781634a --- /dev/null +++ b/app/src/test/java/com/pasich/encly/platform/RecentsScreenshotTest.kt @@ -0,0 +1,79 @@ +package com.pasich.encly.platform + +import android.app.Activity +import android.app.Application +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** An activity that records what it was told about the task switcher thumbnail (Android 13+). */ +class RecentsRecordingActivity : Activity() { + val recentsCalls = mutableListOf() + + override fun setRecentsScreenshotEnabled(enabled: Boolean) { + recentsCalls += enabled + } +} + +/** + * The task switcher shows no thumbnail of a window that may be captured (issue #16): while the user allows + * screenshots, the recents snapshot is switched off (`setRecentsScreenshotEnabled(false)`, Android 13+), and + * back on once the allowance ends. A protected window needs no call: FLAG_SECURE already blanks its thumbnail. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35], application = Application::class) +class RecentsScreenshotTest { + private fun window(): Pair { + val activity = Robolectric.buildActivity(RecentsRecordingActivity::class.java).setup().get() + return activity to AndroidAppWindow(activity, activity.window.decorView) + } + + @Test + fun allowingScreenshotsSwitchesTheRecentsThumbnailOff() { + val (activity, window) = window() + window.enforceSecure() + assertTrue("a protected window needs no call", activity.recentsCalls.isEmpty()) + + window.setCaptureAllowed(true) + + assertEquals(listOf(false), activity.recentsCalls) + } + + @Test + fun theThumbnailStaysOffWhileTheWindowLeavesAndReturnsToTheForeground() { + val (activity, window) = window() + + window.setCaptureAllowed(true) + window.setInForeground(true) + window.setInForeground(false) + window.setInForeground(true) + window.enforceSecure() + + assertEquals("one call, not one per frame or per lifecycle step", listOf(false), activity.recentsCalls) + } + + @Test + fun endingTheAllowanceSwitchesTheThumbnailBackToTheDefault() { + val (activity, window) = window() + window.setCaptureAllowed(true) + + window.setCaptureAllowed(false) + + assertEquals(listOf(false, true), activity.recentsCalls) + } + + @Test + @Config(sdk = [32]) + fun beforeAndroid13TheCallIsNeverMade() { + val (activity, window) = window() + + window.setCaptureAllowed(true) + window.setCaptureAllowed(false) + + assertTrue(activity.recentsCalls.isEmpty()) + } +} diff --git a/app/src/test/java/com/pasich/encly/release/ManifestPermissionsTest.kt b/app/src/test/java/com/pasich/encly/release/ManifestPermissionsTest.kt new file mode 100644 index 00000000..1335f706 --- /dev/null +++ b/app/src/test/java/com/pasich/encly/release/ManifestPermissionsTest.kt @@ -0,0 +1,60 @@ +package com.pasich.encly.release + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Test +import java.io.File + +/** + * The permissions the app itself asks for are pinned (issue #14): Encly never touches the network, so a new + * `` in the source manifests is a decision, not a side effect. A library may add its own on + * merge; the merged manifest of the F-Droid release is pinned, in full, by the `release` job of + * `.github/workflows/android.yml` (it needs a build, which a unit test cannot run). + */ +class ManifestPermissionsTest { + private val repoRoot = listOf(File(".."), File(".")).first { File(it, "version.properties").isFile } + + private val manifests = File(repoRoot, "app/src").listFiles().orEmpty() + .filter { it.isDirectory && it.name != "androidTest" } + .map { File(it, "AndroidManifest.xml") } + .filter { it.isFile } + + private fun permissionsOf(manifest: File): Set = USES_PERMISSION.findAll(manifest.readText()) + .map { it.groupValues[1] } + .toSet() + + @Test + fun theMainManifestAsksForExactlyTheKnownPermissions() { + val main = File(repoRoot, "app/src/main/AndroidManifest.xml") + + assertEquals( + setOf("android.permission.USE_BIOMETRIC", "android.permission.HIDE_OVERLAY_WINDOWS"), + permissionsOf(main), + ) + } + + @Test + fun noSourceManifestAsksForTheNetworkOrStorage() { + assertFalse("no manifests found", manifests.isEmpty()) + manifests.forEach { manifest -> + val permissions = permissionsOf(manifest) + BANNED.forEach { banned -> + assertFalse("${manifest.path} asks for $banned", banned in permissions) + } + } + } + + private companion object { + val USES_PERMISSION = Regex("""]*android:name="([^"]+)"""") + + val BANNED = listOf( + "android.permission.INTERNET", + "android.permission.ACCESS_NETWORK_STATE", + "android.permission.READ_EXTERNAL_STORAGE", + "android.permission.WRITE_EXTERNAL_STORAGE", + "android.permission.MANAGE_EXTERNAL_STORAGE", + "android.permission.POST_NOTIFICATIONS", + "android.permission.SCHEDULE_EXACT_ALARM", + ) + } +} diff --git a/app/src/test/java/com/pasich/encly/testutil/FakeAndroidKeyStore.kt b/app/src/test/java/com/pasich/encly/testutil/FakeAndroidKeyStore.kt index 3ad16445..28ed4f5b 100644 --- a/app/src/test/java/com/pasich/encly/testutil/FakeAndroidKeyStore.kt +++ b/app/src/test/java/com/pasich/encly/testutil/FakeAndroidKeyStore.kt @@ -29,6 +29,7 @@ import javax.crypto.spec.SecretKeySpec internal object FakeAndroidKeyStore { private const val NAME = "AndroidKeyStore" private const val HMAC = "HmacSHA256" + private const val AES = "AES" private val keys = mutableMapOf() @@ -85,7 +86,11 @@ internal object FakeAndroidKeyStore { override fun newInstance(constructorParameter: Any?): Any = FakeKeyStoreSpi() }) putService(object : Service(this, "KeyGenerator", HMAC, FakeKeyGenerator::class.java.name, null, null) { - override fun newInstance(constructorParameter: Any?): Any = FakeKeyGenerator() + override fun newInstance(constructorParameter: Any?): Any = FakeKeyGenerator(HMAC) + }) + // The biometric slot's AES key: the spec it was asked for is recorded; the key is a plain software one. + putService(object : Service(this, "KeyGenerator", AES, FakeKeyGenerator::class.java.name, null, null) { + override fun newInstance(constructorParameter: Any?): Any = FakeKeyGenerator(AES) }) putService(object : Service(this, "Mac", HMAC, FakeMac::class.java.name, null, null) { override fun newInstance(constructorParameter: Any?): Any = FakeMac() @@ -93,7 +98,7 @@ internal object FakeAndroidKeyStore { } } - private class FakeKeyGenerator : KeyGeneratorSpi() { + private class FakeKeyGenerator(private val algorithm: String) : KeyGeneratorSpi() { private var spec: KeyGenParameterSpec? = null override fun engineInit(random: SecureRandom?) = throw UnsupportedOperationException() @@ -108,7 +113,7 @@ internal object FakeAndroidKeyStore { val current = checkNotNull(spec) specs += current onGenerate(current) - val key = SecretKeySpec(ByteArray(current.keySize / 8).also { SecureRandom().nextBytes(it) }, HMAC) + val key = SecretKeySpec(ByteArray(current.keySize / 8).also { SecureRandom().nextBytes(it) }, algorithm) keys[current.keystoreAlias] = key return key } diff --git a/core/database/src/androidDeviceTest/kotlin/com/pasich/encly/data/database/Release23MigrationTest.kt b/core/database/src/androidDeviceTest/kotlin/com/pasich/encly/data/database/Release23MigrationTest.kt new file mode 100644 index 00000000..3d1b642f --- /dev/null +++ b/core/database/src/androidDeviceTest/kotlin/com/pasich/encly/data/database/Release23MigrationTest.kt @@ -0,0 +1,212 @@ +package com.pasich.encly.data.database + +import android.content.Context +import androidx.sqlite.db.SupportSQLiteDatabase +import androidx.sqlite.db.SupportSQLiteOpenHelper +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.pasich.encly.data.model.NoteWithTags +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import net.zetetic.database.sqlcipher.SupportOpenHelperFactory +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +/** + * An ENCRYPTED vault of 2.3.x (database schema 6) goes through the real unlock + * ([SecureDatabaseManager.unlockDatabase]) and the 6 -> 7 -> 8 migrations, and its data comes out intact. + * [AppDatabaseSchemaTest] migrates the same versions, but on a plain database; this is the same path under + * SQLCipher, which every upgraded user takes on the first unlock. + * + * How the 2.3.x vault is made: with sqlcipher-android 4.19.1 (the version 2.3.1 shipped, see the catalog), + * through [SupportOpenHelperFactory] and the DEK as the raw key `x'<64 hex>'` as ASCII, which is what 2.3.x + * handed to it. The tables, indices and `room_master_table` row are Room's own export of schema 6 + * (core/database/schemas/.../6.json, committed with 2.3.x); the uid triggers are the ones 2.3.x installed + * on creation. The file's `user_version` is 6. It is not a binary taken out of a 2.3.1 build: only the 6.json + * export and the write path are reproduced, which is what the migration and the unlock depend on. + * The key is a test key, never a real user's. + * + * Runs inside the app under test and deletes its database.db: run it on an emulator. + */ +@RunWith(AndroidJUnit4::class) +class Release23MigrationTest { + private val context = ApplicationProvider.getApplicationContext() + private lateinit var manager: SecureDatabaseManager + private val dek = ByteArray(32) { (it * 7 + 3).toByte() } + + @Before + fun setUp() { + manager = SecureDatabaseManager(AndroidDatabasePlatform(context)) + manager.wipe() + } + + @After + fun tearDown() { + manager.wipe() + } + + @Test + fun anEncryptedSchema6VaultMigratesThroughUnlockAndKeepsItsData() = runBlocking { + writeSchema6Vault() + assertTrue(manager.hasEncryptedDatabase()) + + val before = System.currentTimeMillis() + assertTrue("unlock must migrate 6 -> 8 under SQLCipher", manager.unlockDatabase(dek)) + assertData(manager.getDatabase(manager.captureLease()!!), before) + + // Every unlock after the first opens an already migrated vault. + manager.reset() + assertTrue(manager.unlockDatabase(dek)) + val reopened = manager.getDatabase(manager.captureLease()!!) + assertData(reopened, before) + + // And it is a working schema 8 vault: a note takes several tags now. + val notes = reopened.notesDao() + notes.insertNoteTags(NOTE_PLAIN, listOf(TAG_WORK, TAG_HOME)) + assertEquals(listOf(TAG_WORK, TAG_HOME), tagIds(notes.getNoteWithTags(NOTE_PLAIN))) + } + + private suspend fun assertData(db: AppDatabase, notBefore: Long) { + val notes = db.notesDao() + + // Notes: the four live ones (the fifth is in the trash), text intact. The tag of each moved to + // note_tags; the dangling one was dropped. + assertEquals( + listOf("Work note", "Home note", "Plain note", "Dangling tag note"), + notes.getAllNotes().first().sortedBy { it.id }.map { it.title }, + ) + assertEquals("body of work", notes.getNoteById(NOTE_WORK)!!.value) + assertEquals(listOf(TAG_WORK), tagIds(notes.getNoteWithTags(NOTE_WORK))) + assertEquals(listOf(TAG_HOME), tagIds(notes.getNoteWithTags(NOTE_HOME))) + assertEquals(emptyList(), tagIds(notes.getNoteWithTags(NOTE_DANGLING))) + + // The trash: the note stays in it with its tag and got the migration's trash time; the others have none. + assertEquals(listOf(NOTE_TRASHED), notes.getTrashNotes().first().map { it.id }) + assertEquals(listOf(TAG_WORK), tagIds(notes.getNoteWithTags(NOTE_TRASHED))) + val trashedAt = notes.getNoteById(NOTE_TRASHED)!!.trashedAt + assertNotNull(trashedAt) + assertTrue( + "trashedAt is the time of the migration", + trashedAt!! in (notBefore - ONE_MINUTE)..(notBefore + ONE_MINUTE), + ) + assertNull(notes.getNoteById(NOTE_WORK)!!.trashedAt) + + assertEquals(listOf("Work", "Home"), db.tagsDao().getTags().first().sortedBy { it.id }.map { it.nameTag }) + + // Tasks and sub-tasks (a foreign key on tasks): the migrations must not have cascaded them away. + val tasks = db.tasksDao().getAllTasks().first() + assertEquals(listOf("Pay rent"), tasks.map { it.title }) + assertEquals(2, tasks.single().priority) + assertEquals( + listOf("Call landlord" to false, "Transfer money" to true), + db.tasksDao().getSubtasks(TASK_ID).sortedBy { it.position }.map { it.title to it.isCompleted }, + ) + } + + private fun tagIds(note: NoteWithTags?): List = checkNotNull(note).tags.map { it.id }.sorted() + + /** The vault file 2.3.x wrote, see the class comment. */ + private fun writeSchema6Vault() { + System.loadLibrary("sqlcipher") + val schema = JSONObject( + InstrumentationRegistry.getInstrumentation().context.assets + .open("com.pasich.encly.data.database.AppDatabase/6.json").bufferedReader().use { it.readText() }, + ).getJSONObject("database") + val passphrase = ("x'" + dek.joinToString("") { "%02x".format(it) } + "'").toByteArray(Charsets.US_ASCII) + val helper = SupportOpenHelperFactory(passphrase, null, false).create( + SupportSQLiteOpenHelper.Configuration.builder(context) + .name(VaultFile.PRIMARY.fileName) + .callback(object : SupportSQLiteOpenHelper.Callback(SCHEMA_VERSION) { + override fun onCreate(db: SupportSQLiteDatabase) = createSchema6(db, schema) + + override fun onUpgrade(db: SupportSQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit + }) + .build(), + ) + try { + check(helper.writableDatabase.version == SCHEMA_VERSION) + } finally { + helper.close() + } + } + + private fun createSchema6(db: SupportSQLiteDatabase, schema: JSONObject) { + check(schema.getInt("version") == SCHEMA_VERSION) + val entities = schema.getJSONArray("entities") + for (i in 0 until entities.length()) { + val entity = entities.getJSONObject(i) + val table = entity.getString("tableName") + db.execSQL(entity.getString("createSql").replace("\${TABLE_NAME}", table)) + val indices = entity.optJSONArray("indices") + for (j in 0 until (indices?.length() ?: 0)) { + db.execSQL(indices!!.getJSONObject(j).getString("createSql").replace("\${TABLE_NAME}", table)) + } + // The uid triggers 2.3.x installed when it created the database. + db.execSQL( + "CREATE TRIGGER IF NOT EXISTS `${table}_uid_on_insert` AFTER INSERT ON `$table` " + + "WHEN NEW.uid = '' BEGIN UPDATE `$table` SET uid = lower(hex(randomblob(16))) " + + "WHERE id = NEW.id; END", + ) + db.execSQL( + "CREATE TRIGGER IF NOT EXISTS `${table}_uid_keep` AFTER UPDATE OF uid ON `$table` " + + "WHEN NEW.uid = '' AND OLD.uid <> '' BEGIN UPDATE `$table` SET uid = OLD.uid " + + "WHERE id = NEW.id; END", + ) + } + val setup = schema.getJSONArray("setupQueries") + for (i in 0 until setup.length()) db.execSQL(setup.getString(i)) + + db.execSQL("INSERT INTO tags (id, name, visibility, position) VALUES ($TAG_WORK, 'Work', 1, 0)") + db.execSQL("INSERT INTO tags (id, name, visibility, position) VALUES ($TAG_HOME, 'Home', 1, 1)") + // One tag per note in 2.3.x (`tagId`); 99 names no tag, as an old version could leave it. + for (note in NOTES) { + db.execSQL( + "INSERT INTO notes (id, title, value, description, date, dateCreate, tagId, isTrash, uid) " + + "VALUES (${note.id}, '${note.title}', 'body of ${note.title.substringBefore(' ').lowercase()}', " + + "'desc', 1700000000000, 1700000000000, ${note.tag ?: "NULL"}, ${note.trash}, 'note-uid-${note.id}')", + ) + } + db.execSQL( + "INSERT INTO tasks (id, title, description, isCompleted, createdDate, priority, position, uid) " + + "VALUES ($TASK_ID, 'Pay rent', 'monthly', 0, 1700000000000, 2, 0, 'task-uid')", + ) + db.execSQL( + "INSERT INTO subtasks (id, taskId, title, isCompleted, position, uid) " + + "VALUES (1, $TASK_ID, 'Call landlord', 0, 0, 'sub-uid-1'), " + + "(2, $TASK_ID, 'Transfer money', 1, 1, 'sub-uid-2')", + ) + } + + /** A row of the schema 6 `notes` table: its tag (`tagId`, or none) and whether it is in the trash. */ + private data class NoteRow(val id: Long, val title: String, val tag: Long?, val trash: Int) + + private companion object { + const val SCHEMA_VERSION = 6 + const val ONE_MINUTE = 60_000L + const val TAG_WORK = 1L + const val TAG_HOME = 2L + const val TASK_ID = 1L + const val NOTE_WORK = 1L + const val NOTE_HOME = 2L + const val NOTE_PLAIN = 3L + const val NOTE_DANGLING = 4L + const val NOTE_TRASHED = 5L + const val NO_SUCH_TAG = 99L + + val NOTES = listOf( + NoteRow(NOTE_WORK, "Work note", TAG_WORK, 0), + NoteRow(NOTE_HOME, "Home note", TAG_HOME, 0), + NoteRow(NOTE_PLAIN, "Plain note", null, 0), + NoteRow(NOTE_DANGLING, "Dangling tag note", NO_SUCH_TAG, 0), + NoteRow(NOTE_TRASHED, "Trashed note", TAG_WORK, 1), + ) + } +} diff --git a/core/resources/src/commonMain/strings/values-ar/strings.xml b/core/resources/src/commonMain/strings/values-ar/strings.xml index 500d227a..156b229c 100644 --- a/core/resources/src/commonMain/strings/values-ar/strings.xml +++ b/core/resources/src/commonMain/strings/values-ar/strings.xml @@ -699,6 +699,16 @@ ما الجديد التغييرات في هذا الإصدار فهمت + سلة المحذوفات تُفرَّغ الآن تلقائيًا + + تحذف سلة المحذوفات الآن الملاحظات نهائيًا بعد 28 يومًا. فيها %d ملاحظة وستُحذف بعد 28 يومًا من هذا التحديث ما لم تستعدها. + تحذف سلة المحذوفات الآن الملاحظات نهائيًا بعد 28 يومًا. فيها ملاحظة واحدة (%d) وستُحذف بعد 28 يومًا من هذا التحديث ما لم تستعدها. + تحذف سلة المحذوفات الآن الملاحظات نهائيًا بعد 28 يومًا. فيها ملاحظتان (%d) وستُحذفان بعد 28 يومًا من هذا التحديث ما لم تستعدهما. + تحذف سلة المحذوفات الآن الملاحظات نهائيًا بعد 28 يومًا. فيها %d ملاحظات وستُحذف بعد 28 يومًا من هذا التحديث ما لم تستعدها. + تحذف سلة المحذوفات الآن الملاحظات نهائيًا بعد 28 يومًا. فيها %d ملاحظة وستُحذف بعد 28 يومًا من هذا التحديث ما لم تستعدها. + تحذف سلة المحذوفات الآن الملاحظات نهائيًا بعد 28 يومًا. فيها %d ملاحظة وستُحذف بعد 28 يومًا من هذا التحديث ما لم تستعدها. + + فتح سلة المحذوفات تحديد الكتلة إعادة ترتيب العنصر نقل العنصر لأعلى diff --git a/core/resources/src/commonMain/strings/values-de/strings.xml b/core/resources/src/commonMain/strings/values-de/strings.xml index dd35b332..91dbacae 100644 --- a/core/resources/src/commonMain/strings/values-de/strings.xml +++ b/core/resources/src/commonMain/strings/values-de/strings.xml @@ -699,6 +699,12 @@ Neuigkeiten Die Änderungen dieser Version Verstanden + Der Papierkorb leert sich jetzt selbst + + Der Papierkorb löscht Notizen jetzt nach 28 Tagen endgültig. Darin liegt %d Notiz: Sie wird 28 Tage nach diesem Update gelöscht, wenn du sie nicht wiederherstellst. + Der Papierkorb löscht Notizen jetzt nach 28 Tagen endgültig. Darin liegen %d Notizen: Sie werden 28 Tage nach diesem Update gelöscht, wenn du sie nicht wiederherstellst. + + Papierkorb öffnen Wie lang darf meine PIN sein? Zwischen 6 und 12 Ziffern, du entscheidest. Kürzere PINs werden nicht angeboten: Die Sperre und der Gerätschlüssel begrenzen die Zahl der Versuche, und 6 Ziffern sind die kürzeste PIN, die damit sicher bleibt. Der Sperrbildschirm zeigt nie, wie lang deine PIN ist: Du tippst auf „Entsperren“, wenn du fertig bist; das gilt auch für Lösch-PIN und Zwangs-PIN. PINs, die du vorher festgelegt hast, funktionieren unverändert. Code diff --git a/core/resources/src/commonMain/strings/values-es/strings.xml b/core/resources/src/commonMain/strings/values-es/strings.xml index d2385704..bf1186f9 100644 --- a/core/resources/src/commonMain/strings/values-es/strings.xml +++ b/core/resources/src/commonMain/strings/values-es/strings.xml @@ -705,6 +705,13 @@ Novedades Los cambios de esta versión Entendido + La papelera ahora se vacía sola + + La papelera ahora borra las notas para siempre a los 28 días. Tienes %d nota en ella: se borrará 28 días después de esta actualización, salvo que la restaures. + La papelera ahora borra las notas para siempre a los 28 días. Tienes %d notas en ella: se borrarán 28 días después de esta actualización, salvo que las restaures. + La papelera ahora borra las notas para siempre a los 28 días. Tienes %d notas en ella: se borrarán 28 días después de esta actualización, salvo que las restaures. + + Abrir la papelera ¿Qué longitud puede tener mi PIN? Entre 6 y 12 dígitos, a tu elección. No se ofrecen PIN más cortos: el bloqueo y la clave del dispositivo limitan los intentos, y 6 dígitos es lo más corto que sigue siendo seguro con esos límites. La pantalla de bloqueo nunca muestra la longitud de tu PIN: pulsas «Desbloquear» cuando terminas, y lo mismo vale para el PIN de borrado y el PIN de coacción. Los PIN que ya tenías siguen funcionando igual. Código diff --git a/core/resources/src/commonMain/strings/values-fr/strings.xml b/core/resources/src/commonMain/strings/values-fr/strings.xml index e687fae0..9ea793d3 100644 --- a/core/resources/src/commonMain/strings/values-fr/strings.xml +++ b/core/resources/src/commonMain/strings/values-fr/strings.xml @@ -705,6 +705,13 @@ Nouveautés Les changements de cette version Compris + La corbeille se vide désormais toute seule + + La corbeille supprime désormais les notes définitivement au bout de 28 jours. Elle contient %d note : elle sera supprimée 28 jours après cette mise à jour, sauf si vous la restaurez. + La corbeille supprime désormais les notes définitivement au bout de 28 jours. Elle contient %d notes : elles seront supprimées 28 jours après cette mise à jour, sauf si vous les restaurez. + La corbeille supprime désormais les notes définitivement au bout de 28 jours. Elle contient %d notes : elles seront supprimées 28 jours après cette mise à jour, sauf si vous les restaurez. + + Ouvrir la corbeille Quelle longueur peut avoir mon code PIN ? Entre 6 et 12 chiffres, à votre choix. Les codes plus courts ne sont pas proposés : le blocage et la clé de l’appareil limitent le nombre d’essais, et 6 chiffres est le minimum qui reste sûr avec ces limites. L’écran de verrouillage n’indique jamais la longueur de votre code : vous touchez « Déverrouiller » quand vous avez fini, de même pour le PIN d’effacement et le PIN de contrainte. Les codes définis auparavant continuent de fonctionner tels quels. Code diff --git a/core/resources/src/commonMain/strings/values-it/strings.xml b/core/resources/src/commonMain/strings/values-it/strings.xml index 2d4f62d1..53500109 100644 --- a/core/resources/src/commonMain/strings/values-it/strings.xml +++ b/core/resources/src/commonMain/strings/values-it/strings.xml @@ -705,6 +705,13 @@ Novità Le novità di questa versione Ho capito + Il cestino ora si svuota da solo + + Il cestino ora elimina le note per sempre dopo 28 giorni. Contiene %d nota: verrà eliminata 28 giorni dopo questo aggiornamento, a meno che tu non la ripristini. + Il cestino ora elimina le note per sempre dopo 28 giorni. Contiene %d note: verranno eliminate 28 giorni dopo questo aggiornamento, a meno che tu non le ripristini. + Il cestino ora elimina le note per sempre dopo 28 giorni. Contiene %d note: verranno eliminate 28 giorni dopo questo aggiornamento, a meno che tu non le ripristini. + + Apri il cestino Quanto può essere lungo il PIN? Da 6 a 12 cifre, a tua scelta. PIN più corti non sono previsti: il blocco e la chiave del dispositivo limitano i tentativi, e 6 cifre è il minimo che resta sicuro con quei limiti. La schermata di blocco non mostra mai la lunghezza del PIN: tocchi «Sblocca» quando hai finito, e lo stesso vale per il PIN di cancellazione e il PIN di coercizione. I PIN impostati prima continuano a funzionare così come sono. Codice diff --git a/core/resources/src/commonMain/strings/values-nl/strings.xml b/core/resources/src/commonMain/strings/values-nl/strings.xml index 25296795..c99539c2 100644 --- a/core/resources/src/commonMain/strings/values-nl/strings.xml +++ b/core/resources/src/commonMain/strings/values-nl/strings.xml @@ -699,6 +699,12 @@ Wat is er nieuw De wijzigingen in deze versie Begrepen + De prullenbak leegt zichzelf nu + + De prullenbak verwijdert notities nu definitief na 28 dagen. Er zit %d notitie in: die wordt 28 dagen na deze update verwijderd, tenzij je die herstelt. + De prullenbak verwijdert notities nu definitief na 28 dagen. Er zitten %d notities in: die worden 28 dagen na deze update verwijderd, tenzij je ze herstelt. + + Prullenbak openen Hoe lang mag mijn pincode zijn? Tussen 6 en 12 cijfers, naar keuze. Kortere pincodes worden niet aangeboden: de blokkade en de sleutel van het apparaat beperken het aantal pogingen, en 6 cijfers is het kortste dat daarmee veilig blijft. Het vergrendelscherm toont nooit hoe lang je pincode is: je tikt op ‘Ontgrendelen’ als je klaar bent, en hetzelfde geldt voor de wis-pincode en de dwangpincode. Pincodes die je eerder instelde, blijven gewoon werken. Code diff --git a/core/resources/src/commonMain/strings/values-pl/strings.xml b/core/resources/src/commonMain/strings/values-pl/strings.xml index d2372bad..185f163f 100644 --- a/core/resources/src/commonMain/strings/values-pl/strings.xml +++ b/core/resources/src/commonMain/strings/values-pl/strings.xml @@ -711,6 +711,14 @@ Co nowego Zmiany w tej wersji Rozumiem + Kosz opróżnia się teraz sam + + Kosz usuwa teraz notatki na zawsze po 28 dniach. Jest w nim %d notatka: zostanie usunięta 28 dni po tej aktualizacji, chyba że ją przywrócisz. + Kosz usuwa teraz notatki na zawsze po 28 dniach. Są w nim %d notatki: zostaną usunięte 28 dni po tej aktualizacji, chyba że je przywrócisz. + Kosz usuwa teraz notatki na zawsze po 28 dniach. Jest w nim %d notatek: wszystkie zostaną usunięte 28 dni po tej aktualizacji, chyba że je przywrócisz. + Kosz usuwa teraz notatki na zawsze po 28 dniach. Są w nim %d notatki: zostaną usunięte 28 dni po tej aktualizacji, chyba że je przywrócisz. + + Otwórz kosz Jak długi może być mój PIN? Od 6 do 12 cyfr, do wyboru. Krótszych PIN-ów nie oferujemy: blokada i klucz urządzenia ograniczają liczbę prób, a 6 cyfr to najkrótszy PIN, który przy tych ograniczeniach pozostaje bezpieczny. Ekran blokady nigdy nie pokazuje długości PIN-u: po wpisaniu stukasz „Odblokuj”, tak samo w przypadku PIN-u kasującego i przymusowego. PIN-y ustawione wcześniej działają bez zmian. Kod diff --git a/core/resources/src/commonMain/strings/values-pt/strings.xml b/core/resources/src/commonMain/strings/values-pt/strings.xml index 6f1617fe..38cda6ef 100644 --- a/core/resources/src/commonMain/strings/values-pt/strings.xml +++ b/core/resources/src/commonMain/strings/values-pt/strings.xml @@ -705,6 +705,13 @@ Novidades As alterações desta versão Entendi + A lixeira agora esvazia-se sozinha + + A lixeira agora elimina as notas de vez ao fim de 28 dias. Tem %d nota: será eliminada 28 dias após esta atualização, a menos que a restaure. + A lixeira agora elimina as notas de vez ao fim de 28 dias. Tem %d notas: serão eliminadas 28 dias após esta atualização, a menos que as restaure. + A lixeira agora elimina as notas de vez ao fim de 28 dias. Tem %d notas: serão eliminadas 28 dias após esta atualização, a menos que as restaure. + + Abrir a lixeira Qual pode ser o tamanho do meu PIN? Entre 6 e 12 dígitos, à sua escolha. PINs mais curtos não são oferecidos: o bloqueio e a chave do dispositivo limitam as tentativas, e 6 dígitos é o mínimo que continua seguro com esses limites. A tela de bloqueio nunca mostra o tamanho do seu PIN: você toca em «Desbloquear» quando terminar, e o mesmo vale para o PIN de apagamento e o PIN de coação. Os PINs definidos antes continuam funcionando como estão. Código diff --git a/core/resources/src/commonMain/strings/values-uk/strings.xml b/core/resources/src/commonMain/strings/values-uk/strings.xml index 7c53d2c6..c04e3667 100644 --- a/core/resources/src/commonMain/strings/values-uk/strings.xml +++ b/core/resources/src/commonMain/strings/values-uk/strings.xml @@ -540,8 +540,8 @@ Підзавдання Показати підзавдання Сховати підзавдання - Немає нотаток з тегом «%1$s» - Тут з’являться нотатки з цим тегом. + Немає нотаток з міткою «%1$s» + Тут з’являться нотатки з цією міткою. Показати всі нотатки Кошик порожній Видалити назавжди @@ -555,13 +555,13 @@ Encly створено з цими бібліотеками та шрифтами. Натисніть, щоб прочитати ліцензію. Бібліотеки Шрифти - Тегів ще немає - Теги групують нотатки. Створіть тег вище, а потім виберіть його для нотатки в меню довгого натискання. - Натисніть тег, щоб перейменувати, приховати чи видалити. Тягніть за ручку, щоб змінити порядок. - Додати тег + Міток ще немає + Мітки групують нотатки. Створіть мітку вище, а потім виберіть її для нотатки в меню довгого натискання. + Натисніть мітку, щоб перейменувати, приховати чи видалити. Тягніть за ручку, щоб змінити порядок. + Додати мітку Назва Показувати в списку нотаток - Коли тег прихований, його нотатки не показуються в списку, лише під його приглушеним фільтром + Коли мітка прихована, її нотатки не показуються в списку, лише під її приглушеним фільтром Перетягніть, щоб змінити порядок Перемістити вгору Перемістити вниз @@ -711,6 +711,14 @@ Що нового Зміни в цій версії Зрозуміло + Кошик тепер очищується сам + + Кошик тепер видаляє нотатки назавжди через 28 днів. У ньому %d нотатка: її буде видалено через 28 днів після цього оновлення, якщо ви її не відновите. + Кошик тепер видаляє нотатки назавжди через 28 днів. У ньому %d нотатки: їх буде видалено через 28 днів після цього оновлення, якщо ви їх не відновите. + Кошик тепер видаляє нотатки назавжди через 28 днів. У ньому %d нотаток: їх буде видалено через 28 днів після цього оновлення, якщо ви їх не відновите. + Кошик тепер видаляє нотатки назавжди через 28 днів. У ньому %d нотатки: їх буде видалено через 28 днів після цього оновлення, якщо ви їх не відновите. + + Відкрити кошик Якої довжини може бути PIN? Від 6 до 12 цифр на ваш вибір. Коротших PIN не пропонується: блокування й ключ пристрою обмежують кількість спроб, а 6 цифр — найкоротший PIN, що лишається безпечним за цих обмежень. Екран блокування ніколи не показує довжину вашого PIN: коли закінчите, натисніть «Розблокувати» — так само для PIN для стирання та PIN під примусом. PIN, задані раніше, працюють без змін. Код diff --git a/core/resources/src/commonMain/strings/values-uk/strings_import.xml b/core/resources/src/commonMain/strings/values-uk/strings_import.xml index e4f8489c..1db420c4 100644 --- a/core/resources/src/commonMain/strings/values-uk/strings_import.xml +++ b/core/resources/src/commonMain/strings/values-uk/strings_import.xml @@ -13,29 +13,29 @@ Google Keep Архів Google Takeout (.zip) як є, без розпакування, або окремі нотатки .json У Google Takeout оберіть лише Keep, створіть експорт і завантажте .zip. Потім оберіть цей .zip тут. - Закріплення й архівація, кольори та вкладення. Тегом стає лише перша мітка. + Закріплення й архівація, кольори та вкладення. Міткою стає лише перша мітка. Standard Notes Розшифрована резервна копія (.txt або .json) або .zip розшифрованого завантаження У Standard Notes завантажте розшифровану резервну копію, а не зашифровану. Потім оберіть файл або .zip тут. - Зашифровані копії відхиляються. Закріплення й архівація, файли та інші типи елементів. Зберігається лише перший тег. + Зашифровані копії відхиляються. Закріплення й архівація, файли та інші типи елементів. Зберігається лише перша мітка. Joplin Архів JEX (.jex), папка RAW або експорт Markdown У Joplin оберіть File → Export all і формат JEX або RAW. Потім оберіть файл або папку тут. - Вкладення та статус завдання (завдання стають звичайними нотатками). Нотатка отримує свій перший тег, а якщо його немає, то назву блокнота. + Вкладення та статус завдання (завдання стають звичайними нотатками). Нотатка отримує свою першу мітку, а якщо її немає, то назву блокнота. Notesnook Експорт Markdown, Markdown з front matter або TXT (.zip) - У Notesnook експортуйте нотатки як Markdown з front matter, щоб зберегти дати й теги. Потім оберіть .zip тут. Зашифровані резервні копії імпортувати не можна. - Вкладення, закріплення й архівація, кольори. Тегом стає перший тег, а якщо його немає, то блокнот. + У Notesnook експортуйте нотатки як Markdown з front matter, щоб зберегти дати й мітки. Потім оберіть .zip тут. Зашифровані резервні копії імпортувати не можна. + Вкладення, закріплення й архівація, кольори. Міткою стає перша мітка, а якщо її немає, то блокнот. Markdown і текст Файли .md і .txt або ціла папка, наприклад з Obsidian чи Markor - Оберіть файли або папку з ними. Назва файлу стає заголовком; простий front matter (заголовок, теги, дати) читається. - Зображення, вкладення, плагіни та форматування, крім заголовків, списків, чеклістів і цитат. Тегом стає перша папка. + Оберіть файли або папку з ними. Назва файлу стає заголовком; простий front matter (заголовок, мітки, дати) читається. + Зображення, вкладення, плагіни та форматування, крім заголовків, списків, чеклістів і цитат. Міткою стає перша папка. Читаємо й розпізнаємо ваші файли… Готово до імпорту Розпізнано: %1$s · %2$s Позначені нотатки буде додано до цього сховища. Нічого не замінюється, а те, що вже є, пропускається. Нотаток зі списками завдань: %1$d - Тегів: %1$d + Міток: %1$d Нотаток, що підуть у кошик: %1$d Уже є в цьому сховищі, пропущено: %1$d Повторюється у вашому виборі, пропущено: %1$d diff --git a/core/resources/src/commonMain/strings/values-uk/strings_security.xml b/core/resources/src/commonMain/strings/values-uk/strings_security.xml index 7ea63052..31a1c65b 100644 --- a/core/resources/src/commonMain/strings/values-uk/strings_security.xml +++ b/core/resources/src/commonMain/strings/values-uk/strings_security.xml @@ -9,8 +9,8 @@ У цій копії: %1$s, %2$s і %3$s. Усе, що тут є, залишиться, а відсутнє додасться. Те, що вже є, буде пропущено. Замінити все - Видалити всі нотатки, завдання й теги на цьому телефоні, а потім відновити копію. - Збережіть усі нотатки, завдання й теги в одному зашифрованому файлі та відновіть їх на будь-якому телефоні. + Видалити всі нотатки, завдання й мітки на цьому телефоні, а потім відновити копію. + Збережіть усі нотатки, завдання й мітки в одному зашифрованому файлі та відновіть їх на будь-якому телефоні. Експорт Імпорт Ваші нотатки зашифровано. Їх відкриває ваш PIN (і відбиток пальця, якщо ввімкнено). @@ -36,10 +36,10 @@ %d завдання - %d тег - %d теги - %d тегів - %d тега + %d мітка + %d мітки + %d міток + %d мітки Ваш PIN більше не може розблокувати Encly на цьому телефоні: його апаратний ключ скинуто. Скористайтеся фразою відновлення (або відбитком пальця), а потім задайте новий PIN. diff --git a/core/resources/src/commonMain/strings/values/strings.xml b/core/resources/src/commonMain/strings/values/strings.xml index d8164da3..6f1af35a 100644 --- a/core/resources/src/commonMain/strings/values/strings.xml +++ b/core/resources/src/commonMain/strings/values/strings.xml @@ -717,6 +717,12 @@ What\'s new The changes in this version Got it + The trash now empties itself + + The trash now deletes notes for good after 28 days. It holds %d note: it will be deleted 28 days after this update, unless you restore it. + The trash now deletes notes for good after 28 days. It holds %d notes: they will be deleted 28 days after this update, unless you restore them. + + Open trash How long can my PIN be? Between 6 and 12 digits, your choice. Shorter PINs are not offered: the lockout and the device key limit how many guesses anyone gets, and 6 digits is the shortest that stays safe with those limits. The lock screen never shows how long your PIN is: you press Unlock when you are done, and the same goes for the wipe PIN and the duress PIN. PINs you set before this option keep working as they are. Code diff --git a/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/AuthenticationEdgeCasesTest.kt b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/AuthenticationEdgeCasesTest.kt index f7971802..611e1db8 100644 --- a/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/AuthenticationEdgeCasesTest.kt +++ b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/AuthenticationEdgeCasesTest.kt @@ -148,6 +148,31 @@ class AuthenticationEdgeCasesTest { assertEquals(PinChange.FAILED, manager.changePin(NEW_PIN.toCharArray(), dek)) } + @Test + fun aPinChangeThatIsCancelledAfterTheCurrentPinWasCheckedLeavesTheOldPinWorking() { + // The change starts by checking the current PIN; the user then backs out and nothing is stored. + assertTrue(auth.verifyPinAuth(PIN.toCharArray())) + + val unlocked = auth.unlockWithPin(PIN.toCharArray()) + assertTrue(unlocked is PinUnlock.Success) + (unlocked as PinUnlock.Success).dek.fill(0) + assertEquals(PinUnlock.WrongPin, auth.unlockWithPin(NEW_PIN.toCharArray())) + } + + @Test + fun aPinChangeThatFailsToStoreLeavesTheOldPinWorking() { + val failingStore = tempVaultStore() + val manager = AuthenticationManager(failingStore, FakePinFactor(), FakeLockoutClock()) + assertTrue(manager.configurePin(PIN.toCharArray(), dek)) + failingStore.beforeRename = { throw java.io.IOException("disk full") } + + assertEquals(PinChange.FAILED, manager.changePin(NEW_PIN.toCharArray(), dek)) + failingStore.beforeRename = null + + assertEquals(PinUnlock.WrongPin, manager.unlockWithPin(NEW_PIN.toCharArray())) + assertTrue(manager.unlockWithPin(PIN.toCharArray()) is PinUnlock.Success) + } + // --- the wipe's progress marker and the retired key ------------------------------------- @Test diff --git a/desktopApp/packaging/flatpak/io.github.pasichdev.Encly.metainfo.xml b/desktopApp/packaging/flatpak/io.github.pasichdev.Encly.metainfo.xml index e468c255..00263daf 100644 --- a/desktopApp/packaging/flatpak/io.github.pasichdev.Encly.metainfo.xml +++ b/desktopApp/packaging/flatpak/io.github.pasichdev.Encly.metainfo.xml @@ -41,6 +41,7 @@ keyboard + diff --git a/desktopApp/src/desktopMain/kotlin/com/pasich/encly/desktop/DesktopApp.kt b/desktopApp/src/desktopMain/kotlin/com/pasich/encly/desktop/DesktopApp.kt index 7622a735..44aa914d 100644 --- a/desktopApp/src/desktopMain/kotlin/com/pasich/encly/desktop/DesktopApp.kt +++ b/desktopApp/src/desktopMain/kotlin/com/pasich/encly/desktop/DesktopApp.kt @@ -7,7 +7,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf @@ -20,6 +19,7 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModelStore import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import androidx.navigation.NavHostController import com.pasich.encly.core.security.InitialStatus @@ -96,7 +96,7 @@ fun DesktopApp( DesktopHostServices(graph, appWindow, services) { // There is no Activity to recreate when the language changes: a new key makes every screen read its // strings again. - val revision by graph.locales.revision.collectAsState() + val revision by graph.locales.revision.collectAsStateWithLifecycle() // The place the user is at survives the rebuild: the replaced controller's back stack goes to the new one // (same entries, so the same ViewModels), instead of the window starting over from the launch-time status. val controllerOfWindow = remember { NavControllerOfWindow() } diff --git a/desktopApp/src/desktopMain/kotlin/com/pasich/encly/desktop/window/WindowHost.kt b/desktopApp/src/desktopMain/kotlin/com/pasich/encly/desktop/window/WindowHost.kt index bb49d26c..d3cdd059 100644 --- a/desktopApp/src/desktopMain/kotlin/com/pasich/encly/desktop/window/WindowHost.kt +++ b/desktopApp/src/desktopMain/kotlin/com/pasich/encly/desktop/window/WindowHost.kt @@ -7,7 +7,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf @@ -33,6 +32,7 @@ import androidx.compose.ui.window.Window import androidx.compose.ui.window.WindowPlacement import androidx.compose.ui.window.WindowPosition import androidx.compose.ui.window.rememberWindowState +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.locale.AppLanguage import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.about @@ -289,7 +289,7 @@ private fun ApplicationScope.EnclyWindow( // The menu titles are read when the bar is composed: a new language needs a new bar (the app below is keyed // on the same revision, see DesktopApp). - val languageRevision by graph.locales.revision.collectAsState() + val languageRevision by graph.locales.revision.collectAsStateWithLifecycle() key(languageRevision) { EnclyMenuBar(os, shortcuts, commands, session) } val appWindow = remember(composeWindow) { @@ -391,7 +391,7 @@ private fun FrameWindowScope.EnclyMenuBar( commands: DesktopCommands, session: WindowSession, ) { - val noteOpen by session.services.navigation.editorOpen.collectAsState() + val noteOpen by session.services.navigation.editorOpen.collectAsStateWithLifecycle() MenuBar { FileMenu(os, shortcuts, commands, noteOpen) ViewMenu(commands) diff --git a/editor/src/androidHostTest/kotlin/com/pasich/encly/editor/ui/blocks/ChecklistLayoutTest.kt b/editor/src/androidHostTest/kotlin/com/pasich/encly/editor/ui/blocks/ChecklistLayoutTest.kt index a4e39eee..d27bf630 100644 --- a/editor/src/androidHostTest/kotlin/com/pasich/encly/editor/ui/blocks/ChecklistLayoutTest.kt +++ b/editor/src/androidHostTest/kotlin/com/pasich/encly/editor/ui/blocks/ChecklistLayoutTest.kt @@ -211,6 +211,21 @@ class ChecklistLayoutTest { assertEquals(1, offsets.map { Math.round(it) }.toSet().size, offsets.toString()) } + @Test + fun theGapDoesNotChangeWhenTheListGrowsToTenItemsAndBack() { + start("a") + show(EditorLineSpacing.DEFAULT, 16) + val density = rule.density.density + for (count in listOf(9, 10, 11, 9)) { + block.items.value = List(count) { ItemListBlock("item $it") } + rule.waitForIdle() + val box = rule.onAllNodesWithTag(CHECK_BOX_TAG, useUnmergedTree = true).fetchSemanticsNodes() + .first().boundsInRoot + val field = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes().first().boundsInRoot + assertEquals(markerGap(fontDp).value * density, field.left - box.right, 1f, "$count items") + } + } + @Test fun aCheckedItemIsStruckByTheFieldNotByATextDecorationAComposingWordCouldReplace() { start("done") diff --git a/editor/src/commonMain/kotlin/com/pasich/encly/editor/ui/blocks/ListBlock.kt b/editor/src/commonMain/kotlin/com/pasich/encly/editor/ui/blocks/ListBlock.kt index 67434724..3c67d6b4 100644 --- a/editor/src/commonMain/kotlin/com/pasich/encly/editor/ui/blocks/ListBlock.kt +++ b/editor/src/commonMain/kotlin/com/pasich/encly/editor/ui/blocks/ListBlock.kt @@ -319,7 +319,8 @@ private fun RegisterItem( @Composable private fun rememberListMarker(type: BlockType, count: Int): ListMarker { val font = listFontDp() - val wide = font * (if (count >= WIDE_MARKER_FROM) WIDE_MARKER_EXTRA else 0f) + // Only a numbered list has two-digit markers: a checkbox's or bullet's gap must not change as items are added. + val wide = font * (if (type == BlockType.LIST_NUMBER && count >= WIDE_MARKER_FROM) WIDE_MARKER_EXTRA else 0f) val metrics = rememberLineMetrics() return remember(type, font, wide, metrics) { ListMarker( diff --git a/editor/src/commonTest/kotlin/com/pasich/encly/editor/state/ListNestingTest.kt b/editor/src/commonTest/kotlin/com/pasich/encly/editor/state/ListNestingTest.kt index 92739e66..c88658d2 100644 --- a/editor/src/commonTest/kotlin/com/pasich/encly/editor/state/ListNestingTest.kt +++ b/editor/src/commonTest/kotlin/com/pasich/encly/editor/state/ListNestingTest.kt @@ -409,6 +409,45 @@ class ListNestingTest { assertEquals(listOf(null, null), converted.items.value.map { it.kind }) } + @Test + fun theChecklistToolOnAnEmptyTopItemConvertsTheWholeListAsItDoesOnAnItemWithText() { + fun converted(itemText: String): Block.ListBlock { + val list = list(BlockType.LIST_BULLET, row("a"), row(itemText), row("c")) + val editor = BlockEditorState { 0L } + editor.load(listOf(list)) + editor.selection.onFocused(list.id) + editor.selection.onItemCaret(list.id, list.items.value[1].id, 0) + editor.applyTool(BlockType.LIST_CHECK) + return editor.blocks.single() as Block.ListBlock + } + + val withText = converted("b") + val empty = converted("") + + assertEquals(BlockType.LIST_CHECK, withText.blockType) + assertEquals(BlockType.LIST_CHECK, empty.blockType) + assertEquals(listOf("a", "", "c"), empty.items.value.map { it.value }) + assertEquals(listOf(null, null, null), empty.items.value.map { it.kind }) + } + + @Test + fun theChecklistToolOnAnEmptyNestedItemSetsOnlyItsSubListAsItDoesOnAnItemWithText() { + fun checkKinds(itemText: String): List { + val list = list(BlockType.LIST_BULLET, row("a"), row(itemText, 1), row("c", 1), row("d")) + editor.load(listOf(list)) + editor.selection.onFocused(list.id) + editor.selection.onItemCaret(list.id, list.items.value[1].id, 0) + editor.applyTool(BlockType.LIST_CHECK) + assertTrue(editor.blocks.single() === list) + assertEquals(BlockType.LIST_BULLET, list.blockType) + return list.items.value.map { it.kind } + } + + val check = BlockType.LIST_CHECK + assertEquals(listOf(null, check, check, null), checkKinds("b")) + assertEquals(listOf(null, check, check, null), checkKinds("")) + } + // --- the item the toolbar acts on ------------------------------------------------------------- @Test diff --git a/fastlane/metadata/android/ar/changelogs/30001.txt b/fastlane/metadata/android/ar/changelogs/30001.txt new file mode 100644 index 00000000..8ce3778d --- /dev/null +++ b/fastlane/metadata/android/ar/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• التغييرات التي تضعف الحماية (قفل تلقائي أطول، إيقاف لوحة المفاتيح الصارمة، معاينات الملاحظات، البصمة) تطلب الآن رمز PIN أولًا. +• قائمة الملاحظة أسهل مع TalkBack: مساحات أكبر للوسوم وتأكيد حذف واضح. +• تنبيه لمرة واحدة لمن يحدّث من 2.x: سلة المحذوفات تُفرَّغ الآن تلقائيًا بعد 28 يومًا. +• مسافة ثابتة بين خانة الاختيار أو النقطة والنص في القوائم الطويلة. diff --git a/fastlane/metadata/android/de-DE/changelogs/30001.txt b/fastlane/metadata/android/de-DE/changelogs/30001.txt new file mode 100644 index 00000000..3517bbc3 --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Änderungen, die den Schutz schwächen (längere Auto-Sperre, strenge Tastatur aus, Notizvorschau, Biometrie), fragen jetzt zuerst nach der PIN. +• Notiz-Menü mit TalkBack besser nutzbar: größere Label-Flächen, klare Löschbestätigung. +• Einmaliger Hinweis beim Update von 2.x: Der Papierkorb leert sich jetzt nach 28 Tagen selbst. +• Gleichmäßiger Abstand zwischen Kästchen oder Punkt und Text in langen Listen. diff --git a/fastlane/metadata/android/en-US/changelogs/30001.txt b/fastlane/metadata/android/en-US/changelogs/30001.txt new file mode 100644 index 00000000..5dc10184 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Changes that weaken security (longer auto-lock, strict keyboard off, note previews, biometric unlock) now ask for your PIN first. +• Note sheet works with TalkBack: bigger tag targets, clear delete confirmation. +• One-time notice for people updating from 2.x: the trash now empties itself after 28 days. +• Even gap between a checkbox or bullet and its text in long lists. diff --git a/fastlane/metadata/android/es-ES/changelogs/30001.txt b/fastlane/metadata/android/es-ES/changelogs/30001.txt new file mode 100644 index 00000000..9a0796c0 --- /dev/null +++ b/fastlane/metadata/android/es-ES/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Los ajustes que debilitan la protección (bloqueo automático más largo, teclado estricto desactivado, vistas previas, biometría) piden primero tu PIN. +• La hoja de la nota funciona mejor con TalkBack: etiquetas más grandes y confirmación de borrado clara. +• Aviso único para quien actualiza desde la 2.x: la papelera ahora se vacía sola a los 28 días. +• Espacio uniforme entre la casilla o viñeta y su texto en listas largas. diff --git a/fastlane/metadata/android/fr-FR/changelogs/30001.txt b/fastlane/metadata/android/fr-FR/changelogs/30001.txt new file mode 100644 index 00000000..c1c78d62 --- /dev/null +++ b/fastlane/metadata/android/fr-FR/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Les réglages qui affaiblissent la protection (verrouillage plus long, clavier strict désactivé, aperçus des notes, biométrie) demandent d'abord votre PIN. +• Le menu de la note est plus accessible avec TalkBack : zones de libellés plus grandes, confirmation de suppression claire. +• Avis unique pour ceux qui passent de la 2.x : la corbeille se vide désormais seule après 28 jours. +• Espace constant entre la case ou la puce et son texte dans les longues listes. diff --git a/fastlane/metadata/android/it-IT/changelogs/30001.txt b/fastlane/metadata/android/it-IT/changelogs/30001.txt new file mode 100644 index 00000000..c3ce2eee --- /dev/null +++ b/fastlane/metadata/android/it-IT/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Le impostazioni che riducono la protezione (blocco automatico più lungo, tastiera rigorosa disattivata, anteprime, biometria) chiedono prima il PIN. +• Il menu della nota funziona meglio con TalkBack: etichette più grandi e conferma di eliminazione chiara. +• Avviso una tantum per chi aggiorna dalla 2.x: il cestino ora si svuota da solo dopo 28 giorni. +• Spazio uniforme tra casella o punto elenco e testo nelle liste lunghe. diff --git a/fastlane/metadata/android/nl-NL/changelogs/30001.txt b/fastlane/metadata/android/nl-NL/changelogs/30001.txt new file mode 100644 index 00000000..a7dffb1f --- /dev/null +++ b/fastlane/metadata/android/nl-NL/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Wijzigingen die de beveiliging verzwakken (langere automatische vergrendeling, strikt toetsenbord uit, notitievoorbeelden, biometrie) vragen eerst om je pincode. +• Het notitiemenu werkt beter met TalkBack: grotere labelvlakken, duidelijke verwijderbevestiging. +• Eenmalige melding bij updaten van 2.x: de prullenbak leegt zich nu na 28 dagen vanzelf. +• Gelijke ruimte tussen selectievakje of bolletje en tekst in lange lijsten. diff --git a/fastlane/metadata/android/pl-PL/changelogs/30001.txt b/fastlane/metadata/android/pl-PL/changelogs/30001.txt new file mode 100644 index 00000000..5b6565c7 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Zmiany osłabiające ochronę (dłuższa blokada, wyłączona ścisła klawiatura, podglądy notatek, biometria) najpierw proszą o PIN. +• Menu notatki działa lepiej z TalkBack: większe pola etykiet, czytelne potwierdzenie usunięcia. +• Jednorazowa informacja dla aktualizujących z 2.x: kosz sam się teraz opróżnia po 28 dniach. +• Stały odstęp między polem wyboru lub punktorem a tekstem w długich listach. diff --git a/fastlane/metadata/android/pt-PT/changelogs/30001.txt b/fastlane/metadata/android/pt-PT/changelogs/30001.txt new file mode 100644 index 00000000..bd9b4af0 --- /dev/null +++ b/fastlane/metadata/android/pt-PT/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• As definições que enfraquecem a proteção (bloqueio automático mais longo, teclado estrito desativado, pré-visualizações, biometria) pedem primeiro o PIN. +• A folha da nota funciona melhor com o TalkBack: etiquetas maiores e confirmação de eliminação clara. +• Aviso único para quem atualiza da 2.x: o lixo passa a esvaziar-se sozinho ao fim de 28 dias. +• Espaço uniforme entre a caixa ou o marcador e o texto em listas longas. diff --git a/fastlane/metadata/android/uk/changelogs/30001.txt b/fastlane/metadata/android/uk/changelogs/30001.txt new file mode 100644 index 00000000..5fc9703b --- /dev/null +++ b/fastlane/metadata/android/uk/changelogs/30001.txt @@ -0,0 +1,6 @@ +Encly 3.0.1 +• Зміни, що послаблюють захист (довше автоблокування, вимкнена сувора клавіатура, прев'ю нотаток, біометрія), тепер спершу просять PIN. +• Меню нотатки зручніше з TalkBack: більші цілі для міток, зрозуміле підтвердження видалення. +• Одноразове повідомлення для тих, хто оновлюється з 2.x: кошик тепер сам очищується через 28 днів. +• Однаковий відступ між прапорцем чи маркером і текстом у довгих списках. +• Скрізь «мітки» замість «теги». diff --git a/fastlane/metadata/desktop/en-US/changelogs/30001.txt b/fastlane/metadata/desktop/en-US/changelogs/30001.txt new file mode 100644 index 00000000..cab409de --- /dev/null +++ b/fastlane/metadata/desktop/en-US/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• The first release for Windows, macOS and Linux: encrypted notes and tasks, tags and a PIN of 6–12 digits. +• The PIN is mixed with a secret kept in your system's keychain; your notes never leave the computer. +• Changes that weaken security now ask for your PIN first. +• Encrypted backups with a 12-word recovery phrase, import from other note apps and export to PDF. diff --git a/fastlane/metadata/desktop/uk/changelogs/30001.txt b/fastlane/metadata/desktop/uk/changelogs/30001.txt new file mode 100644 index 00000000..2c31c8e3 --- /dev/null +++ b/fastlane/metadata/desktop/uk/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Перший випуск для Windows, macOS і Linux: зашифровані нотатки й завдання, мітки та PIN від 6 до 12 цифр. +• PIN змішується з секретом у системній в'язці ключів; нотатки не залишають комп'ютер. +• Зміни, що послаблюють захист, тепер спершу просять PIN. +• Зашифровані резервні копії з фразою відновлення з 12 слів, імпорт з інших застосунків для нотаток і експорт у PDF. diff --git a/fastlane/metadata/ios/en-US/changelogs/30001.txt b/fastlane/metadata/ios/en-US/changelogs/30001.txt new file mode 100644 index 00000000..1f0a7d59 --- /dev/null +++ b/fastlane/metadata/ios/en-US/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• The first release for iPhone and iPad: encrypted notes and tasks, tags, a PIN of 6–12 digits and Face ID / Touch ID unlock. +• The vault locks when you leave the app; your notes never leave the device. +• Changes that weaken security now ask for your PIN first. +• Encrypted backups with a 12-word recovery phrase, and import from other note apps. diff --git a/fastlane/metadata/ios/uk/changelogs/30001.txt b/fastlane/metadata/ios/uk/changelogs/30001.txt new file mode 100644 index 00000000..ac85cdae --- /dev/null +++ b/fastlane/metadata/ios/uk/changelogs/30001.txt @@ -0,0 +1,5 @@ +Encly 3.0.1 +• Перший випуск для iPhone та iPad: зашифровані нотатки й завдання, мітки, PIN від 6 до 12 цифр і розблокування через Face ID / Touch ID. +• Сховище блокується, коли ви виходите з застосунку; нотатки не залишають пристрій. +• Зміни, що послаблюють захист, тепер спершу просять PIN. +• Зашифровані резервні копії з фразою відновлення з 12 слів та імпорт з інших застосунків для нотаток. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 6615856a..571643d7 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,7 +5,7 @@ [versions] agp = "9.5.1" kotlin = "2.4.21" -ksp = "2.3.13" +ksp = "2.3.14" metro = "1.6.0" detekt = "1.23.8" kover = "0.9.11" @@ -39,7 +39,8 @@ datetime = "0.8.0" kotlinxIo = "0.9.3" # SynchronizedObject and synchronized {} for common code (the locks of :core:security); the Gradle plugin is not used. atomicfu = "0.33.0" -sqlcipher = "4.20.0" +# What 2.3.1 shipped; used only by the device tests that write a vault the way 2.3 did (the app itself uses Sealite). +sqlcipher = "4.19.1" sealite = "1.0.1" sqliteKtx = "2.7.1" iconsLucide = "1.1.0" diff --git a/shared/src/androidHostTest/kotlin/com/pasich/encly/presentation/dialogs/NoteCardBottomSheetTest.kt b/shared/src/androidHostTest/kotlin/com/pasich/encly/presentation/dialogs/NoteCardBottomSheetTest.kt index 4a89b23c..9a72299f 100644 --- a/shared/src/androidHostTest/kotlin/com/pasich/encly/presentation/dialogs/NoteCardBottomSheetTest.kt +++ b/shared/src/androidHostTest/kotlin/com/pasich/encly/presentation/dialogs/NoteCardBottomSheetTest.kt @@ -3,6 +3,7 @@ package com.pasich.encly.presentation.dialogs import androidx.activity.ComponentDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.remember +import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher @@ -21,6 +22,7 @@ import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.unit.dp import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.back import com.pasich.encly.core.resources.delete @@ -39,6 +41,7 @@ import com.pasich.encly.core.resources.note_tags_more import com.pasich.encly.core.resources.note_unarchive import com.pasich.encly.core.resources.note_unpin import com.pasich.encly.core.resources.save +import com.pasich.encly.core.resources.tag_hidden import com.pasich.encly.core.resources.tap_again_to_delete import com.pasich.encly.core.resources.task_description_placeholder import com.pasich.encly.core.resources.untitled @@ -59,6 +62,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Test import org.robolectric.shadows.ShadowDialog @@ -214,6 +218,46 @@ class NoteCardBottomSheetTest : ComposeScreenTest() { assertEquals(listOf(NoteAction.Delete), actions) } + @Test + fun anArmedDeleteTileIsALiveRegionSoTalkBackSpeaksTheNewLabel() { + show() + rule.onNodeWithText(str(Res.string.delete)).performClick() + rule.waitForIdle() + + rule.onNode(hasText(str(Res.string.tap_again_to_delete))) + .assert(SemanticsMatcher.expectValue(SemanticsProperties.LiveRegion, LiveRegionMode.Polite)) + } + + @Test + fun aTagChipHasAtLeastA48DpTouchTarget() { + show() + + // The pill stays 36 dp; the touch bounds around it are the 48 dp minimum. + val touch = rule.onNode(hasText("Work") and isOff()).fetchSemanticsNode().touchBoundsInRoot + val minimum = with(rule.density) { 48.dp.toPx() } + assertTrue("chip touch target is ${touch.height}px, needs $minimum", touch.height >= minimum - 1f) + } + + @Test + fun aHiddenTagChipIsMarkedHiddenAndAPlainOneIsNot() { + show(allTags = listOf(Tag(id = 1, nameTag = "Work"), Tag(id = 2, nameTag = "Secret", isVisible = false))) + + rule.onNode(hasText("Secret")) + .assert(SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, str(Res.string.tag_hidden))) + rule.onNode(hasText("Work")) + .assert(SemanticsMatcher.keyNotDefined(SemanticsProperties.StateDescription)) + } + + @Test + fun theSectionTitlesAreHeadings() { + show() + + rule.onNode(hasText(str(Res.string.main_drawer_tags).uppercase())) + .assert(SemanticsMatcher.keyIsDefined(SemanticsProperties.Heading)) + rule.onNode(hasText(str(Res.string.note_color_title).uppercase())) + .assert(SemanticsMatcher.keyIsDefined(SemanticsProperties.Heading)) + } + @Test fun aColourSwatchAppliesAtOnceAndKeepsTheSheetOpen() { show() diff --git a/shared/src/androidHostTest/kotlin/com/pasich/encly/presentation/viewmodel/BackupViewModelTest.kt b/shared/src/androidHostTest/kotlin/com/pasich/encly/presentation/viewmodel/BackupViewModelTest.kt index 4fc1af87..974128db 100644 --- a/shared/src/androidHostTest/kotlin/com/pasich/encly/presentation/viewmodel/BackupViewModelTest.kt +++ b/shared/src/androidHostTest/kotlin/com/pasich/encly/presentation/viewmodel/BackupViewModelTest.kt @@ -5,6 +5,7 @@ import com.pasich.encly.core.resources.backup_error_no_picker import com.pasich.encly.core.resources.backup_phrase_exists import com.pasich.encly.core.resources.lock_wrong_pin import com.pasich.encly.core.resources.security_erase_failed +import com.pasich.encly.core.security.AutoLockDelay import com.pasich.encly.core.security.ScreenshotAllowance import com.pasich.encly.core.security.SecurityManager import com.pasich.encly.core.security.SessionLockManager @@ -265,6 +266,105 @@ class BackupViewModelTest { assertFalse(screenshots.allowed.value) } + @Test + fun aWeakeningChangeAsksForThePinAndAppliesOnlyAfterTheRightOne() { + `when`(security.verifyPin(anyCharArray())).thenReturn(false) + var applied = 0 + viewModel.changeAutoLock(AutoLockDelay.SECONDS_15, AutoLockDelay.MINUTE_1) { applied++ } + assertEquals(BackupStep.Reauth(BackupAction.CONFIRM_SETTING, biometric = false), viewModel.uiState.value.step) + assertEquals(0, applied) + + // A wrong PIN keeps the old value. + viewModel.reauthFlow.submitPin("111111".toCharArray()) + waitForStep { it is BackupStep.Reauth && it.error != null } + assertEquals(0, applied) + + `when`(security.verifyPin(anyCharArray())).thenReturn(true) + viewModel.reauthFlow.submitPin("123456".toCharArray()) + + waitForStep { it == BackupStep.Idle } + assertEquals(1, applied) + } + + @Test + fun cancellingAWeakeningChangeKeepsTheOldValue() { + `when`(security.verifyPin(anyCharArray())).thenReturn(true) + var applied = 0 + viewModel.changeStrictKeyboard(strict = false) { applied++ } + + viewModel.cancel() + // A later PIN entry for another flow must not release the dropped change. + viewModel.start(BackupAction.ALLOW_SCREENSHOTS) + viewModel.reauthFlow.submitPin("123456".toCharArray()) + waitForStep { it == BackupStep.Idle } + + assertEquals(0, applied) + } + + @Test + fun aLockBetweenTheRequestAndThePinDiscardsTheChange() { + `when`(security.isLockable()).thenReturn(true) + `when`(security.isDatabaseUnlocked()).thenReturn(true) + `when`(security.verifyPin(anyCharArray())).thenAnswer { + sessionLock.lockNow() + true + } + var applied = 0 + viewModel.changeNotePreviews(show = true) { applied++ } + + viewModel.reauthFlow.submitPin("123456".toCharArray()) + + waitForStep { it == BackupStep.Idle } + assertTrue(sessionLock.locked.value) + assertEquals(0, applied) + } + + @Test + fun aLockWhileTheDialogIsOpenDropsTheChange() { + `when`(security.isLockable()).thenReturn(true) + `when`(security.isDatabaseUnlocked()).thenReturn(true) + var applied = 0 + viewModel.changeNotePreviews(show = true) { applied++ } + + sessionLock.lockNow() + assertEquals(BackupStep.Idle, viewModel.uiState.value.step) + + `when`(security.verifyPin(anyCharArray())).thenReturn(true) + viewModel.start(BackupAction.ALLOW_SCREENSHOTS) + viewModel.reauthFlow.submitPin("123456".toCharArray()) + waitForStep { it == BackupStep.Idle } + assertEquals(0, applied) + } + + @Test + fun strengtheningChangesApplyAtOnceWithoutAPrompt() { + viewModel.cancel() + var applied = 0 + + viewModel.changeAutoLock(AutoLockDelay.MINUTE_1, AutoLockDelay.SECONDS_15) { applied++ } + viewModel.changeAutoLock(AutoLockDelay.MINUTE_1, AutoLockDelay.MINUTE_1) { applied++ } + viewModel.changeStrictKeyboard(strict = true) { applied++ } + viewModel.changeNotePreviews(show = false) { applied++ } + viewModel.changeBiometric(enable = false) { applied++ } + + assertEquals(5, applied) + assertEquals(BackupStep.Idle, viewModel.uiState.value.step) + } + + @Test + fun enablingBiometricAsksForThePinBeforeTheEnrolment() { + `when`(security.verifyPin(anyCharArray())).thenReturn(true) + var enrolled = 0 + viewModel.changeBiometric(enable = true) { enrolled++ } + assertEquals(0, enrolled) + assertEquals(BackupStep.Reauth(BackupAction.CONFIRM_SETTING, biometric = false), viewModel.uiState.value.step) + + viewModel.reauthFlow.submitPin("123456".toCharArray()) + + waitForStep { it == BackupStep.Idle } + assertEquals(1, enrolled) + } + @Test fun aRefusedEraseIsReportedAsFailed() { `when`(security.verifyPin(anyCharArray())).thenReturn(true) diff --git a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/EnclyAppFreshStartTest.kt b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/EnclyAppFreshStartTest.kt new file mode 100644 index 00000000..57d7c92e --- /dev/null +++ b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/EnclyAppFreshStartTest.kt @@ -0,0 +1,102 @@ +package com.pasich.encly.ui.screens + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performTouchInput +import androidx.lifecycle.ViewModel +import androidx.navigation.NavHostController +import com.pasich.encly.core.resources.Res +import com.pasich.encly.core.resources.loss_hold_to_wipe +import com.pasich.encly.core.security.InitialStatus +import com.pasich.encly.platform.AppInfo +import com.pasich.encly.presentation.navigation.EnclyApp +import com.pasich.encly.presentation.navigation.NavRoutes +import com.pasich.encly.presentation.viewmodel.LossRecoveryViewModel +import com.pasich.encly.presentation.viewmodel.ThemeViewModel +import com.pasich.encly.testutil.InMemoryKeyValueStore +import com.pasich.encly.whatsnew.WhatsNewTracker +import dev.zacsweers.metrox.viewmodel.LocalMetroViewModelFactory +import dev.zacsweers.metrox.viewmodel.MetroViewModelFactory +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.mockito.Mockito.`when` +import kotlin.reflect.KClass + +/** + * What the app root tells the version tracker. "Erase all data" and the loss-recovery wipe clear the recorded + * version and go back to onboarding in the same process: the vault made there is new, so it must not get + * "What's new" and the trash notice that an update from 2.x gets. + */ +class EnclyAppFreshStartTest : ComposeScreenTest() { + private val app by lazy { TestApp() } + + /** What a wipe leaves: a vault that was installed, with no version recorded. */ + private val clearedFlags = WhatsNewTracker(InMemoryKeyValueStore(), AppInfo.Default) + + private var controller: NavHostController? = null + + private fun route() = rule.runOnIdle { controller?.currentBackStackEntry?.destination?.route } + + private class Prebuilt(vararg viewModels: ViewModel) : MetroViewModelFactory() { + override val viewModelProviders: Map, () -> ViewModel> = + viewModels.associate { it::class to { it } } + } + + /** The app started on the damaged-vault screen: a vault that exists, so not a fresh install. */ + private fun showDamagedVault() { + `when`(app.security.isDatabaseUnlocked()).thenReturn(false) + `when`(app.security.hasRecoverySeed()).thenReturn(true) + val factory = Prebuilt( + ThemeViewModel(app.settings), + app.lock(), + *app.home(), + app.editor(), + app.markdownExport(), + app.onboarding(), + app.authSetup(), + app.startup(clearedFlags), + LossRecoveryViewModel(app.security), + ) + rule.setContent { + CompositionLocalProvider(LocalMetroViewModelFactory provides factory) { + EnclyApp(InitialStatus.LOSS_DATABASE, app.security, app.sessionLock, onNavController = { + controller = it + }) + } + } + rule.waitForIdle() + } + + private fun holdToWipe() { + val button = rule.onNodeWithText(str(Res.string.loss_hold_to_wipe)) + button.performTouchInput { down(center) } + rule.mainClock.advanceTimeBy(HOLD_MS + 500) + rule.waitForIdle() + } + + @Test + fun aVaultMadeAfterAWipeInTheSameProcessIsNotToldItWasUpdated() { + showDamagedVault() + holdToWipe() + + waitFor { route() == NavRoutes.OnboardingRoute.name } + assertNull(clearedFlags.takeUpdate()) + } + + @Test + fun anExistingVaultWithNoVersionRecordedIsStillToldItWasUpdatedFromBeforeTheTrashRetention() { + showDamagedVault() + + assertEquals(NavRoutes.LossDataRoute.name, route()) + val update = clearedFlags.takeUpdate() + assertNotNull(update) + assertTrue(update!!.fromBeforeTrashRetention) + } + + private companion object { + const val HOLD_MS = 4_000L + } +} diff --git a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/EnclyAppTest.kt b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/EnclyAppTest.kt index 534304f8..42319a6e 100644 --- a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/EnclyAppTest.kt +++ b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/EnclyAppTest.kt @@ -2,12 +2,15 @@ package com.pasich.encly.ui.screens import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.lifecycle.ViewModel import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.empty_notes import com.pasich.encly.core.resources.lock_title import com.pasich.encly.core.resources.main_drawer_settings +import com.pasich.encly.core.resources.note_add +import com.pasich.encly.core.resources.note_title_placeholder import com.pasich.encly.core.resources.settings_language import com.pasich.encly.core.security.InitialStatus import com.pasich.encly.presentation.navigation.EnclyApp @@ -35,7 +38,8 @@ class EnclyAppTest : ComposeScreenTest() { private fun show(status: InitialStatus?, unlocked: Boolean = true) { `when`(app.security.isDatabaseUnlocked()).thenReturn(unlocked) `when`(app.security.hasRecoverySeed()).thenReturn(true) - val factory = Prebuilt(ThemeViewModel(app.settings), app.lock(), *app.home()) + val factory = + Prebuilt(ThemeViewModel(app.settings), app.lock(), app.editor(), app.markdownExport(), *app.home()) rule.setContent { CompositionLocalProvider(LocalMetroViewModelFactory provides factory) { EnclyApp(status, app.security, app.sessionLock) @@ -48,6 +52,8 @@ class EnclyAppTest : ComposeScreenTest() { private fun onHome() = countText(str(Res.string.empty_notes)) > 0 + private fun onEditor() = countText(str(Res.string.note_title_placeholder)) > 0 + @Test fun anOpenVaultStartsOnHome() { show(InitialStatus.MAIN) @@ -93,4 +99,30 @@ class EnclyAppTest : ComposeScreenTest() { waitFor { onLockScreen() } assertEquals(0, countText(str(Res.string.settings_language))) } + + @Test + fun aLockWhileTheEditorIsOpenReplacesItWithTheLockScreen() { + show(InitialStatus.MAIN) + waitFor { onHome() } + rule.onNodeWithText(str(Res.string.note_add), useUnmergedTree = true).performClick() + waitFor { onEditor() } + + rule.runOnIdle { app.sessionLock.requireUnlock() } + + waitFor { onLockScreen() } + assertEquals(0, countText(str(Res.string.note_title_placeholder))) + } + + @Test + fun aLockWhileASettingsScreenIsOpenReplacesItWithTheLockScreen() { + show(InitialStatus.MAIN) + waitFor { onHome() } + rule.onNodeWithContentDescription(str(Res.string.main_drawer_settings)).performClick() + waitForText(str(Res.string.settings_language)) + + rule.runOnIdle { app.sessionLock.requireUnlock() } + + waitFor { onLockScreen() } + assertEquals(0, countText(str(Res.string.settings_language))) + } } diff --git a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/NotePreviewsTest.kt b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/NotePreviewsTest.kt index d4c8f6d4..f973c974 100644 --- a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/NotePreviewsTest.kt +++ b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/NotePreviewsTest.kt @@ -11,6 +11,8 @@ import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo import androidx.compose.ui.test.performTextInput import com.pasich.encly.core.resources.Res +import com.pasich.encly.core.resources.backup_reauth_title +import com.pasich.encly.core.resources.cancel import com.pasich.encly.core.resources.security_previews_title import com.pasich.encly.data.model.Note import com.pasich.encly.data.model.NoteWithTags @@ -23,10 +25,12 @@ import com.pasich.encly.presentation.components.tiles.NoteItem import com.pasich.encly.presentation.navigation.NavRoutes import com.pasich.encly.presentation.screen.MainRootScreen import com.pasich.encly.presentation.screen.settings.SecuritySettingsScreen +import com.pasich.encly.testutil.anyCharArray import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test +import org.mockito.Mockito.`when` /** "Show note previews": off, a card is the title, tag and date; search still reads the whole note. */ class NotePreviewsTest : ComposeScreenTest() { @@ -124,7 +128,8 @@ class NotePreviewsTest : ComposeScreenTest() { } @Test - fun theSecuritySwitchTurnsPreviewsOffAndOn() { + fun theSecuritySwitchHidesPreviewsAtOnceAndShowingThemAsksForThePin() { + `when`(app.security.verifyPin(anyCharArray())).thenReturn(true) setNavScreen( viewModels(app.securitySettings(), app.notePreviewsVm(), app.toolbarVm(), app.backup()), route = NavRoutes.SecuritySettingsRoute.name, @@ -135,8 +140,19 @@ class NotePreviewsTest : ComposeScreenTest() { rule.onNode(isToggleable() and hasText(title)).performScrollTo().performClick() waitFor { !app.notePreviews.show.value } + assertEquals(0, countText(str(Res.string.backup_reauth_title))) + // Showing them again asks first, and the switch keeps its value until the PIN is right. rule.onNode(isToggleable() and hasText(title)).performScrollTo().performClick() + waitForText(str(Res.string.backup_reauth_title)) + assertTrue(!app.notePreviews.show.value) + rule.onNodeWithText(str(Res.string.cancel)).performClick() + rule.waitForIdle() + assertTrue(!app.notePreviews.show.value) + + rule.onNode(isToggleable() and hasText(title)).performScrollTo().performClick() + waitForText(str(Res.string.backup_reauth_title)) + enterPin("123456") waitFor { app.notePreviews.show.value } } } diff --git a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/SecurityScreensTest.kt b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/SecurityScreensTest.kt index 4f96da08..9f59fb20 100644 --- a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/SecurityScreensTest.kt +++ b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/SecurityScreensTest.kt @@ -6,11 +6,13 @@ import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.hasText import androidx.compose.ui.test.isToggleable import androidx.compose.ui.test.onAllNodesWithContentDescription +import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.auth_method_pin_title import com.pasich.encly.core.resources.auto_lock_title +import com.pasich.encly.core.resources.back import com.pasich.encly.core.resources.backup_error_phrase_setup import com.pasich.encly.core.resources.backup_needs_phrase_title import com.pasich.encly.core.resources.backup_phrase_exists @@ -255,6 +257,21 @@ class SecurityScreensTest : ComposeScreenTest() { private fun biometricSwitch() = rule.onNode(isToggleable() and hasText(str(Res.string.security_biometric_title))) + @Test + fun cancellingAPinChangeAfterTheNewPinWasTypedStoresNothingAndKeepsTheOldPin() { + showPinChange() + + enterPin("123456") + waitForText(str(Res.string.pin_create_title)) + enterPin("654321") + waitForText(str(Res.string.pin_change_confirm_title)) + rule.onNodeWithContentDescription(str(Res.string.back)).performClick() + + waitFor { currentRoute() == NavRoutes.SecuritySettingsRoute.name } + // Only the current PIN was ever checked; the vault was never asked to change it. + verify(app.security, never()).changePin(anyCharArray()) + } + @Test fun aMismatchedConfirmationStartsTheNewPinAgain() { showPinChange() diff --git a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/TestApp.kt b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/TestApp.kt index daacaab7..a4972a7f 100644 --- a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/TestApp.kt +++ b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/TestApp.kt @@ -216,6 +216,7 @@ internal class TestApp { fun startup(tracker: WhatsNewTracker = freshInstall()) = StartupViewModel( tracker, PurgeExpiredTrashUseCase(notes, InMemoryKeyValueStore()), + notes, ) /** A tracker that has already recorded the version, as after the install: no "What's new" is due. */ diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/HomeTaskWidget.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/HomeTaskWidget.kt index 3e90e8b1..bde4a6ca 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/HomeTaskWidget.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/HomeTaskWidget.kt @@ -3,11 +3,11 @@ package com.pasich.encly.presentation.components import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.home_tasks_none_open import com.pasich.encly.core.resources.home_tasks_open @@ -38,7 +38,7 @@ fun HomeTaskWidget( onNewTask: () -> Unit = onTasksClick, viewModel: TasksViewModel = metroViewModel(), ) { - val uiState by viewModel.uiState.collectAsState() + val uiState by viewModel.uiState.collectAsStateWithLifecycle() val preview = remember(uiState.activeTasks) { widgetTasks(uiState.activeTasks) } // Nothing until the first read, so the card does not flash "none open" over real tasks. if (uiState.isLoading) return diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/editNote/NoteBottomBar.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/editNote/NoteBottomBar.kt index b7b1c69c..0bff8c67 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/editNote/NoteBottomBar.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/editNote/NoteBottomBar.kt @@ -18,7 +18,6 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -33,6 +32,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.block_duplicate import com.pasich.encly.core.resources.block_more_tools @@ -90,7 +90,7 @@ fun NoteBottomBar( ) { var showMore by rememberSaveable { mutableStateOf(false) } // Re-evaluated when the block the user works on or the blocks (their order) change. - val interactedBlockId by viewModel.interactedBlockId.collectAsState() + val interactedBlockId by viewModel.interactedBlockId.collectAsStateWithLifecycle() val activeTool by remember(viewModel) { derivedStateOf { viewModel.blocks.firstOrNull { it.id == interactedBlockId }?.toolType() } } @@ -98,7 +98,7 @@ fun NoteBottomBar( derivedStateOf { viewModel.blocks.firstOrNull { it.id == interactedBlockId }?.exactType() } } val checklistLock = rememberChecklistLock(viewModel, interactedBlockId) - val blockFocused = viewModel.focusedBlockId.collectAsState().value != null + val blockFocused = viewModel.focusedBlockId.collectAsStateWithLifecycle().value != null val anchor = rememberKeyboardAnchor() // A change that replaces the focused field runs inside the anchor, so the keyboard stays up. val keepingKeyboard: (() -> Unit) -> Unit = { change -> diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/editNote/ToolbarState.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/editNote/ToolbarState.kt index 0f203037..64e8a6d3 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/editNote/ToolbarState.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/editNote/ToolbarState.kt @@ -1,11 +1,11 @@ package com.pasich.encly.presentation.components.editNote import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.editor.model.Block import com.pasich.encly.editor.model.BlockType import com.pasich.encly.presentation.viewmodel.EditNoteViewModel @@ -15,8 +15,8 @@ import kotlinx.coroutines.flow.MutableStateFlow @Composable internal fun rememberHistoryTools(viewModel: EditNoteViewModel, keepingKeyboard: (() -> Unit) -> Unit): HistoryTools { - val canUndo by viewModel.canUndo.collectAsState() - val canRedo by viewModel.canRedo.collectAsState() + val canUndo by viewModel.canUndo.collectAsStateWithLifecycle() + val canRedo by viewModel.canRedo.collectAsStateWithLifecycle() return HistoryTools( onUndo = if (canUndo) ({ keepingKeyboard { viewModel.undo() } }) else null, onRedo = if (canRedo) ({ keepingKeyboard { viewModel.redo() } }) else null, @@ -76,7 +76,7 @@ internal fun rememberChecklistLock(viewModel: EditNoteViewModel, interactedBlock } } val lockState = remember(checklist) { checklist?.locked ?: MutableStateFlow(false) } - val locked by lockState.collectAsState() + val locked by lockState.collectAsStateWithLifecycle() return checklist?.let { list -> ChecklistLock(locked) { viewModel.toggleChecklistLock(list) } } } diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/tiles/TagItem.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/tiles/TagItem.kt index ac2c3a43..e261f778 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/tiles/TagItem.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/components/tiles/TagItem.kt @@ -3,8 +3,6 @@ package com.pasich.encly.presentation.components.tiles import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.semantics.stateDescription import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.tag_hidden import com.pasich.encly.data.model.Tag @@ -29,8 +27,7 @@ fun TagItem( selected = isSelected, count = count, onClick = onItemClick, - modifier = modifier - .alpha(if (item.isVisible) 1f else HIDDEN_TAG_ALPHA) - .semantics { if (!item.isVisible) stateDescription = hiddenLabel }, + stateDescription = if (item.isVisible) null else hiddenLabel, + modifier = modifier.alpha(if (item.isVisible) 1f else HIDDEN_TAG_ALPHA), ) } diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/designsystem/SheetTile.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/designsystem/SheetTile.kt index d39e39dc..2a70534a 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/designsystem/SheetTile.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/designsystem/SheetTile.kt @@ -26,7 +26,9 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics @@ -135,6 +137,8 @@ private fun SheetTileButton(tile: SheetTile, containerColor: Color, modifier: Mo .semantics { role = Role.Button if (tile.active) selected = true + // Arming only changes the label: a live region makes TalkBack speak it ("Tap again to delete"). + if (tile.confirmFirst) liveRegion = LiveRegionMode.Polite }, ) { Column( diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/designsystem/Surfaces.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/designsystem/Surfaces.kt index 066d263c..03f1ca97 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/designsystem/Surfaces.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/designsystem/Surfaces.kt @@ -18,6 +18,7 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -25,7 +26,9 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.unit.dp import com.pasich.encly.ui.theme.EnclyTheme @@ -126,7 +129,8 @@ fun EnclyCallout( * 1 dp `outlineVariant` border. [count] is shown after the label in the data style. * * With [leadsTo] the chip is not a toggle but a button that leads on (a "+N" chip that opens the full list): - * [leadsTo] is what it is read out as, in place of its label. + * [leadsTo] is what it is read out as, in place of its label. [stateDescription], when set, is read out as the + * chip's state (a hidden tag). */ @Composable fun EnclyChip( @@ -136,6 +140,7 @@ fun EnclyChip( modifier: Modifier = Modifier, count: Int? = null, leadsTo: String? = null, + stateDescription: String? = null, ) { val colors = MaterialTheme.colorScheme val content = if (selected) colors.onPrimaryContainer else colors.onSurface @@ -144,7 +149,8 @@ fun EnclyChip( color = if (selected) colors.primaryContainer else Color.Transparent, contentColor = content, border = BorderStroke(1.dp, if (selected) colors.primaryContainer else colors.outlineVariant), - modifier = modifier, + // The pill stays 36 dp; the touch target around it is the 48 dp minimum. + modifier = modifier.minimumInteractiveComponentSize(), ) { // The toggle sits inside the Surface so its ripple is clipped to the pill, not a square. Row( @@ -161,6 +167,7 @@ fun EnclyChip( .semantics { contentDescription = leadsTo } }, ) + .semantics { if (stateDescription != null) this.stateDescription = stateDescription } .heightIn(min = 36.dp) .padding(horizontal = 14.dp, vertical = EnclyTheme.spacing.xs), ) { @@ -178,14 +185,14 @@ fun EnclyChip( private const val COUNT_ALPHA = 0.85f -/** A section heading: the uppercase data overline in `onSurfaceVariant`. */ +/** A section heading: the uppercase data overline in `onSurfaceVariant`, announced as a heading. */ @Composable fun SectionOverline(text: String, modifier: Modifier = Modifier) { Text( text = text.uppercase(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = modifier, + modifier = modifier.semantics { heading() }, ) } diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/dialogs/NoteCardBottomSheet.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/dialogs/NoteCardBottomSheet.kt index ba510c74..b809597b 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/dialogs/NoteCardBottomSheet.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/dialogs/NoteCardBottomSheet.kt @@ -23,7 +23,6 @@ import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf @@ -40,10 +39,10 @@ import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.common.valueOrNull import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.delete @@ -65,6 +64,7 @@ import com.pasich.encly.data.model.Note import com.pasich.encly.data.model.NoteWithTags import com.pasich.encly.domain.model.NoteColor import com.pasich.encly.platform.vaultTextKeyboardOptions +import com.pasich.encly.presentation.components.tiles.TagItem import com.pasich.encly.presentation.designsystem.EnclyBackButton import com.pasich.encly.presentation.designsystem.EnclyButton import com.pasich.encly.presentation.designsystem.EnclyChip @@ -75,6 +75,7 @@ import com.pasich.encly.presentation.designsystem.EnclySheetGroupDivider import com.pasich.encly.presentation.designsystem.EnclySheetGroupRow import com.pasich.encly.presentation.designsystem.EnclySheetTiles import com.pasich.encly.presentation.designsystem.EnclyTextField +import com.pasich.encly.presentation.designsystem.SectionOverline import com.pasich.encly.presentation.designsystem.SheetTile import com.pasich.encly.presentation.designsystem.bleed import com.pasich.encly.presentation.viewmodel.TagListViewModel @@ -217,7 +218,7 @@ private fun NoteRows( // The sheet is `surfaceContainer`: tiles on the group colour stand out from it, as its groups do. containerColor = MaterialTheme.colorScheme.surfaceContainerLowest, ) - NoteSection(title = stringResource(Res.string.note_color_title)) { + SheetSection(title = stringResource(Res.string.note_color_title)) { EnclyNoteColorPicker( selected = NoteColor.fromKey(item.note.color), onSelect = { onAction(NoteAction.ChangeColor(it)) }, @@ -225,7 +226,7 @@ private fun NoteRows( contentPadding = PaddingValues(horizontal = EnclyTheme.spacing.gutter), ) } - NoteSection(title = stringResource(Res.string.main_drawer_tags)) { + SheetSection(title = stringResource(Res.string.main_drawer_tags)) { NoteTagChips( selectedTagIds = item.tags.mapTo(HashSet()) { it.id }, onToggle = { tagId, tagged -> onAction(NoteAction.ChangeTag(tagId, tagged)) }, @@ -248,16 +249,11 @@ private fun NoteRows( } } -/** A section of the first page: its small [title] label over its [content]. */ +/** A section of the first page: its [title] as a heading over its [content]. */ @Composable -private fun NoteSection(title: String, content: @Composable () -> Unit) { +private fun SheetSection(title: String, content: @Composable () -> Unit) { Column(verticalArrangement = Arrangement.spacedBy(EnclyTheme.spacing.xs)) { - Text( - text = title.uppercase(), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = EnclyTheme.spacing.xxs).semantics { heading() }, - ) + SectionOverline(text = title, modifier = Modifier.padding(horizontal = EnclyTheme.spacing.xxs)) content() } } @@ -316,7 +312,7 @@ private fun NoteTagChips( modifier: Modifier = Modifier, tagListViewModel: TagListViewModel = metroViewModel(), ) { - val tags by tagListViewModel.state.collectAsState() + val tags by tagListViewModel.state.collectAsStateWithLifecycle() val all = tags.tagsLoad.valueOrNull() ?: return if (all.isEmpty()) { Text( @@ -337,7 +333,9 @@ private fun NoteTagChips( val shown = all.filterIndexed { index, tag -> index < TAG_CHIPS_SHOWN || tag.id in selectedTagIds } shown.forEach { tag -> val tagged = tag.id in selectedTagIds - EnclyChip(label = tag.nameTag, selected = tagged, onClick = { onToggle(tag.id, !tagged) }) + // A hidden tag is faded and read out as hidden, as on the tags page: tapping it takes the note off + // the main list while the sheet stays open. + TagItem(isSelected = tagged, item = tag, onItemClick = { onToggle(tag.id, !tagged) }) } val hidden = all.size - shown.size if (hidden > 0) { @@ -410,7 +408,7 @@ private fun TagsPage( modifier: Modifier = Modifier, tagListViewModel: TagListViewModel = metroViewModel(), ) { - val state by tagListViewModel.state.collectAsState() + val state by tagListViewModel.state.collectAsStateWithLifecycle() NotePage(title = stringResource(Res.string.main_drawer_tags), onBack = onBack, modifier = modifier) { EnclySheetGroup(modifier = Modifier.weight(1f, fill = false)) { Column(modifier = Modifier.verticalScroll(rememberScrollState())) { diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/dialogs/NotesSortBottomSheet.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/dialogs/NotesSortBottomSheet.kt index 8b1c232b..7503582b 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/dialogs/NotesSortBottomSheet.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/dialogs/NotesSortBottomSheet.kt @@ -3,8 +3,8 @@ package com.pasich.encly.presentation.dialogs import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.SheetState import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.sort_by import com.pasich.encly.core.resources.view_switch_to_grid @@ -30,7 +30,7 @@ fun NotesSortBottomSheet( isBottomSheetVisible: Boolean = false, noteListViewModel: NoteListViewModel = metroViewModel(), ) { - val state by noteListViewModel.state.collectAsState() + val state by noteListViewModel.state.collectAsStateWithLifecycle() if (isBottomSheetVisible) { AdaptiveSheet( diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/navigation/EnclyApp.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/navigation/EnclyApp.kt index cf9a0a24..a9e82066 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/navigation/EnclyApp.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/navigation/EnclyApp.kt @@ -10,7 +10,6 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -24,8 +23,10 @@ import androidx.compose.ui.unit.LayoutDirection import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import androidx.navigation.NavHostController +import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.savedstate.SavedState import androidx.savedstate.read @@ -94,16 +95,21 @@ fun EnclyApp( val startup = metroViewModel() val freshInstall = startStatus == InitialStatus.ONBOARDING || startStatus == InitialStatus.SETUP_AUTH LaunchedEffect(startup) { startup.onAppStart(freshInstall) } + // "Erase all data" and the loss-recovery wipe clear the recorded version and go back to onboarding in the same + // process: the vault made there is new too, so it must not be told it was updated (What's new, the trash notice). + val onOnboarding = navController.currentBackStackEntryAsState().value?.destination?.route == + NavRoutes.OnboardingRoute.name + LaunchedEffect(startup, onOnboarding) { if (onOnboarding) startup.onAppStart(freshInstall = true) } // Auto re-lock. Collected without a lifecycle gate so the value is already true in // the first frame after returning from the background. That frame still composes // the pre-lock destination (e.g. an open note), so the shield below covers the // NavHost until the lock screen is the only visible entry. Navigation itself runs // after the frame, from this effect. - val locked by sessionLockManager.locked.collectAsState() + val locked by sessionLockManager.locked.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() // A lock still waiting for the editors' saves: nothing may show or run meanwhile (SessionLockManager.locking). - val locking by sessionLockManager.locking.collectAsState() + val locking by sessionLockManager.locking.collectAsStateWithLifecycle() val currentLocked by rememberUpdatedState(locked) val currentLocking by rememberUpdatedState(locking) val router = remember(navController, scope, sessionLockManager) { @@ -116,7 +122,7 @@ fun EnclyApp( LockRouteGuard(navController, securityManager::isDatabaseUnlocked) HostNavigationRequests(navController, router, commandsAllowed) SessionResumeGuard(navController, sessionLockManager) - val visibleEntries by navController.visibleEntries.collectAsState() + val visibleEntries by navController.visibleEntries.collectAsStateWithLifecycle() // An empty list is the first frame of a restored back stack: shielded as well. val shielded = (locked || locking) && ( visibleEntries.isEmpty() || visibleEntries.any { it.destination.route != NavRoutes.LockRoute.name } @@ -325,8 +331,8 @@ private fun AppContent( .fillMaxSize() .background(MaterialTheme.colorScheme.background), ) { - val showPreviews by metroViewModel().show.collectAsState() - val toolbar by metroViewModel().layout.collectAsState() + val showPreviews by metroViewModel().show.collectAsStateWithLifecycle() + val toolbar by metroViewModel().layout.collectAsStateWithLifecycle() val unlockReveal = remember { UnlockRevealState() } // A re-lock during the reveal ends it: no deferred navigation into the vault, // no reveal left covering the lock screen. diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/navigation/NavHost.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/navigation/NavHost.kt index f47c953c..467ff064 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/navigation/NavHost.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/navigation/NavHost.kt @@ -4,9 +4,9 @@ import androidx.compose.animation.SharedTransitionLayout import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavBackStackEntry import androidx.navigation.NavHostController import androidx.navigation.NavType @@ -292,7 +292,7 @@ private fun EditNoteDestination( entry: NavBackStackEntry, viewModel: EditNoteViewModel = metroViewModel(), ) { - val noteState by viewModel.state.collectAsState() + val noteState by viewModel.state.collectAsStateWithLifecycle() val eraseEpoch = LocalEraseEpoch.current LaunchedEffect(entry, noteState.note.id, eraseEpoch) { val state = entry.savedStateHandle @@ -312,7 +312,7 @@ private fun StorageUnreadableRoute( navController: NavHostController, viewModel: StorageUnreadableViewModel = metroViewModel(), ) { - val stillUnreadable by viewModel.stillUnreadable.collectAsState() + val stillUnreadable by viewModel.stillUnreadable.collectAsStateWithLifecycle() StorageUnreadableScreen( stillUnreadable = stillUnreadable, onRetry = { diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/LockScreen.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/LockScreen.kt index 2e3e02e9..66a2eb96 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/LockScreen.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/LockScreen.kt @@ -2,12 +2,12 @@ package com.pasich.encly.presentation.screen import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.backhandler.BackHandler import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import com.pasich.encly.core.security.RecoveryStage import com.pasich.encly.platform.LocalBiometricHost @@ -93,7 +93,7 @@ private fun NavHostController.leaveForRecoveryStage(stage: RecoveryStage) { @Composable fun LockScreen(exits: LockExits, modifier: Modifier = Modifier, viewModel: LockViewModel = metroViewModel()) { val host = LocalBiometricHost.current - val busy by viewModel.busy.collectAsState() + val busy by viewModel.busy.collectAsStateWithLifecycle() // Above the loading view below: the forms' input and errors survive the credential check. val form = remember { LockFormState() } @@ -101,7 +101,7 @@ fun LockScreen(exits: LockExits, modifier: Modifier = Modifier, viewModel: LockV // [LockExits.onBack], or nowhere: by default Back never leaves the lock screen. BackHandler(enabled = true) { onLockBack(busy, form, exits.onBack) } - val biometricInvalidated by viewModel.biometricInvalidated.collectAsState() + val biometricInvalidated by viewModel.biometricInvalidated.collectAsStateWithLifecycle() val biometricUsable = remember { viewModel.biometricEnabled() && viewModel.biometricAvailable() } diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/MainScreen.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/MainScreen.kt index 6d181229..7f3ac118 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/MainScreen.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/MainScreen.kt @@ -23,7 +23,6 @@ import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.State -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -85,7 +84,7 @@ fun MainRootScreen(navController: NavHostController, modifier: Modifier = Modifi WidthClass.Medium -> MediumMainRoot(navController, modifier) WidthClass.Expanded -> ExpandedMainRoot(navController, modifier) } - UnlockedStartup() + UnlockedStartup(navController) } /** The phone layout: the notes, with the navigation drawer sliding over them. */ @@ -140,8 +139,8 @@ fun MainScreen( searchViewModel: NoteSearchViewModel = metroViewModel(), lockNowViewModel: LockNowViewModel = metroViewModel(), ) { - val isGrid by mainListStateViewModel.isGridNoteList.collectAsState() - val showTasks by settingsViewModel.showTasksFlow.collectAsState() + val isGrid by mainListStateViewModel.isGridNoteList.collectAsStateWithLifecycle() + val showTasks by settingsViewModel.showTasksFlow.collectAsStateWithLifecycle() // The field reads local state (a flow round trip can drop fast keystrokes); the ViewModel // gets every change. // Plain remember: a search query is note content and must not land in saved state. @@ -189,7 +188,7 @@ fun MainScreen( listScrollState = listScrollState, gridScrollState = gridScrollState, search = NotesSearch(query, searchResults), - swipe = settingsViewModel.swipeSettings.collectAsState().value ?: SwipeSettings.Off, + swipe = settingsViewModel.swipeSettings.collectAsStateWithLifecycle().value ?: SwipeSettings.Off, onItemClick = { note -> notes.editNote(note.id) }, onSecondActionClick = { note -> notes.editNote(-1, "?copySource=${note.id}") }, tabs = notes.tabs(), diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/NotesListScreen.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/NotesListScreen.kt index 81f0b59a..dc298571 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/NotesListScreen.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/NotesListScreen.kt @@ -25,7 +25,6 @@ import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -194,7 +193,9 @@ internal fun NoteActionsSheet( // The sheet shows the note as stored now, not as the list held it when the sheet opened: a tag // changed here moves the note out of this list, and the next action must still act on the right row. val activeId = sheet.active?.note?.id - val live by remember(activeId) { activeId?.let(observeNote) ?: emptyFlow() }.collectAsState(initial = null) + val live by remember(activeId) { + activeId?.let(observeNote) ?: emptyFlow() + }.collectAsStateWithLifecycle(initialValue = null) // The sheet slides away before it leaves the composition, and before its action runs. val close = rememberSheetCloser(bottomSheetState, onDismiss = sheet::close) diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/TasksScreen.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/TasksScreen.kt index e8def90a..561a294e 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/TasksScreen.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/TasksScreen.kt @@ -16,7 +16,6 @@ import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -29,6 +28,7 @@ import androidx.compose.ui.platform.LocalFocusManager import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.done @@ -85,14 +85,14 @@ fun TasksScreen( openNewTask: Boolean = false, viewModel: TasksViewModel = metroViewModel(), ) { - val uiState by viewModel.uiState.collectAsState() + val uiState by viewModel.uiState.collectAsStateWithLifecycle() val snackbarHostState = remember { SnackbarHostState() } var confirmClear by remember { mutableStateOf(false) } OpenOnArrival(openNewTask, viewModel::showAddTaskDialog) LaunchedEffect(viewModel) { showTaskMessages(viewModel, snackbarHostState) } val listState = rememberTasksListState(uiState) - val list = TasksListState(uiState, viewModel.stepsChosen.collectAsState().value, viewModel.inlineEdit) + val list = TasksListState(uiState, viewModel.stepsChosen.collectAsStateWithLifecycle().value, viewModel.inlineEdit) val itemActions = remember(viewModel) { taskItemActions(viewModel) } // Backgrounding re-locks the vault and drops this screen: save the inline field first (see OnPause). OnPause(viewModel::flushInlineEditForBackground) @@ -145,8 +145,8 @@ fun TasksScreen( @Composable private fun TaskSheet(viewModel: TasksViewModel = metroViewModel()) { val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) - val visible by viewModel.showAddTaskDialog.collectAsState() - val editing by viewModel.editingTask.collectAsState() + val visible by viewModel.showAddTaskDialog.collectAsStateWithLifecycle() + val editing by viewModel.editingTask.collectAsStateWithLifecycle() val shown = remember { ShownTask() } if (visible) { shown.task = editing diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/UnlockedStartup.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/UnlockedStartup.kt index 50dff33e..5ecc4dd4 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/UnlockedStartup.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/UnlockedStartup.kt @@ -2,32 +2,69 @@ package com.pasich.encly.presentation.screen import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.navigation.NavHostController +import androidx.navigation.NavOptions +import com.pasich.encly.core.resources.Res +import com.pasich.encly.core.resources.trash_notice_message +import com.pasich.encly.core.resources.trash_notice_open +import com.pasich.encly.core.resources.trash_notice_title +import com.pasich.encly.core.resources.whats_new_dismiss import com.pasich.encly.platform.LocalHostPlatform +import com.pasich.encly.presentation.designsystem.DialogAction +import com.pasich.encly.presentation.designsystem.EnclyDialog import com.pasich.encly.presentation.dialogs.WhatsNewSheet import com.pasich.encly.presentation.effects.LocalUnlockReveal import com.pasich.encly.presentation.navigation.LocalVaultLocked +import com.pasich.encly.presentation.navigation.NavRoutes import com.pasich.encly.presentation.viewmodel.StartupViewModel import com.pasich.encly.utils.currentLanguageTag import com.pasich.encly.whatsnew.Changelogs import dev.zacsweers.metrox.viewmodel.metroViewModel +import org.jetbrains.compose.resources.pluralStringResource +import org.jetbrains.compose.resources.stringResource /** * What the home screen starts when the vault is open: the trash is emptied of notes older than 28 days, and, the * first time after an update, the "What's new" sheet is shown. The sheet waits for the unlock animation to end - * and is never drawn while the vault is locked, so it cannot appear over the lock screen. + * and is never drawn while the vault is locked, so it cannot appear over the lock screen. After an update from a + * version below 3.0.0 with notes in the trash, a notice says the trash now empties itself, with a button to open it; + * it waits for the sheet to be closed. */ @Composable -internal fun UnlockedStartup(viewModel: StartupViewModel = metroViewModel()) { +internal fun UnlockedStartup(navController: NavHostController, viewModel: StartupViewModel = metroViewModel()) { val languageTag = currentLanguageTag() val bundled = Changelogs.bundledFor(LocalHostPlatform.current) LaunchedEffect(viewModel) { viewModel.onUnlocked(languageTag, bundled) } - val due by viewModel.whatsNewDue.collectAsState() + val due by viewModel.whatsNewDue.collectAsStateWithLifecycle() val revealing = LocalUnlockReveal.current?.running == true val locked = LocalVaultLocked.current val notes = due if (notes != null && !revealing && !locked) { WhatsNewSheet(notes = notes, onDismiss = viewModel::dismissWhatsNew) } + val trashCount by viewModel.trashNoticeCount.collectAsStateWithLifecycle() + val inTrash = trashCount + val free = notes == null && !revealing && !locked + if (inTrash != null && free) TrashNotice(inTrash, viewModel::dismissTrashNotice, navController) +} + +/** Says that the trash now empties itself, with [count] notes in it; its button opens the trash. */ +@Composable +private fun TrashNotice(count: Int, onDismiss: () -> Unit, navController: NavHostController) { + EnclyDialog( + title = stringResource(Res.string.trash_notice_title), + text = pluralStringResource(Res.plurals.trash_notice_message, count, count), + onDismissRequest = onDismiss, + confirm = DialogAction( + stringResource(Res.string.trash_notice_open), + onClick = { + onDismiss() + val options = NavOptions.Builder().setLaunchSingleTop(true).setRestoreState(true).build() + navController.navigate(NavRoutes.TrashRoute.name, options) + }, + ), + dismiss = DialogAction(stringResource(Res.string.whats_new_dismiss), onDismiss), + ) } diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditNoteScreen.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditNoteScreen.kt index f6b8bd70..cb3b14f8 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditNoteScreen.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditNoteScreen.kt @@ -20,7 +20,6 @@ import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.MutableState -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -138,12 +137,12 @@ fun EditNoteScreen( val fontStyle by viewModel.fontStyle.collectAsStateWithLifecycle() val lineSpacing by viewModel.noteLineSpacing.collectAsStateWithLifecycle() val simpleEdit by viewModel.simpleEdit.collectAsStateWithLifecycle() - val contentLoadFailed by viewModel.contentLoadFailed.collectAsState() - val editedElsewhere by viewModel.editedElsewhere.collectAsState() + val contentLoadFailed by viewModel.contentLoadFailed.collectAsStateWithLifecycle() + val editedElsewhere by viewModel.editedElsewhere.collectAsStateWithLifecycle() val overlays = rememberEditorOverlays() val listState = rememberLazyListState() val focusRegistry = rememberBlockFocusRegistry(viewModel.blocks) - val findState = viewModel.find.collectAsState() + val findState = viewModel.find.collectAsStateWithLifecycle() val highlights = remember(findState) { FindHighlights(findState) } val controller = rememberEditorController() val host = remember(controller, focusRegistry, highlights) { @@ -221,11 +220,11 @@ private fun EditorScaffold( viewModel: EditNoteViewModel = metroViewModel(), content: @Composable (PaddingValues) -> Unit, ) { - val lockEditor by viewModel.lockEditor.collectAsState() - val picking by viewModel.selectedBlocks.ids.collectAsState() - val textRange by viewModel.textRange.ends.collectAsState() + val lockEditor by viewModel.lockEditor.collectAsStateWithLifecycle() + val picking by viewModel.selectedBlocks.ids.collectAsStateWithLifecycle() + val textRange by viewModel.textRange.ends.collectAsStateWithLifecycle() val crossBlocks = textRange != null && viewModel.textRange.isCrossField - val contentLoadFailed by viewModel.contentLoadFailed.collectAsState() + val contentLoadFailed by viewModel.contentLoadFailed.collectAsStateWithLifecycle() val findOpen by rememberFindOpen() val pageColor = rememberPageColor() Scaffold( @@ -272,7 +271,7 @@ private fun EditorScaffold( */ @Composable private fun rememberPageColor(viewModel: EditNoteViewModel = metroViewModel()): Color { - val noteState = viewModel.state.collectAsState() + val noteState = viewModel.state.collectAsStateWithLifecycle() val colorKey by remember(noteState) { derivedStateOf { noteState.value.note.color } } val scheme = MaterialTheme.colorScheme val target = remember(colorKey, scheme) { @@ -317,7 +316,7 @@ private fun EditorOverlays( val clipboard = LocalSensitiveClipboard.current val copyLabel = stringResource(Res.string.markdown_copy) val copyConfirmation = stringResource(Res.string.markdown_copied) - val lockEditor by viewModel.lockEditor.collectAsState() + val lockEditor by viewModel.lockEditor.collectAsStateWithLifecycle() EditorConfirmDialogs( visible = ConfirmationsVisible( delete = overlays.isDeleteDialogVisible, @@ -412,13 +411,13 @@ private fun EditorBlocks( val spacing = LocalEditorTheme.current.lineSpacing val controller = rememberEditorController() val headerGap = if (spacing.isCompact) EnclyTheme.spacing.labelGap else 0.dp - val lockEditor by viewModel.lockEditor.collectAsState() - val contentLoadFailed by viewModel.contentLoadFailed.collectAsState() - val editedElsewhere by viewModel.editedElsewhere.collectAsState() - val editingLinkIds by viewModel.editingLinkIds.collectAsState() - val templatesOffered by viewModel.templatesOffered.collectAsState() + val lockEditor by viewModel.lockEditor.collectAsStateWithLifecycle() + val contentLoadFailed by viewModel.contentLoadFailed.collectAsStateWithLifecycle() + val editedElsewhere by viewModel.editedElsewhere.collectAsStateWithLifecycle() + val editingLinkIds by viewModel.editingLinkIds.collectAsStateWithLifecycle() + val templatesOffered by viewModel.templatesOffered.collectAsStateWithLifecycle() // Only whether it is loading: a save changing the status must not recompose the list. - val status = viewModel.status.collectAsState() + val status = viewModel.status.collectAsStateWithLifecycle() val loading by remember(status) { derivedStateOf { status.value == SaveStatusNote.LOADING } } CompositionLocalProvider(LocalOverscrollFactory provides null) { @@ -486,11 +485,11 @@ private fun EditorOverline( tagViewModel: TagListViewModel = metroViewModel(), ) { // Read through derived state: a title keystroke or a save does not recompose the overline. - val noteState = viewModel.state.collectAsState() - val status = viewModel.status.collectAsState() + val noteState = viewModel.state.collectAsStateWithLifecycle() + val status = viewModel.status.collectAsStateWithLifecycle() val meta by remember(noteState) { derivedStateOf { noteState.value.note.let { it.tagIds to it.date } } } val notSaved by remember(status) { derivedStateOf { status.value == SaveStatusNote.FAILED } } - val tagState by tagViewModel.state.collectAsState() + val tagState by tagViewModel.state.collectAsStateWithLifecycle() val (tagIds, date) = meta NoteOverline( // In the tags' own order, the one of the tags screen. diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorEffects.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorEffects.kt index 6b81362f..cfa2d427 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorEffects.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorEffects.kt @@ -7,7 +7,6 @@ import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.State -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -22,6 +21,7 @@ import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.editor.focus.BlockFocusRegistry import com.pasich.encly.editor.ui.FindHighlights import com.pasich.encly.editor.ui.sheets.BlockSheetKind @@ -154,7 +154,7 @@ internal fun rememberBlockSheetState(): BlockSheetState { @Composable internal fun rememberFindOpen(viewModel: EditNoteViewModel = metroViewModel()): State { val open = remember(viewModel) { viewModel.find.map { it.isOpen }.distinctUntilChanged() } - return open.collectAsState(initial = false) + return open.collectAsStateWithLifecycle(initialValue = false) } /** @@ -172,7 +172,7 @@ internal fun ScrollToFindMatch( // Keyed on the user's requests, not on the match: a refresh while typing can move the current index onto another // match, and the note must not scroll away from the caret for that. val request = remember(viewModel) { viewModel.find.map { it.revealRequest }.distinctUntilChanged() } - val revealRequest by request.collectAsState(initial = 0) + val revealRequest by request.collectAsStateWithLifecycle(initialValue = 0) val currentBlocksStart by rememberUpdatedState(blocksStart) LaunchedEffect(revealRequest) { val found = viewModel.find.value.currentMatch ?: return@LaunchedEffect @@ -186,7 +186,7 @@ internal fun ScrollToFindMatch( @Composable internal fun CloseFindOrSlashOnBack(viewModel: EditNoteViewModel = metroViewModel()) { val findOpen by rememberFindOpen() - val slashMenu by viewModel.slashPicker.menu.collectAsState() + val slashMenu by viewModel.slashPicker.menu.collectAsStateWithLifecycle() val slashShown = slashMenu?.isShown == true BackHandler(enabled = findOpen || slashShown) { if (findOpen) viewModel.closeFind() else viewModel.slashPicker.dismiss() @@ -200,7 +200,7 @@ internal fun CloseFindOrSlashOnBack(viewModel: EditNoteViewModel = metroViewMode */ @Composable internal fun PaneTabBinding(pane: EditorPane, exits: EditorExits, viewModel: EditNoteViewModel = metroViewModel()) { - val noteState by viewModel.state.collectAsState() + val noteState by viewModel.state.collectAsStateWithLifecycle() val note = noteState.note LaunchedEffect(pane, note.id, note.title) { pane.tabs.report(pane.tabKey, note.id, note.title) } val currentExits by rememberUpdatedState(exits) diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorFindBar.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorFindBar.kt index 2b079716..78f0b70b 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorFindBar.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorFindBar.kt @@ -13,7 +13,6 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.withFrameNanos @@ -24,6 +23,7 @@ import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.semantics +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.find_close import com.pasich.encly.core.resources.find_count @@ -49,7 +49,7 @@ private const val FOCUS_FRAMES = 3 */ @Composable internal fun EditorFindBar(modifier: Modifier = Modifier, viewModel: EditNoteViewModel = metroViewModel()) { - val state by viewModel.find.collectAsState() + val state by viewModel.find.collectAsStateWithLifecycle() val focus = remember { FocusRequester() } LaunchedEffect(focus) { // The field is in the tree after a frame or two; asking for focus brings the keyboard up. diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorSelection.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorSelection.kt index f2add26e..f566171d 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorSelection.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorSelection.kt @@ -1,11 +1,11 @@ package com.pasich.encly.presentation.screen.editnote import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.backhandler.BackHandler +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.markdown_copied import com.pasich.encly.core.resources.markdown_copy @@ -88,7 +88,7 @@ internal fun EditorSelectionBar(onMessage: (String) -> Unit, viewModel: EditNote val label = stringResource(Res.string.markdown_copy) val copied = stringResource(Res.string.selection_copied) val copiedMarkdown = stringResource(Res.string.markdown_copied) - val locked by viewModel.lockEditor.collectAsState() + val locked by viewModel.lockEditor.collectAsStateWithLifecycle() val actions = remember(viewModel, clipboard, label, copied, copiedMarkdown, locked) { SelectedBlocksActions( canEdit = viewModel.canEditBlocks, @@ -115,7 +115,7 @@ internal fun EditorTextRangeBar( val label = stringResource(Res.string.markdown_copy) val copied = stringResource(Res.string.selection_copied) val copiedMarkdown = stringResource(Res.string.markdown_copied) - val locked by viewModel.lockEditor.collectAsState() + val locked by viewModel.lockEditor.collectAsStateWithLifecycle() val actions = remember(viewModel, clipboard, label, copied, copiedMarkdown, locked) { fun copy(markdown: Boolean, message: String) { if (copyBlocks(clipboard, viewModel, viewModel.textRangeBlocks(), markdown, label)) { @@ -142,8 +142,8 @@ internal fun EditorTextRangeBar( /** Back leaves block selection mode, or a text selection across blocks, before it does anything else. */ @Composable internal fun LeaveBlockSelectionOnBack(viewModel: EditNoteViewModel = metroViewModel()) { - val picking by viewModel.selectedBlocks.ids.collectAsState() - val textRange by viewModel.textRange.ends.collectAsState() + val picking by viewModel.selectedBlocks.ids.collectAsStateWithLifecycle() + val textRange by viewModel.textRange.ends.collectAsStateWithLifecycle() BackHandler(enabled = picking.isNotEmpty() || (textRange != null && viewModel.textRange.isCrossField)) { viewModel.selectedBlocks.clear() viewModel.textRange.clear() diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorSheets.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorSheets.kt index 882b16f8..1d0e92ba 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorSheets.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/EditorSheets.kt @@ -21,13 +21,13 @@ import androidx.compose.material3.IconToggleButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.delete_from_trash import com.pasich.encly.core.resources.edit_tags @@ -71,8 +71,8 @@ internal fun EditorTagSheet( viewModel: EditNoteViewModel = metroViewModel(), tagViewModel: TagListViewModel = metroViewModel(), ) { - val tagState by tagViewModel.state.collectAsState() - val noteState by viewModel.state.collectAsState() + val tagState by tagViewModel.state.collectAsStateWithLifecycle() + val noteState by viewModel.state.collectAsStateWithLifecycle() NoteTagSheet( tags = tagState.listTags, selectedTagIds = noteState.note.tagIds, diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/NoteClaim.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/NoteClaim.kt index 63b8a342..b5ba2c50 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/NoteClaim.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/editnote/NoteClaim.kt @@ -3,7 +3,6 @@ package com.pasich.encly.presentation.screen.editnote import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf @@ -11,6 +10,7 @@ import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.platform.LocalNoteEditClaims import com.pasich.encly.presentation.viewmodel.EditNoteViewModel import dev.zacsweers.metrox.viewmodel.metroViewModel @@ -27,7 +27,7 @@ import kotlinx.coroutines.flow.first @Composable internal fun ClaimNoteForEditing(viewModel: EditNoteViewModel = metroViewModel()) { val claims = LocalNoteEditClaims.current ?: return - val state = viewModel.state.collectAsState() + val state = viewModel.state.collectAsStateWithLifecycle() val noteId by remember(state) { derivedStateOf { state.value.note.id } } if (viewModel.isReadTrashOnly || noteId <= 0L) return var retry by remember(noteId) { mutableIntStateOf(0) } diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/handoff/ImportFromMyNotesScreen.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/handoff/ImportFromMyNotesScreen.kt index 22b7f61e..e1d68b4e 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/handoff/ImportFromMyNotesScreen.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/handoff/ImportFromMyNotesScreen.kt @@ -12,11 +12,11 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.backhandler.BackHandler +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.backup_count_notes import com.pasich.encly.core.resources.backup_count_tags @@ -70,8 +70,8 @@ fun ImportFromMyNotesScreen( modifier: Modifier = Modifier, viewModel: ImportFromMyNotesViewModel = metroViewModel(), ) { - val locked by viewModel.locked.collectAsState() - val step by viewModel.step.collectAsState() + val locked by viewModel.locked.collectAsStateWithLifecycle() + val step by viewModel.step.collectAsStateWithLifecycle() // A failure shows even while the vault is closed: "nothing can open the vault" comes from // the lock screen itself, and nothing of the vault is on that page. if (locked && step !is HandoffStep.Failed) { diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/NotePreviewsSetting.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/NotePreviewsSetting.kt index 54c7a7e9..2230996d 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/NotePreviewsSetting.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/NotePreviewsSetting.kt @@ -2,9 +2,9 @@ package com.pasich.encly.presentation.screen.settings import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier +import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.security_previews_desc import com.pasich.encly.core.resources.security_previews_title @@ -16,17 +16,24 @@ import com.pasich.encly.ui.theme.EnclyTheme import dev.zacsweers.metrox.viewmodel.metroViewModel import org.jetbrains.compose.resources.stringResource -/** "Show note previews" (see NotePreviews): on by default; off, the note lists show no text of the notes. */ +/** + * "Show note previews" (see NotePreviews): on by default; off, the note lists show no text of the notes. A change + * goes through [onChange] with the value and the action that applies it, so showing the text can ask for the PIN first. + */ @Composable -internal fun NotePreviewsSetting(modifier: Modifier = Modifier, viewModel: NotePreviewsViewModel = metroViewModel()) { - val show by viewModel.show.collectAsState() +internal fun NotePreviewsSetting( + onChange: (show: Boolean, apply: () -> Unit) -> Unit, + modifier: Modifier = Modifier, + viewModel: NotePreviewsViewModel = metroViewModel(), +) { + val show by viewModel.show.collectAsStateWithLifecycle() EnclyGroup(modifier = modifier) { EnclySwitchRow( title = stringResource(Res.string.security_previews_title), supporting = stringResource(Res.string.security_previews_desc), icon = EnclyIcons.Eye, checked = show, - onCheckedChange = viewModel::setShow, + onCheckedChange = { value -> onChange(value) { viewModel.setShow(value) } }, modifier = Modifier.padding(horizontal = EnclyTheme.spacing.s), ) } diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/SecuritySettingsScreen.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/SecuritySettingsScreen.kt index ccec4e7a..0659d080 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/SecuritySettingsScreen.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/SecuritySettingsScreen.kt @@ -39,6 +39,7 @@ import com.pasich.encly.platform.BiometricWording import com.pasich.encly.platform.LocalBiometricHost import com.pasich.encly.platform.LocalBiometricWording import com.pasich.encly.platform.LocalScreenshotAllowance +import com.pasich.encly.platform.ScreenBiometricHost import com.pasich.encly.platform.hostString import com.pasich.encly.presentation.designsystem.EnclyGroup import com.pasich.encly.presentation.designsystem.EnclyGroupDivider @@ -58,6 +59,10 @@ import com.pasich.encly.presentation.viewmodel.BackupAction import com.pasich.encly.presentation.viewmodel.BackupMessage import com.pasich.encly.presentation.viewmodel.BackupViewModel import com.pasich.encly.presentation.viewmodel.SecuritySettingsViewModel +import com.pasich.encly.presentation.viewmodel.changeAutoLock +import com.pasich.encly.presentation.viewmodel.changeBiometric +import com.pasich.encly.presentation.viewmodel.changeNotePreviews +import com.pasich.encly.presentation.viewmodel.changeStrictKeyboard import com.pasich.encly.ui.theme.EnclyTheme import dev.zacsweers.metrox.viewmodel.metroViewModel import kotlinx.coroutines.launch @@ -109,15 +114,7 @@ fun SecuritySettingsScreen( securityState = securityState, options = options, vaultBusy = vaultState.busy, - actions = SecurityActions( - onOpen = { route -> navController.openRoute(route.name) }, - onBiometric = { enabled -> - if (host != null) securityViewModel.toggleBiometric(host, enabled) - }, - onVaultAction = vaultViewModel::start, - onStrictKeyboard = securityViewModel::setStrictKeyboard, - onAutoLock = securityViewModel::setAutoLockDelay, - ), + actions = securityActions(navController, securityViewModel, vaultViewModel, host), modifier = Modifier.padding(paddingValues), ) } @@ -128,6 +125,30 @@ fun SecuritySettingsScreen( } } +private fun securityActions( + navController: NavHostController, + securityViewModel: SecuritySettingsViewModel, + vaultViewModel: BackupViewModel, + host: ScreenBiometricHost?, +) = SecurityActions( + onOpen = { route -> navController.openRoute(route.name) }, + onBiometric = { enabled -> + if (host != null) { + vaultViewModel.changeBiometric(enabled) { securityViewModel.toggleBiometric(host, enabled) } + } + }, + onVaultAction = vaultViewModel::start, + onStrictKeyboard = { strict -> + vaultViewModel.changeStrictKeyboard(strict) { securityViewModel.setStrictKeyboard(strict) } + }, + onAutoLock = { delay -> + vaultViewModel.changeAutoLock(securityViewModel.autoLockDelay.value, delay) { + securityViewModel.setAutoLockDelay(delay) + } + }, + onNotePreviews = vaultViewModel::changeNotePreviews, +) + /** What the security page can start. */ private class SecurityActions( val onOpen: (NavRoutes) -> Unit, @@ -135,6 +156,7 @@ private class SecurityActions( val onVaultAction: (BackupAction) -> Unit, val onStrictKeyboard: (Boolean) -> Unit, val onAutoLock: (AutoLockDelay) -> Unit, + val onNotePreviews: (Boolean, () -> Unit) -> Unit, ) /** The page's own preferences: strict keyboard privacy, the auto-lock delay and the screenshots allowance. */ @@ -242,7 +264,7 @@ private fun SecurityRows( onStrictKeyboard = actions.onStrictKeyboard, screenshots = options.screenshots, ) - NotePreviewsSetting() + NotePreviewsSetting(onChange = actions.onNotePreviews) ProtectionSection() EraseSection(busy = vaultBusy, onErase = { actions.onVaultAction(BackupAction.ERASE) }) } diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/SettingsScreen.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/SettingsScreen.kt index aba4ecd0..978ce0ca 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/SettingsScreen.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/screen/settings/SettingsScreen.kt @@ -12,10 +12,10 @@ import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import com.pasich.encly.core.resources.Res import com.pasich.encly.core.resources.main_drawer_settings @@ -47,13 +47,13 @@ fun SettingsScreen( settingViewState: SettingsViewModel = metroViewModel(), securityDisable: Boolean = false, ) { - val showTasks by settingViewState.showTasksFlow.collectAsState() - val simpleEdit by settingViewState.simpleEditFlow.collectAsState() + val showTasks by settingViewState.showTasksFlow.collectAsStateWithLifecycle() + val simpleEdit by settingViewState.simpleEditFlow.collectAsStateWithLifecycle() - val swipe by settingViewState.swipeSettings.collectAsState() + val swipe by settingViewState.swipeSettings.collectAsStateWithLifecycle() val swipeSettings = swipe ?: SwipeSettings() - val swipeDialogSide by settingViewState.swipeDialogSide.collectAsState() - val languageDialogVisible by settingViewState.languageDialogVisible.collectAsState() + val swipeDialogSide by settingViewState.swipeDialogSide.collectAsStateWithLifecycle() + val languageDialogVisible by settingViewState.languageDialogVisible.collectAsStateWithLifecycle() val settingsBuilder = remember { SettingsBuilder() } val settingsCategories = settingsBuilder.buildSettingsCategories( diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/BackupFlows.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/BackupFlows.kt index 2db29eba..a0fbd7f5 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/BackupFlows.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/BackupFlows.kt @@ -39,9 +39,19 @@ import org.jetbrains.compose.resources.StringResource * start from Settings → Security; they share the re-authentication and phrase steps with * backups. [EXPORT_MARKDOWN] is the plaintext export, run by [MarkdownExportViewModel] (it needs * no recovery phrase and writes no encrypted backup). [ALLOW_SCREENSHOTS] is "Allow screenshots until the app - * locks": the re-authentication is the whole flow, then the allowance is on. + * locks": the re-authentication is the whole flow, then the allowance is on. [CONFIRM_SETTING] is a security + * setting changed to a weaker value: the change waits in [BackupViewModel.confirmSetting] and is applied after it. */ -enum class BackupAction { EXPORT, EXPORT_MARKDOWN, IMPORT, CREATE_PHRASE, REPLACE_PHRASE, ERASE, ALLOW_SCREENSHOTS } +enum class BackupAction { + EXPORT, + EXPORT_MARKDOWN, + IMPORT, + CREATE_PHRASE, + REPLACE_PHRASE, + ERASE, + ALLOW_SCREENSHOTS, + CONFIRM_SETTING, +} /** Where a backup or vault flow currently is. Each step is one dialog or system picker. */ sealed interface BackupStep { diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/BackupViewModel.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/BackupViewModel.kt index 1f10d980..ae2a2817 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/BackupViewModel.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/BackupViewModel.kt @@ -33,6 +33,7 @@ import kotlinx.coroutines.withContext @ContributesIntoMap(AppScope::class, binding()) @ViewModelKey @Inject +@Suppress("TooManyFunctions") // One entry point per flow of the page; the flows themselves are in BackupFlows. class BackupViewModel( backupManager: BackupManager, private val phraseSetup: BackupPhraseSetup, @@ -56,6 +57,9 @@ class BackupViewModel( /** The session the re-authentication was started in, and the lock requests there had been by then. */ private var reauthSession = SessionMark(generation = 0L, lockRequests = 0L) + /** A weakening setting change waiting for the re-authentication; never kept past a cancel or a lock. */ + private val pendingSetting = PendingSetting() + init { // A re-lock drops every plaintext buffer (a decrypted backup, new recovery words) at // once, even while the app is in the background and this screen is not composed. An @@ -66,6 +70,7 @@ class BackupViewModel( phraseFlow.drop() importFlow.drop() action = null + pendingSetting.clear() state.ui.update { it.copy(step = BackupStep.Idle, busy = false) } } } @@ -80,6 +85,15 @@ class BackupViewModel( state.go(BackupStep.Reauth(action, biometric)) } + /** + * Asks for the PIN (or biometric) before [apply], a change that weakens a security setting, runs. [apply] is + * dropped unapplied on cancel, on a wrong-PIN flow that is left, and on any lock; keep it to the value to set. + */ + fun confirmSetting(apply: () -> Unit) { + start(BackupAction.CONFIRM_SETTING) + pendingSetting.hold(apply) + } + private suspend fun proceed(action: BackupAction) { when { action == BackupAction.IMPORT -> state.go(BackupStep.PickImportFile) @@ -94,12 +108,18 @@ class BackupViewModel( // with no delay), this must not switch the allowance on after the lock that ended it. A lock that // still waits for the editors' saves has not set `locked` yet, so the lock requests are compared // too, as an unlock does (SessionLockManager.onUnlocked). - if (!sessionLockManager.locked.value && sessionLockManager.mark() == reauthSession) { + if (sessionLockManager.unchangedSince(reauthSession)) { screenshots.allow() } state.go(BackupStep.Idle) } + // Same guard as above: a lock after the request, even one still waiting for the editors, discards it. + action == BackupAction.CONFIRM_SETTING -> { + pendingSetting.release(sessionLockManager.unchangedSince(reauthSession)) + state.go(BackupStep.Idle) + } + // Held for five seconds on the security page, then re-authenticated: that is the // confirmation, so the erase runs straight away. action == BackupAction.ERASE -> { @@ -183,6 +203,7 @@ class BackupViewModel( } private fun dropPending() { + pendingSetting.clear() exportFlow.drop() phraseFlow.drop() importFlow.drop() @@ -196,3 +217,6 @@ class BackupViewModel( private data class SessionMark(val generation: Long, val lockRequests: Long) private fun SessionLockManager.mark() = SessionMark(sessionGeneration, lockRequests()) + +/** Unlocked, and no lock was asked for since [session] was marked (see [ALLOW_SCREENSHOTS] in `proceed`). */ +private fun SessionLockManager.unchangedSince(session: SessionMark) = !locked.value && mark() == session diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/SecurityChanges.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/SecurityChanges.kt new file mode 100644 index 00000000..c27f61b5 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/SecurityChanges.kt @@ -0,0 +1,49 @@ +package com.pasich.encly.presentation.viewmodel + +import com.pasich.encly.core.security.AutoLockDelay + +/* + * Settings → Security: a change that weakens protection asks for the PIN (or biometric) first, a change that + * strengthens it applies at once. The switches read their value from the stores, so until [apply] runs they keep + * showing the old value; a cancel or a wrong PIN leaves it. + */ + +/** A longer auto-lock delay keeps the vault open longer, so it asks; the same or a shorter one does not. */ +internal fun BackupViewModel.changeAutoLock(current: AutoLockDelay, new: AutoLockDelay, apply: () -> Unit) = + askUnless(new.millis <= current.millis, apply) + +/** Turning strict keyboard privacy off lets the keyboard learn note text again; turning it on does not ask. */ +internal fun BackupViewModel.changeStrictKeyboard(strict: Boolean, apply: () -> Unit) = askUnless(strict, apply) + +/** Showing note previews puts note text in the lists; hiding them does not ask. */ +internal fun BackupViewModel.changeNotePreviews(show: Boolean, apply: () -> Unit) = askUnless(!show, apply) + +/** + * Enabling biometric unlock asks for the PIN first (the re-authentication offers a fingerprint only when it is + * already on); disabling keeps its own strong-biometric confirmation. + */ +internal fun BackupViewModel.changeBiometric(enable: Boolean, apply: () -> Unit) = askUnless(!enable, apply) + +private fun BackupViewModel.askUnless(harmless: Boolean, apply: () -> Unit) { + if (harmless) apply() else confirmSetting(apply) +} + +/** The one weakening setting change waiting for its re-authentication. */ +internal class PendingSetting { + private var apply: (() -> Unit)? = null + + fun hold(apply: () -> Unit) { + this.apply = apply + } + + fun clear() { + apply = null + } + + /** Runs the held change when [allowed] and forgets it either way. */ + fun release(allowed: Boolean) { + val change = apply + apply = null + if (allowed) change?.invoke() + } +} diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/StartupViewModel.kt b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/StartupViewModel.kt index 10d7dec0..3eeca37e 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/StartupViewModel.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/presentation/viewmodel/StartupViewModel.kt @@ -2,6 +2,7 @@ package com.pasich.encly.presentation.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import com.pasich.encly.domain.repository.NotesRepository import com.pasich.encly.domain.usecase.note.PurgeExpiredTrashUseCase import com.pasich.encly.whatsnew.BundledChangelogs import com.pasich.encly.whatsnew.Changelogs @@ -15,23 +16,36 @@ import dev.zacsweers.metrox.viewmodel.ViewModelKey import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch /** * What the app does once per start and once per unlock, off any screen's own business: tells [WhatsNewTracker] * about a fresh install, and, when the vault has been opened, empties the trash of notes older than 28 days and - * decides whether "What's new" is due. + * decides whether "What's new" is due, and whether the person who came from a version below 3.0.0 is told that the + * trash now empties itself. */ @ContributesIntoMap(AppScope::class, binding()) @ViewModelKey @Inject -class StartupViewModel(private val whatsNew: WhatsNewTracker, private val purgeTrash: PurgeExpiredTrashUseCase) : - ViewModel() { +class StartupViewModel( + private val whatsNew: WhatsNewTracker, + private val purgeTrash: PurgeExpiredTrashUseCase, + private val notes: NotesRepository, +) : ViewModel() { private val _whatsNewDue = MutableStateFlow(null) /** The notes to show in the "What's new" sheet, or null when none is due (or it was dismissed). */ val whatsNewDue: StateFlow = _whatsNewDue.asStateFlow() + private val _trashNoticeCount = MutableStateFlow(null) + + /** + * How many notes are in the trash, when this start is the first after an update from a version below 3.0.0 (it + * did not empty the trash) and the trash has notes; else null. Shown once, then [dismissTrashNotice]. + */ + val trashNoticeCount: StateFlow = _trashNoticeCount.asStateFlow() + private var unlocked = false /** The app started: a [freshInstall] has seen no version before this one, so it has nothing new to read. */ @@ -43,8 +57,19 @@ class StartupViewModel(private val whatsNew: WhatsNewTracker, private val purgeT fun onUnlocked(languageTag: String, bundled: Map = BundledChangelogs.notes) { if (unlocked) return unlocked = true - viewModelScope.launch { purgeTrash() } - if (whatsNew.takeUnseen()) _whatsNewDue.value = Changelogs.notes(languageTag, bundled) + val update = whatsNew.takeUpdate() + viewModelScope.launch { + purgeTrash() + if (update?.fromBeforeTrashRetention == true) { + val inTrash = notes.getTrashNotes().first().size + if (inTrash > 0) _trashNoticeCount.value = inTrash + } + } + if (update != null) _whatsNewDue.value = Changelogs.notes(languageTag, bundled) + } + + fun dismissTrashNotice() { + _trashNoticeCount.value = null } fun dismissWhatsNew() { diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/whatsnew/WhatsNewTracker.kt b/shared/src/commonMain/kotlin/com/pasich/encly/whatsnew/WhatsNewTracker.kt index aeb22f26..50d22289 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/whatsnew/WhatsNewTracker.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/whatsnew/WhatsNewTracker.kt @@ -25,17 +25,36 @@ class WhatsNewTracker(private val flags: KeyValueStore, private val appInfo: App * True once per version: when this version is newer than the one recorded (or none is recorded, an install * from before this existed). The version is recorded at once, so the next call is false. */ - fun takeUnseen(): Boolean { + fun takeUnseen(): Boolean = takeUpdate() != null + + /** + * Like [takeUnseen], but tells which version the update came from: null when nothing is due (same version, a + * downgrade or a fresh install), else the [VersionUpdate]. The version is recorded at once, so the next call + * is null. + */ + fun takeUpdate(): VersionUpdate? { val last = flags.getString(LAST_SEEN_KEY, null) val current = appInfo.versionName - if (last == current) return false + if (last == current) return null record() - return last == null || isNewer(current, last) + return if (last == null || isNewer(current, last)) VersionUpdate(last) else null } private fun record() = flags.edit { putString(LAST_SEEN_KEY, appInfo.versionName) } + /** An update to this version from [previous]; null when nothing was recorded (an install from before this). */ + class VersionUpdate(val previous: String?) { + /** + * True when the install came from a version below 3.0.0, which did not delete trashed notes after 28 days. A + * version that is not `MAJOR.MINOR.PATCH` is not counted: its trash is not known to be new to the person. + */ + val fromBeforeTrashRetention: Boolean + get() = previous == null || code(previous)?.let { it < TRASH_RETENTION_VERSION_CODE } == true + } + private companion object { + /** 3.0.0, the first version that empties the trash on its own. */ + const val TRASH_RETENTION_VERSION_CODE = 30_000L const val LAST_SEEN_KEY = "whats_new_last_seen_version" val VERSION = Regex("""^(\d+)\.(\d+)\.(\d+)""") diff --git a/shared/src/commonTest/kotlin/com/pasich/encly/presentation/editor/persistence/NotePersistenceTest.kt b/shared/src/commonTest/kotlin/com/pasich/encly/presentation/editor/persistence/NotePersistenceTest.kt index 9623422c..76126164 100644 --- a/shared/src/commonTest/kotlin/com/pasich/encly/presentation/editor/persistence/NotePersistenceTest.kt +++ b/shared/src/commonTest/kotlin/com/pasich/encly/presentation/editor/persistence/NotePersistenceTest.kt @@ -497,6 +497,22 @@ class NotePersistenceTest { assertTrue(repository.deletedIds.isEmpty()) } + @Test + fun aFailedDeleteIsReportedAndTheNoteIsStillThere() = runTest(dispatcher) { + storeNote(text("body")) + val persistence = persistence(loading = true) + persistence.load(NOTE_ID, isCopy = false) { blocks = it } + repository.deleteNoteFails = true + + assertFalse(persistence.delete()) + + // The editor is not closed: a later delete, once the disk answers, goes through. + assertEquals(listOf(NOTE_ID), repository.deletedIds) + repository.deleteNoteFails = false + assertTrue(persistence.delete()) + assertEquals(listOf(NOTE_ID, NOTE_ID), repository.deletedIds) + } + @Test fun aDuplicateIsStoredAsACopy() = runTest(dispatcher) { val persistence = persistence() diff --git a/shared/src/commonTest/kotlin/com/pasich/encly/presentation/screen/editnote/EditorExitsTest.kt b/shared/src/commonTest/kotlin/com/pasich/encly/presentation/screen/editnote/EditorExitsTest.kt new file mode 100644 index 00000000..80f33632 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/pasich/encly/presentation/screen/editnote/EditorExitsTest.kt @@ -0,0 +1,195 @@ +package com.pasich.encly.presentation.screen.editnote + +import androidx.lifecycle.SavedStateHandle +import com.pasich.encly.core.resources.Res +import com.pasich.encly.core.resources.note_delete_failed +import com.pasich.encly.core.resources.note_save_failed +import com.pasich.encly.data.model.Note +import com.pasich.encly.data.model.NoteWithTags +import com.pasich.encly.domain.usecase.note.UpdateNoteArchiveStatusUseCase +import com.pasich.encly.domain.usecase.note.UpdateNoteTrashStatusUseCase +import com.pasich.encly.editor.codec.BlockConverter +import com.pasich.encly.editor.model.Block +import com.pasich.encly.presentation.viewmodel.EditNoteViewModel +import com.pasich.encly.testutil.TestNotesRepository +import com.pasich.encly.testutil.TestSettingsRepository +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.jetbrains.compose.resources.StringResource +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The ways out of the editor write first and leave only once the write went through (issues #3 and #5): a slow + * write holds the editor on screen, a failed one keeps it open and says so. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class EditorExitsTest { + private val dispatcher = StandardTestDispatcher() + private val repository = TestNotesRepository() + private val place = RecordingPlace() + private val failures = mutableListOf() + private var beforeLeavingCalls = 0 + + private class RecordingPlace : EditorPlace { + var closed = 0 + override fun close() { + closed += 1 + } + + override fun openCopy(copyId: Long) = Unit + } + + @BeforeTest + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun backWaitsForASlowSaveBeforeLeaving() = runTest(dispatcher) { + storeNote() + val exits = exits(editorWithEdit()) + val gate = CompletableDeferred() + repository.updateGate = gate + + exits.back() + runCurrent() + + // The write is under way and not finished: the editor stays, and says nothing yet. + assertEquals(1, repository.updateCalls) + assertEquals(0, place.closed) + assertEquals(0, beforeLeavingCalls) + assertTrue(failures.isEmpty()) + + // A second Back (gesture and arrow) while it runs neither writes again nor pops twice. + exits.back() + runCurrent() + assertEquals(1, repository.updateCalls) + + gate.complete(Unit) + advanceUntilIdle() + + assertEquals(1, place.closed) + assertEquals(1, beforeLeavingCalls) + assertTrue(failures.isEmpty()) + } + + @Test + fun aFailedSaveKeepsTheEditorOpenWithTheErrorAndBackWorksAgainAfterwards() = runTest(dispatcher) { + storeNote() + val exits = exits(editorWithEdit()) + repository.updateResult = false + + exits.back() + advanceUntilIdle() + + assertEquals(0, place.closed) + assertEquals(0, beforeLeavingCalls) + assertEquals(listOf(Res.string.note_save_failed), failures) + + repository.updateResult = true + exits.back() + advanceUntilIdle() + + assertEquals(1, place.closed) + assertEquals(listOf(Res.string.note_save_failed), failures) + } + + @Test + fun aFailedFirstSaveOfANewNoteKeepsTheEditorOpenWithTheError() = runTest(dispatcher) { + repository.insertResult = 0L + val viewModel = viewModel(SavedStateHandle()) + advanceUntilIdle() + viewModel.updateTitle("Never stored") + val exits = exits(viewModel) + + exits.back() + advanceUntilIdle() + + assertEquals(0, place.closed) + assertEquals(listOf(Res.string.note_save_failed), failures) + } + + @Test + fun aFailedSingleNoteDeleteIsReportedNotShownAsSuccess() = runTest(dispatcher) { + storeNote(isTrash = true) + val viewModel = viewModel(SavedStateHandle(mapOf("idNote" to NOTE_ID, "isReadTrashOnly" to true))) + advanceUntilIdle() + val exits = exits(viewModel) + repository.deleteNoteFails = true + + exits.delete() + advanceUntilIdle() + + // The delete was tried, failed, and the editor neither left nor claimed it worked. + assertEquals(listOf(NOTE_ID), repository.deletedIds) + assertEquals(0, place.closed) + assertEquals(0, beforeLeavingCalls) + assertEquals(listOf(Res.string.note_delete_failed), failures) + + repository.deleteNoteFails = false + exits.delete() + advanceUntilIdle() + + assertEquals(1, place.closed) + assertEquals(listOf(Res.string.note_delete_failed), failures) + } + + private fun exits(viewModel: EditNoteViewModel) = EditorExits( + viewModel = viewModel, + where = place, + scope = CoroutineScope(dispatcher), + onFailure = { failures += it }, + beforeLeaving = { beforeLeavingCalls += 1 }, + ) + + private fun TestScope.editorWithEdit(): EditNoteViewModel { + val viewModel = viewModel(SavedStateHandle(mapOf("idNote" to NOTE_ID))) + advanceUntilIdle() + viewModel.updateTitle("Edited") + return viewModel + } + + private fun storeNote(isTrash: Boolean = false) { + val note = Note( + id = NOTE_ID, + title = "Stored", + value = BlockConverter.blocksToJson(listOf(Block.TextBlock(MutableStateFlow("body")))), + isTrash = isTrash, + ) + repository.allNotesWithTags.value = listOf(NoteWithTags(note, emptyList())) + } + + private fun viewModel(handle: SavedStateHandle) = EditNoteViewModel( + notesRepository = repository, + savedStateHandle = handle, + updateNoteTrashStatusUseCase = UpdateNoteTrashStatusUseCase(repository), + updateNoteArchiveStatusUseCase = UpdateNoteArchiveStatusUseCase(repository), + settingsRepository = TestSettingsRepository(), + appScope = CoroutineScope(dispatcher), + ioDispatcher = dispatcher, + copyTitle = { "$it (Copy)" }, + ) + + private companion object { + const val NOTE_ID = 12L + } +} diff --git a/shared/src/commonTest/kotlin/com/pasich/encly/testutil/TestNotesRepository.kt b/shared/src/commonTest/kotlin/com/pasich/encly/testutil/TestNotesRepository.kt index 667fb42d..41d9b11e 100644 --- a/shared/src/commonTest/kotlin/com/pasich/encly/testutil/TestNotesRepository.kt +++ b/shared/src/commonTest/kotlin/com/pasich/encly/testutil/TestNotesRepository.kt @@ -52,10 +52,14 @@ internal class TestNotesRepository : NotesRepository { /** The `base` of every [updateEdited], in call order. */ val updateBases = mutableListOf() + /** When set, [updateEdited] waits for it after recording the call: a slow write a test finishes when it likes. */ + var updateGate: CompletableDeferred? = null + override suspend fun updateEdited(note: Note, base: Note?): Result { updateCalls += 1 updatedNotes += note updateBases += base + updateGate?.await() return if (updateResult) Result.success(Unit) else Result.failure(IllegalStateException()) } @@ -126,8 +130,12 @@ internal class TestNotesRepository : NotesRepository { /** Every id passed to [deleteNoteById], in call order. */ val deletedIds = mutableListOf() + /** Set to make [deleteNoteById] fail: the call is recorded, the note stays. */ + var deleteNoteFails = false + override suspend fun deleteNoteById(id: Long): Result { deletedIds += id + if (deleteNoteFails) return Result.failure(IllegalStateException("disk")) return Result.success(Unit) } diff --git a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/presentation/viewmodel/NoteListViewModelTest.kt b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/presentation/viewmodel/NoteListViewModelTest.kt index 2d9a722c..56972427 100644 --- a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/presentation/viewmodel/NoteListViewModelTest.kt +++ b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/presentation/viewmodel/NoteListViewModelTest.kt @@ -20,7 +20,9 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest @@ -214,6 +216,62 @@ class NoteListViewModelTest { assertEquals(second, viewModel.scrollToTopRequest.value) } + @Test + fun rapidTagAndSortSwitchesEndOnTheLastSelectionWithoutAStaleOrDoubledList() = runTest { + val repository = TestNotesRepository() + val settings = mock(SettingsRepository::class.java) + val sortFlow = MutableStateFlow(NoteSortOption.UPDATED_DESC) + `when`(settings.getSortNotes).thenReturn(sortFlow) + val tagSelection = SelectedTagHolder() + val viewModel = NoteListViewModel( + observeNotesUseCase = ObserveNotesUseCase(repository, dispatcher), + updateNoteTrashStatusUseCase = UpdateNoteTrashStatusUseCase(repository), + updateNoteTagUseCase = UpdateNoteTagUseCase(repository), + selectedTagHolder = tagSelection, + settingsRepository = settings, + updateNoteDescriptionUseCase = UpdateNoteDescriptionUseCase(repository), + updateNotePinStatusUseCase = UpdateNotePinStatusUseCase(repository), + updateNoteArchiveStatusUseCase = UpdateNoteArchiveStatusUseCase(repository), + updateNoteColorUseCase = UpdateNoteColorUseCase(repository), + ) + val work = Tag(id = WORK_TAG_ID, nameTag = "Work") + val home = Tag(id = HOME_TAG_ID, nameTag = "Home") + repository.allNotesWithTags.value = listOf(noteWithTitle(1, "all-1"), noteWithTitle(2, "all-2")) + repository.tagFlow(WORK_TAG_ID).value = + listOf(noteWithTitle(3, "work-3", work), noteWithTitle(4, "work-4", work)) + repository.tagFlow(HOME_TAG_ID).value = + listOf(noteWithTitle(5, "home-5", home), noteWithTitle(6, "home-6", home)) + advanceUntilIdle() + + // Every list the screen is ever handed: none may repeat a note. + val shown = mutableListOf>() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + viewModel.state.collect { state -> shown += state.notes.map { it.note.id } } + } + + // Several switches in a row, none awaited: only the last tag and the last sort may remain. + viewModel.onEvent(NoteListEvent.SelectTag(work)) + sortFlow.value = NoteSortOption.CREATED_ASC + viewModel.onEvent(NoteListEvent.SelectTag(home)) + viewModel.onEvent(NoteListEvent.SelectTag(Tag())) + sortFlow.value = NoteSortOption.UPDATED_DESC + viewModel.onEvent(NoteListEvent.SelectTag(work)) + sortFlow.value = NoteSortOption.CREATED_ASC + advanceUntilIdle() + + val state = viewModel.state.value + assertEquals(WORK_TAG_ID, state.selectedTag) + assertEquals(NoteSortOption.CREATED_ASC, state.noteSortOption) + assertEquals(listOf("work-3", "work-4"), state.notes.map { it.note.title }) + shown.forEach { ids -> assertEquals("a list repeats a note: $ids", ids.distinct(), ids) } + + // A late change of a list that is no longer selected does not reach the screen. + repository.allNotesWithTags.value = listOf(noteWithTitle(7, "all-late")) + repository.tagFlow(HOME_TAG_ID).value = listOf(noteWithTitle(8, "home-late", home)) + advanceUntilIdle() + assertEquals(listOf("work-3", "work-4"), viewModel.state.value.notes.map { it.note.title }) + } + private fun noteWithTitle(id: Long, title: String, tag: Tag? = null): NoteWithTags = NoteWithTags( Note( id = id, @@ -227,6 +285,7 @@ class NoteListViewModelTest { private companion object { const val WORK_TAG_ID = 7L + const val HOME_TAG_ID = 8L const val ALL_NOTE_ID = 11L const val TAGGED_NOTE_ID = 12L const val STALE_NOTE_ID = 13L diff --git a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/whatsnew/WhatsNewTest.kt b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/whatsnew/WhatsNewTest.kt index 8e4b3409..a3a4bcb0 100644 --- a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/whatsnew/WhatsNewTest.kt +++ b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/whatsnew/WhatsNewTest.kt @@ -194,6 +194,7 @@ class WhatsNewTest { private fun startup(version: String, repository: TestNotesRepository = TestNotesRepository()) = StartupViewModel( tracker(version), PurgeExpiredTrashUseCase(repository, flags), + repository, ) @Test @@ -259,4 +260,65 @@ class WhatsNewTest { assertEquals(listOf(1L), repository.deletedIds) } + + private fun inTrash(count: Int) = TestNotesRepository().also { repository -> + repository.trashNotes.value = + List(count) { Note(id = it + 1L, isTrash = true, trashedAt = System.currentTimeMillis()) } + } + + /** An install that last ran [from] (null: nothing recorded) and now runs [to], unlocked with [repository]. */ + private fun unlockAfter(from: String?, to: String, repository: TestNotesRepository): StartupViewModel { + if (from != null) tracker(from).recordFreshInstall() + return startup(to, repository).also { it.onUnlocked("en", bundled = emptyMap()) } + } + + @Test + fun anUpdateFromBeforeThreeNoticesTheTrashOnceAndNotAgain() { + val repository = inTrash(3) + val viewModel = unlockAfter("2.5.0", "3.0.1", repository) + assertEquals(3, viewModel.trashNoticeCount.value) + + viewModel.dismissTrashNotice() + assertNull(viewModel.trashNoticeCount.value) + val again = startup("3.0.1", repository) + again.onUnlocked("en", bundled = emptyMap()) + assertNull("the next unlock, a fresh ViewModel, has nothing to say", again.trashNoticeCount.value) + } + + @Test + fun anInstallFromBeforeTheVersionWasRecordedIsTold() { + assertEquals(2, unlockAfter(null, "3.0.1", inTrash(2)).trashNoticeCount.value) + } + + @Test + fun anUpdateFromThreeOrLaterIsNotToldBecauseItsCountdownIsRunning() { + assertNull(unlockAfter("3.0.0", "3.0.1", inTrash(3)).trashNoticeCount.value) + assertNull(unlockAfter("3.0.1", "3.1.0", inTrash(3)).trashNoticeCount.value) + } + + @Test + fun aFreshInstallIsNotTold() { + val viewModel = startup("3.0.1", inTrash(3)) + viewModel.onAppStart(freshInstall = true) + viewModel.onUnlocked("en", bundled = emptyMap()) + + assertNull(viewModel.trashNoticeCount.value) + } + + @Test + fun anEmptyTrashIsNotTold() { + assertNull(unlockAfter("2.5.0", "3.0.1", inTrash(0)).trashNoticeCount.value) + } + + @Test + fun theNoticeCountsWhatIsLeftAfterTheCleaningOfExpiredNotes() { + val repository = inTrash(2) + repository.trashNotes.value += Note( + id = 9, + isTrash = true, + trashedAt = System.currentTimeMillis() - TRASH_RETENTION_MILLIS - 60_000, + ) + + assertEquals(2, unlockAfter("2.5.0", "3.0.1", repository).trashNoticeCount.value) + } } diff --git a/version.properties b/version.properties index 575cf048..b3f07cd2 100644 --- a/version.properties +++ b/version.properties @@ -8,4 +8,4 @@ # refuses a tag that does not match this file. See CONTRIBUTING.md > Releasing. VERSION_MAJOR=3 VERSION_MINOR=0 -VERSION_PATCH=0 +VERSION_PATCH=1