diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml new file mode 100644 index 0000000..7a9c576 --- /dev/null +++ b/.forgejo/workflows/ci.yml @@ -0,0 +1,95 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + macos: + runs-on: macos-arm64 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + path: carrier + # Cargo.toml depends on fumi-core via a relative sibling path + # (../fumi/core), matching how it's checked out locally. Fetched as + # its own sibling checkout here so that path resolves the same way. + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + repository: randogoth/fumi + ref: main + path: fumi + # Cache key includes the OS explicitly: target/ artifacts are + # platform-specific, so macOS and Linux must never share a cache key + # or they'd clobber each other's compiled objects. + - uses: https://code.forgejo.org/actions/cache@v4 + with: + path: | + ~/.cargo/registry + carrier/target + fumi/target + key: cargo-macos-${{ hashFiles('carrier/Cargo.lock') }} + restore-keys: cargo-macos- + # Forgejo auto-injects GITHUB_TOKEN (GH Actions compatibility), scoped + # to this Forgejo instance. Nix auto-detects that env var and assumes + # it's a github.com credential, so it sends it to api.github.com when + # fetching nixpkgs tarballs for devbox - which rejects it with 401. + # Clearing it here falls back to unauthenticated (fine for public + # nixpkgs fetches, same as this succeeds locally with no token set). + - run: devbox run check + working-directory: carrier + env: + GITHUB_TOKEN: "" + + linux: + runs-on: linux-x86_64 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + path: carrier + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + repository: randogoth/fumi + ref: main + path: fumi + - uses: https://code.forgejo.org/actions/cache@v4 + with: + path: | + ~/.cargo/registry + carrier/target + fumi/target + key: cargo-linux-${{ hashFiles('carrier/Cargo.lock') }} + restore-keys: cargo-linux- + - run: devbox run check + working-directory: carrier + env: + GITHUB_TOKEN: "" + + windows: + runs-on: windows-x86_64 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + path: carrier + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + repository: randogoth/fumi + ref: main + path: fumi + - uses: https://code.forgejo.org/actions/cache@v4 + with: + path: | + ~/.cargo/registry + carrier/target + fumi/target + key: cargo-windows-${{ hashFiles('carrier/Cargo.lock') }} + restore-keys: cargo-windows- + # No devbox on Windows: the runner host itself is the MSYS2 MINGW64 + # toolchain that windows/setup.sh installs, so this runs the same + # commands devbox's `check` script runs on the other two platforms + # straight from cargo. + - run: cargo fmt --check && cargo build && cargo test + working-directory: carrier + shell: bash diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml new file mode 100644 index 0000000..feb7796 --- /dev/null +++ b/.forgejo/workflows/release.yml @@ -0,0 +1,229 @@ +name: Release + +on: + push: + tags: ["v*"] + +jobs: + macos: + runs-on: macos-arm64 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + path: carrier + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + repository: randogoth/fumi + ref: main + path: fumi + - uses: https://code.forgejo.org/actions/cache@v4 + with: + path: | + ~/.cargo/registry + carrier/target + fumi/target + key: cargo-macos-${{ hashFiles('carrier/Cargo.lock') }} + restore-keys: cargo-macos- + - run: devbox run build + working-directory: carrier + env: + GITHUB_TOKEN: "" + - run: mv target/release/carrier target/release/carrier-macos-arm64 + working-directory: carrier + # This runner is a laptop that's frequently asleep/offline, so this + # job must not gate the release (and must not be gated by it either). + # Instead of going through actions/forgejo-release - which only knows + # how to blind-create a release, not append to one that may already + # exist - this polls for the release the linux+flatpak job creates + # and appends its own asset directly via the Forgejo API, landing + # next to whatever binaries are already there. grep (not jq, whose + # presence here isn't guaranteed) is safe for pulling the id out: per + # Forgejo's structs.Release, ID is the first declared field and Go's + # encoding/json marshals in declaration order, ahead of the nested + # per-asset "id" fields in the "assets" array. + - run: | + REPO="${{ forge.repository }}" + TAG="${{ forge.ref_name }}" + FORGEJO="${{ env.FORGEJO_SERVER_URL }}" + FORGEJO="${FORGEJO%%/}" + TOKEN="${{ forge.token }}" + FILE="target/release/carrier-macos-arm64" + NAME="carrier-macos-arm64" + + release_id="" + for i in $(seq 1 40); do + body=$(curl --retry 5 -sS -H "Authorization: token $TOKEN" "$FORGEJO/api/v1/repos/$REPO/releases/tags/$TAG") + release_id=$(echo "$body" | grep -o '"id":[0-9]*' | head -1 | grep -o '[0-9]*') + if [ -n "$release_id" ]; then + break + fi + echo "release for $TAG not ready yet, waiting 15s ($i/40)" + sleep 15 + done + + if [ -z "$release_id" ]; then + echo "release for $TAG never appeared after 10 minutes" >&2 + exit 1 + fi + + curl --retry 5 --fail -sS -X POST \ + -H "Authorization: token $TOKEN" \ + -H "Content-Type: multipart/form-data" \ + -F "attachment=@$FILE" \ + "$FORGEJO/api/v1/repos/$REPO/releases/$release_id/assets?name=$NAME" + working-directory: carrier + + # Same non-gating strategy as the macos job above: this runner is a + # desktop machine that isn't guaranteed to be on when a tag is pushed, + # so it must never gate the release (and must not be gated by it + # either). It builds and bundles via windows/bundle.sh - the same + # script windows/setup.sh runs for local one-command builds - wraps + # the bundle in an Inno Setup installer (windows/installer.sh; Inno + # lives in this runner host's user profile), then appends both the + # portable zip and the setup.exe to the release the linux+flatpak jobs + # create, with the same poll-for-the-release the macos job does. + windows: + runs-on: windows-x86_64 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + path: carrier + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + repository: randogoth/fumi + ref: main + path: fumi + - uses: https://code.forgejo.org/actions/cache@v4 + with: + path: | + ~/.cargo/registry + carrier/target + fumi/target + key: cargo-windows-${{ hashFiles('carrier/Cargo.lock') }} + restore-keys: cargo-windows- + - run: bash windows/bundle.sh + working-directory: carrier + shell: bash + - run: bash windows/installer.sh + working-directory: carrier + shell: bash + - run: | + REPO="${{ forge.repository }}" + TAG="${{ forge.ref_name }}" + FORGEJO="${{ env.FORGEJO_SERVER_URL }}" + FORGEJO="${FORGEJO%%/}" + TOKEN="${{ forge.token }}" + VERSION=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1) + FILES="carrier-windows-$VERSION.zip carrier-windows-$VERSION-setup.exe" + + release_id="" + for i in $(seq 1 40); do + body=$(curl --retry 5 -sS -H "Authorization: token $TOKEN" "$FORGEJO/api/v1/repos/$REPO/releases/tags/$TAG") + release_id=$(echo "$body" | grep -o '"id":[0-9]*' | head -1 | grep -o '[0-9]*') + if [ -n "$release_id" ]; then + break + fi + echo "release for $TAG not ready yet, waiting 15s ($i/40)" + sleep 15 + done + + if [ -z "$release_id" ]; then + echo "release for $TAG never appeared after 10 minutes" >&2 + exit 1 + fi + + for FILE in $FILES; do + curl --retry 5 --fail -sS -X POST \ + -H "Authorization: token $TOKEN" \ + -H "Content-Type: multipart/form-data" \ + -F "attachment=@$FILE" \ + "$FORGEJO/api/v1/repos/$REPO/releases/$release_id/assets?name=$FILE" + done + working-directory: carrier + shell: bash + + linux: + runs-on: linux-x86_64 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + path: carrier + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + repository: randogoth/fumi + ref: main + path: fumi + - uses: https://code.forgejo.org/actions/cache@v4 + with: + path: | + ~/.cargo/registry + carrier/target + fumi/target + key: cargo-linux-${{ hashFiles('carrier/Cargo.lock') }} + restore-keys: cargo-linux- + - run: devbox run build + working-directory: carrier + env: + GITHUB_TOKEN: "" + - run: mv target/release/carrier target/release/carrier-linux-x86_64 + working-directory: carrier + - uses: https://code.forgejo.org/forgejo/upload-artifact@v5 + with: + name: carrier-linux-x86_64 + path: carrier/target/release/carrier-linux-x86_64 + + # Builds from source inside flatpak-builder's own sandbox, via the + # rust-stable SDK extension (same as com.randogoth.carrier.json already + # does for local `devbox run package`). Reusing the linux job's binary + # was tried and reverted: that binary is dynamically linked against ~100 + # libraries at absolute /nix/store paths, including its own ELF + # interpreter - none of which exist inside the Flatpak sandbox, so it + # can never execute there regardless of how it's packaged in. + flatpak: + runs-on: linux-x86_64 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + path: carrier + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + repository: randogoth/fumi + ref: main + path: fumi + - run: devbox run bundle-flatpak + working-directory: carrier + env: + GITHUB_TOKEN: "" + - uses: https://code.forgejo.org/forgejo/upload-artifact@v5 + with: + name: carrier-x86_64.flatpak + path: carrier/carrier-x86_64.flatpak + + # forgejo-release.sh (the engine behind actions/forgejo-release) always + # does a blind create-then-upload of the release for the tag, with no + # check for one already existing - running it from two parallel jobs + # against the same tag either hard-fails the second create (override: + # false) or races a delete-and-recreate that can wipe out the first job's + # just-uploaded assets (override: true). So platform jobs only ever + # produce artifacts; exactly one job, gated on both finishing, does the + # single release create + upload. macos is deliberately left out of + # needs (see that job): re-running this job after macos has appended its + # asset will wipe that asset out via override - rerun macos again after + # to restore it. + release: + needs: [linux, flatpak] + runs-on: linux-x86_64 + steps: + - uses: https://code.forgejo.org/forgejo/download-artifact@v7 + with: + path: dist/release + merge-multiple: true + - uses: https://code.forgejo.org/actions/forgejo-release@v2.13.4 + with: + direction: upload + release-dir: dist/release + # Safe here specifically because this is the only job that ever + # calls forgejo-release for a given tag: re-running this same job + # for the same tag (e.g. a manual rerun) replaces its release + # cleanly instead of failing on "already exists". + override: true diff --git a/.gitignore b/.gitignore index 88d9f7a..51989d3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,16 @@ /target .flatpak .flatpak-builder +.flatpak-repo +.flatpak-build +*.flatpak +carrier-linux-x86_64 result result-* *.key *.db *.db-wal *.db-shm +/dist +carrier-windows-*.zip +carrier-windows-*-setup.exe diff --git a/AI-DECLARATION.md b/AI-DECLARATION.md new file mode 100644 index 0000000..1b5def6 --- /dev/null +++ b/AI-DECLARATION.md @@ -0,0 +1,12 @@ +--- +version: "0.1.2" +level: copilot +--- + +This format is based on [AI-DECLARATION.md](https://ai-declaration.md/en/0.1.2). + +## Notes + +- I directed the work step by step, reviewed and committed the results, and verified the UI live; build, packaging and cross-platform scripts. +- Mistral Vibe acted on a migration from Iced to Replm4, the follow-up refinement sessions, and the Flatpak and MSYS2 packaging. +- Claude Code was used throughout, prompted and reviewed by me at each step. Its main task was GTK4/adwaita refinements. diff --git a/Cargo.lock b/Cargo.lock index d4eb85f..afbbcc1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -116,8 +116,9 @@ dependencies = [ [[package]] name = "carrier" -version = "0.1.0" +version = "0.3.1" dependencies = [ + "fluent-bundle", "fumi-core", "gtk4", "libadwaita", @@ -125,6 +126,8 @@ dependencies = [ "rand_core", "relm4", "tempfile", + "unic-langid", + "winresource", ] [[package]] @@ -277,6 +280,17 @@ dependencies = [ "subtle", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "ed25519" version = "2.2.3" @@ -358,6 +372,41 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "fluent-bundle" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01203cb8918f5711e73891b347816d932046f95f54207710bda99beaeb423bf4" +dependencies = [ + "fluent-langneg", + "fluent-syntax", + "intl-memoizer", + "intl_pluralrules", + "rustc-hash", + "self_cell", + "smallvec", + "unic-langid", +] + +[[package]] +name = "fluent-langneg" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eebbe59450baee8282d71676f3bfed5689aeab00b27545e83e5f14b1195e8b0" +dependencies = [ + "unic-langid", +] + +[[package]] +name = "fluent-syntax" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54f0d287c53ffd184d04d8677f590f4ac5379785529e5e08b1c8083acdd5c198" +dependencies = [ + "memchr", + "thiserror", +] + [[package]] name = "flume" version = "0.11.1" @@ -381,7 +430,7 @@ dependencies = [ [[package]] name = "fumi-core" -version = "0.1.0" +version = "0.1.1" dependencies = [ "chacha20poly1305", "data-encoding", @@ -844,6 +893,25 @@ dependencies = [ "generic-array", ] +[[package]] +name = "intl-memoizer" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "310da2e345f5eb861e7a07ee182262e94975051db9e4223e909ba90f392f163f" +dependencies = [ + "type-map", + "unic-langid", +] + +[[package]] +name = "intl_pluralrules" +version = "7.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" +dependencies = [ + "unic-langid", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1126,6 +1194,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustc_version" version = "0.4.1" @@ -1160,6 +1234,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + [[package]] name = "semver" version = "1.0.28" @@ -1351,6 +1431,37 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + [[package]] name = "tokio" version = "1.53.1" @@ -1442,12 +1553,39 @@ dependencies = [ "once_cell", ] +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash", +] + [[package]] name = "typenum" version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unic-langid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05" +dependencies = [ + "unic-langid-impl", +] + +[[package]] +name = "unic-langid-impl" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658" +dependencies = [ + "tinystr", +] + [[package]] name = "unicode-ident" version = "1.0.26" @@ -1630,6 +1768,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winresource" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0986a8b1d586b7d3e4fe3d9ea39fb451ae22869dcea4aa109d287a374d866087" +dependencies = [ + "toml", + "version_check", +] + [[package]] name = "x25519-dalek" version = "2.0.1" @@ -1662,6 +1810,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" + [[package]] name = "zeroize" version = "1.9.0" @@ -1682,6 +1836,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "serde", + "zerofrom", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 6773e0a..b124695 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,19 +1,25 @@ [package] name = "carrier" -version = "0.1.0" +version = "0.3.1" edition = "2021" description = "A minimalist smolmail client built on fumi-core, with a Relm4 UI" license = "Apache-2.0" [dependencies] fumi-core = { path = "../fumi/core" } -gtk = { version = "0.9", package = "gtk4" } +# v4_10 unlocks gtk::FileDialog, used for the backup export/import pickers. +gtk = { version = "0.9", package = "gtk4", features = ["v4_10"] } # Relm4 pulls libadwaita in; the direct entry only raises the API level, # since Cargo unions features and the rows and dialogs used here are 1.5. libadwaita = { version = "0.7", features = ["v1_5"] } relm4 = { version = "0.9", features = ["libadwaita"] } rand_core = { version = "0.6", features = ["getrandom"] } qrcodegen = "1" +fluent-bundle = "0.16.0" +unic-langid = "0.9.6" + +[build-dependencies] +winresource = "0.1" [dev-dependencies] tempfile = "3" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c98d27d --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/LICENSE-2.0 + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md index afa3be6..e38ac4c 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,39 @@ # carrier -A minimalist desktop client for [Smol Mail](../smolmail): one compact window — the list above, the article below — built on [fumi-core](../fumi), the reference CLI's own library, with a [Relm4](https://relm4.org) (GTK4) UI built from libadwaita's own widgets, so it follows the user's theme and accent colour. One 32-byte seed is the only secret; mail stays sealed at rest and opens on demand. +[![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE) [![Built with Devbox](https://www.jetify.com/img/devbox/shield_galaxy.svg)](https://github.com/jetify-com/devbox/) [![AI-DECLARATION: copilot](https://img.shields.io/badge/䷼%20AI--DECLARATION-copilot-fee2e2?labelColor=fee2e2)](https://ai-declaration.md) + +A simple desktop client for [Smol Mail](../smolmail). One compact window: the message list above, the article below. It's built on [fumi-core](../fumi), the reference CLI's own library, with a [Relm4](https://relm4.org) (GTK4) UI made from libadwaita's own widgets, so it follows your theme and accent colour. One 32-byte seed is the only secret; mail stays sealed at rest and opens on demand. + +![carrier showing an inbox and an open message](docs/screenshots/carrier.png) ## What it does -- Create or restore an identity from a seed, shown once at creation time. -- Pin a server's key — paste the operator's, or connect and pin what it presents — then register a username or recall an existing address. -- Fetch (with cancel), read, reply and send sealed mail; the inbox, the requests tier and sent copies each keep their own folder. -- Composes closed by any sidebar trip are stashed as drafts — kept beside the store, reopened from a folder that appears only once one exists; Cancel is the only way to throw one away. -- Accept or block a requester when their mail carried a self-certifying reply address; accept tokens attach to accepted contacts automatically. -- Contacts with verified/tofu marks and smol:// import; your own identity opens in the same detail view, its address in the header bar with a QR share beside it, key, fingerprint and URI below. -- Key rotation with a confirm-first step, server pin management, a network timeout, and gsmol backup export/import that never contains the seed. +- Create an identity from a seed, or restore one you already have. The seed shows once, at creation. +- Pin a server's key, either by pasting the operator's key or connecting and trusting what the server presents. Then register a username, or recall an address you already own. +- Fetch, read, reply to and send sealed mail. Your inbox, requests and sent mail each live in their own folder. +- Close a compose window from the sidebar and carrier saves it as a draft automatically. Drafts live beside your mail store, in a folder that shows up once you have one; Cancel is the only way to throw one away. +- Add your own `Key: value` headers when writing mail, one per line under the subject. carrier checks each line against the frontmatter rules and won't let you override its own fields (subject, reply-to, in-reply-to, accept). When you open mail with custom headers, they show up between the meta line and the body, and replying offers to carry them into your draft, where you can still edit them. +- Accept or block someone who writes to you with a self-certifying reply address. Accepting also attaches an accept token to that contact automatically. +- Import contacts from a smol:// link and see whether they're verified or just trust-on-first-use. Each contact's detail view names the server their address lives on, whether you've pinned that server's key, and a button to pin it if you haven't. Your own identity opens the same way, with a QR code next to your address in the header bar and your key, fingerprint and URI below. +- Turn on strict first contact to make carrier pause before writing to someone new whose address carries no key. With it on, carrier offers to fetch and pin the server's key first, so you can check it against what the operator published, before the send goes out. A smol:// address with a key that differs from the one on file asks before replacing it, strict mode or not. +- Rotate your key with a confirmation step and a network timeout. Export and import gsmol backups that never contain the seed. Log out to erase your local files and return to onboarding. Your preferences live in a small sidecar file next to the store, so they survive a restart. -## Layout +## Download -``` -src/main.rs config directory, demo seeding, launch -src/app.rs state and update; blocking calls run on the worker pool -src/view.rs the Relm4 component: widgets, the op adapter, the re-render -src/ops.rs fumi-core calls, key/read-mark files, and the offline tests +Each release carries its binaries on the forge: [downloads for carrier](https://code.randogoth.com/randogoth/carrier/releases). + +### Flatpak + +```bash +flatpak install --user carrier-x86_64.flatpak +flatpak run com.randogoth.carrier ``` -## State +### Windows -Everything lives under `$XDG_CONFIG_HOME/carrier` (default `~/.config/carrier`): `carrier.key` is the master seed, written 0600; `carrier.db` is fumi-core's sealed store; `read.txt` is carrier's own read marks, one hex id per line. +Download the [installer](https://code.randogoth.com/randogoth/carrier/releases/download/v0.2.0/carrier-windows-0.2.0-setup.exe) and run it -## Run and verify +## Build ``` devbox run run # build release and launch @@ -33,23 +41,21 @@ devbox run check # fmt --check, build, tests devbox run test # tests only ``` -The tests run offline against an in-memory store: seed and key parsing, a sealed envelope listed and opened end to end, contact import, a full backup round-trip, pin labels and the date formatter. `scripts/devbox-libs.sh` puts the GUI stack's runtime libraries (wayland, xkbcommon, EGL, vulkan) on the library path inside the devbox shell — they are dlopened, so nothing that links the binary can provide them. +Tests run offline against an in-memory store and cover seed and key parsing, listing and opening a sealed envelope end to end, importing a contact, a full backup round-trip, pin labels and the date formatter. `scripts/devbox-libs.sh` adds the GUI stack's runtime libraries (wayland, xkbcommon, EGL, vulkan) to the library path inside the devbox shell, since they're loaded at runtime and nothing that links the binary can provide them. -## Status +### Packaging -Work in progress: the UI is unexercised against a live server — the store, crypto and address paths are covered by tests, the network flows (register, fetch, send, rotate) are wired to fumi-core's operations but only smoke-tested as far as launching the window. - -## Packaging - -`devbox run package` builds and installs the app as a Flatpak from -`com.randogoth.carrier.json` — the binary, the desktop file, the metainfo and -the icon all come from the repo, and the tooling (`flatpak`, `flatpak-builder`, -`appstreamcli`) lives in the devbox environment. The flatpak runtime is the one -dependency outside devbox; install it once: +Run `devbox run package` to build carrier and install it as a Flatpak, using `com.randogoth.carrier.json`. It picks up the binary, desktop file, metainfo and icon from the repo, and devbox provides the tooling (`flatpak`, `flatpak-builder`, `appstreamcli`). The one thing outside devbox is the flatpak runtime itself; install it once: flatpak install --user flathub org.gnome.Sdk//51 org.freedesktop.Sdk.Extension.rust-stable//26.08 -The result is installed into the user flatpak and runs as -`flatpak run com.randogoth.carrier`. Inside the sandbox the app keeps its -config under `~/.var/app/com.randogoth.carrier/config/carrier`, so a flatpak -install starts with a fresh identity rather than the dev build's account. +After that, carrier lives in your user flatpak and runs with `flatpak run com.randogoth.carrier`. Inside the sandbox it keeps its config under `~/.var/app/com.randogoth.carrier/config/carrier`, so a flatpak install starts with a fresh identity rather than your dev build's account. + +### Windows + +Install MSYS2 (`winget install MSYS2.MSYS2`), open the **MSYS2 MINGW64** shell, and run the setup script from your carrier checkout: + + git clone ssh://git@code.randogoth.com:2222/randogoth/carrier.git + cd carrier && windows/setup.sh + +`windows/setup.sh` installs the GTK and Rust stack into MSYS2, clones fumi next to carrier if you don't already have it, builds carrier, and bundles carrier.exe with the GTK runtime into `dist/` and a zip, a complete Windows distribution. carrier keeps its config in `%APPDATA%\carrier`. If MSYS2 updates its core mid-run, the shell may close; just rerun the script and it picks up where it left off. Cloning over SSH needs your key in `~/.ssh` inside the MSYS2 home. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..62b6d1b --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,1129 @@ +# Third-Party Notices + +carrier incorporates the third-party components listed below. Components are grouped by license, each with the copyright notice that applies to it, followed by the full license text. A component listed under several licenses is multi-licensed under those options; any one of them may be chosen. All components are redistributed unmodified from their published sources. + +The Rust crates listed are all crates resolved by `Cargo.lock`, including transitive dependencies, which are statically linked into the carrier binary. +The SQLite C library is bundled in source form by the `libsqlite3-sys` crate and is public domain (see the final section). + +## Apache License 2.0 + +- aead 0.5.2 - Copyright (c) 2019 The RustCrypto Project Developers Copyright (c) 2019 MobileCoin, LLC +- aes 0.8.4 - Copyright (c) 2018 Artyom Pavlov +- aes-gcm 0.10.3 - Copyright (c) 2019 The RustCrypto Project Developers +- ahash 0.8.12 - Copyright (c) 2018 Tom Kaitchuck +- autocfg 1.5.1 - Copyright (c) 2018 Josh Stone +- base64ct 1.8.3 - Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com) Copyright (c) 2021-2025 The RustCrypto Project Developers +- bitflags 2.13.2 - Copyright (c) 2014 The Rust Project Developers +- blake2 0.10.6 - Copyright (c) 2015-2016 The blake2-rfc Developers, Cesar Barros Copyright (c) 2017 Artyom Pavlov +- block-buffer 0.10.4 - Copyright (c) 2018-2019 The RustCrypto Project Developers +- bumpalo 3.20.3 - Copyright (c) 2019 Nick Fitzgerald +- cc 1.5.1 - Copyright (c) 2014 Alex Crichton +- cfg-expr 0.20.10 - Copyright (c) 2019 Embark Studios +- cfg-if 1.0.5 - Copyright (c) 2014 Alex Crichton +- chacha20 0.9.1 - Copyright (c) 2019-2023 The RustCrypto Project Developers +- chacha20poly1305 0.10.1 - Copyright (c) 2019 The RustCrypto Project Developers +- cipher 0.4.4 - Copyright (c) 2016-2020 RustCrypto Developers +- const-oid 0.9.6 - Copyright (c) 2020-2022 The RustCrypto Project Developers +- cpufeatures 0.2.17 - Copyright (c) 2020-2025 The RustCrypto Project Developers +- crypto-common 0.1.7 - Copyright (c) 2021 RustCrypto Developers +- ctr 0.9.2 - Copyright (c) 2018-2022 RustCrypto Developers Copyright (c) 2018 Artyom Pavlov +- curve25519-dalek-derive 0.1.1 - The curve25519-dalek-derive developers +- der 0.7.10 - Copyright (c) 2020-2023 The RustCrypto Project Developers +- digest 0.10.7 - Copyright (c) 2017 Artyom Pavlov +- displaydoc 0.2.7 - Jane Lusby +- ed25519 2.2.3 - Copyright 2018-2022 RustCrypto Developers +- equivalent 1.0.2 - Copyright (c) 2016--2023 +- errno 0.3.14 - Copyright (c) 2014 Chris Wong +- fallible-iterator 0.3.0 - Copyright (c) 2015 The rust-openssl-verify Developers +- fallible-streaming-iterator 0.1.9 - Copyright (c) 2016 The fallible-streaming-iterator Developers +- fastrand 2.5.0 - Stjepan Glavina +- fiat-crypto 0.2.9 - Copyright 2015-2020 the fiat-crypto authors (see the AUTHORS file) +- field-offset 0.3.6 - Copyright (c) 2016-2021 Diggory Blake, and other contributors. +- find-msvc-tools 0.1.14 - Copyright (c) 2014 Alex Crichton +- fluent-bundle 0.16.0 - Copyright 2017 Mozilla +- fluent-langneg 0.13.1 - Zibi Braniecki +- fluent-syntax 0.12.0 - Copyright 2017 Mozilla +- flume 0.11.1 - Joshua Barretto +- fragile 2.1.0 - Armin Ronacher +- futures 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-channel 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-core 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-executor 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-io 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-macro 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-sink 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-task 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-util 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- getrandom 0.2.17 - Copyright (c) 2018-2024 The rust-random Project Developers Copyright (c) 2014 The Rust Project Developers +- getrandom 0.4.3 - Copyright (c) 2018-2026 The rust-random Project Developers Copyright (c) 2014 The Rust Project Developers +- ghash 0.5.1 - Copyright (c) 2019 RustCrypto Developers +- hashbrown 0.14.5 - Copyright (c) 2016 Amanieu d'Antras +- hashbrown 0.17.1 - Copyright (c) 2016 Amanieu d'Antras +- hashlink 0.9.1 - kyren +- heck 0.5.0 - Copyright (c) 2015 The Rust Project Developers +- hkdf 0.12.4 - Copyright (c) 2015-2018 Vlad Filippov Copyright (c) 2018-2021 RustCrypto Developers +- hmac 0.12.1 - Copyright (c) 2017 Artyom Pavlov +- indexmap 2.14.2 - Copyright (c) 2016--2017 +- inout 0.1.4 - Copyright (c) 2022 The RustCrypto Project Developers Copyright (c) 2022 Artyom Pavlov +- intl-memoizer 0.5.3 - Copyright 2017 Mozilla +- intl_pluralrules 7.0.2 - Kekoa Riggin , Zibi Braniecki +- itoa 1.0.18 - David Tolnay +- js-sys 0.3.106 - Copyright (c) 2014 Alex Crichton +- libc 0.2.189 - Copyright (c) The Rust Project Developers +- linux-raw-sys 0.12.1 - Dan Gohman +- lock_api 0.4.14 - Copyright (c) 2016 The Rust Project Developers +- once_cell 1.21.4 - Aleksey Kladov +- opaque-debug 0.3.1 - Copyright (c) 2018-2024 The RustCrypto Project Developers +- pin-project-lite 0.2.17 - The pin-project-lite developers +- pkcs8 0.10.2 - Copyright (c) 2020-2023 The RustCrypto Project Developers +- pkg-config 0.3.34 - Copyright (c) 2014 Alex Crichton +- poly1305 0.8.0 - Copyright (c) 2015-2019 RustCrypto Developers +- polyval 0.6.2 - Copyright (c) 2019-2023 RustCrypto Developers +- proc-macro-crate 3.5.0 - Bastian Köcher +- proc-macro2 1.0.107 - David Tolnay , Alex Crichton +- quote 1.0.47 - David Tolnay +- r-efi 6.0.0 - The r-efi developers +- rand_core 0.6.4 - Copyright 2018 Developers of the Rand project Copyright (c) 2014 The Rust Project Developers +- relm4 0.9.1 - Aaron Erhardt +- relm4-css 0.9.0 - Aaron Erhardt +- relm4-macros 0.9.1 - Aaron Erhardt +- rustc-hash 2.1.3 - The Rust Project Developers +- rustc_version 0.4.1 - Copyright (c) 2016 The Rust Project Developers +- rustix 1.1.5 - Dan Gohman , Jakub Konka +- rustversion 1.0.23 - David Tolnay +- scopeguard 1.2.0 - Copyright (c) 2016-2019 Ulrik Sverdrup "bluss" and scopeguard developers +- self_cell 1.3.0 - Lukas Bergdoll +- semver 1.0.28 - David Tolnay +- serde 1.0.229 - Erick Tryzelaar , David Tolnay +- serde_core 1.0.229 - Erick Tryzelaar , David Tolnay +- serde_derive 1.0.229 - Erick Tryzelaar , David Tolnay +- serde_json 1.0.151 - Erick Tryzelaar , David Tolnay +- serde_spanned 1.1.1 - Copyright (c) Individual contributors +- sha2 0.10.9 - Copyright (c) 2006-2009 Graydon Hoare Copyright (c) 2009-2013 Mozilla Foundation Copyright (c) 2016 Artyom Pavlov +- shlex 2.0.1 - Copyright 2015 Nicholas Allegra (comex). +- signature 2.2.0 - Copyright (c) 2018-2023 RustCrypto Developers +- smallvec 1.16.2 - Copyright (c) 2018 The Servo Project Developers +- snow 0.9.6 - Copyright (c) 2021 Jake McGinty +- spki 0.7.3 - Copyright (c) 2021-2023 The RustCrypto Project Developers +- syn 2.0.119 - David Tolnay +- syn 3.0.6 - David Tolnay +- system-deps 7.0.8 - Guillaume Desmottes , Josh Triplett +- target-lexicon 0.13.5 - Dan Gohman +- tempfile 3.27.0 - Copyright (c) 2015 Steven Allen +- thiserror 2.0.21 - David Tolnay +- thiserror-impl 2.0.21 - David Tolnay +- toml 1.1.6+spec-1.1.0 - Copyright (c) Individual contributors +- toml_datetime 1.1.1+spec-1.1.0 - Copyright (c) Individual contributors +- toml_edit 0.25.15+spec-1.1.0 - Copyright (c) Individual contributors +- toml_parser 1.1.3+spec-1.1.0 - Copyright (c) Individual contributors +- toml_writer 1.1.2+spec-1.1.0 - Copyright (c) Individual contributors +- type-map 0.5.1 - Copyright 2017-NOW Actix Team +- typenum 1.20.1 - Copyright 2014 Paho Lurie-Gregg +- unic-langid 0.9.6 - Zibi Braniecki +- unic-langid-impl 0.9.6 - Zibi Braniecki +- unicode-ident 1.0.26 - David Tolnay +- universal-hash 0.5.1 - Copyright (c) 2019-2020 RustCrypto Developers +- vcpkg 0.2.15 - Copyright (c) 2017 Jim McGrath +- version_check 0.9.5 - Copyright (c) 2017-2018 Sergio Benitez +- wasi 0.11.1+wasi-snapshot-preview1 - The Cranelift Project Developers +- wasm-bindgen 0.2.129 - Copyright (c) 2014 Alex Crichton +- wasm-bindgen-macro 0.2.129 - Copyright (c) 2014 Alex Crichton +- wasm-bindgen-macro-support 0.2.129 - Copyright (c) 2014 Alex Crichton +- wasm-bindgen-shared 0.2.129 - Copyright (c) 2014 Alex Crichton +- windows-link 0.2.1 - The windows-link developers +- windows-sys 0.59.0 - Microsoft +- windows-sys 0.61.2 - The windows-sys developers +- windows-targets 0.52.6 - Microsoft +- windows_aarch64_gnullvm 0.52.6 - Microsoft +- windows_aarch64_msvc 0.52.6 - Microsoft +- windows_i686_gnu 0.52.6 - Microsoft +- windows_i686_gnullvm 0.52.6 - Microsoft +- windows_i686_msvc 0.52.6 - Microsoft +- windows_x86_64_gnu 0.52.6 - Microsoft +- windows_x86_64_gnullvm 0.52.6 - Microsoft +- windows_x86_64_msvc 0.52.6 - Microsoft +- zerocopy 0.8.59 - Copyright 2023 The Fuchsia Authors +- zerocopy-derive 0.8.59 - Copyright 2023 The Fuchsia Authors +- zeroize 1.9.0 - Copyright (c) 2018-2026 The RustCrypto Project Developers +- zeroize_derive 1.5.0 - Copyright (c) 2019-2026 The RustCrypto Project Developers + +``` +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +## MIT License + +- aead 0.5.2 - Copyright (c) 2019 The RustCrypto Project Developers Copyright (c) 2019 MobileCoin, LLC +- aes 0.8.4 - Copyright (c) 2018 Artyom Pavlov +- aes-gcm 0.10.3 - Copyright (c) 2019 The RustCrypto Project Developers +- ahash 0.8.12 - Copyright (c) 2018 Tom Kaitchuck +- autocfg 1.5.1 - Copyright (c) 2018 Josh Stone +- base64ct 1.8.3 - Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com) Copyright (c) 2021-2025 The RustCrypto Project Developers +- bitflags 2.13.2 - Copyright (c) 2014 The Rust Project Developers +- blake2 0.10.6 - Copyright (c) 2015-2016 The blake2-rfc Developers, Cesar Barros Copyright (c) 2017 Artyom Pavlov +- block-buffer 0.10.4 - Copyright (c) 2018-2019 The RustCrypto Project Developers +- bumpalo 3.20.3 - Copyright (c) 2019 Nick Fitzgerald +- cairo-rs 0.20.12 - The gtk-rs Project Developers +- cairo-sys-rs 0.20.10 - The gtk-rs Project Developers +- cc 1.5.1 - Copyright (c) 2014 Alex Crichton +- cfg-expr 0.20.10 - Copyright (c) 2019 Embark Studios +- cfg-if 1.0.5 - Copyright (c) 2014 Alex Crichton +- chacha20 0.9.1 - Copyright (c) 2019-2023 The RustCrypto Project Developers +- chacha20poly1305 0.10.1 - Copyright (c) 2019 The RustCrypto Project Developers +- cipher 0.4.4 - Copyright (c) 2016-2020 RustCrypto Developers +- const-oid 0.9.6 - Copyright (c) 2020-2022 The RustCrypto Project Developers +- cpufeatures 0.2.17 - Copyright (c) 2020-2025 The RustCrypto Project Developers +- crypto-common 0.1.7 - Copyright (c) 2021 RustCrypto Developers +- ctr 0.9.2 - Copyright (c) 2018-2022 RustCrypto Developers Copyright (c) 2018 Artyom Pavlov +- curve25519-dalek-derive 0.1.1 - The curve25519-dalek-derive developers +- data-encoding 2.11.1 - Copyright (c) 2015-2020 Julien Cretin Copyright (c) 2017-2020 Google Inc. +- der 0.7.10 - Copyright (c) 2020-2023 The RustCrypto Project Developers +- digest 0.10.7 - Copyright (c) 2017 Artyom Pavlov +- displaydoc 0.2.7 - Jane Lusby +- ed25519 2.2.3 - Copyright (c) 2018-2023 RustCrypto Developers +- equivalent 1.0.2 - Copyright (c) 2016--2023 +- errno 0.3.14 - Copyright (c) 2014 Chris Wong +- fallible-iterator 0.3.0 - Copyright (c) 2015 The rust-openssl-verify Developers +- fallible-streaming-iterator 0.1.9 - Copyright (c) 2016 The fallible-streaming-iterator Developers +- fastrand 2.5.0 - Stjepan Glavina +- fiat-crypto 0.2.9 - Copyright (c) 2015-2020 the fiat-crypto authors (see the AUTHORS file). +- field-offset 0.3.6 - Copyright (c) 2016-2021 Diggory Blake, and other contributors. +- find-msvc-tools 0.1.14 - Copyright (c) 2014 Alex Crichton +- fluent-bundle 0.16.0 - Copyright 2017 Mozilla +- fluent-langneg 0.13.1 - Zibi Braniecki +- fluent-syntax 0.12.0 - Copyright 2017 Mozilla +- flume 0.11.1 - Joshua Barretto +- futures 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-channel 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-core 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-executor 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-io 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-macro 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-sink 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-task 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- futures-util 0.3.34 - Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors +- gdk-pixbuf 0.20.10 - The gtk-rs Project Developers +- gdk-pixbuf-sys 0.20.10 - The gtk-rs Project Developers +- gdk4 0.9.6 - The gtk-rs Project Developers +- gdk4-sys 0.9.6 - The gtk-rs Project Developers +- generic-array 0.14.7 - Copyright (c) 2015 Bartłomiej Kamiński +- getrandom 0.2.17 - Copyright (c) 2018-2024 The rust-random Project Developers Copyright (c) 2014 The Rust Project Developers +- getrandom 0.4.3 - Copyright (c) 2018-2026 The rust-random Project Developers Copyright (c) 2014 The Rust Project Developers +- ghash 0.5.1 - Copyright (c) 2019 RustCrypto Developers +- gio 0.20.12 - The gtk-rs Project Developers +- gio-sys 0.20.10 - The gtk-rs Project Developers +- glib 0.20.12 - The gtk-rs Project Developers +- glib-macros 0.20.12 - The gtk-rs Project Developers +- glib-sys 0.20.10 - The gtk-rs Project Developers +- gobject-sys 0.20.10 - The gtk-rs Project Developers +- graphene-rs 0.20.10 - The gtk-rs Project Developers +- graphene-sys 0.20.10 - The gtk-rs Project Developers +- gsk4 0.9.6 - The gtk-rs Project Developers +- gsk4-sys 0.9.6 - The gtk-rs Project Developers +- gtk4 0.9.7 - The gtk-rs Project Developers +- gtk4-macros 0.9.5 - The gtk-rs Project Developers +- gtk4-sys 0.9.6 - The gtk-rs Project Developers +- hashbrown 0.14.5 - Copyright (c) 2016 Amanieu d'Antras +- hashbrown 0.17.1 - Copyright (c) 2016 Amanieu d'Antras +- hashlink 0.9.1 - kyren +- heck 0.5.0 - Copyright (c) 2015 The Rust Project Developers +- hkdf 0.12.4 - Copyright (c) 2015-2018 Vlad Filippov Copyright (c) 2018-2021 RustCrypto Developers +- hmac 0.12.1 - Copyright (c) 2017 Artyom Pavlov +- indexmap 2.14.2 - Copyright (c) 2016--2017 +- inout 0.1.4 - Copyright (c) 2022 The RustCrypto Project Developers Copyright (c) 2022 Artyom Pavlov +- intl-memoizer 0.5.3 - Copyright 2017 Mozilla +- intl_pluralrules 7.0.2 - Kekoa Riggin , Zibi Braniecki +- itoa 1.0.18 - David Tolnay +- js-sys 0.3.106 - Copyright (c) 2014 Alex Crichton +- libadwaita 0.7.2 - Bilal Elmoussaoui +- libadwaita-sys 0.7.2 - Bilal Elmoussaoui +- libc 0.2.189 - Copyright (c) The Rust Project Developers +- libsqlite3-sys 0.30.1 - Copyright (c) 2014-2021 The rusqlite developers +- linux-raw-sys 0.12.1 - Dan Gohman +- lock_api 0.4.14 - Copyright (c) 2016 The Rust Project Developers +- memchr 2.8.3 - Copyright (c) 2015 Andrew Gallant +- memoffset 0.9.1 - Copyright (c) 2017 Gilad Naaman +- once_cell 1.21.4 - Aleksey Kladov +- opaque-debug 0.3.1 - Copyright (c) 2018-2024 The RustCrypto Project Developers +- pango 0.20.12 - The gtk-rs Project Developers +- pango-sys 0.20.10 - The gtk-rs Project Developers +- pin-project-lite 0.2.17 - The pin-project-lite developers +- pkcs8 0.10.2 - Copyright (c) 2020-2023 The RustCrypto Project Developers +- pkg-config 0.3.34 - Copyright (c) 2014 Alex Crichton +- poly1305 0.8.0 - Copyright (c) 2015-2019 RustCrypto Developers +- polyval 0.6.2 - Copyright (c) 2019-2023 RustCrypto Developers +- proc-macro-crate 3.5.0 - Bastian Köcher +- proc-macro2 1.0.107 - David Tolnay , Alex Crichton +- qrcodegen 1.8.0 - Project Nayuki +- quote 1.0.47 - David Tolnay +- r-efi 6.0.0 - The r-efi developers +- rand_core 0.6.4 - Copyright 2018 Developers of the Rand project Copyright (c) 2014 The Rust Project Developers +- relm4 0.9.1 - Aaron Erhardt +- relm4-css 0.9.0 - Aaron Erhardt +- relm4-macros 0.9.1 - Aaron Erhardt +- rusqlite 0.32.1 - Copyright (c) 2014-2021 The rusqlite developers +- rustc-hash 2.1.3 - The Rust Project Developers +- rustc_version 0.4.1 - Copyright (c) 2016 The Rust Project Developers +- rustix 1.1.5 - Dan Gohman , Jakub Konka +- rustversion 1.0.23 - David Tolnay +- scopeguard 1.2.0 - Copyright (c) 2016-2019 Ulrik Sverdrup "bluss" and scopeguard developers +- semver 1.0.28 - David Tolnay +- serde 1.0.229 - Erick Tryzelaar , David Tolnay +- serde_core 1.0.229 - Erick Tryzelaar , David Tolnay +- serde_derive 1.0.229 - Erick Tryzelaar , David Tolnay +- serde_json 1.0.151 - Erick Tryzelaar , David Tolnay +- serde_spanned 1.1.1 - Copyright (c) Individual contributors +- sha2 0.10.9 - Copyright (c) 2006-2009 Graydon Hoare Copyright (c) 2009-2013 Mozilla Foundation Copyright (c) 2016 Artyom Pavlov +- shlex 2.0.1 - Copyright (c) 2015 Nicholas Allegra (comex). +- signature 2.2.0 - Copyright (c) 2018-2023 RustCrypto Developers +- slab 0.4.12 - Copyright (c) 2019 Carl Lerche +- smallvec 1.16.2 - Copyright (c) 2018 The Servo Project Developers +- snow 0.9.6 - Copyright (c) 2021 Jake McGinty +- spin 0.9.9 - Copyright (c) 2014 Mathijs van de Nes +- spki 0.7.3 - Copyright (c) 2021-2023 The RustCrypto Project Developers +- syn 2.0.119 - David Tolnay +- syn 3.0.6 - David Tolnay +- system-deps 7.0.8 - Guillaume Desmottes , Josh Triplett +- tempfile 3.27.0 - Copyright (c) 2015 Steven Allen +- thiserror 2.0.21 - David Tolnay +- thiserror-impl 2.0.21 - David Tolnay +- tokio 1.53.1 - Copyright (c) Tokio Contributors +- toml 1.1.6+spec-1.1.0 - Copyright (c) Individual contributors +- toml_datetime 1.1.1+spec-1.1.0 - Copyright (c) Individual contributors +- toml_edit 0.25.15+spec-1.1.0 - Copyright (c) Individual contributors +- toml_parser 1.1.3+spec-1.1.0 - Copyright (c) Individual contributors +- toml_writer 1.1.2+spec-1.1.0 - Copyright (c) Individual contributors +- tracing 0.1.44 - Copyright (c) 2019 Tokio Contributors +- tracing-attributes 0.1.31 - Copyright (c) 2019 Tokio Contributors +- tracing-core 0.1.36 - Copyright (c) 2019 Tokio Contributors +- type-map 0.5.1 - Copyright (c) 2022 Jacob Brown +- typenum 1.20.1 - Copyright (c) 2014 Paho Lurie-Gregg +- unic-langid 0.9.6 - Zibi Braniecki +- unic-langid-impl 0.9.6 - Zibi Braniecki +- unicode-ident 1.0.26 - David Tolnay +- universal-hash 0.5.1 - Copyright (c) 2019-2020 RustCrypto Developers +- vcpkg 0.2.15 - Copyright (c) 2017 Jim McGrath +- version-compare 0.2.1 - Copyright (c) 2017 Tim Visée +- version_check 0.9.5 - Copyright (c) 2017-2018 Sergio Benitez +- wasi 0.11.1+wasi-snapshot-preview1 - The Cranelift Project Developers +- wasm-bindgen 0.2.129 - Copyright (c) 2014 Alex Crichton +- wasm-bindgen-macro 0.2.129 - Copyright (c) 2014 Alex Crichton +- wasm-bindgen-macro-support 0.2.129 - Copyright (c) 2014 Alex Crichton +- wasm-bindgen-shared 0.2.129 - Copyright (c) 2014 Alex Crichton +- windows-link 0.2.1 - The windows-link developers +- windows-sys 0.59.0 - Microsoft +- windows-sys 0.61.2 - The windows-sys developers +- windows-targets 0.52.6 - Microsoft +- windows_aarch64_gnullvm 0.52.6 - Microsoft +- windows_aarch64_msvc 0.52.6 - Microsoft +- windows_i686_gnu 0.52.6 - Microsoft +- windows_i686_gnullvm 0.52.6 - Microsoft +- windows_i686_msvc 0.52.6 - Microsoft +- windows_x86_64_gnu 0.52.6 - Microsoft +- windows_x86_64_gnullvm 0.52.6 - Microsoft +- windows_x86_64_msvc 0.52.6 - Microsoft +- winnow 1.0.4 - The winnow developers +- winresource 0.1.31 - Copyright 2016 Max Resch +- zerocopy 0.8.59 - Copyright 2023 The Fuchsia Authors +- zerocopy-derive 0.8.59 - Copyright 2023 The Fuchsia Authors +- zeroize 1.9.0 - Copyright (c) 2018-2026 The RustCrypto Project Developers +- zeroize_derive 1.5.0 - Copyright (c) 2019-2026 The RustCrypto Project Developers +- zmij 1.0.23 - David Tolnay + +``` +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +``` + +## BSD 3-Clause License + +- curve25519-dalek 4.1.3 - Copyright (c) 2016-2021 isis agora lovecruft. All rights reserved. Copyright (c) 2016-2021 Henry de Valence. All rights reserved. +- ed25519-dalek 2.2.0 - Copyright (c) 2017-2019 isis agora lovecruft. All rights reserved. +- subtle 2.6.1 - Copyright (c) 2016-2017 Isis Agora Lovecruft, Henry de Valence. All rights reserved. Copyright (c) 2016-2024 Isis Agora Lovecruft. All rights reserved. +- x25519-dalek 2.0.1 - Copyright (c) 2017-2021 isis agora lovecruft. All rights reserved. Copyright (c) 2019-2021 DebugSteven. All rights reserved. + +``` +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +======================================================================== + +Portions of curve25519-dalek were originally derived from Adam Langley's +Go ed25519 implementation, found at , +under the following licence: + +======================================================================== + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +## BSD 2-Clause License + +- zerocopy 0.8.59 - Copyright 2019 The Fuchsia Authors. +- zerocopy-derive 0.8.59 - Copyright 2019 The Fuchsia Authors. + +``` +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +## BSD 1-Clause License + +- fiat-crypto 0.2.9 - Copyright (c) 2015-2020 the fiat-crypto authors (see the AUTHORS file) All rights reserved. + +``` +The BSD 1-Clause License (BSD-1-Clause) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY the fiat-crypto authors "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Berkeley Software Design, +Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +## The Unlicense + +- memchr 2.8.3 - Andrew Gallant , bluss + +``` +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to +``` + +## Unicode License v3 + +- tinystr 0.8.4 (Unicode license applies in addition to MIT OR Apache-2.0) - The ICU4X Project Developers +- unicode-ident 1.0.26 (Unicode license applies in addition to MIT OR Apache-2.0) - Copyright © 1991-2023 Unicode, Inc. +- zerofrom 0.1.8 (Unicode license applies in addition to MIT OR Apache-2.0) - The ICU4X Project Developers +- zerovec 0.11.8 (Unicode license applies in addition to MIT OR Apache-2.0) - The ICU4X Project Developers + +``` +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2023 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. +``` + +## LLVM Exception (to the Apache License 2.0) + +The component above may additionally be used under Apache-2.0 or MIT; when used under Apache-2.0, the license text above is modified by the following exception: + +- linux-raw-sys 0.12.1 (when used under Apache-2.0) - Dan Gohman +- rustix 1.1.5 (when used under Apache-2.0) - Dan Gohman , Jakub Konka +- target-lexicon 0.13.5 (when used under Apache-2.0) - Dan Gohman +- wasi 0.11.1+wasi-snapshot-preview1 (when used under Apache-2.0) - The Cranelift Project Developers + +``` +---- LLVM Exceptions to the Apache 2.0 License ---- + + As an exception, if, as a result of your compiling your source code, portions + of this Software are embedded into an Object form of such source code, you + may redistribute such embedded portions in such Object form without complying + with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + + In addition, if you combine or link compiled forms of this Software with + software that is licensed under the GPLv2 ("Combined Software") and if a + court of competent jurisdiction determines that the patent provision (Section + 3), the indemnity provision (Section 9) or other Section of the License + conflicts with the conditions of the GPLv2, you may retroactively and + prospectively choose to deem waived or otherwise exclude such Section(s) of + the License, but only in their entirety and only with respect to the Combined + Software. +``` + +## Zlib License + +- nanorand 0.7.0 - Lucy + +``` +zlib License + +This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. +``` + +## GNU LGPL v2.1 or later + +- r-efi 6.0.0 - The r-efi developers + +``` +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! +``` + +## GNU GPL v2 only + +- self_cell 1.3.0 - Lukas Bergdoll + +``` +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + + c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author + + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. + +signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice +``` + +## SQLite (public domain) + +SQLite 3.46.0 is bundled in source form by the `libsqlite3-sys` crate (the crate itself is listed with the crates above). The SQLite authors have placed the code in the public domain; the notice accompanying the SQLite distribution: + +``` +The author disclaims copyright to the source code. Although no +laws apply, the author would appreciate it if you did not remove +this notice and attributed the source to the SQLite project. +``` diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..b242a43 --- /dev/null +++ b/build.rs @@ -0,0 +1,10 @@ +// Windows reads the taskbar and Explorer icon from the exe's resource +// section; desktop environments on other platforms use the desktop file. +fn main() { + println!("cargo:rerun-if-changed=data/icons/com.randogoth.carrier.ico"); + if std::env::var("CARGO_CFG_WINDOWS").is_ok() { + let mut res = winresource::WindowsResource::new(); + res.set_icon("data/icons/com.randogoth.carrier.ico"); + res.compile().expect("failed to embed Windows icon"); + } +} diff --git a/data/com.randogoth.carrier.metainfo.xml b/data/com.randogoth.carrier.metainfo.xml index 1ccb0e1..e8a4fa9 100644 --- a/data/com.randogoth.carrier.metainfo.xml +++ b/data/com.randogoth.carrier.metainfo.xml @@ -14,6 +14,9 @@ com.randogoth.carrier.desktop + + + diff --git a/data/icons/com.randogoth.carrier.ico b/data/icons/com.randogoth.carrier.ico new file mode 100644 index 0000000..8305c58 Binary files /dev/null and b/data/icons/com.randogoth.carrier.ico differ diff --git a/devbox.json b/devbox.json index a517954..312b2c8 100644 --- a/devbox.json +++ b/devbox.json @@ -1,32 +1,32 @@ { "$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json", - "packages": [ - "rustc@latest", - "cargo@latest", - "pkg-config@latest", - "rustfmt@latest", - "nixpkgs#wayland", - "nixpkgs#libxkbcommon", - "nixpkgs#mesa", - "nixpkgs#libGL", - "nixpkgs#vulkan-loader", - "nixpkgs#gcc", - "nixpkgs#gtk4", - "nixpkgs#glib", - "nixpkgs#pango", - "nixpkgs#cairo", - "nixpkgs#graphene", - "nixpkgs#gdk-pixbuf", - "nixpkgs#harfbuzz", - "nixpkgs#libadwaita", - "nixpkgs#adwaita-icon-theme", - "nixpkgs#flatpak", - "nixpkgs#flatpak-builder", - "nixpkgs#appstream" - ], + "packages": { + "rustc": "latest", + "cargo": "latest", + "pkg-config": "latest", + "rustfmt": "latest", + "gtk4": { + "version": "latest", + "platforms": ["x86_64-linux", "aarch64-linux"], + "outputs": ["out", "dev"] + }, + "libadwaita": { + "version": "latest", + "platforms": ["x86_64-linux", "aarch64-linux"], + "outputs": ["out", "dev"] + }, + "appstream": { + "version": "latest", + "platforms": ["x86_64-linux", "aarch64-linux"] + } + }, + "env": { + "PATH": "/opt/homebrew/bin:/opt/homebrew/sbin:$PATH" + }, "shell": { "init_hook": [ - ". \"$PWD/scripts/devbox-libs.sh\"" + "export PKG_CONFIG_PATH=\"$DEVBOX_PACKAGES_DIR/lib/pkgconfig:$PKG_CONFIG_PATH\"", + "if [[ \"$(uname)\" == \"Darwin\" ]]; then export PKG_CONFIG_PATH=\"/opt/homebrew/lib/pkgconfig:$PKG_CONFIG_PATH\"; export PKG_CONFIG_PATH_arm64_apple_darwin=\"/opt/homebrew/lib/pkgconfig\"; fi" ], "scripts": { "build": [ @@ -46,6 +46,10 @@ ], "package": [ "flatpak-builder --force-clean --user --install-deps-from=flathub --install .flatpak com.randogoth.carrier.json" + ], + "bundle-flatpak": [ + "flatpak-builder --force-clean --user --disable-rofiles-fuse --repo=.flatpak-repo --install-deps-from=flathub .flatpak-build com.randogoth.carrier.json", + "flatpak build-bundle .flatpak-repo carrier-x86_64.flatpak com.randogoth.carrier" ] } } diff --git a/devbox.lock b/devbox.lock index a6f3109..2471f13 100644 --- a/devbox.lock +++ b/devbox.lock @@ -1,6 +1,68 @@ { "lockfile_version": "1", "packages": { + "appstream@latest": { + "last_modified": "2026-08-27T23:47:58Z", + "resolved": "github:NixOS/nixpkgs/7d1a7c21a4c00ea653fc7ed5c083d261340f185f#appstream", + "source": "devbox-search", + "version": "1.1.3", + "systems": { + "aarch64-darwin": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/zrpxip93379i7iphgi9r12vfkmjpln8k-appstream-1.1.3", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/c3svyp4qcd4kwscjjhba6r5ajm2kfr0q-appstream-1.1.3-dev" + }, + { + "name": "installedTests", + "path": "/nix/store/2b6x9xz39605jg62jjvcc2d6iszs5ylj-appstream-1.1.3-installedTests" + } + ], + "store_path": "/nix/store/zrpxip93379i7iphgi9r12vfkmjpln8k-appstream-1.1.3" + }, + "aarch64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/66jhy5isw71z0xmwsva5wbj0cl65b04j-appstream-1.1.3", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/akhbgsjmqkwcfp219bv3mszmfhjvv3gl-appstream-1.1.3-dev" + }, + { + "name": "installedTests", + "path": "/nix/store/xvr3ldwd4vk8fiky1lbbq8fp3a6kyzms-appstream-1.1.3-installedTests" + } + ], + "store_path": "/nix/store/66jhy5isw71z0xmwsva5wbj0cl65b04j-appstream-1.1.3" + }, + "x86_64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/i2azliw8fyn0dv751hkwcjp25w0k3raq-appstream-1.1.3", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/xxw2gcxw4fjhrz7flkrmsc9n75fnadcy-appstream-1.1.3-dev" + }, + { + "name": "installedTests", + "path": "/nix/store/4gbbz6ip5lmblfsl33xdxhrdpj9mgzk7-appstream-1.1.3-installedTests" + } + ], + "store_path": "/nix/store/i2azliw8fyn0dv751hkwcjp25w0k3raq-appstream-1.1.3" + } + } + }, "cargo@latest": { "last_modified": "2026-08-27T07:16:00Z", "resolved": "github:NixOS/nixpkgs/c27cdad491a991b11ed731760aa2ef8db0cb0410#cargo", @@ -43,81 +105,159 @@ "last_modified": "2026-09-29T03:29:29Z", "resolved": "github:NixOS/nixpkgs/b6c8664de9b6cc07fe5666a29f91884ba81197c4?lastModified=1790652569&narHash=sha256-641r7xrlSOHYoktL9%2FaArPIYNgZJ9eM5URzSEOtPJDY%3D" }, - "nixpkgs#adwaita-icon-theme": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#adwaita-icon-theme" + "gtk4@latest": { + "last_modified": "2026-08-28T08:26:42Z", + "resolved": "github:NixOS/nixpkgs/0e7911a191ea0fb9d6e8e771d24736d3618f8b1f#gtk4", + "source": "devbox-search", + "version": "4.22.4", + "systems": { + "aarch64-darwin": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/zip9cgwsmacrd8rv9x8j6v5d93fyxb6d-gtk4-4.22.4", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/34wj0s7jwk37sfxaw1vljl8aq1v43mxg-gtk4-4.22.4-dev" + } + ], + "store_path": "/nix/store/zip9cgwsmacrd8rv9x8j6v5d93fyxb6d-gtk4-4.22.4" + }, + "aarch64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/x2y5vykblarp5jzs7n85sh5gixi4r7hx-gtk4-4.22.4", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/cgr4b28yx7zzdxkjifwba2v5f9zprh8p-gtk4-4.22.4-dev" + }, + { + "name": "devdoc", + "path": "/nix/store/qpm15s7r2g7qwrr0fnjpgl4jkvh820x9-gtk4-4.22.4-devdoc" + }, + { + "name": "debug", + "path": "/nix/store/hkpjzp8nah9cj5gmp51ydh658rbnh9s8-gtk4-4.22.4-debug" + } + ], + "store_path": "/nix/store/x2y5vykblarp5jzs7n85sh5gixi4r7hx-gtk4-4.22.4" + }, + "x86_64-darwin": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/3la8zml5yi34lssl8j3g1w7n2qs2j40w-gtk4-4.22.4", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/8vgk08hbgzswqrf6nbm0m7w5qxzi5j7i-gtk4-4.22.4-dev" + } + ], + "store_path": "/nix/store/3la8zml5yi34lssl8j3g1w7n2qs2j40w-gtk4-4.22.4" + }, + "x86_64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/4j905cjgk8idkzg4szhyryzjx2q1b6br-gtk4-4.22.4", + "default": true + }, + { + "name": "debug", + "path": "/nix/store/r7hhl6pbzld4m34qza3xr08xmm13ssmk-gtk4-4.22.4-debug" + }, + { + "name": "dev", + "path": "/nix/store/dczin2m9wvwsfjyfbnksm983ljgmibfk-gtk4-4.22.4-dev" + }, + { + "name": "devdoc", + "path": "/nix/store/7jwx0qmwvx9w2z5b5m5fw2d9k2d1a3wd-gtk4-4.22.4-devdoc" + } + ], + "store_path": "/nix/store/4j905cjgk8idkzg4szhyryzjx2q1b6br-gtk4-4.22.4" + } + } }, - "nixpkgs#appstream": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#appstream" - }, - "nixpkgs#cairo": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#cairo" - }, - "nixpkgs#flatpak": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#flatpak" - }, - "nixpkgs#flatpak-builder": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#flatpak-builder" - }, - "nixpkgs#gcc": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#gcc" - }, - "nixpkgs#gdk-pixbuf": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#gdk-pixbuf" - }, - "nixpkgs#glib": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#glib" - }, - "nixpkgs#graphene": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#graphene" - }, - "nixpkgs#gtk4": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#gtk4" - }, - "nixpkgs#harfbuzz": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#harfbuzz" - }, - "nixpkgs#libGL": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#libGL" - }, - "nixpkgs#libadwaita": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#libadwaita" - }, - "nixpkgs#libxkbcommon": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#libxkbcommon" - }, - "nixpkgs#mesa": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#mesa" - }, - "nixpkgs#pango": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#pango" - }, - "nixpkgs#vulkan-loader": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#vulkan-loader" - }, - "nixpkgs#wayland": { - "last_modified": "1970-01-01T00:00:00Z", - "resolved": "path:/nix/store/v8ynlbrldn7k8byb1kx0j0wka8dsbrw9-source?narHash=sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg%3D#wayland" + "libadwaita@latest": { + "last_modified": "2026-08-29T00:50:12Z", + "resolved": "github:NixOS/nixpkgs/e8be7818e19ada32105a8af937a6a473b38167ca#libadwaita", + "source": "devbox-search", + "version": "1.9.3", + "systems": { + "aarch64-darwin": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/dcz2cyp4bzlbbwrq0z9rpaijrhbm1nv2-libadwaita-1.9.3", + "default": true + }, + { + "name": "devdoc", + "path": "/nix/store/sqp0z2gcbgpzs9gcfrs7jzpy1v1k5qv0-libadwaita-1.9.3-devdoc" + }, + { + "name": "dev", + "path": "/nix/store/a39iqc19qfbkki6ibsylh8kard0yajhy-libadwaita-1.9.3-dev" + } + ], + "store_path": "/nix/store/dcz2cyp4bzlbbwrq0z9rpaijrhbm1nv2-libadwaita-1.9.3" + }, + "aarch64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/czi84wxq4v7vl7k4dr59nrwwk91pc5d4-libadwaita-1.9.3", + "default": true + }, + { + "name": "debug", + "path": "/nix/store/yg7bgsvyyp8ky0mbgr8hm6szixcw71bs-libadwaita-1.9.3-debug" + }, + { + "name": "dev", + "path": "/nix/store/hss38kikfq0v5cd5hi353qj5smnhwiga-libadwaita-1.9.3-dev" + }, + { + "name": "devdoc", + "path": "/nix/store/rrkay1bb7zyicqb76n9ynk695bzra7l0-libadwaita-1.9.3-devdoc" + } + ], + "store_path": "/nix/store/czi84wxq4v7vl7k4dr59nrwwk91pc5d4-libadwaita-1.9.3" + }, + "x86_64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/x8v08wl57vkyk6qfcblx32a0w6cphnpy-libadwaita-1.9.3", + "default": true + }, + { + "name": "devdoc", + "path": "/nix/store/4bi0mlap06fcw0ycsd0yslyzk57lir9r-libadwaita-1.9.3-devdoc" + }, + { + "name": "debug", + "path": "/nix/store/l4h0wjg04i4bdz5xvafchxw9hh1a9dc1-libadwaita-1.9.3-debug" + }, + { + "name": "dev", + "path": "/nix/store/0gvpb9gszkl274wgb3zgcwlclbwj6cch-libadwaita-1.9.3-dev" + } + ], + "store_path": "/nix/store/x8v08wl57vkyk6qfcblx32a0w6cphnpy-libadwaita-1.9.3" + } + } }, "pkg-config@latest": { - "last_modified": "2025-11-23T21:50:36Z", - "resolved": "github:NixOS/nixpkgs/ee09932cedcef15aaf476f9343d1dea2cb77e261#pkg-config", + "last_modified": "2026-10-05T09:07:57Z", + "resolved": "github:NixOS/nixpkgs/aa48d347080940b8a2b8d2f48228674e280a3514#pkg-config", "source": "devbox-search", "version": "0.29.2", "systems": { @@ -125,39 +265,39 @@ "outputs": [ { "name": "out", - "path": "/nix/store/hygaaqwk9ylklp0ybwppqhw75nz8ya41-pkg-config-wrapper-0.29.2", + "path": "/nix/store/nhgylvj98klqggy54h7gbc3b2ia4a00y-pkg-config-wrapper-0.29.2", "default": true }, { "name": "man", - "path": "/nix/store/9px0sji43x3r2w4zxl3j3idwsql7lwxx-pkg-config-wrapper-0.29.2-man", + "path": "/nix/store/rk4dw0mj2lakbw5hml11mfpmdx9xjzfa-pkg-config-wrapper-0.29.2-man", "default": true }, { "name": "doc", - "path": "/nix/store/hqk44ra6qxw7iixardl6c3hdgb9kq6ns-pkg-config-wrapper-0.29.2-doc" + "path": "/nix/store/xzlcs9f8xl9dvnbwifmlfbxy15jq53j1-pkg-config-wrapper-0.29.2-doc" } ], - "store_path": "/nix/store/hygaaqwk9ylklp0ybwppqhw75nz8ya41-pkg-config-wrapper-0.29.2" + "store_path": "/nix/store/nhgylvj98klqggy54h7gbc3b2ia4a00y-pkg-config-wrapper-0.29.2" }, "aarch64-linux": { "outputs": [ { "name": "out", - "path": "/nix/store/lbiigi8qbp7mzf1lpr7p982l1kyf01ql-pkg-config-wrapper-0.29.2", + "path": "/nix/store/h82n3d0wdrgskdc3yvmz5l3c50h2snvp-pkg-config-wrapper-0.29.2", "default": true }, { "name": "man", - "path": "/nix/store/10060k24qggqyzlwdsfmni9y32zxcg0j-pkg-config-wrapper-0.29.2-man", + "path": "/nix/store/8960pp9vb5hx49q3h315hwr33gb0k2k0-pkg-config-wrapper-0.29.2-man", "default": true }, { "name": "doc", - "path": "/nix/store/0y4v51ndpyvkj09hwlfqkz0c3h17zfmc-pkg-config-wrapper-0.29.2-doc" + "path": "/nix/store/dxpxspf67kl1gydpl3v3f7pxa3l9wyvq-pkg-config-wrapper-0.29.2-doc" } ], - "store_path": "/nix/store/lbiigi8qbp7mzf1lpr7p982l1kyf01ql-pkg-config-wrapper-0.29.2" + "store_path": "/nix/store/h82n3d0wdrgskdc3yvmz5l3c50h2snvp-pkg-config-wrapper-0.29.2" }, "x86_64-darwin": { "outputs": [ @@ -182,20 +322,20 @@ "outputs": [ { "name": "out", - "path": "/nix/store/8vdiwpbh0g4avsd6x5v4s0di32vcl3dp-pkg-config-wrapper-0.29.2", + "path": "/nix/store/b9izmrfjp0qnnyahdwwrzdwi87s1h179-pkg-config-wrapper-0.29.2", "default": true }, { "name": "man", - "path": "/nix/store/j9xfpnrygg3v37svc5pfin9q5bm49r94-pkg-config-wrapper-0.29.2-man", + "path": "/nix/store/c8asqjndyv84qh5y2z84w9np0c369ill-pkg-config-wrapper-0.29.2-man", "default": true }, { "name": "doc", - "path": "/nix/store/x3bypxdxaq20kykybhkf21x4jczsiy8y-pkg-config-wrapper-0.29.2-doc" + "path": "/nix/store/8fsw8ybdnhcif89dmk8pp85ykjpvh3pr-pkg-config-wrapper-0.29.2-doc" } ], - "store_path": "/nix/store/8vdiwpbh0g4avsd6x5v4s0di32vcl3dp-pkg-config-wrapper-0.29.2" + "store_path": "/nix/store/b9izmrfjp0qnnyahdwwrzdwi87s1h179-pkg-config-wrapper-0.29.2" } } }, diff --git a/docs/screenshots/carrier.png b/docs/screenshots/carrier.png new file mode 100644 index 0000000..7509353 Binary files /dev/null and b/docs/screenshots/carrier.png differ diff --git a/locales/en-US/main.ftl b/locales/en-US/main.ftl new file mode 100644 index 0000000..1315e25 --- /dev/null +++ b/locales/en-US/main.ftl @@ -0,0 +1,461 @@ +## Loaded once at startup by `src/i18n.rs`; every user-facing string in +## the app lives here, grouped by the feature it belongs to. + +## Seed parsing — restoring an identity from a pasted seed + +seed-bad-hex = That's not valid hex. Check for typos or extra characters. +seed-wrong-length = A seed is 32 bytes. Check you copied the whole thing. + +## Local files — errors reading/writing the key and its sidecars + +file-error = { $path }: { $reason } +key-file-wrong-length = { $path }: not a 32-byte secret + +## Compose — validating a typed `Key: value` header row + +compose-header-colon-missing = Headers need a colon, like `Key: value`. +compose-header-reserved-key = { $key } is set automatically and can't be changed. +compose-header-invalid-key = Keys can be 1 to 64 letters, digits, and dashes. +compose-header-value-multiline = Values need to stay on one line. +compose-header-duplicate-key = { $key } is set twice. Remove one of them. +compose-headers-too-large = Your headers take up too much space. Remove some and try again. +compose-headers-too-many = You have too many headers. Remove some and try again. + +## Contacts — importing a smol:// address + +contacts-import-needs-key = Import needs a smol:// address that includes a key. + +## Mail — opening a message by id + +mail-message-id-wrong-length = Message IDs are 64 hex characters. +mail-message-id-wrong-bytes = Message IDs are 32 bytes. +mail-message-not-found = Message not found. + +## Fetch — the status note after a fetch completes +## +## Split from one selector into one message per combination of "N +## rejected" and "(cancelled)" that can apply; the caller in ops.rs +## picks the id to match, since a flat message can't branch on a +## variable itself. + +fetch-result-note-rejected = { $total } fetched, { $stored } stored, { $rejected } rejected +fetch-result-note-cancelled = { $total } fetched, { $stored } stored (cancelled) +fetch-result-note-rejected-cancelled = { $total } fetched, { $stored } stored, { $rejected } rejected (cancelled) +fetch-result-note-plain = { $total } fetched, { $stored } stored +mail-envelope-id-mismatch-error = id does not match the envelope +mail-fetch-summary-counts = { $stored } new, { $rejected } rejected +mail-fetch-summary-verified-one = { $verified } sender verified from a signed Reply-To +mail-fetch-summary-verified-other = { $verified } senders verified from a signed Reply-To +mail-fetch-summary-left-on-server = left on the server + +## Send — the status note after a send completes +## +## Split from one selector into one message per combination of +## trust-change clause and accept-token clause that can apply; the +## caller in ops.rs picks the id to match. Any warning fumi itself +## reports is appended separately in code, since that text is fumi's +## own and not part of this catalogue. + +send-result-note-token = Sent to { $address } ({ $bytes } bytes), accept token attached +send-result-note-unverified = Sent to { $address } ({ $bytes } bytes); new contact learned from an unpinned server (unverified) +send-result-note-unverified-token = Sent to { $address } ({ $bytes } bytes), accept token attached; new contact learned from an unpinned server (unverified) +send-result-note-tofu = Sent to { $address } ({ $bytes } bytes); new contact learned (trust on first use) +send-result-note-tofu-token = Sent to { $address } ({ $bytes } bytes), accept token attached; new contact learned (trust on first use) +send-result-note-rotated = Sent to { $address } ({ $bytes } bytes); contact rotated to a new key (chain verified) +send-result-note-rotated-token = Sent to { $address } ({ $bytes } bytes), accept token attached; contact rotated to a new key (chain verified) +send-result-note-plain = Sent to { $address } ({ $bytes } bytes) +mail-sent-note = sent to { $address } +mail-sent-note-accepted = sent to { $address } (accepted) + +## Background-operation status notes +## +## Built in `spawn_op` (src/view.rs) rather than ops.rs, since that is +## where each `PendingOp` result is assembled for the worker thread. + +status-registered-note = Registered +status-restored-note = Restored at rotation { $index } +status-deleted-note = Deleted +status-accepted-note = Accepted { $address } +status-blocked-note = Blocked { $address } +status-not-blocked-note = { $address } was not blocked +contacts-no-key-error = no key for { $address } yet +# Split from one selector into flat siblings for the token count, matching +# this file's existing convention (see fetch-result-note-* above). +contacts-accepted-note-one = { $address } accepted; server now holds { $held } accept token +contacts-accepted-note-other = { $address } accepted; server now holds { $held } accept tokens +contacts-blocked-note-one = { $address } blocked; server now holds { $held } accept token +contacts-blocked-note-other = { $address } blocked; server now holds { $held } accept tokens +status-imported-note = Imported { $address } (verified) +status-rotated-note = Rotated to index { $index }; new key { $key_prefix }… + +## Backup + +backup-written-note = Backup written to { $path } + +## Drafts + +draft-saved-note = Draft saved + +## Log out + +logged-out-note = Signed out. Create a new identity or restore a seed. +logged-out-switched-note = Signed out. You're now using { $address }. + +## Onboarding + +identity-created-note = Identity created. Write the seed down. It's the only secret. +seed-restored-note = Seed restored. Bind a username or recall an address. +seed-reused-note = Secret copied. Bind a username or recall an address. + +## Signup + +signup-enter-host-error = Enter the server host first. +signup-enter-user-host-error = Enter the user and host. +# A pin is keyed by bare host, so these two catch the mistakes that would +# otherwise silently pin a string nothing looks up again: a whole address, +# or a host with its port still attached. +signup-host-looks-like-address-error = "{ $host }" looks like an address, not a server — the part after the @ goes here +signup-host-has-port-error = "{ $host }": a pin is by host only, no port — just the part before the colon + +## Compose + +compose-enter-recipient-error = Enter a recipient. +compose-header-row-error = Header { $index }: { $reason } +reply-no-address-error = This sender left no address to reply to. +reply-subject-prefix = Re: { $subject } +address-invalid-error = That address isn't in the right format. + +## Contacts + +contacts-reply-address-invalid-error = The sender's reply address isn't in the right format. +contacts-sender-key-invalid-error = The sender's key isn't in the right format. +contacts-accept-no-address-error = This sender left no address to accept. +contacts-block-no-address-error = This sender left no address to block. +contacts-sender-key-mismatch-error = that address carries a different key than this message's sender +# A pinned, conflicting Reply-To claim is refused outright rather than asked +# about — see saveContactChecked's dialog for the softer self-certifying case. +contacts-reply-key-conflict-error = { $address } is already known with a different key — verify out of band before replying +# Shown when a typed address or a smol:// link would overwrite an address +# already saved under a different key, and the user declined the prompt +# that showed both fingerprints and asked. +contacts-key-kept-note = kept the existing key for { $address } +contacts-sender-saved-note-verified = { $address } saved for this sender (verified key) +contacts-sender-saved-note-unverified = { $address } saved for this sender +# Richer than status-imported-note: this client shows the imported key and +# its fingerprint alongside the confirmation. +contacts-import-detail-note = imported { $address } { $key } (verified){"\u000A"}fingerprint: { $fingerprint } + +## Common — short words reused verbatim across several buttons/dialogs + +action-cancel = Cancel +action-back = Back +action-block = Block +action-unblock = Unblock +action-accept = Accept +action-reply = Reply +action-delete = Delete +# Shown wherever a fetched server key is on screen before it's pinned: +# the compose's pin card, the signup server step, and the contact detail +# body when a key was fetched for that contact. +trust-fingerprint-hint = If the server operator published a key or fingerprint, make sure it matches before trusting it. +# Reused wherever an action needs an identity that doesn't exist yet +# (sending, fetching, pushing accept tokens). +identity-missing-error = no identity yet +account-not-registered-fetch-warning = not registered yet — claim an address in settings +account-not-registered-tokens-note = not registered; the set will be pushed with your first fetch + +## Sidebar + +mail-fetch-button = Fetch +mail-write-button = Write +folder-inbox = Inbox +folder-requests = Requests +folder-sent = Sent +folder-drafts = Drafts +settings-nav-label = Settings +settings-close-aria-label = close settings +settings-close-tooltip = close +identity-you-caption = you +contacts-caption = contacts +contacts-import-placeholder = Import a smol:// address +contacts-import-button = Import +# "Follow the system" is a real preference, not the absence of one, so it +# gets its own label rather than defaulting silently to one of the other two. +theme-auto-label = theme: following the system +theme-light-label = theme: light +theme-dark-label = theme: dark +account-not-registered-value = not registered +mail-search-placeholder = search { $folder } + +## Mail — the open-message meta line +## +## Split from one selector into one message per variant, each a full +## sentence; the caller in view.rs picks `-yes`/`-no` to match `$kept`. + +mail-meta-to = to +mail-meta-from = from +mail-meta-line-no = { $label } { $from } · { $time } UTC · id { $id }… +mail-meta-line-yes = { $label } { $from } · { $time } UTC · id { $id }… · a server copy still exists +mail-no-subject = (no subject) +mail-no-reply-address = no reply address: can't accept or block +contacts-empty-hint = no contacts +# The §4/§8 trust chip on an open message: a signature always verifies, or +# unseal() would have thrown already — what varies is the binding between +# the key that signed it and an address. +mail-back-to-list-button = messages +mail-meta-sent = to: { $recipient }{"\u000A"}id: { $id }{"\u000A"}sent: { $time } +mail-meta-received = from: { $from }{"\u000A"}id: { $id }{"\u000A"}date: { $time } +mail-trust-own-copy = your own sealed copy +mail-trust-verified-sender = verified sender key +mail-trust-tofu-sender = key pinned on first use +mail-trust-unbound-sender = key bound to no address +mail-sender-unbound-tooltip = sender key not bound to an address +mail-signed-reply-hint = this message carries the sender's signed address: { $address } +mail-save-sender-reply-button = save sender & reply +mail-name-sender-button = name sender & reply +mail-unknown-sender-hint = The wire carries no sender name, only this signed key. To reply, give the sender's address — it is checked against this key: +mail-delete-not-registered-error = not registered; cannot reach the server to delete this message +mail-request-unaccepted-hint = unsolicited mail from { $address }, not yet accepted into your main tier +mail-accept-button = accept — future mail lands in your main tier + +## Mail list — empty-folder messages, and the own-identity detail + +mail-inbox-empty-title = Inbox is empty +mail-inbox-empty-description = Fetch to check the mailbox. +mail-requests-empty-title = No requests +mail-requests-empty-description = Mail from senders you haven't accepted yet arrives here. +mail-sent-empty-title = Nothing sent yet +mail-sent-empty-description = Messages you send keep a sealed copy here. +mail-drafts-empty-title = No drafts +mail-drafts-empty-description = Closing a compose from the sidebar keeps it here. +own-identity-meta = you · rotation { $rotations } +contacts-pin-button-fetched = Pin this key +contacts-pin-button-unfetched = Pin server + +mail-empty-title = No message selected +mail-empty-description = Pick a message from the list above to read it. +# The two sentences shown under Fetch when the inbox is empty. +mail-empty-hint = Fetching removes mail from the server once it's stored here. Turn on "Leave mail on server" in Settings to keep it there instead. +detail-qr-tooltip = Show the address as a QR code +detail-copy-tooltip = Copy the address +mail-row-unreadable-error = +mail-contacts-reader-hint = contacts and their keys are listed alongside +mail-list-count-one = { $count } message +mail-list-count-other = { $count } messages +mail-list-shown-of-total = { $shown } of { $total } + +## Compose + +compose-to-label = To +compose-subject-label = Subject +compose-add-header-button = + header +compose-send-button = Send +compose-header-placeholder = Key: value +compose-header-remove-tooltip = Remove this header +compose-body-placeholder = message +compose-anonymous-label = anonymous — omit my address + +## Contacts — trust state shown in the sidebar and the detail pane + +contact-state-accepted = accepted +contact-state-blocked = blocked +contact-state-verified = verified +contact-state-tofu = trust on first use +# `$state` is one of the four words above, already resolved by the caller +# through `contact_state`. Split from one selector into one message per +# pin state; the caller in view.rs picks `-yes`/`-no` to match `$pinned`. +contact-meta-line-yes = { $state } · server pinned +contact-meta-line-no = { $state } · server not pinned + +## Detail pane — the monospace key/value block shared by contacts and the +## own identity view. Column widths are padded to these labels in code +## (14 characters), so a much longer translation would throw the +## alignment off; flagged in the extraction report. + +detail-key-label = key +detail-fingerprint-label = fingerprint +detail-address-label = address +detail-server-label = server +contact-server-key-offered = this server presents +contacts-server-pinned-badge = pinned +contacts-server-not-pinned-badge = not pinned +contacts-history-badge = { $count } previous +contacts-import-empty-hint = no contacts yet — import a smol:// address above, or write to someone +contacts-refresh-button = re-resolve +contacts-accept-token-title = accept token +contacts-accepted-hint = This contact's mail lands in your main tier. +contacts-unaccepted-hint = This contact's mail lands in requests until accepted. +contacts-history-title = previous keys ({ $count }) +contacts-history-hint = Replaced by a signed rotation chain. Mail signed with these was sent before the change; rotation is not revocation, so a stolen key can still rotate onward. +contacts-history-replaced = replaced { $time } + +## Settings — tab switcher labels + +settings-tab-identity = Identity +settings-tab-server = Server +settings-tab-backup = Backup +settings-tab-advanced = Advanced + +## Settings — Identity tab + +settings-field-address = Address +settings-field-key = Key +settings-field-fingerprint = Fingerprint +settings-field-uri = URI +property-row-copy-tooltip = Copy the { $field } +settings-recovery-secret-title = Recovery secret +settings-secret-reveal-button = reveal +settings-secret-hide-button = hide +settings-secret-reveal-tooltip = Reveal the recovery secret +settings-secret-hide-tooltip = Hide the recovery secret +settings-secret-copy-tooltip = Copy the recovery secret +settings-secret-warning = Anyone who holds this can read your mail and write as you, and losing it loses the address with it — there is no reset. Keep it in a password manager. +# A copy button's own label, flashed on click instead of a toast. +copy-button-idle = copy +copy-button-success = copied +copy-button-failed = failed +settings-not-registered-value = not registered yet +settings-uri-claim-hint = claim an address to get one + +## Settings — Server tab + +settings-field-host = Host +settings-field-public-key = Public key +settings-public-key-not-pinned = not pinned yet +server-connection-title = Connection +server-timeout-title = Timeout +server-timeout-subtitle = Seconds before a network call gives up +server-fetching-title = Fetching +server-leave-mail-title = Leave mail on server +server-leave-mail-subtitle = Keep a copy on the server after fetching, so you can fetch it again from another app or device. When this is on, deleting a message removes it here and on the server. + +## Settings — Backup tab + +backup-page-description = One file with your mail, contacts, and server info, for moving to another app or keeping what the server no longer has. It's sealed to this identity and never includes the secret itself. +backup-export-title = Export +backup-export-subtitle = Write a backup file +backup-import-title = Import +backup-import-subtitle = Restore from a backup file +backup-export-dialog-title = Export backup +backup-import-dialog-title = Import backup + +## Settings — Advanced tab + +advanced-trust-section-title = trust +advanced-rotations-title = Rotations +advanced-rotations-description = Issues a fresh key from your secret with a signed certificate proving it replaces this one. Contacts accept the change from that chain, and the old key stays readable. Rotation is not revocation. +advanced-rotations-completed = Completed +advanced-rotate-button = Rotate identity +advanced-rotate-needs-account-error = rotate needs a registered account +advanced-first-contact-title = First contact +advanced-first-contact-description = A recipient who isn't a contact yet, and whose address carries no key, has to be looked up on their own server. That answer is only as good as the server: one with no pinned key can return a key of its own and read what you send. +advanced-strict-pinning-title = Require a pinned server +advanced-strict-pinning-subtitle = Stop that send and offer to pin the server's key first, so you can check it against what the operator published. With this off, the key's taken on trust, and the send is only reported as unverified afterwards. +advanced-logout-title = Sign out +advanced-logout-description = Removes this account from this app: the secret, pins, contacts, and every cached message. Other accounts stay as they are. Without a backup of the secret, you can't get back in. Mail already fetched here may have no other copy anywhere, unless "Leave mail on server" was on. Whatever's still on the server comes back on the first fetch after you sign back in. +advanced-logout-button = Sign out and delete this account's data + +## Onboarding +## +## The app name itself ("carrier") is a brand, not translated prose, and +## is left as a literal in code — see the extraction report. + +onboard-welcome-title = welcome +onboard-welcome-description = Encrypted mail with no password. Each identity is one secret, stored only on this device. +onboard-tagline = smolmail: one seed, sealed mail, five operations +onboard-create-button = Create a new identity +onboard-restore-button = Restore an existing identity from a seed +onboard-created-title = Write this seed down +onboard-created-description = It's the only secret, and it's shown once. +onboard-saved-button = I saved it +onboard-restore-title = Restore from a seed +onboard-restore-description = Paste the secret you saved. Your keys come back from it — it is all this client needs. +onboard-seed-entry-title = Seed: 32 bytes, base32 or hex +onboard-restore-go-button = Restore + +## Accounts — the switcher on the sidebar identity row, and adding one + +accounts-menu-tooltip = Switch account +accounts-add-button = Add account +# Shown when signup is about to bind an address another account in this app already uses. +accounts-duplicate-error = { $address } is already in carrier. Switch to it from the account menu. +accounts-add-cancel-button = Cancel adding account +onboard-reuse-title = Use the secret from another account +onboard-reuse-description = Both addresses will share one public key, so anyone who sees both can tell they belong together. + +## Signup + +signup-server-title = Set up the server +signup-host-label = host +signup-fetch-key-button = Fetch the server's key +signup-continue-button = Continue +signup-start-over-button = Start over +signup-account-title = Choose your address +signup-mode-new-label = Create a new address +signup-mode-existing-label = I already have this address +signup-user-label = User +signup-invite-label = Invite token (if the server requires one) +signup-register-button = Register +signup-recall-button = Restore access + +## Compose — the inline pin card shown after a blocked send + +compose-pin-title = { $host } isn't pinned +compose-pin-body = { $address } isn't a contact yet, so carrier would have to ask this server for its key. A server with no pinned key can answer with one of its own, then read the message. +compose-pin-button-fetch = Fetch their server's key +compose-pin-button-send = Pin and send + +## Dialogs + +delete-dialog-title = Delete this message? +delete-dialog-body-kept = Deleting it here leaves the server's copy in place. Deleting it everywhere asks the server to drop that copy too. +delete-dialog-body-gone = This removes the only copy, which is sealed and stored on this device. +delete-dialog-everywhere-button = Delete everywhere +rotate-dialog-title = Rotate the identity? +rotate-dialog-confirm-button = Rotate +reset-dialog-title = Sign out and delete this account's data? +reset-dialog-confirm-button = Sign Out +# `$list` is the sender's own frontmatter rows, already typed by a human +# and reproduced verbatim — not translatable prose itself, just data +# interpolated into this one sentence. +reply-dialog-title = Carry the sender's fields into the reply? +reply-dialog-body = This message has its own headers:{"\u000A"}{"\u000A"}{ $list }{"\u000A"}{"\u000A"}Reply with copies of these fields, or start with none. The fields stay editable either way. +reply-dialog-cancel-button = Cancel reply +reply-dialog-without-button = Reply without +reply-dialog-copy-button = Copy fields +key-change-dialog-title = Replace this contact's key? +key-change-dialog-body = { $address } is already on file with a different key.{"\u000A"}{"\u000A"}known { $known_fingerprint }{"\u000A"}new { $offered_fingerprint }{"\u000A"}{"\u000A"}The address you were given carries the new key and would replace the one on file. If this contact didn't hand it to you themselves, stop: a key swapped in on the way reads everything you send them. +key-change-dialog-replace-button = Replace key + +## Status bar +## +## `model.busy` also doubles as an internal state-machine key compared +## against literal English in app.rs (e.g. `self.busy.as_deref() == +## Some("fetching")`), so that value itself is not translated — only its +## display here is, via this lookup from the internal label to a phrase. +## See the extraction report for the coupling this implies. + +status-busy-fetching = fetching… +status-busy-refreshing = refreshing… +status-busy-registering = registering… +status-busy-restoring = restoring… +status-busy-rotating = rotating… +status-fetching-progress = fetching… { $count } in inbox + +## First contact / server trust + +first-contact-blocked-error = { $address } isn't a contact yet, and { $host } isn't pinned. Pin their server's key to send. +server-key-offered-note = The server presented this key. Pin it only if the fingerprint matches what the operator published. +server-key-already-pinned-note = This server's key is already pinned. +server-key-pinned-note = Server key pinned +connect-unpinned-warning = { $host } is not pinned; its key is { $key }.{"\u000A"}Lookups from this session are UNVERIFIED. +recall-rotation-not-found-error = the key bound to { $address } is not derived from this master within { $max } rotations +contacts-refresh-embedded-key-error = that address already carries a key; use import instead +# Shared by a first send to a never-before-seen recipient and a contact's +# own "re-resolve" button — both land here the same way, by RESOLVE finding +# no existing key for the address. +contacts-resolved-note = { $address } pinned (trust on first use) +contacts-resolved-note-unverified = { $address } pinned (trust on first use, UNVERIFIED server) +contacts-refresh-unchanged-note = { $address }: key unchanged +contacts-refresh-rotated-note = { $address } rotated its key; a signed chain confirms it.{"\u000A"}now { $key } +contacts-refresh-no-chain-warning = { $address } presents a different key with no valid rotation chain.{"\u000A"}Verify out of band, then import the new smol:// address. diff --git a/src/app.rs b/src/app.rs index 8859f80..986132e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -10,11 +10,12 @@ use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use fumi_core::address::Address; -use fumi_core::crypto::{unb32, KEY_LEN}; +use fumi_core::address::{trust_label, Address, Scheme}; +use fumi_core::crypto::{fingerprint, unb32, KEY_LEN}; use fumi_core::store::Store; use gtk::prelude::*; +use crate::i18n; use crate::ops::{self, Draft, Folder, OpenedMsg, Row, Snapshot}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -59,6 +60,16 @@ impl ReadMarks { } } +/// One account folder, as the switcher lists it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccountEntry { + pub id: String, + /// The registered address; None until signup completes. + pub label: Option, + /// Whether the folder holds a master another account can reuse. + pub has_key: bool, +} + /// Onboarding: create a master or restore one from a pasted seed. pub struct Onboard { pub mode: OnboardMode, @@ -75,14 +86,28 @@ pub enum OnboardMode { /// Signup: bind the identity to a username, or recall an existing address. pub struct Signup { + pub step: SignupStep, + pub mode: SignupMode, pub user: String, pub host: String, pub invite: String, - /// The server's base32 static key, pasted from what the operator - /// published; pinned before the registration connects. - pub key: String, - /// True when onboarding just wrote the key file, so Back is offered. - pub fresh: bool, + /// True once this host's key is known to be pinned — either a fetch + /// was just confirmed (see `Carrier::pin_offer`) or it already was + /// from an earlier session — so the server step's button reads + /// "Continue" instead of "Fetch the server's key". + pub key_trusted: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SignupStep { + Server, + Account, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SignupMode { + New, + Existing, } /// The compose view: `to` takes a short address or a smol:// URI. @@ -93,6 +118,22 @@ pub struct Compose { pub body: String, /// The message this replies to, as 64 hex characters. pub reply_to: Option, + /// Frontmatter rows as typed — `Key: value` text, parsed at send. + pub headers: Vec, +} + +/// A correspondent's server that has to be pinned before carrier will +/// take their key from it, and the key fetched for it so far. The compose +/// and the contact detail both prompt through this one slot: they are +/// never on screen together, since selecting a contact stashes the +/// compose. Signup keeps its own `pin_offer` — there the address arrives +/// late from a live entry, and "already pinned" is a third state this +/// struct has no room for. +#[derive(Debug, Clone)] +pub struct PinPrompt { + pub addr: Address, + /// None until the fetch lands, Some once the key is on screen. + pub offered: Option<[u8; KEY_LEN]>, } #[derive(Debug, Clone)] @@ -105,6 +146,59 @@ pub enum Dialog { }, /// Rotation only moves the index forward, so the action asks first. Rotate, + /// Factory reset erases every local file, so it asks first too. + Reset, + /// The message being answered carries the sender's own frontmatter + /// fields; the reply asks whether to carry copies of them. + Reply { + to: String, + subject: String, + id: String, + rows: Vec, + }, + /// A `smol://` address whose key is not the one on file for that + /// contact. `save_contact` is an upsert and both ways in use it with + /// `verified = true`, so a replacement would silently displace a + /// known-good key and skip fumi's own rotation-chain check. It is + /// confirmed here instead. + KeyChange { + address: String, + offered: [u8; KEY_LEN], + known_fingerprint: String, + offered_fingerprint: String, + resume: KeyChangeResume, + }, +} + +/// What confirming a key change goes on to do. +#[derive(Debug, Clone)] +pub enum KeyChangeResume { + Send, + Import { uri: String }, +} + +/// Which question a dialog is asking. The alert's response demux keys off +/// this instead of one boolean per variant, so a new dialog adds arms +/// rather than widening a tuple. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DialogKind { + Delete, + Rotate, + Reset, + Reply, + KeyChange, +} + +impl Dialog { + pub fn kind(&self) -> DialogKind { + match self { + Dialog::Delete { .. } => DialogKind::Delete, + Dialog::Rotate => DialogKind::Rotate, + Dialog::Reset => DialogKind::Reset, + Dialog::Reply { .. } => DialogKind::Reply, + Dialog::KeyChange { .. } => DialogKind::KeyChange, + } + } } /// UI inputs. Background results arrive as [`OpResult`] instead, so the @@ -118,21 +212,31 @@ pub enum Message { OnboardSeedChanged(String), OnboardRestoreFromSeed, OnboardSeedSaved, + /// Copies the master of the named account into this one, so both + /// addresses share a key. + OnboardReuse(String), + + // Accounts + AccountSwitch(String), + AccountAdd, + /// Abandons an account that's still being set up and returns to + /// `Carrier::previous`. + AccountAddCancelled, // Signup SignupUserChanged(String), SignupHostChanged(String), SignupInviteChanged(String), - SignupKeyChanged(String), - SignupBack, - SignupLearnKey, + /// The server step's one button: fetches the host's key, or — once + /// one is on screen (fetched this session or already pinned) — pins + /// it and advances. + SignupKeyAction, + SignupStepBack, + SignupStartOver, + SignupModeChanged(SignupMode), SignupRegister, SignupRecall, - // Pin offer (signup and settings share it) - PinAccept, - PinDiscard, - // Mail GotoMail(Folder), Goto(Page), @@ -146,9 +250,18 @@ pub enum Message { ComposeToChanged(String), ComposeSubjectChanged(String), ComposeBodyChanged(String), + ComposeHeaderAdded, + ComposeHeaderChanged(usize, String), + ComposeHeaderRemoved(usize), ComposeClosed, SendPressed, + /// The pin card's one button, on whichever surface shows it: fetches + /// the server's key, then — once it is on screen — pins it, and in a + /// compose sends in the same press. + PinServerAction, ReplyPressed, + ReplyCancelled, + ReplyConfirmed(bool), DeletePressed, DeleteConfirmed(bool), DeleteCancelled, @@ -167,18 +280,23 @@ pub enum Message { ContactAccept(String, String), ContactBlock(String), ContactUnblock(String), - CopyExport, // Settings - SettingsLearnKey, + SecretRevealToggled, + CopySecret, + KeepMailChanged(bool), + StrictPinningChanged(bool), TimeoutChanged(String), RotatePressed, RotateConfirmed, RotateCancelled, - UnpinPressed(String), - ExportPressed, - ImportBodyChanged(String), - ImportPressed, + ExportBackupTo(PathBuf), + ImportBackupFrom(String), + ResetPressed, + ResetConfirmed, + ResetCancelled, + KeyChangeConfirmed, + KeyChangeCancelled, } /// What a background operation reports back. @@ -190,8 +308,6 @@ pub enum OpResult { /// The key a server presented with no pin in place (sec 4 tofu). PinOffered(Result, String>), Pinned(Result<(), String>), - /// (note, backup text) — the text is for the clipboard and the view. - Exported(Result<(String, String), String>), } /// One background operation to run on the blocking pool, carrying every @@ -204,8 +320,6 @@ pub enum PendingOp { Register { addr: Address, invite: Option, - /// A pasted operator key, pinned before the registration connects. - key: String, }, Restore { addr: Address, @@ -225,6 +339,7 @@ pub enum PendingOp { subject: String, body: String, reply_to: Option, + headers: Vec<(String, String)>, }, Delete { id: String, @@ -242,11 +357,8 @@ pub enum PendingOp { uri: String, }, Rotate, - Unpin { - label: String, - }, Export { - dir: PathBuf, + path: PathBuf, }, ImportBackup { text: String, @@ -254,7 +366,14 @@ pub enum PendingOp { } pub struct Carrier { + /// The config root holding `accounts/` and `active.txt`. + pub root: PathBuf, + /// The active account's id and folder. + pub id: String, pub dir: PathBuf, + pub accounts: Vec, + /// The account to return to when one still being set up is cancelled. + pub previous: Option, pub store: Arc, pub master: Option<[u8; KEY_LEN]>, pub marks: ReadMarks, @@ -263,6 +382,13 @@ pub struct Carrier { pub status_error: bool, pub busy: Option, pub cancel: Arc, + /// Off by default: a fetch acknowledges what it takes, so mail is + /// removed from the server once it's stored here. + pub keep_mail: bool, + /// Refuse a send that would take a recipient's key from a server with + /// no pin: `client::resolve` verifies nothing, so such a key is + /// whatever answered the connection. + pub strict_pinning: bool, pub timeout: u64, pub timeout_text: String, pub onboard: Onboard, @@ -280,18 +406,55 @@ pub struct Carrier { /// the drafts sidecar; the folder only shows once it holds one. pub drafts: Vec, pub snapshot: Option, + /// Signup's offer only; correspondents' servers prompt through + /// `pin_prompt`. pub pin_offer: Option<(Address, [u8; KEY_LEN])>, - pub backup_text: Option, - pub import_body: String, + pub pin_prompt: Option, + /// The Identity tab's recovery secret is masked until this is toggled. + pub secret_revealed: bool, pub contact_import: String, pub dialog: Option, /// The view syncs entry text from the model once after a prefill /// (reply, write-to-contact), then leaves typing to the widgets. pub compose_fresh: Cell, + /// Same pattern for the onboarding/signup entries: a programmatic + /// reset (factory reset, discarding a cancelled identity) clears the + /// model, and this flag makes the view push that blank state into + /// the entries once, instead of leaving stale typed text on screen. + pub form_fresh: Cell, } impl Carrier { - pub fn boot(dir: PathBuf) -> (Carrier, Option) { + /// Opens the account `active.txt` names, else the first one, else a + /// fresh empty one. + pub fn boot(root: PathBuf) -> (Carrier, Option) { + let id = match ops::load_active(&root) + .or_else(|| ops::list_accounts(&root).into_iter().next()) + { + Some(id) => id, + None => match ops::new_account(&root) { + Ok(id) => id, + Err(e) => { + eprintln!("cannot create an account in {}: {e}", root.display()); + std::process::exit(1); + } + }, + }; + Carrier::boot_account(root, id) + } + + pub fn boot_account(root: PathBuf, id: String) -> (Carrier, Option) { + let dir = ops::account_dir(&root, &id); + if let Err(e) = ops::save_active(&root, &id) { + eprintln!("{e}"); + } + let accounts = load_accounts(&root); + // An unregistered account next to registered ones is one being + // added, even after a restart, so it always offers a way back. + let previous = accounts + .iter() + .find(|entry| entry.id != id && entry.label.is_some()) + .map(|entry| entry.id.clone()); let store = match Store::open(&dir.join("carrier.db")) { Ok(store) => Arc::new(store), Err(e) => { @@ -308,9 +471,15 @@ impl Carrier { (true, true) => Page::Mail, }; let drafts = ops::load_drafts(&dir.join("drafts.txt")); - let app = Carrier { + let settings = ops::load_settings(&dir.join("settings.txt")); + let previous = previous.filter(|_| !registered); + let mut app = Carrier { marks: ReadMarks::load(dir.join("read.txt")), + root, + id, dir, + accounts, + previous, store, master, page, @@ -318,19 +487,22 @@ impl Carrier { status_error: false, busy: None, cancel: Arc::new(AtomicBool::new(false)), - timeout: 30, - timeout_text: "30".to_string(), + keep_mail: settings.keep_mail, + strict_pinning: settings.strict_pinning, + timeout: settings.timeout, + timeout_text: settings.timeout.to_string(), onboard: Onboard { mode: OnboardMode::Start, seed: String::new(), seed_shown: String::new(), }, signup: Signup { + step: SignupStep::Server, + mode: SignupMode::New, user: String::new(), host: String::new(), invite: String::new(), - key: String::new(), - fresh: false, + key_trusted: false, }, folder: Folder::Inbox, lists: vec![Vec::new(), Vec::new(), Vec::new()], @@ -341,18 +513,36 @@ impl Carrier { drafts, snapshot: None, pin_offer: None, - backup_text: None, - import_body: String::new(), + pin_prompt: None, + secret_revealed: false, contact_import: String::new(), dialog: None, compose_fresh: Cell::new(false), + form_fresh: Cell::new(true), }; - let op = registered.then(|| PendingOp::Snapshot { - read: app.marks.snapshot(), - }); + // Through the busy guard, so a switch can't land while this + // snapshot is still loading the old account's lists. + let op = if registered { app.refresh() } else { None }; (app, op) } + /// Accounts other than this one whose master a new account can reuse. + pub fn reusable_accounts(&self) -> Vec<&AccountEntry> { + self.accounts + .iter() + .filter(|entry| entry.id != self.id && entry.has_key) + .collect() + } + + /// Whether another account already holds this address. Two stores + /// fetching one mailbox would split its mail between them. + fn address_taken(&self, addr: &Address) -> bool { + let short = addr.short(); + self.accounts + .iter() + .any(|entry| entry.id != self.id && entry.label.as_deref() == Some(short.as_str())) + } + fn master(&self) -> [u8; KEY_LEN] { self.master.unwrap_or([0u8; KEY_LEN]) } @@ -365,6 +555,19 @@ impl Carrier { self.dir.join("drafts.txt") } + /// Rewritten on every change: three values in one short file, the + /// same whole-file rewrite the drafts sidecar does. + fn save_settings(&self) { + ops::save_settings( + &self.dir.join("settings.txt"), + &ops::Settings { + keep_mail: self.keep_mail, + timeout: self.timeout, + strict_pinning: self.strict_pinning, + }, + ); + } + /// Every sidebar trip closes the compose this way: a compose with /// anything in it becomes a draft, an empty one is thrown away, and /// Cancel stays the only way to discard work outright. @@ -372,22 +575,25 @@ impl Carrier { let Some(compose) = self.compose.take() else { return; }; + let rows = compose.headers.iter().any(|row| !row.trim().is_empty()); if compose.to.trim().is_empty() && compose.subject.trim().is_empty() && compose.body.trim().is_empty() + && !rows { return; } self.drafts.push(Draft { - id: ops::draft_id(), + id: ops::random_id(), to: compose.to, subject: compose.subject, body: compose.body, reply_to: compose.reply_to, + headers: compose.headers, at: fumi_core::store::now(), }); ops::save_drafts(&self.drafts_path(), &self.drafts); - self.note("draft saved".into()); + self.note(i18n::t("draft-saved-note")); } /// Tapping a draft in the folder puts it back in the compose it came @@ -403,10 +609,90 @@ impl Carrier { subject: draft.subject, body: draft.body, reply_to: draft.reply_to, + headers: draft.headers, }); self.compose_fresh.set(true); } + /// Deletes the active account's folder, then boots `next`, or + /// whichever account `boot` picks. The connection is swapped out + /// before the files go because Windows refuses to remove a file a + /// live connection holds, and the busy guard has already seen to it + /// that no operation holds a clone of the store. + fn remove_active(&mut self, next: Option) -> Result, String> { + self.store = Arc::new(Store::open_in_memory().map_err(|e| e.to_string())?); + ops::remove_account(&self.root, &self.id)?; + let root = self.root.clone(); + let (app, op) = match next { + Some(id) => Carrier::boot_account(root, id), + None => Carrier::boot(root), + }; + *self = app; + Ok(op) + } + + /// Signing out removes this account only; the app moves on to another + /// one, or back to onboarding when it was the last. + fn factory_reset(&mut self) -> Option { + match self.remove_active(None) { + Ok(op) => { + match self.store.account().ok().flatten() { + Some(addr) => self.note(i18n::t1( + "logged-out-switched-note", + "address", + addr.short(), + )), + None => self.note(i18n::t("logged-out-note")), + } + op + } + Err(e) => { + self.fail(e); + None + } + } + } + + /// Replaces the model with another account's, keeping nothing of this + /// one but what's already on disk. + fn switch_to(&mut self, id: String) -> Option { + let (app, op) = Carrier::boot_account(self.root.clone(), id); + *self = app; + op + } + + /// Cancelling out of a not-yet-registered identity removes the key + /// file too, so Back always leaves onboarding resumable from a clean + /// start — never behind a stale key a later Create could silently + /// overwrite and orphan the server registration against. The seed + /// already shown (or pasted) still regenerates the same master, so + /// nothing is actually lost. + fn discard_identity(&mut self) { + if self.store.account().ok().flatten().is_none() { + if let Err(e) = ops::delete_key(&self.key_path()) { + self.fail(e); + return; + } + self.master = None; + } + self.onboard = Onboard { + mode: OnboardMode::Start, + seed: String::new(), + seed_shown: String::new(), + }; + self.signup = Signup { + step: SignupStep::Server, + mode: SignupMode::New, + user: String::new(), + host: String::new(), + invite: String::new(), + key_trusted: false, + }; + self.pin_offer = None; + self.page = Page::Onboard; + self.form_fresh.set(true); + } + /// The current folder's rows, drafts included: drafts carry the /// recipient where mail carries the sender, newest first. pub fn rows(&self) -> Vec { @@ -469,11 +755,6 @@ impl Carrier { }) } - /// The account address, for the settings page's learn-key action. - fn account_address(&self) -> Option
{ - self.store.account().ok().flatten() - } - /// `user@host` as typed on the signup page, defaulting the port. fn signup_address(&self) -> Option
{ let user = self.signup.user.trim(); @@ -484,6 +765,60 @@ impl Carrier { Address::parse(&format!("{user}@{host}")).ok() } + /// The recipient's address when sending to it would make carrier take + /// their key from a server it has never pinned: no key in the address, + /// no contact on file, no pin for the host. A pin is enough to make + /// the lookup trustworthy — `connect` rejects a mismatch whatever + /// `require_pin` says. RNS has nothing to pin: there the destination + /// hash in the address is itself the pin. + fn unpinned_first_contact(&self, to: &str) -> Option
{ + let addr = Address::parse(to).ok()?; + if addr.scheme != Scheme::Tcp || addr.identity.is_some() { + return None; + } + // A store error reads as "not known, not pinned": this gate errs + // towards asking. + let known = self.store.contact(&addr.short()).ok().flatten().is_some(); + let pinned = self + .store + .server_pin(&addr.host, addr.port) + .ok() + .flatten() + .is_some(); + (!known && !pinned).then_some(addr) + } + + /// A self-certifying address whose key differs from the contact on + /// file. Both keys are public and about to be shown side by side, so + /// a plain comparison is all this needs. + fn key_change(&self, text: &str) -> Option<(String, [u8; KEY_LEN], [u8; KEY_LEN])> { + let addr = Address::parse(text).ok()?; + let offered = addr.identity?; + let (known, _) = self.store.contact(&addr.short()).ok().flatten()?; + (known != offered).then_some((addr.short(), known, offered)) + } + + /// The key the pin card fetched, if it was fetched for this very + /// recipient; taken, so editing the address cannot reuse it. + fn take_offered_pin(&mut self, to: &str) -> Option<(Address, [u8; KEY_LEN])> { + let wanted = Address::parse(to).ok()?.short(); + let prompt = self.pin_prompt.as_ref()?; + let key = prompt.offered.filter(|_| prompt.addr.short() == wanted)?; + let prompt = self.pin_prompt.take()?; + Some((prompt.addr, key)) + } + + /// The host as typed on the signup page's server step, before a + /// username exists — `learn_key`/`connect` only read host/port/scheme, + /// so a throwaway username satisfies `Address::parse`'s grammar. + fn signup_host_address(&self) -> Option
{ + let host = self.signup.host.trim(); + if host.is_empty() { + return None; + } + Address::parse(&format!("x@{host}")).ok() + } + /// Opens one message and marks it read inline: opening an envelope and /// re-listing is local and fast, so it needs no background pass. fn select_message(&mut self, folder: Folder, id: String) { @@ -518,8 +853,24 @@ impl Carrier { compose.body = body; } } - Message::ImportBodyChanged(text) => { - self.import_body = text; + Message::ComposeHeaderAdded => { + if let Some(compose) = &mut self.compose { + compose.headers.push(String::new()); + } + } + Message::ComposeHeaderChanged(index, text) => { + if let Some(compose) = &mut self.compose { + if let Some(row) = compose.headers.get_mut(index) { + *row = text; + } + } + } + Message::ComposeHeaderRemoved(index) => { + if let Some(compose) = &mut self.compose { + if index < compose.headers.len() { + compose.headers.remove(index); + } + } } Message::ContactSelected(address) => { self.stash_draft(); @@ -557,19 +908,32 @@ impl Carrier { } Message::SignupHostChanged(host) => { self.signup.host = host; + // A different host invalidates whatever key was on + // screen: there is only ever one key pending trust. + self.signup.key_trusted = false; + self.pin_offer = None; } Message::SignupInviteChanged(invite) => { self.signup.invite = invite; } - Message::SignupKeyChanged(key) => { - self.signup.key = key; - } Message::ContactImportChanged(text) => { self.contact_import = text; } + Message::KeepMailChanged(keep) => { + self.keep_mail = keep; + self.save_settings(); + } + Message::StrictPinningChanged(strict) => { + self.strict_pinning = strict; + self.save_settings(); + } + Message::SecretRevealToggled => { + self.secret_revealed = !self.secret_revealed; + } Message::TimeoutChanged(text) => { if let Ok(timeout) = text.trim().parse::() { self.timeout = timeout; + self.save_settings(); } self.timeout_text = text; } @@ -584,6 +948,52 @@ impl Carrier { } } _ if self.busy.is_some() => return Vec::new(), + Message::AccountSwitch(id) => { + if id == self.id || !self.accounts.iter().any(|entry| entry.id == id) { + return Vec::new(); + } + self.stash_draft(); + return self.switch_to(id).into_iter().collect(); + } + Message::AccountAdd => { + self.stash_draft(); + match ops::new_account(&self.root) { + Ok(id) => { + let previous = self.id.clone(); + self.switch_to(id); + self.previous = Some(previous); + } + Err(e) => self.fail(e), + } + } + Message::AccountAddCancelled => { + let Some(previous) = self.previous.clone() else { + return Vec::new(); + }; + return match self.remove_active(Some(previous)) { + Ok(op) => op.into_iter().collect(), + Err(e) => { + self.fail(e); + Vec::new() + } + }; + } + Message::OnboardReuse(id) => { + if id == self.id { + return Vec::new(); + } + let source = ops::account_dir(&self.root, &id).join("carrier.key"); + let copied = ops::load_key(&source) + .and_then(|master| ops::save_key(&self.key_path(), &master).map(|()| master)); + match copied { + Ok(master) => { + self.master = Some(master); + self.page = Page::Signup; + self.note(i18n::t("seed-reused-note")); + } + Err(e) => self.fail(e), + } + } Message::OnboardCreate => { let master = ops::new_master(); if let Err(e) = ops::save_key(&self.key_path(), &master) { @@ -592,16 +1002,20 @@ impl Carrier { self.master = Some(master); self.onboard.seed_shown = ops::seed_text(&master); self.onboard.mode = OnboardMode::Created; - self.note( - "Identity created. Write the seed down; it is the only secret.".into(), - ); + self.note(i18n::t("identity-created-note")); } } Message::OnboardRestore => { self.onboard.mode = OnboardMode::Restore; } Message::OnboardBack => { - self.onboard.mode = OnboardMode::Start; + if self.onboard.mode == OnboardMode::Created { + self.discard_identity(); + } else { + self.onboard.mode = OnboardMode::Start; + self.onboard.seed.clear(); + self.form_fresh.set(true); + } } Message::OnboardRestoreFromSeed => match ops::parse_seed(&self.onboard.seed) { Ok(master) => { @@ -609,60 +1023,78 @@ impl Carrier { self.fail(e); } else { self.master = Some(master); - self.signup.fresh = true; self.page = Page::Signup; - self.note("Seed restored. Bind a username or recall an address.".into()); + self.note(i18n::t("seed-restored-note")); } } Err(e) => self.fail(e), }, Message::OnboardSeedSaved => { - self.signup.fresh = true; self.page = Page::Signup; } - Message::SignupBack => { - self.page = Page::Onboard; + Message::SignupStepBack => { + self.signup.step = SignupStep::Server; } - Message::SignupLearnKey => { - let Some(addr) = self.signup_address() else { - self.fail("enter user and host first".into()); + Message::SignupStartOver => { + self.discard_identity(); + } + Message::SignupModeChanged(mode) => { + self.signup.mode = mode; + } + Message::SignupKeyAction => { + if let Some((addr, key)) = self.pin_offer.take() { + self.signup.step = SignupStep::Account; + return vec![PendingOp::Pin { addr, key }]; + } + if self.signup.key_trusted { + self.signup.step = SignupStep::Account; + return Vec::new(); + } + let Some(addr) = self.signup_host_address() else { + self.fail(i18n::t("signup-enter-host-error")); return Vec::new(); }; return vec![PendingOp::LearnKey { addr }]; } - Message::SettingsLearnKey => { - let Some(addr) = self.account_address() else { - return Vec::new(); - }; - return vec![PendingOp::LearnKey { addr }]; - } - Message::PinDiscard => { - self.pin_offer = None; - } - Message::PinAccept => { - let Some((addr, key)) = self.pin_offer.take() else { - return Vec::new(); - }; - return vec![PendingOp::Pin { addr, key }]; - } Message::SignupRegister => { let Some(addr) = self.signup_address() else { - self.fail("enter user and host".into()); + self.fail(i18n::t("signup-enter-user-host-error")); return Vec::new(); }; + if self.address_taken(&addr) { + self.fail(i18n::t1( + "accounts-duplicate-error", + "address", + addr.short(), + )); + return Vec::new(); + } let invite = if self.signup.invite.is_empty() { None } else { Some(self.signup.invite.clone()) }; - let key = self.signup.key.trim().to_string(); - return vec![PendingOp::Register { addr, invite, key }]; + if !self.start("registering") { + return Vec::new(); + } + return vec![PendingOp::Register { addr, invite }]; } Message::SignupRecall => { let Some(addr) = self.signup_address() else { - self.fail("enter user and host".into()); + self.fail(i18n::t("signup-enter-user-host-error")); return Vec::new(); }; + if self.address_taken(&addr) { + self.fail(i18n::t1( + "accounts-duplicate-error", + "address", + addr.short(), + )); + return Vec::new(); + } + if !self.start("restoring") { + return Vec::new(); + } return vec![PendingOp::Restore { addr }]; } Message::GotoMail(folder) => { @@ -712,6 +1144,7 @@ impl Carrier { subject: String::new(), body: String::new(), reply_to: None, + headers: Vec::new(), }); self.compose_fresh.set(true); } @@ -723,7 +1156,7 @@ impl Carrier { let to = if let Some(uri) = &msg.reply_to { uri.clone() } else if msg.from.starts_with('<') { - self.fail("this sender left no address to reply to".into()); + self.fail(i18n::t("reply-no-address-error")); return Vec::new(); } else { msg.from.clone() @@ -731,13 +1164,51 @@ impl Carrier { let subject = if msg.subject.is_empty() || msg.subject.starts_with("Re:") { msg.subject.clone() } else { - format!("Re: {}", msg.subject) + i18n::t1("reply-subject-prefix", "subject", msg.subject.clone()) + }; + // The sender's own fields are the one thing a reply has to + // decide about: carry copies, or start clean. Only the + // fields that would survive send-time validation ask — + // a mail whose only extra field is the threading id + // replies straight through. + let rows = ops::reply_rows(&msg.headers); + if rows.is_empty() { + self.compose = Some(Compose { + to, + subject, + body: String::new(), + reply_to: Some(msg.id.clone()), + headers: Vec::new(), + }); + self.compose_fresh.set(true); + } else { + self.dialog = Some(Dialog::Reply { + to, + subject, + id: msg.id.clone(), + rows, + }); + } + } + Message::ReplyCancelled => { + self.dialog = None; + } + Message::ReplyConfirmed(copy) => { + let Some(Dialog::Reply { + to, + subject, + id, + rows, + }) = self.dialog.take() + else { + return Vec::new(); }; self.compose = Some(Compose { to, subject, body: String::new(), - reply_to: Some(msg.id.clone()), + reply_to: Some(id), + headers: if copy { rows } else { Vec::new() }, }); self.compose_fresh.set(true); } @@ -749,18 +1220,123 @@ impl Carrier { return Vec::new(); }; if compose.to.trim().is_empty() { - self.fail("enter a recipient".into()); + self.fail(i18n::t("compose-enter-recipient-error")); + return Vec::new(); + } + let mut headers = Vec::new(); + for (index, row) in compose.headers.iter().enumerate() { + match ops::header_row(row) { + Ok(Some(pair)) => headers.push(pair), + Ok(None) => {} + Err(reason) => { + let mut args = fluent_bundle::FluentArgs::new(); + args.set("index", (index + 1) as i64); + args.set("reason", reason); + self.fail(i18n::t_args("compose-header-row-error", Some(&args))); + return Vec::new(); + } + } + } + if let Err(reason) = ops::validate_headers(&headers) { + self.fail(reason); + return Vec::new(); + } + let to = compose.to.trim().to_string(); + // Asked before anything else: a pasted address carrying a + // different key is a question about who the recipient is, + // which has to settle before how to reach them. + if let Some((address, known, offered)) = self.key_change(&to) { + self.dialog = Some(Dialog::KeyChange { + address, + offered, + known_fingerprint: fingerprint(&known), + offered_fingerprint: fingerprint(&offered), + resume: KeyChangeResume::Send, + }); return Vec::new(); } let op = PendingOp::Send { - to: compose.to.trim().to_string(), + to: to.clone(), subject: compose.subject.trim().to_string(), body: compose.body.clone(), reply_to: compose.reply_to.clone(), + headers, }; + // The card's second press: the key on screen was fetched + // for this recipient's server, so pin it here — a local + // write — and the send below opens a pinned session. + // Writing the pin first is also what stops the re-entry + // in PinServerAction from looping back into the gate. + if let Some((addr, key)) = self.take_offered_pin(&to) { + if let Err(e) = ops::pin(&self.store, &addr, &key) { + self.fail(e); + return Vec::new(); + } + } + if self.strict_pinning { + if let Some(addr) = self.unpinned_first_contact(&to) { + let mut args = fluent_bundle::FluentArgs::new(); + args.set("address", addr.short()); + args.set("host", trust_label(&addr.host, addr.port)); + self.fail(i18n::t_args("first-contact-blocked-error", Some(&args))); + self.pin_prompt = Some(PinPrompt { + addr, + offered: None, + }); + // The compose stays open: its text is the message + // the user is still trying to send. + return Vec::new(); + } + } + self.pin_prompt = None; self.compose = None; return vec![op]; } + Message::PinServerAction => { + // The surface is the address: a compose's recipient, or + // the contact whose detail is open. Never both at once. + let Some(to) = self + .compose + .as_ref() + .map(|compose| compose.to.trim().to_string()) + .or_else(|| self.selected_contact.clone()) + else { + return Vec::new(); + }; + let Ok(addr) = Address::parse(&to) else { + self.fail(i18n::t("address-invalid-error")); + return Vec::new(); + }; + let fetched = self + .pin_prompt + .as_ref() + .is_some_and(|p| p.offered.is_some() && p.addr.short() == addr.short()); + if !fetched { + self.pin_prompt = Some(PinPrompt { + addr: addr.clone(), + offered: None, + }); + return vec![PendingOp::LearnKey { addr }]; + } + // In a compose the pin is only ever the first half of the + // send the user already asked for, and SendPressed writes + // it before re-checking the gate — so this does not loop. + if self.compose.is_some() { + return self.handle(Message::SendPressed); + } + let Some(prompt) = self.pin_prompt.take() else { + return Vec::new(); + }; + return prompt + .offered + .map(|key| { + vec![PendingOp::Pin { + addr: prompt.addr, + key, + }] + }) + .unwrap_or_default(); + } Message::DeletePressed => { let Some((folder, msg)) = &self.open else { return Vec::new(); @@ -792,17 +1368,17 @@ impl Carrier { return Vec::new(); } let Some(uri) = msg.reply_to.clone() else { - self.fail("this sender left no address to accept".into()); + self.fail(i18n::t("contacts-accept-no-address-error")); return Vec::new(); }; let Ok(addr) = Address::parse(&uri) else { - self.fail("the sender's reply address does not parse".into()); + self.fail(i18n::t("contacts-reply-address-invalid-error")); return Vec::new(); }; let Ok(identity) = <[u8; KEY_LEN]>::try_from(unb32(&msg.sender).unwrap_or_default()) else { - self.fail("the sender's key does not parse".into()); + self.fail(i18n::t("contacts-sender-key-invalid-error")); return Vec::new(); }; return vec![PendingOp::Accept { @@ -815,11 +1391,11 @@ impl Carrier { return Vec::new(); }; let Some(uri) = msg.reply_to.clone() else { - self.fail("this sender left no address to block".into()); + self.fail(i18n::t("contacts-block-no-address-error")); return Vec::new(); }; let Ok(addr) = Address::parse(&uri) else { - self.fail("the sender's reply address does not parse".into()); + self.fail(i18n::t("contacts-reply-address-invalid-error")); return Vec::new(); }; return vec![PendingOp::Block { @@ -831,8 +1407,45 @@ impl Carrier { if uri.is_empty() { return Vec::new(); } + if let Some((address, known, offered)) = self.key_change(&uri) { + self.dialog = Some(Dialog::KeyChange { + address, + offered, + known_fingerprint: fingerprint(&known), + offered_fingerprint: fingerprint(&offered), + resume: KeyChangeResume::Import { uri }, + }); + return Vec::new(); + } return vec![PendingOp::ImportContact { uri }]; } + Message::KeyChangeCancelled => { + self.dialog = None; + } + Message::KeyChangeConfirmed => { + let Some(Dialog::KeyChange { + address, + offered, + resume, + .. + }) = self.dialog.take() + else { + return Vec::new(); + }; + match resume { + // Recording the accepted key is also what keeps the + // re-dispatch below from asking the same question. + KeyChangeResume::Send => { + match ops::save_contact(&self.store, &address, &offered) { + Ok(()) => return self.handle(Message::SendPressed), + Err(e) => self.fail(e), + } + } + KeyChangeResume::Import { uri } => { + return vec![PendingOp::ImportContact { uri }] + } + } + } Message::ContactWrite(address) => { let key = self .snapshot @@ -850,6 +1463,7 @@ impl Carrier { subject: String::new(), body: String::new(), reply_to: None, + headers: Vec::new(), }); self.compose_fresh.set(true); } @@ -881,11 +1495,10 @@ impl Carrier { }; return vec![PendingOp::Accept { address, identity }]; } - Message::CopyExport => { - if let Some(text) = &self.backup_text { - if let Some(display) = gtk::gdk::Display::default() { - display.clipboard().set_text(text); - } + Message::CopySecret => { + let text = ops::seed_text(&self.master()); + if let Some(display) = gtk::gdk::Display::default() { + display.clipboard().set_text(&text); } } Message::RotatePressed => { @@ -894,24 +1507,28 @@ impl Carrier { Message::RotateCancelled => { self.dialog = None; } + Message::ResetPressed => { + self.dialog = Some(Dialog::Reset); + } + Message::ResetCancelled => { + self.dialog = None; + } + Message::ResetConfirmed => { + self.dialog = None; + return self.factory_reset().into_iter().collect(); + } Message::RotateConfirmed => { self.dialog = None; return vec![PendingOp::Rotate]; } - Message::UnpinPressed(label) => { - return vec![PendingOp::Unpin { label }]; + Message::ExportBackupTo(path) => { + return vec![PendingOp::Export { path }]; } - Message::ExportPressed => { - let dir = self.dir.clone(); - return vec![PendingOp::Export { dir }]; - } - Message::ImportPressed => { - if self.import_body.trim().is_empty() { + Message::ImportBackupFrom(text) => { + if text.trim().is_empty() { return Vec::new(); } - return vec![PendingOp::ImportBackup { - text: self.import_body.clone(), - }]; + return vec![PendingOp::ImportBackup { text }]; } } Vec::new() @@ -935,6 +1552,15 @@ impl Carrier { OpResult::Generic(Ok(note)) => { self.done(); self.note(note); + // The only `Generic` ops reachable from the signup page are + // Register and Restore — LearnKey/Pin report through their + // own variants — so a success here always means the + // address is bound and it's safe to leave the page. + if self.page == Page::Signup { + self.page = Page::Mail; + self.accounts = load_accounts(&self.root); + self.previous = None; + } self.refresh() } OpResult::Generic(Err(e)) => { @@ -944,17 +1570,28 @@ impl Carrier { } OpResult::PinOffered(Ok(Some((addr, key)))) => { self.done(); - self.pin_offer = Some((addr, key)); - self.note( - "The server presented this key. Pin it only if the fingerprint \ - matches what the operator published." - .into(), - ); + // The prompt is armed synchronously before the fetch is + // ever spawned, so an offer that matches it belongs to a + // correspondent's server; anything else is signup's. + match self + .pin_prompt + .as_mut() + .filter(|prompt| prompt.addr.short() == addr.short()) + { + Some(prompt) => prompt.offered = Some(key), + None => self.pin_offer = Some((addr, key)), + } + self.note(i18n::t("server-key-offered-note")); None } OpResult::PinOffered(Ok(None)) => { self.done(); - self.note("This server's key is already pinned.".into()); + // A pin appeared in the meantime: a correspondent prompt + // has nothing left to ask, and signup can advance. + if self.pin_prompt.take().is_none() { + self.signup.key_trusted = true; + } + self.note(i18n::t("server-key-already-pinned-note")); None } OpResult::PinOffered(Err(e)) => { @@ -964,7 +1601,13 @@ impl Carrier { } OpResult::Pinned(Ok(())) => { self.done(); - self.note("server key pinned".into()); + self.note(i18n::t("server-key-pinned-note")); + // The contact detail shows the pin state, so that pane + // needs the fresh row; signup's own pin changes nothing + // that is on screen. + if self.page == Page::Mail { + return self.refresh(); + } None } OpResult::Pinned(Err(e)) => { @@ -972,21 +1615,24 @@ impl Carrier { self.fail(e); None } - OpResult::Exported(Ok((note, text))) => { - self.done(); - self.backup_text = Some(text); - self.note(note); - None - } - OpResult::Exported(Err(e)) => { - self.done(); - self.fail(e); - None - } } } } +fn load_accounts(root: &std::path::Path) -> Vec { + ops::list_accounts(root) + .into_iter() + .map(|id| { + let dir = ops::account_dir(root, &id); + AccountEntry { + label: ops::account_label(&dir), + has_key: dir.join("carrier.key").exists(), + id, + } + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -997,6 +1643,136 @@ mod tests { app } + /// A registered account folder under `root`, with its own master. + fn registered(root: &std::path::Path, address: &str) -> String { + let id = ops::new_account(root).unwrap(); + let dir = ops::account_dir(root, &id); + ops::save_key(&dir.join("carrier.key"), &ops::new_master()).unwrap(); + let store = Store::open(&dir.join("carrier.db")).unwrap(); + store + .set_account(&Address::parse(address).unwrap()) + .unwrap(); + id + } + + /// Two registered accounts, booted into `alice`. + fn two_accounts() -> (Carrier, String, String) { + let root = tempfile::tempdir().unwrap().keep(); + let alice = registered(&root, "alice@example.org"); + let bob = registered(&root, "bob@example.org"); + ops::save_active(&root, &alice).unwrap(); + let (app, _) = Carrier::boot(root); + (app, alice, bob) + } + + #[test] + fn boot_opens_the_active_account_through_the_busy_guard() { + let (app, alice, _) = two_accounts(); + assert_eq!(app.id, alice); + assert_eq!(app.page, Page::Mail); + assert_eq!(app.accounts.len(), 2); + assert!(app.previous.is_none()); + // The boot snapshot holds the guard, so no switch can overtake it. + assert_eq!(app.busy.as_deref(), Some("refreshing")); + } + + #[test] + fn switching_keeps_each_accounts_drafts_and_settings_apart() { + let (mut app, alice, bob) = two_accounts(); + app.busy = None; + app.handle(Message::StrictPinningChanged(true)); + app.handle(Message::ComposePressed); + app.handle(Message::ComposeSubjectChanged("half written".into())); + + let ops = app.handle(Message::AccountSwitch(bob.clone())); + assert!(matches!(ops.as_slice(), [PendingOp::Snapshot { .. }])); + assert_eq!(app.id, bob); + assert_eq!(ops::load_active(&app.root).as_deref(), Some(bob.as_str())); + assert!(app.compose.is_none()); + assert!(app.drafts.is_empty()); + assert!(!app.strict_pinning); + + app.busy = None; + app.handle(Message::AccountSwitch(alice.clone())); + assert_eq!(app.drafts.len(), 1); + assert_eq!(app.drafts[0].subject, "half written"); + assert!(app.strict_pinning); + } + + #[test] + fn switching_waits_for_the_running_operation() { + let (mut app, alice, bob) = two_accounts(); + app.busy = Some("fetching".into()); + assert!(app.handle(Message::AccountSwitch(bob)).is_empty()); + assert_eq!(app.id, alice); + } + + #[test] + fn adding_an_account_can_reuse_a_secret_or_be_cancelled() { + let (mut app, alice, _) = two_accounts(); + app.busy = None; + app.handle(Message::AccountAdd); + assert_eq!(app.page, Page::Onboard); + assert_eq!(app.previous.as_deref(), Some(alice.as_str())); + assert_eq!(app.accounts.len(), 3); + assert_eq!(app.reusable_accounts().len(), 2); + let added = app.dir.clone(); + + app.handle(Message::OnboardReuse(alice.clone())); + assert_eq!(app.page, Page::Signup); + let alice_master = ops::load_key(&ops::account_dir(&app.root, &alice).join("carrier.key")); + assert_eq!(app.master, alice_master.ok()); + assert_eq!(ops::load_key(&added.join("carrier.key")).ok(), app.master); + + app.handle(Message::AccountAddCancelled); + assert!(!added.exists()); + assert_eq!(app.id, alice); + assert_eq!(app.page, Page::Mail); + assert_eq!(app.accounts.len(), 2); + } + + /// Quitting halfway through adding an account must not strand the + /// user in onboarding with no way back. + #[test] + fn an_unfinished_account_offers_a_way_back_after_a_restart() { + let (mut app, alice, _) = two_accounts(); + app.busy = None; + app.handle(Message::AccountAdd); + let (rebooted, _) = Carrier::boot(app.root.clone()); + assert_eq!(rebooted.page, Page::Onboard); + assert_eq!(rebooted.previous.as_deref(), Some(alice.as_str())); + } + + #[test] + fn an_address_another_account_holds_is_refused() { + let (mut app, _, _) = two_accounts(); + app.busy = None; + app.handle(Message::AccountAdd); + app.handle(Message::OnboardCreate); + app.handle(Message::OnboardSeedSaved); + app.signup.user = "bob".into(); + app.signup.host = "example.org".into(); + assert!(app.handle(Message::SignupRegister).is_empty()); + assert!(app.status_error); + assert!(app.handle(Message::SignupRecall).is_empty()); + assert!(app.busy.is_none()); + } + + #[test] + fn signing_out_of_one_account_moves_to_the_other() { + let (mut app, alice, bob) = two_accounts(); + app.busy = None; + let alice_dir = app.dir.clone(); + app.handle(Message::ResetPressed); + let ops = app.handle(Message::ResetConfirmed); + assert!(matches!(ops.as_slice(), [PendingOp::Snapshot { .. }])); + assert!(!alice_dir.exists()); + assert_eq!(app.id, bob); + assert_eq!(app.page, Page::Mail); + assert!(app.accounts.iter().all(|entry| entry.id != alice)); + assert!(app.dir.join("carrier.key").exists()); + } + /// Results clear the busy flag instead of deadlocking: this is the /// regression test for the guard bug the Iced version shipped with. #[test] @@ -1029,6 +1805,482 @@ mod tests { assert_eq!(app.busy.as_deref(), Some("fetching")); } + /// Off by default — a fetch deletes what it takes — and the Settings + /// switch is a plain toggle, not busy-guarded like a network action. + #[test] + fn keep_mail_defaults_off_and_toggles() { + let mut app = app(); + assert!(!app.keep_mail); + app.handle(Message::KeepMailChanged(true)); + assert!(app.keep_mail); + app.handle(Message::KeepMailChanged(false)); + assert!(!app.keep_mail); + } + + fn composing(to: &str) -> Compose { + Compose { + to: to.into(), + subject: "hello".into(), + body: "a message".into(), + reply_to: None, + headers: Vec::new(), + } + } + + /// `client::resolve` verifies nothing, so a first contact over a + /// server with no pin seals the message to whatever answered. Strict + /// mode stops exactly that case, and keeps the compose so the text + /// the user is trying to send survives the refusal. + #[test] + fn strict_pinning_blocks_first_contact_over_an_unpinned_server() { + let mut app = app(); + app.master = Some([0u8; KEY_LEN]); + app.strict_pinning = true; + app.compose = Some(composing("bob@example.org")); + + assert!(app.handle(Message::SendPressed).is_empty()); + assert!(app.compose.is_some(), "the draft must survive the refusal"); + assert!(app.status_error); + let prompt = app.pin_prompt.as_ref().expect("the card must be armed"); + assert_eq!(prompt.addr.short(), "bob@example.org"); + assert!(prompt.offered.is_none()); + + // A pin is all the gate wants: `connect` rejects a mismatch + // whatever it was asked for, so the lookup is now trustworthy. + app.store + .pin_server("example.org", 1961, &[7u8; KEY_LEN]) + .unwrap(); + let ops = app.handle(Message::SendPressed); + assert!(matches!(ops.as_slice(), [PendingOp::Send { .. }])); + assert!(app.compose.is_none()); + } + + /// The gate only bites where a key would have to be learned: an + /// address that carries one, a contact already on file, and RNS — + /// where the destination hash is itself the pin — all go straight out. + #[test] + fn strict_pinning_lets_carried_keys_contacts_and_rns_through() { + let mut app = app(); + app.master = Some([0u8; KEY_LEN]); + app.strict_pinning = true; + let key = [3u8; KEY_LEN]; + + let carried = fumi_core::crypto::b32(&key); + app.compose = Some(composing(&format!("smol://bob@example.org/{carried}"))); + assert!(matches!( + app.handle(Message::SendPressed).as_slice(), + [PendingOp::Send { .. }] + )); + + app.store + .save_contact("carol@example.org", &key, false) + .unwrap(); + app.compose = Some(composing("carol@example.org")); + assert!(matches!( + app.handle(Message::SendPressed).as_slice(), + [PendingOp::Send { .. }] + )); + + let hash = "8f2c1d0a7b6e5f4c3d2a1b0e9f8c7d6a"; + app.compose = Some(composing(&format!("smol+rns://dave@{hash}"))); + assert!( + matches!( + app.handle(Message::SendPressed).as_slice(), + [PendingOp::Send { .. }] + ), + "rns has nothing to pin, so the gate must not strand it" + ); + } + + #[test] + fn strict_pinning_off_sends_over_an_unpinned_server() { + let mut app = app(); + app.master = Some([0u8; KEY_LEN]); + app.handle(Message::StrictPinningChanged(false)); + app.compose = Some(composing("bob@example.org")); + assert!(matches!( + app.handle(Message::SendPressed).as_slice(), + [PendingOp::Send { .. }] + )); + } + + /// The card's two presses: fetch, then pin and send in one go. The + /// offer must land in `pin_prompt` and leave signup's own slot alone, + /// and the pin must be written before the send is dispatched — that + /// ordering is what keeps the re-entry from looping. + #[test] + fn the_pin_card_fetches_then_pins_and_sends() { + let mut app = app(); + app.master = Some([0u8; KEY_LEN]); + app.strict_pinning = true; + app.compose = Some(composing("bob@example.org")); + app.handle(Message::SendPressed); + + let ops = app.handle(Message::PinServerAction); + assert!(matches!(ops.as_slice(), [PendingOp::LearnKey { .. }])); + + let addr = Address::parse("bob@example.org").unwrap(); + let key = [5u8; KEY_LEN]; + app.handle_result(OpResult::PinOffered(Ok(Some((addr, key))))); + assert!(app.pin_offer.is_none(), "signup's slot must stay empty"); + assert_eq!(app.pin_prompt.as_ref().unwrap().offered, Some(key)); + + let ops = app.handle(Message::PinServerAction); + assert!(matches!(ops.as_slice(), [PendingOp::Send { .. }])); + assert_eq!( + app.store.server_pin("example.org", 1961).unwrap(), + Some(key) + ); + assert!(app.pin_prompt.is_none()); + assert!(app.compose.is_none()); + } + + /// A pin that appeared in the meantime retires the prompt without + /// touching signup, which shares the result variant. + #[test] + fn an_already_pinned_server_retires_the_prompt() { + let mut app = app(); + app.pin_prompt = Some(PinPrompt { + addr: Address::parse("bob@example.org").unwrap(), + offered: None, + }); + app.handle_result(OpResult::PinOffered(Ok(None))); + assert!(app.pin_prompt.is_none()); + assert!(!app.signup.key_trusted); + + app.handle_result(OpResult::PinOffered(Ok(None))); + assert!(app.signup.key_trusted, "an unarmed offer is signup's"); + } + + /// `save_contact` is an upsert, so a pasted address carrying a + /// different key would quietly displace a known-good one and skip + /// fumi's own rotation-chain check. It has to be confirmed. + #[test] + fn a_changed_smol_key_asks_before_replacing_a_contact() { + let mut app = app(); + app.master = Some([0u8; KEY_LEN]); + let known = [1u8; KEY_LEN]; + let swapped = [2u8; KEY_LEN]; + app.store + .save_contact("bob@example.org", &known, true) + .unwrap(); + let uri = format!( + "smol://bob@example.org/{}", + fumi_core::crypto::b32(&swapped) + ); + + app.compose = Some(composing(&uri)); + assert!(app.handle(Message::SendPressed).is_empty()); + assert!(matches!( + app.dialog, + Some(Dialog::KeyChange { + resume: KeyChangeResume::Send, + .. + }) + )); + + // Cancelling leaves both the draft and the stored key alone, and + // pressing Send again asks the same question. + app.handle(Message::KeyChangeCancelled); + assert!(app.dialog.is_none()); + assert!(app.compose.is_some()); + assert_eq!( + app.store.contact("bob@example.org").unwrap().unwrap().0, + known + ); + assert!(app.handle(Message::SendPressed).is_empty()); + + let ops = app.handle(Message::KeyChangeConfirmed); + assert!(matches!(ops.as_slice(), [PendingOp::Send { .. }])); + assert_eq!( + app.store.contact("bob@example.org").unwrap().unwrap().0, + swapped + ); + assert!(app.compose.is_none()); + + // The same address carrying the key already on file is not a + // change, so it goes straight out. + app.compose = Some(composing(&uri)); + assert!(matches!( + app.handle(Message::SendPressed).as_slice(), + [PendingOp::Send { .. }] + )); + } + + #[test] + fn a_changed_smol_key_asks_before_importing_it() { + let mut app = app(); + let known = [1u8; KEY_LEN]; + let swapped = [2u8; KEY_LEN]; + app.store + .save_contact("bob@example.org", &known, true) + .unwrap(); + + app.contact_import = format!( + "smol://bob@example.org/{}", + fumi_core::crypto::b32(&swapped) + ); + assert!(app.handle(Message::ContactImportPressed).is_empty()); + assert!(matches!( + app.dialog, + Some(Dialog::KeyChange { + resume: KeyChangeResume::Import { .. }, + .. + }) + )); + assert!(matches!( + app.handle(Message::KeyChangeConfirmed).as_slice(), + [PendingOp::ImportContact { .. }] + )); + + // An address with no contact on file is not a change either. + app.contact_import = format!("smol://new@example.org/{}", fumi_core::crypto::b32(&known)); + assert!(matches!( + app.handle(Message::ContactImportPressed).as_slice(), + [PendingOp::ImportContact { .. }] + )); + } + + /// Off by default — this one is opt-in — and a plain toggle, not + /// busy-guarded like a network action. + #[test] + fn strict_pinning_defaults_off_and_toggles() { + let mut app = app(); + assert!(!app.strict_pinning); + app.busy = Some("fetching".into()); + app.handle(Message::StrictPinningChanged(true)); + assert!(app.strict_pinning); + app.handle(Message::StrictPinningChanged(false)); + assert!(!app.strict_pinning); + } + + /// Settings are the one piece of state a restart used to forget, + /// which would have let a security toggle lapse on every launch. + #[test] + fn settings_survive_a_reboot() { + let dir = tempfile::tempdir().unwrap().keep(); + let (mut app, _) = Carrier::boot(dir.clone()); + app.handle(Message::StrictPinningChanged(true)); + app.handle(Message::KeepMailChanged(true)); + app.handle(Message::TimeoutChanged("90".into())); + assert!(app.dir.join("settings.txt").exists()); + + let (rebooted, _) = Carrier::boot(dir); + assert!(rebooted.strict_pinning); + assert!(rebooted.keep_mail); + assert_eq!(rebooted.timeout, 90); + assert_eq!(rebooted.timeout_text, "90"); + } + + #[test] + fn secret_reveal_toggles() { + let mut app = app(); + assert!(!app.secret_revealed); + app.handle(Message::SecretRevealToggled); + assert!(app.secret_revealed); + app.handle(Message::SecretRevealToggled); + assert!(!app.secret_revealed); + } + + /// Export/Import now go through a native file dialog rather than a + /// paste box, so the model only ever sees the chosen path/text — + /// an empty import (e.g. an empty file) is a no-op, like before. + #[test] + fn export_and_import_dispatch_on_the_chosen_path() { + let mut app = app(); + let path = std::path::PathBuf::from("/tmp/wherever.gsmol"); + let ops = app.handle(Message::ExportBackupTo(path.clone())); + assert!(matches!(ops.as_slice(), [PendingOp::Export { path: p }] if *p == path)); + + assert!(app + .handle(Message::ImportBackupFrom(" ".into())) + .is_empty()); + let ops = app.handle(Message::ImportBackupFrom("some backup text".into())); + assert!(matches!(ops.as_slice(), [PendingOp::ImportBackup { .. }])); + } + + /// A factory reset asks first, then erases every file in the config + /// directory and returns the model to onboarding, as if the app had + /// never run. + #[test] + fn factory_reset_erases_the_files_and_returns_to_onboarding() { + let dir = tempfile::tempdir().unwrap().keep(); + let (mut app, _) = Carrier::boot(dir); + let account = app.dir.clone(); + let master = ops::new_master(); + ops::save_key(&account.join("carrier.key"), &master).unwrap(); + app.master = Some(master); + std::fs::write(account.join("read.txt"), "ab").unwrap(); + std::fs::write(account.join("drafts.txt"), "draft2 id 1 -\n\n\n\n").unwrap(); + app.signup.host = "typed-before-the-reset.example".into(); + app.signup.user = "alice".into(); + app.handle(Message::StrictPinningChanged(true)); + + // The button is busy-guarded like every other action. + app.busy = Some("fetching".into()); + app.handle(Message::ResetPressed); + assert!(app.dialog.is_none()); + + app.busy = None; + app.handle(Message::ResetPressed); + assert!(matches!(app.dialog, Some(Dialog::Reset))); + + app.handle(Message::ResetConfirmed); + assert!(app.dialog.is_none()); + assert_eq!(app.page, Page::Onboard); + assert_eq!(app.onboard.mode, OnboardMode::Start); + assert!(app.master.is_none()); + assert!(app.snapshot.is_none()); + assert!(app.drafts.is_empty()); + // The fields themselves, not just the model, must come back + // clean — form_fresh tells the view to push the blank state + // into the entries instead of leaving stale typed text on them. + assert!(app.signup.host.is_empty()); + assert!(app.signup.user.is_empty()); + assert!(app.form_fresh.get()); + for name in ["carrier.key", "read.txt", "drafts.txt", "settings.txt"] { + assert!(!account.join(name).exists(), "{name} survived the reset"); + } + // The last account's folder goes too; boot starts a fresh one. + assert!(!account.exists()); + assert_ne!(app.dir, account); + // Preferences go with everything else, so the rebooted model is + // back to its defaults rather than the logged-out user's. + assert!(!app.strict_pinning); + assert!(app.dir.join("carrier.db").exists()); + assert!(app.store.account().unwrap().is_none()); + } + + /// Backing out of a freshly created, not-yet-registered identity must + /// discard it — otherwise a later Create can silently overwrite it out + /// from under an in-flight or already-committed registration. + #[test] + fn onboard_back_from_created_discards_the_key() { + let dir = tempfile::tempdir().unwrap().keep(); + let (mut app, _) = Carrier::boot(dir.clone()); + app.handle(Message::OnboardCreate); + assert!(app.master.is_some()); + assert!(app.dir.join("carrier.key").exists()); + + app.handle(Message::OnboardBack); + assert!(app.master.is_none()); + assert!(!app.dir.join("carrier.key").exists()); + assert_eq!(app.page, Page::Onboard); + assert_eq!(app.onboard.mode, OnboardMode::Start); + } + + /// Restore mode writes no key until the seed is actually submitted, so + /// backing out of it has nothing to discard — just the typed seed. + #[test] + fn onboard_back_from_restore_only_clears_the_typed_seed() { + let mut app = app(); + app.handle(Message::OnboardRestore); + app.handle(Message::OnboardSeedChanged("not yet submitted".into())); + app.handle(Message::OnboardBack); + assert!(app.master.is_none()); + assert!(app.onboard.seed.is_empty()); + assert_eq!(app.onboard.mode, OnboardMode::Start); + } + + /// Start Over on the signup page's server step is the same discard, + /// reachable after onboarding has already handed off to Page::Signup. + #[test] + fn signup_start_over_discards_the_key() { + let dir = tempfile::tempdir().unwrap().keep(); + let (mut app, _) = Carrier::boot(dir.clone()); + app.handle(Message::OnboardCreate); + app.handle(Message::OnboardSeedSaved); + assert_eq!(app.page, Page::Signup); + app.signup.host = "example.org".into(); + + app.handle(Message::SignupStartOver); + assert!(app.master.is_none()); + assert!(!app.dir.join("carrier.key").exists()); + assert_eq!(app.page, Page::Onboard); + assert!(app.signup.host.is_empty()); + } + + /// Register and Restore are long-running, so Back (and a second click) + /// must be locked out for their whole in-flight window, the same way + /// FetchPressed already locks out everything else. + #[test] + fn signup_register_and_recall_engage_the_busy_guard() { + let mut app = app(); + app.master = Some([0u8; KEY_LEN]); + app.page = Page::Signup; + app.signup.user = "alice".into(); + app.signup.host = "example.org".into(); + + let ops = app.handle(Message::SignupRegister); + assert_eq!(app.busy.as_deref(), Some("registering")); + assert!(matches!(ops.as_slice(), [PendingOp::Register { .. }])); + assert!(app.handle(Message::SignupStartOver).is_empty()); + assert_eq!(app.page, Page::Signup); + + app.busy = None; + let ops = app.handle(Message::SignupRecall); + assert_eq!(app.busy.as_deref(), Some("restoring")); + assert!(matches!(ops.as_slice(), [PendingOp::Restore { .. }])); + } + + /// A successful Register/Restore must leave the signup page, or a + /// lingering Back there could still race a fresh identity into + /// existence against an address the store already considers bound. + #[test] + fn generic_success_on_the_signup_page_moves_on_to_mail() { + let mut app = app(); + app.page = Page::Signup; + app.busy = Some("registering".into()); + app.handle_result(OpResult::Generic(Ok("registered".into()))); + assert_eq!(app.page, Page::Mail); + } + + /// The server step's one button fetches a key when none is on + /// screen yet, then pins it and advances once one is. + #[test] + fn signup_key_action_fetches_then_pins_and_advances() { + let mut app = app(); + app.signup.host = "example.org".into(); + + let ops = app.handle(Message::SignupKeyAction); + assert!(matches!(ops.as_slice(), [PendingOp::LearnKey { .. }])); + assert_eq!(app.signup.step, SignupStep::Server); + + let addr = Address::parse("x@example.org").unwrap(); + app.pin_offer = Some((addr, [0u8; KEY_LEN])); + let ops = app.handle(Message::SignupKeyAction); + assert!(matches!(ops.as_slice(), [PendingOp::Pin { .. }])); + assert!(app.pin_offer.is_none()); + assert_eq!(app.signup.step, SignupStep::Account); + } + + /// An already-trusted host (pinned in an earlier session) needs no + /// key to show — Continue just advances with no background op. + #[test] + fn signup_key_action_advances_without_a_pin_when_already_trusted() { + let mut app = app(); + app.signup.host = "example.org".into(); + app.signup.key_trusted = true; + + let ops = app.handle(Message::SignupKeyAction); + assert!(ops.is_empty()); + assert_eq!(app.signup.step, SignupStep::Account); + } + + /// Editing the host after a key was fetched (or already trusted) + /// invalidates it: there is only ever one key pending trust. + #[test] + fn editing_the_host_resets_a_fetched_or_trusted_key() { + let mut app = app(); + let addr = Address::parse("x@example.org").unwrap(); + app.pin_offer = Some((addr, [0u8; KEY_LEN])); + app.signup.key_trusted = true; + + app.handle(Message::SignupHostChanged("example.net".into())); + assert!(app.pin_offer.is_none()); + assert!(!app.signup.key_trusted); + } + fn opened() -> OpenedMsg { OpenedMsg { id: "ab".repeat(32), @@ -1038,11 +2290,11 @@ mod tests { body: String::new(), sender: String::new(), reply_to: None, + headers: Vec::new(), kept: false, } } - #[test] #[test] fn contact_selection_and_message_selection_supersede_each_other() { let mut app = app(); @@ -1090,6 +2342,7 @@ mod tests { subject: String::new(), body: String::new(), reply_to: None, + headers: Vec::new(), }); app.busy = Some("fetching".into()); app.handle(Message::ComposeBodyChanged("typing while busy".into())); @@ -1145,6 +2398,135 @@ mod tests { assert!(app.drafts.is_empty()); } + #[test] + fn header_rows_pass_the_busy_guard_and_edit_the_compose() { + let mut app = app(); + app.handle(Message::ComposePressed); + app.busy = Some("fetching".into()); + app.handle(Message::ComposeHeaderAdded); + app.handle(Message::ComposeHeaderAdded); + app.handle(Message::ComposeHeaderChanged(0, "Urgency: high".into())); + app.handle(Message::ComposeHeaderRemoved(1)); + assert_eq!( + app.compose.as_ref().expect("compose open").headers, + ["Urgency: high"] + ); + // An index that no longer exists is ignored, not a panic. + app.handle(Message::ComposeHeaderChanged(5, "no".into())); + assert_eq!(app.compose.as_ref().unwrap().headers, ["Urgency: high"]); + } + + #[test] + fn an_invalid_header_blocks_the_send() { + let mut app = app(); + app.handle(Message::ComposePressed); + app.handle(Message::ComposeToChanged("bob@localhost".into())); + + // A reserved key shadows the client's own field, so it is rejected. + app.handle(Message::ComposeHeaderAdded); + app.handle(Message::ComposeHeaderChanged(0, "Subject: shadow".into())); + assert!(app.handle(Message::SendPressed).is_empty()); + assert!(app.compose.is_some()); + assert!(app.status_error); + + // Case-insensitive duplicates are rejected too. + app.handle(Message::ComposeHeaderChanged(0, "Urgency: high".into())); + app.handle(Message::ComposeHeaderAdded); + app.handle(Message::ComposeHeaderChanged(1, "urgency: low".into())); + assert!(app.handle(Message::SendPressed).is_empty()); + assert!(app.status_error); + + // Removing the duplicate lets the send go through with the pair; + // the earlier error note stays until the op result replaces it. + app.handle(Message::ComposeHeaderRemoved(1)); + let ops = app.handle(Message::SendPressed); + assert_eq!(ops.len(), 1); + assert!(app.compose.is_none()); + assert!(matches!( + &ops[0], + PendingOp::Send { headers, .. } + if headers == &[("Urgency".to_string(), "high".to_string())] + )); + } + + #[test] + fn replying_to_custom_fields_asks_what_to_carry() { + let mut app = app(); + app.open = Some(( + Folder::Inbox, + OpenedMsg { + subject: "hello".into(), + headers: vec![ + ("priority".to_string(), "high".to_string()), + ("in-reply-to".to_string(), "cd".repeat(32)), + ], + ..opened() + }, + )); + + // The ask: a dialog, not a compose yet, and cancelling aborts. + app.handle(Message::ReplyPressed); + assert!(app.compose.is_none()); + assert!(matches!(app.dialog, Some(Dialog::Reply { .. }))); + app.handle(Message::ReplyCancelled); + assert!(app.dialog.is_none()); + assert!(app.compose.is_none()); + + // Either answer opens the same reply; the fields follow the choice. + app.handle(Message::ReplyPressed); + app.handle(Message::ReplyConfirmed(false)); + let compose = app.compose.as_ref().expect("reply open"); + assert_eq!(compose.subject, "Re: hello"); + assert!(compose.headers.is_empty()); + assert_eq!(compose.reply_to.as_deref(), Some("ab".repeat(32).as_str())); + + app.compose = None; + app.handle(Message::ReplyPressed); + app.handle(Message::ReplyConfirmed(true)); + let compose = app.compose.as_ref().expect("reply open"); + // The sender's field arrives; the threading id does not — the + // reply carries its own. + assert_eq!(compose.headers, ["priority: high"]); + } + + #[test] + fn a_thread_only_mail_replies_straight_through() { + let mut app = app(); + app.open = Some(( + Folder::Inbox, + OpenedMsg { + subject: "hello".into(), + headers: vec![("in-reply-to".to_string(), "cd".repeat(32))], + ..opened() + }, + )); + app.handle(Message::ReplyPressed); + assert!(app.dialog.is_none()); + assert!(app.compose.is_some()); + assert!(app.compose.as_ref().unwrap().headers.is_empty()); + } + + #[test] + fn headers_survive_a_stash_and_reopen() { + let mut app = app(); + app.handle(Message::ComposePressed); + app.handle(Message::ComposeToChanged("bob@localhost".into())); + app.handle(Message::ComposeHeaderAdded); + app.handle(Message::ComposeHeaderChanged(0, "Urgency: high".into())); + app.handle(Message::ComposeHeaderAdded); + app.handle(Message::ComposeHeaderChanged(1, "not valid yet".into())); + // A contact trip stashes without starting a refresh, so the + // reopen below is not swallowed by the busy guard. + app.handle(Message::ContactSelected("bob@localhost".into())); + assert_eq!(app.drafts.len(), 1); + let id = app.drafts[0].id.clone(); + app.handle(Message::MessageSelected(Folder::Drafts, id)); + let compose = app.compose.as_ref().expect("draft reopened"); + // Rows return exactly as typed, valid or not: validation is a + // send-time concern, not a stash-time one. + assert_eq!(compose.headers, ["Urgency: high", "not valid yet"]); + } + #[test] fn fetch_tick_lists_mail_as_it_lands() { use fumi_core::message::{build_frontmatter, message_id, seal}; diff --git a/src/demo.rs b/src/demo.rs index f93e7da..dc038f4 100644 --- a/src/demo.rs +++ b/src/demo.rs @@ -1,7 +1,8 @@ //! Sample data for layout work, compiled into dev builds only. The dev //! build uses its own `carrier-demo` profile directory; seeding runs once -//! when it has no key yet, so read marks survive across refinement +//! when it has no accounts yet, so read marks survive across refinement //! sessions and the release profile's real account is never touched. +//! Two accounts are planted so the account switcher has something to show. use std::path::Path; @@ -22,15 +23,58 @@ fn identity(tag: u8) -> Identity { Identity::from_seed([tag; KEY_LEN]) } -pub fn seed(dir: &Path) { - if dir.join("carrier.key").exists() { +pub fn seed(root: &Path) { + if !crate::ops::list_accounts(root).is_empty() { return; } - if let Err(e) = plant(dir) { + let planted = (|| { + for id in ["demo", "demo2"] { + let dir = crate::ops::account_dir(root, id); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + } + plant(&crate::ops::account_dir(root, "demo"))?; + plant_second(&crate::ops::account_dir(root, "demo2"))?; + crate::ops::save_active(root, "demo") + })(); + if let Err(e) = planted { eprintln!("demo seed failed: {e}"); } } +/// A sparse second account with its own master, so switching shows a +/// visibly different inbox. +fn plant_second(dir: &Path) -> Result<(), String> { + let master: [u8; KEY_LEN] = core::array::from_fn(|i| i as u8 + 101); + crate::ops::save_key(&dir.join("carrier.key"), &master)?; + let store = Store::open(&dir.join("carrier.db")).map_err(|e| e.to_string())?; + let me = Account::new(master, 0).map_err(|e| e.to_string())?; + let addr = Address::parse("demo2@carrier.local").map_err(|e| e.to_string())?; + store.set_account(&addr).map_err(|e| e.to_string())?; + store + .pin_server(&addr.host, addr.port, &identity(42).pk()) + .map_err(|e| e.to_string())?; + let sender = identity(11); + let uri = Address::parse("alice@example.org") + .unwrap() + .uri(&sender.pk()); + let text = build_frontmatter( + &[("Subject", "your second address works"), ("Reply-To", &uri)], + "This inbox belongs to the second demo account.", + ); + let envelope = seal(&sender, &me.me().pk(), text.as_bytes(), now() - 3600, true) + .map_err(|e| e.to_string())?; + store + .store_inbox( + &message_id(&envelope), + &envelope, + now() - 3600, + false, + false, + ) + .map_err(|e| e.to_string())?; + Ok(()) +} + fn plant(dir: &Path) -> Result<(), String> { let master = demo_master(); crate::ops::save_key(&dir.join("carrier.key"), &master)?; @@ -39,6 +83,11 @@ fn plant(dir: &Path) -> Result<(), String> { let me = Account::new(master, 0).map_err(|e| e.to_string())?; let addr = Address::parse("demo@carrier.local").map_err(|e| e.to_string())?; store.set_account(&addr).map_err(|e| e.to_string())?; + // Our own server is pinned, the contacts' server is not: the two + // states the trust lines and the pin prompts distinguish. + store + .pin_server(&addr.host, addr.port, &identity(42).pk()) + .map_err(|e| e.to_string())?; let pk = me.me().pk(); let mut read_ids: Vec = Vec::new(); @@ -158,6 +207,30 @@ fn plant(dir: &Path) -> Result<(), String> { true, )?; + // one inbox mail with the sender's own frontmatter fields, so the + // detail view has a custom header block to show + { + let sender = identity(11); + let uri = Address::parse("alice@example.org") + .unwrap() + .uri(&sender.pk()); + let text = build_frontmatter( + &[ + ("Subject", "canary rollout report"), + ("Reply-To", &uri), + ("Priority", "high"), + ("X-Stage", "canary at 5%"), + ], + "The custom fields on this one are the sender's own — carrier shows them between the meta line and the body.", + ); + let envelope = seal(&sender, &pk, text.as_bytes(), now() - 12 * 3600, true) + .map_err(|e| e.to_string())?; + let id = message_id(&envelope); + store + .store_inbox(&id, &envelope, now() - 12 * 3600, false, false) + .map_err(|e| e.to_string())?; + } + // requests: senders not in the contact list deliver( &identity(31), @@ -227,6 +300,7 @@ fn plant(dir: &Path) -> Result<(), String> { to: "grace@example.org".into(), subject: "Re: quarterly infrastructure review".into(), body: "started a reply, will finish it after the review call".into(), + headers: vec!["Urgency: low".into()], reply_to: None, at: now() - 3 * 3600, }], diff --git a/src/i18n.rs b/src/i18n.rs new file mode 100644 index 0000000..bda0fbe --- /dev/null +++ b/src/i18n.rs @@ -0,0 +1,64 @@ +//! A single Fluent bundle, loaded once from `locales/en-US/main.ftl` and +//! baked into the binary via `include_str!`. Every user-facing string in +//! the app is looked up through `t`/`t1`/`t_args` rather than written +//! inline, so copy review and translation both have one place to work +//! from. There is only one locale today; a future one would plug in here +//! without touching a call site. + +use std::sync::OnceLock; + +use fluent_bundle::concurrent::FluentBundle; +use fluent_bundle::{FluentArgs, FluentResource, FluentValue}; + +fn bundle() -> &'static FluentBundle { + static BUNDLE: OnceLock> = OnceLock::new(); + BUNDLE.get_or_init(|| { + let ftl = include_str!("../locales/en-US/main.ftl"); + let resource = + FluentResource::try_new(ftl.to_string()).expect("main.ftl must parse as Fluent"); + let locale = "en-US".parse().expect("\"en-US\" is a valid language tag"); + let mut bundle = FluentBundle::new_concurrent(vec![locale]); + // Bidi isolation marks are invisible but real characters; with a + // single left-to-right locale they only cost correctness — + // copy/paste, clipboard round-trips and plain string equality all + // pick them up — for no visible benefit. + bundle.set_use_isolating(false); + bundle + .add_resource(resource) + .expect("main.ftl must not redefine a message id"); + bundle + }) +} + +/// Looks up a message with no variables. +pub fn t(id: &str) -> String { + t_args(id, None) +} + +/// Looks up a message with one variable — the common case, since most +/// interpolated strings here carry a single value. +pub fn t1(id: &str, key: &'static str, value: impl Into>) -> String { + let mut args = FluentArgs::new(); + args.set(key, value); + t_args(id, Some(&args)) +} + +/// Looks up a message against a caller-built argument set, for the rare +/// string that interpolates more than one value. +pub fn t_args(id: &str, args: Option<&FluentArgs>) -> String { + let bundle = bundle(); + // A missing id or a value-less term is a copy bug, not a runtime + // condition to hide: surface it in the string itself rather than + // silently falling back to English prose that isn't there to fall + // back to (there's only the one locale). + let Some(message) = bundle.get_message(id) else { + return format!("???{id}???"); + }; + let Some(pattern) = message.value() else { + return format!("???{id}???"); + }; + let mut errors = Vec::new(); + bundle + .format_pattern(pattern, args, &mut errors) + .into_owned() +} diff --git a/src/main.rs b/src/main.rs index a2c2c78..962bdc6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,17 @@ //! carrier — a minimalist smolmail client built on fumi-core, with a -//! Relm4 UI. State lives in the config directory: `carrier.key` (the -//! master, 0600), `carrier.db` (fumi-core's sealed store) and `read.txt` -//! (read marks, carrier's own sidecar). +//! Relm4 UI. Each account lives in its own `accounts//` folder under +//! the config directory: `carrier.key` (the master, 0600), `carrier.db` +//! (fumi-core's sealed store) and carrier's own sidecars (read marks, +//! drafts, settings). `active.txt` names the account the app opens. + +// No console window when the Windows release build is double-clicked. +// Debug builds keep it for eprintln output. +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] mod app; #[cfg(debug_assertions)] mod demo; +mod i18n; mod ops; mod view; @@ -17,6 +23,10 @@ fn main() { eprintln!("cannot create {}: {e}", dir.display()); std::process::exit(1); } + if let Err(e) = ops::migrate_legacy(&dir) { + eprintln!("cannot move the account into {}: {e}", dir.display()); + std::process::exit(1); + } #[cfg(debug_assertions)] demo::seed(&dir); view::run(dir); @@ -25,9 +35,7 @@ fn main() { fn config_dir() -> PathBuf { let base = match std::env::var("XDG_CONFIG_HOME") { Ok(xdg) if !xdg.is_empty() => PathBuf::from(xdg).join("carrier"), - _ => PathBuf::from(std::env::var("HOME").unwrap_or_default()) - .join(".config") - .join("carrier"), + _ => default_config_root(), }; // Dev builds get their own profile, seeded with sample data in // `demo.rs`, so layout work never touches the real account. @@ -35,3 +43,20 @@ fn config_dir() -> PathBuf { let base = base.with_file_name("carrier-demo"); base } + +// HOME is rarely set on Windows, and when it is missing the Unix +// fallback would resolve .config\carrier against the working +// directory - for an installed copy that's Program Files, which isn't +// writable, so the app would die on startup. Roaming AppData is the +// per-user config location there. +#[cfg(windows)] +fn default_config_root() -> PathBuf { + PathBuf::from(std::env::var("APPDATA").unwrap_or_default()).join("carrier") +} + +#[cfg(not(windows))] +fn default_config_root() -> PathBuf { + PathBuf::from(std::env::var("HOME").unwrap_or_default()) + .join(".config") + .join("carrier") +} diff --git a/src/ops.rs b/src/ops.rs index 2a3a577..103bce0 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -7,12 +7,15 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::AtomicBool; use std::sync::Arc; -use fumi_core::address::{Address, DEFAULT_PORT}; +use fumi_core::address::{trust_label, Address, Scheme}; use fumi_core::client::{FetchOptions, TrustChange}; use fumi_core::crypto::{b32, fingerprint, unb32, KEY_LEN}; use fumi_core::error::Error; +use fumi_core::message::{FRONTMATTER_KEYS, FRONTMATTER_MAX}; use fumi_core::store::Store; -use fumi_core::{account, client, export, store}; +use fumi_core::{account, client, export}; + +use crate::i18n; /// One message in a folder list, already opened for its metadata. #[derive(Debug, Clone)] @@ -36,6 +39,9 @@ pub struct OpenedMsg { pub sender: String, /// The sender's self-certifying address, when the payload carried one. pub reply_to: Option, + /// The frontmatter fields carrier does not already show or act on, + /// in the order the reader's map keeps them (sorted by key). + pub headers: Vec<(String, String)>, pub kept: bool, } @@ -48,13 +54,24 @@ pub struct Contact { pub verified: bool, /// Some(true) accepted, Some(false) blocked, None never decided. pub accepted: Option, + /// The server this address lives on, as the label pins are keyed by. + pub server: String, + /// Whether that server's key is pinned. A key learned over a session + /// with no pin is only as good as whoever answered, which `accepted` + /// stops saying anything about once it is Some. + pub pinned: bool, } #[derive(Debug, Clone)] pub struct Who { pub address: String, + pub host: String, + /// Paired with `host` to build the label pins are keyed by, so the + /// account's own pin can be told apart from a correspondent's. + pub port: u16, pub key: String, pub fingerprint: String, + pub uri: String, pub rotations: u32, } @@ -116,11 +133,13 @@ pub struct Draft { pub body: String, /// The message this draft replies to, as 64 hex characters. pub reply_to: Option, + /// Frontmatter rows as typed — `Key: value` text, parsed at send. + pub headers: Vec, pub at: i64, } -/// A fresh draft id: 8 random bytes as hex, unique within the sidecar. -pub fn draft_id() -> String { +/// A fresh id for a draft or an account folder: 8 random bytes as hex. +pub fn random_id() -> String { use rand_core::RngCore; let mut bytes = [0u8; 8]; rand_core::OsRng.fill_bytes(&mut bytes); @@ -133,6 +152,7 @@ fn line(text: &str) -> String { text.replace('\\', "\\\\") .replace('\n', "\\n") .replace('\r', "\\r") + .replace('\u{1f}', "\\\u{1e}") } fn unline(text: &str) -> String { @@ -143,6 +163,7 @@ fn unline(text: &str) -> String { match chars.next() { Some('n') => out.push('\n'), Some('r') => out.push('\r'), + Some('\u{1e}') => out.push('\u{1f}'), Some(other) => out.push(other), None => out.push('\\'), } @@ -159,11 +180,16 @@ pub fn save_drafts(path: &Path, drafts: &[Draft]) { let mut text = String::new(); for draft in drafts { let reply_to = draft.reply_to.as_deref().unwrap_or("-"); + let headers: Vec = draft.headers.iter().map(|row| line(row)).collect(); use std::fmt::Write; - let _ = writeln!(text, "draft {} {} {}", draft.id, draft.at, reply_to); + let _ = writeln!(text, "draft2 {} {} {}", draft.id, draft.at, reply_to); let _ = writeln!(text, "{}", line(&draft.to)); let _ = writeln!(text, "{}", line(&draft.subject)); let _ = writeln!(text, "{}", line(&draft.body)); + // Rows joined on a control separator, so any typed text is + // reversible; keys are [A-Za-z0-9-] but values can hold colons, + // semicolons — anything but a newline, which line() escapes. + let _ = writeln!(text, "{}", headers.join("\u{1f}")); } let _ = std::fs::write(path, text); } @@ -174,12 +200,12 @@ pub fn load_drafts(path: &Path) -> Vec { let text = std::fs::read_to_string(path).unwrap_or_default(); let lines: Vec<&str> = text.lines().collect(); let mut drafts = Vec::new(); - for record in lines.chunks(4) { - let [header, to, subject, body] = record else { - break; - }; + let mut index = 0; + while index + 4 <= lines.len() { + let header = lines[index]; + let (to, subject, body) = (lines[index + 1], lines[index + 2], lines[index + 3]); let mut parts = header.split_whitespace(); - let (Some("draft"), Some(id), Some(at), reply_to) = + let (kind, Some(id), Some(at), reply_to) = (parts.next(), parts.next(), parts.next(), parts.next()) else { break; @@ -188,6 +214,22 @@ pub fn load_drafts(path: &Path) -> Vec { break; }; let id = id.to_string(); + index += 4; + // draft2 carries a fifth line of header rows; the old draft + // records stop at four and the next line is another record. + let headers = if kind == Some("draft2") && index < lines.len() { + index += 1; + let raw = lines[index - 1]; + if raw.is_empty() { + Vec::new() + } else { + raw.split('\u{1f}').map(unline).collect() + } + } else if kind == Some("draft") { + Vec::new() + } else { + break; + }; drafts.push(Draft { id, to: unline(to), @@ -197,16 +239,98 @@ pub fn load_drafts(path: &Path) -> Vec { None | Some("-") => None, Some(other) => Some(other.to_string()), }, + headers, at, }); } drafts } +/// Carrier's own preferences, beside the store as one `key value` line +/// each: nothing here is secret, and plaintext keeps a hand edit honest. +/// Unknown keys and unreadable values are skipped, so a file from another +/// build — or a torn write — costs only the lines it broke. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Settings { + pub keep_mail: bool, + pub timeout: u64, + /// Refuse to learn a recipient's key from a server with no pin. + pub strict_pinning: bool, +} + +impl Default for Settings { + fn default() -> Settings { + Settings { + keep_mail: false, + timeout: 30, + strict_pinning: false, + } + } +} + +fn flag(value: &str) -> Option { + match value.trim() { + "1" => Some(true), + "0" => Some(false), + _ => None, + } +} + +pub fn load_settings(path: &Path) -> Settings { + let mut settings = Settings::default(); + let text = std::fs::read_to_string(path).unwrap_or_default(); + for row in text.lines() { + let Some((key, value)) = row.split_once(' ') else { + continue; + }; + match key.trim() { + "keep_mail" => settings.keep_mail = flag(value).unwrap_or(settings.keep_mail), + "strict_pinning" => { + settings.strict_pinning = flag(value).unwrap_or(settings.strict_pinning) + } + // Out of the spin row's range is as good as unreadable: the + // widget would clamp it and write the clamp straight back. + "timeout" => { + settings.timeout = value + .trim() + .parse() + .ok() + .filter(|seconds| (1..=600).contains(seconds)) + .unwrap_or(settings.timeout) + } + _ => {} + } + } + settings +} + +pub fn save_settings(path: &Path, settings: &Settings) { + let text = format!( + "keep_mail {}\nstrict_pinning {}\ntimeout {}\n", + u8::from(settings.keep_mail), + u8::from(settings.strict_pinning), + settings.timeout, + ); + let _ = std::fs::write(path, text); +} + fn explain(e: Error) -> String { e.to_string() } +/// `{ $path }: { $reason }` — the one shared shape every local file error +/// here takes; `reason` is whatever the OS says, which this catalogue +/// cannot translate, so only the separator around it is localized. +fn file_error_args( + path: &Path, + reason: &dyn std::fmt::Display, +) -> fluent_bundle::FluentArgs<'static> { + let mut args = fluent_bundle::FluentArgs::new(); + args.set("path", path.display().to_string()); + args.set("reason", reason.to_string()); + args +} + pub fn new_master() -> [u8; KEY_LEN] { use rand_core::RngCore; let mut master = [0u8; KEY_LEN]; @@ -224,23 +348,26 @@ pub fn parse_seed(text: &str) -> Result<[u8; KEY_LEN], String> { let bytes = if text.len() == 64 && text.chars().all(|c| c.is_ascii_hexdigit()) { let mut raw = Vec::with_capacity(32); for pair in text.as_bytes().chunks(2) { - let hi = (pair[0] as char).to_digit(16).ok_or("bad hex")?; - let lo = (pair[1] as char).to_digit(16).ok_or("bad hex")?; + let hi = (pair[0] as char) + .to_digit(16) + .ok_or_else(|| i18n::t("seed-bad-hex"))?; + let lo = (pair[1] as char) + .to_digit(16) + .ok_or_else(|| i18n::t("seed-bad-hex"))?; raw.push((hi * 16 + lo) as u8); } raw } else { unb32(text).map_err(|e| explain(e))? }; - bytes - .try_into() - .map_err(|_| "a seed is 32 bytes".to_string()) + bytes.try_into().map_err(|_| i18n::t("seed-wrong-length")) } pub fn load_key(path: &Path) -> Result<[u8; KEY_LEN], String> { - let raw = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; + let raw = std::fs::read(path) + .map_err(|e| i18n::t_args("file-error", Some(&file_error_args(path, &e))))?; raw.try_into() - .map_err(|_| format!("{}: not a 32-byte master", path.display())) + .map_err(|_| i18n::t1("key-file-wrong-length", "path", path.display().to_string())) } pub fn save_key(path: &Path, master: &[u8; KEY_LEN]) -> Result<(), String> { @@ -262,6 +389,143 @@ pub fn save_key(path: &Path, master: &[u8; KEY_LEN]) -> Result<(), String> { err } +/// Removes a not-yet-registered master key when onboarding is cancelled. +/// Idempotent, like `factory_reset`: a missing file is fine. +pub fn delete_key(path: &Path) -> Result<(), String> { + match std::fs::remove_file(path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(i18n::t_args("file-error", Some(&file_error_args(path, &e)))), + } +} + +/// Removes every file an account owns: the store, the key and the sidecars. +/// A missing file is fine — reset is idempotent — but a file that cannot +/// be removed is reported, so a reset that did not take is never silent. +/// The caller must close the store first: Windows refuses to remove a +/// file a live connection holds. +pub fn factory_reset(dir: &Path) -> Result<(), String> { + for name in ACCOUNT_FILES { + let path = dir.join(name); + if let Err(e) = std::fs::remove_file(&path) { + if e.kind() != std::io::ErrorKind::NotFound { + return Err(i18n::t_args( + "file-error", + Some(&file_error_args(&path, &e)), + )); + } + } + } + Ok(()) +} + +/// The files one account owns. The WAL pair is listed so a migration never +/// strands commits a crash left uncheckpointed. +const ACCOUNT_FILES: [&str; 7] = [ + "carrier.db", + "carrier.db-wal", + "carrier.db-shm", + "carrier.key", + "read.txt", + "drafts.txt", + "settings.txt", +]; + +pub fn accounts_dir(root: &Path) -> PathBuf { + root.join("accounts") +} + +pub fn account_dir(root: &Path, id: &str) -> PathBuf { + accounts_dir(root).join(id) +} + +/// Moves a single-account config root into `accounts//` and makes it +/// the active account. Runs before anything opens the files; a root that +/// already has `accounts/`, or holds none of the files, is left alone. +pub fn migrate_legacy(root: &Path) -> Result<(), String> { + if accounts_dir(root).exists() { + return Ok(()); + } + let present: Vec<&str> = ACCOUNT_FILES + .into_iter() + .filter(|name| root.join(name).exists()) + .collect(); + if present.is_empty() { + return Ok(()); + } + let id = random_id(); + let dir = account_dir(root, &id); + std::fs::create_dir_all(&dir) + .map_err(|e| i18n::t_args("file-error", Some(&file_error_args(&dir, &e))))?; + for name in present { + let from = root.join(name); + std::fs::rename(&from, dir.join(name)) + .map_err(|e| i18n::t_args("file-error", Some(&file_error_args(&from, &e))))?; + } + save_active(root, &id) +} + +/// Account folder names, sorted so the switcher's order is stable. +pub fn list_accounts(root: &Path) -> Vec { + let mut ids: Vec = std::fs::read_dir(accounts_dir(root)) + .map(|entries| { + entries + .flatten() + .filter(|entry| entry.path().is_dir()) + .filter_map(|entry| entry.file_name().into_string().ok()) + .collect() + }) + .unwrap_or_default(); + ids.sort(); + ids +} + +/// The active account's id, if `active.txt` names a folder that exists. +pub fn load_active(root: &Path) -> Option { + let id = std::fs::read_to_string(root.join("active.txt")).ok()?; + let id = id.trim().to_string(); + (!id.is_empty() && account_dir(root, &id).is_dir()).then_some(id) +} + +pub fn save_active(root: &Path, id: &str) -> Result<(), String> { + let path = root.join("active.txt"); + std::fs::write(&path, format!("{id}\n")) + .map_err(|e| i18n::t_args("file-error", Some(&file_error_args(&path, &e)))) +} + +/// Creates an empty account folder and returns its id. +pub fn new_account(root: &Path) -> Result { + let id = random_id(); + let dir = account_dir(root, &id); + std::fs::create_dir_all(&dir) + .map_err(|e| i18n::t_args("file-error", Some(&file_error_args(&dir, &e))))?; + Ok(id) +} + +/// Deletes an account's files, then its folder. Same contract as +/// `factory_reset`: the caller must close the account's store first. +pub fn remove_account(root: &Path, id: &str) -> Result<(), String> { + let dir = account_dir(root, id); + factory_reset(&dir)?; + match std::fs::remove_dir(&dir) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(i18n::t_args("file-error", Some(&file_error_args(&dir, &e)))), + } +} + +/// The address an account folder is registered under, read from its own +/// store; None for a folder that isn't registered or can't be opened. +pub fn account_label(dir: &Path) -> Option { + // Opening a missing database would create one. + let path = dir.join("carrier.db"); + if !path.exists() { + return None; + } + let store = Store::open(&path).ok()?; + store.account().ok().flatten().map(|addr| addr.short()) +} + pub fn account(store: &Store, master: &[u8; KEY_LEN]) -> Result { let index = store.rotations().map_err(explain)?; account::Account::new(*master, index).map_err(explain) @@ -271,14 +535,6 @@ pub fn parse_address(text: &str) -> Result { Address::parse(text).map_err(explain) } -/// A base32 public key, the form the operator publishes and pins are shown in. -pub fn parse_key(text: &str) -> Result<[u8; KEY_LEN], String> { - unb32(text.trim()) - .map_err(explain)? - .try_into() - .map_err(|_| "keys are 32 bytes of base32".to_string()) -} - pub fn register( store: &Store, master: &[u8; KEY_LEN], @@ -326,19 +582,6 @@ pub fn pin(store: &Store, addr: &Address, key: &[u8; KEY_LEN]) -> Result<(), Str .map_err(explain) } -/// Splits a stored pin label (`host` or `host:port`) back into its parts. -fn label_parts(label: &str) -> (String, u16) { - match label.rsplit_once(':') { - Some((host, port)) => (host.to_string(), port.parse().unwrap_or(DEFAULT_PORT)), - None => (label.to_string(), DEFAULT_PORT), - } -} - -pub fn unpin(store: &Store, label: &str) -> Result<(), String> { - let (host, port) = label_parts(label); - store.unpin_server(&host, port).map_err(explain) -} - pub fn pins(store: &Store) -> Result, String> { store.pins().map_err(explain) } @@ -348,25 +591,111 @@ pub fn fetch( store: &Store, master: &[u8; KEY_LEN], cancel: Arc, + keep: bool, timeout: u64, ) -> Result { let me = account(store, master)?; let opts = FetchOptions { - keep: false, + keep, reset: false, timeout, dial: None, cancel: Some(&cancel), }; let fetched = client::fetch_with(store, &me, opts).map_err(explain)?; - let mut note = format!("{} fetched, {} stored", fetched.total, fetched.stored); - if !fetched.rejected.is_empty() { - note.push_str(&format!(", {} rejected", fetched.rejected.len())); + let variant = match (!fetched.rejected.is_empty(), fetched.cancelled) { + (true, true) => "rejected-cancelled", + (true, false) => "rejected", + (false, true) => "cancelled", + (false, false) => "plain", + }; + let mut args = fluent_bundle::FluentArgs::new(); + args.set("total", fetched.total as i64); + args.set("stored", fetched.stored as i64); + args.set("rejected", fetched.rejected.len() as i64); + Ok(i18n::t_args( + &format!("fetch-result-note-{variant}"), + Some(&args), + )) +} + +/// Fields fumi itself attaches to every message (sec 5.7, 5.8); a +/// user copy of any of them would shadow the client's own, since the +/// reader keeps the first occurrence of a key. +const RESERVED_HEADERS: [&str; 4] = ["subject", "in-reply-to", "reply-to", "accept"]; + +/// Parses one compose header row as the user typed it — `Key: value`. +/// An empty row is allowed and simply skipped on send; anything else +/// that breaks the frontmatter block (sec 5.5) is rejected, because a +/// single malformed line makes the reader drop every field. +pub fn header_row(text: &str) -> Result, String> { + let text = text.trim(); + if text.is_empty() { + return Ok(None); } - if fetched.cancelled { - note.push_str(" (cancelled)"); + let Some((key, value)) = text.split_once(':') else { + return Err(i18n::t("compose-header-colon-missing")); + }; + let key = key.trim(); + if RESERVED_HEADERS + .iter() + .any(|reserved| key.eq_ignore_ascii_case(reserved)) + { + return Err(i18n::t1( + "compose-header-reserved-key", + "key", + key.to_string(), + )); } - Ok(note) + if key.is_empty() + || key.len() > 64 + || !key + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + { + return Err(i18n::t("compose-header-invalid-key")); + } + if value.contains('\n') || value.contains('\r') { + return Err(i18n::t("compose-header-value-multiline")); + } + Ok(Some((key.to_string(), value.trim().to_string()))) +} + +/// The rules across all rows: keys are case-insensitive and must be +/// unique, and the whole block — fumi's own fields included — has to +/// stay inside the reader's budget (sec 5.5). +pub fn validate_headers(headers: &[(String, String)]) -> Result<(), String> { + let mut seen: std::collections::HashSet = std::collections::HashSet::new(); + for (key, _) in headers { + if !seen.insert(key.to_ascii_lowercase()) { + return Err(i18n::t1("compose-header-duplicate-key", "key", key.clone())); + } + } + let budget: usize = headers + .iter() + .map(|(key, value)| format!("{key}: {value}").len() + 1) + .sum(); + // The client adds Subject, In-Reply-To, a Reply-To URI and possibly an + // Accept token on top of the user's rows; 512 bytes covers them all. + if budget + 512 > FRONTMATTER_MAX { + return Err(i18n::t("compose-headers-too-large")); + } + if headers.len() + 4 > FRONTMATTER_KEYS { + return Err(i18n::t("compose-headers-too-many")); + } + Ok(()) +} + +/// The frontmatter rows a reply could carry over from the message it +/// answers. The reserved fields never make it — `in-reply-to` in +/// particular shows in the detail but belongs to the reply context the +/// client sets itself — so anything left is the sender's own metadata. +pub fn reply_rows(headers: &[(String, String)]) -> Vec { + headers + .iter() + .filter_map(|(key, value)| header_row(&format!("{key}: {value}")).ok().flatten()) + .map(|(key, value)| format!("{key}: {value}")) + .collect() } pub fn send( @@ -376,34 +705,52 @@ pub fn send( subject: Option<&str>, body: &str, reply_to: Option<&str>, + headers: &[(String, String)], timeout: u64, ) -> Result { let addr = parse_address(to)?; let me = account(store, master)?; + let owned: Vec<(&str, &str)> = headers + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())) + .collect(); let draft = client::SendDraft { address: &addr, - text: body.to_string(), + // Trimmed at the send site, before the payload is signed, so the + // signature covers exactly the text the author meant. A compose buffer + // ends with whatever the author last pressed, and a trailing newline + // is not content — but it is content once it has been signed, and + // nothing downstream can remove it without invalidating the + // signature. smolboid, for one, refuses a post whose text carries a + // line break, because a published record is one line of a feed. + text: body.trim().to_string(), subject, reply_to, - headers: &[], + headers: &owned, anonymous: false, no_pad: false, }; let sent = client::send(store, &me, &draft, timeout).map_err(explain)?; - let change = match sent.change { - TrustChange::New { unverified: true } => { - "; new contact learned from an unpinned server (unverified)" - } - TrustChange::New { unverified: false } => "; new contact learned (trust on first use)", - TrustChange::Rotated => "; contact rotated to a new key (chain verified)", - TrustChange::None => "", + let trust = match sent.change { + TrustChange::New { unverified: true } => Some("unverified"), + TrustChange::New { unverified: false } => Some("tofu"), + TrustChange::Rotated => Some("rotated"), + TrustChange::None => None, }; - let mut note = format!("sent to {} ({} bytes)", addr.short(), sent.bytes); - if sent.token_used { - note.push_str(", accept token attached"); - } - note.push_str(change); + let variant = match (trust, sent.token_used) { + (Some(trust), true) => format!("{trust}-token"), + (Some(trust), false) => trust.to_string(), + (None, true) => "token".to_string(), + (None, false) => "plain".to_string(), + }; + let mut args = fluent_bundle::FluentArgs::new(); + args.set("address", addr.short()); + args.set("bytes", sent.bytes as i64); + let mut note = i18n::t_args(&format!("send-result-note-{variant}"), Some(&args)); if let Some(warning) = sent.warning { + // Fumi's own warning text, appended as a second, independent + // clause rather than folded into the catalogue — it isn't ours + // to translate. note.push_str(&format!("; {warning}")); } Ok(note) @@ -455,11 +802,19 @@ pub fn block_contact( } /// Adds a contact from a self-certifying `smol://` address. +/// Saves a key the user has confirmed, verified because it came from a +/// self-certifying address they chose to accept. +pub fn save_contact(store: &Store, address: &str, key: &[u8; KEY_LEN]) -> Result<(), String> { + store.save_contact(address, key, true).map_err(explain) +} + +/// A plain upsert: a key that would displace a known-good one is caught +/// at the app layer, which asks before this runs. pub fn import_contact(store: &Store, uri: &str) -> Result<(String, String), String> { let addr = parse_address(uri)?; let key = addr .identity - .ok_or("import needs a self-certifying smol:// address carrying a key")?; + .ok_or_else(|| i18n::t("contacts-import-needs-key"))?; store .save_contact(&addr.short(), &key, true) .map_err(explain)?; @@ -471,12 +826,31 @@ pub fn contacts(store: &Store) -> Result, String> { .contact_rows() .map_err(explain)? .into_iter() - .map(|(address, identity, verified, accepted)| Contact { - address, - key: b32(&identity), - fingerprint: fingerprint(&identity), - verified, - accepted: accepted.map(|state| state == 1), + .map(|(address, identity, verified, accepted)| { + let (server, pinned) = match Address::parse(&address) { + // On RNS the destination hash in the address is itself + // the pin: there is nothing to pin and nothing to warn + // about. + Ok(addr) if addr.scheme == Scheme::Rns => (addr.host.clone(), true), + Ok(addr) => ( + trust_label(&addr.host, addr.port), + store + .server_pin(&addr.host, addr.port) + .ok() + .flatten() + .is_some(), + ), + Err(_) => (String::new(), false), + }; + Contact { + address, + key: b32(&identity), + fingerprint: fingerprint(&identity), + verified, + accepted: accepted.map(|state| state == 1), + server, + pinned, + } }) .collect()) } @@ -491,16 +865,16 @@ pub fn rotate( Ok((store.rotations().map_err(explain)?, b32(&rotated.new_pk))) } -/// Writes the gsmol backup beside the store and returns it for the clipboard. -pub fn export_backup( - store: &Store, - master: &[u8; KEY_LEN], - dir: &Path, -) -> Result<(PathBuf, String), String> { +/// Writes the gsmol backup to the chosen path. +pub fn export_backup(store: &Store, master: &[u8; KEY_LEN], path: &Path) -> Result { let text = export::export(store, master).map_err(explain)?; - let path = dir.join(format!("carrier-backup-{}.gsmol", store::now())); - std::fs::write(&path, &text).map_err(|e| format!("{}: {e}", path.display()))?; - Ok((path, text)) + std::fs::write(path, &text) + .map_err(|e| i18n::t_args("file-error", Some(&file_error_args(path, &e))))?; + Ok(i18n::t1( + "backup-written-note", + "path", + path.display().to_string(), + )) } pub fn import_backup(store: &Store, master: &[u8; KEY_LEN], text: &str) -> Result { @@ -515,10 +889,10 @@ fn hex32(text: &str) -> Result<[u8; KEY_LEN], String> { .collect::, _>>() .map_err(|e| e.to_string())? } else { - return Err("message ids are 64 hex characters".to_string()); + return Err(i18n::t("mail-message-id-wrong-length")); }; raw.try_into() - .map_err(|_| "message ids are 32 bytes".to_string()) + .map_err(|_| i18n::t("mail-message-id-wrong-bytes")) } /// Lists one folder as rows, marking unread against the local read set. @@ -572,8 +946,19 @@ pub fn open( .map_err(explain)? .into_iter() .find(|m| m.id == raw) - .ok_or_else(|| "message not found".to_string())?; + .ok_or_else(|| i18n::t("mail-message-not-found"))?; let described = client::describe(store, &me, &stored).map_err(explain)?; + // The subject sits in the header, the reply address powers Reply and + // the accept/block actions, and the Accept token is consumed by the + // contact flow — everything else the sender put in the frontmatter + // is theirs to say and ours to show. + const CONSUMED: [&str; 3] = ["subject", "reply-to", "accept"]; + let headers = described + .fields + .iter() + .filter(|(key, _)| !CONSUMED.contains(&key.as_str())) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); Ok(OpenedMsg { id: id.to_string(), from: match folder { @@ -585,21 +970,35 @@ pub fn open( body: described.text, sender: b32(&described.sender), reply_to: described.fields.get("reply-to").cloned(), + headers, kept: stored.kept, }) } pub fn whoami(store: &Store, master: &[u8; KEY_LEN]) -> Result { let me = account(store, master)?; - let address = store - .account() - .map_err(explain)? + let account = store.account().map_err(explain)?; + let pk = me.me().pk(); + let address = account + .as_ref() .map(|addr| addr.short()) .unwrap_or_default(); + let host = account + .as_ref() + .map(|addr| addr.host.clone()) + .unwrap_or_default(); + let port = account.as_ref().map(|addr| addr.port).unwrap_or_default(); + let uri = account + .as_ref() + .map(|addr| addr.uri(&pk)) + .unwrap_or_default(); Ok(Who { address, - key: b32(&me.me().pk()), - fingerprint: fingerprint(&me.me().pk()), + host, + port, + key: b32(&pk), + fingerprint: fingerprint(&pk), + uri, rotations: me.index(), }) } @@ -641,25 +1040,109 @@ mod tests { use fumi_core::message::{build_frontmatter, message_id, seal}; use fumi_core::store::now; + /// A settings file from another build, or one a hand edit broke, has + /// to degrade a line at a time rather than resetting the lot. + #[test] + fn settings_round_trip_and_degrade_per_line() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.txt"); + assert_eq!(load_settings(&path), Settings::default()); + assert!(!Settings::default().strict_pinning); + + let settings = Settings { + keep_mail: true, + timeout: 90, + strict_pinning: true, + }; + save_settings(&path, &settings); + assert_eq!(load_settings(&path), settings); + + // Each unreadable value keeps the default; the readable one still + // lands, and an unknown key is simply skipped. + std::fs::write( + &path, + "keep_mail yes\ntimeout 0\nstrict_pinning 1\nwhat even 3\n", + ) + .unwrap(); + let degraded = load_settings(&path); + assert!(!degraded.keep_mail); + assert_eq!(degraded.timeout, 30); + assert!(degraded.strict_pinning); + + // Out of the spin row's range counts as unreadable. + std::fs::write(&path, "timeout 9999\n").unwrap(); + assert_eq!(load_settings(&path).timeout, 30); + } + + #[test] + fn a_legacy_root_migrates_into_an_account_folder_once() { + let root = tempfile::tempdir().unwrap(); + let root = root.path(); + // A fresh root has nothing to move. + migrate_legacy(root).unwrap(); + assert!(list_accounts(root).is_empty()); + + for name in ["carrier.key", "carrier.db", "carrier.db-wal", "read.txt"] { + std::fs::write(root.join(name), name).unwrap(); + } + migrate_legacy(root).unwrap(); + let ids = list_accounts(root); + assert_eq!(ids.len(), 1); + assert_eq!(load_active(root).as_ref(), Some(&ids[0])); + let dir = account_dir(root, &ids[0]); + for name in ["carrier.key", "carrier.db", "carrier.db-wal", "read.txt"] { + assert!(!root.join(name).exists(), "{name} stayed in the root"); + assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), name); + } + + // Once `accounts/` exists, stray root files are left alone. + std::fs::write(root.join("carrier.key"), "stray").unwrap(); + migrate_legacy(root).unwrap(); + assert_eq!(list_accounts(root).len(), 1); + assert!(root.join("carrier.key").exists()); + } + + #[test] + fn the_active_account_must_name_an_existing_folder() { + let root = tempfile::tempdir().unwrap(); + let root = root.path(); + save_active(root, "gone").unwrap(); + assert!(load_active(root).is_none()); + let id = new_account(root).unwrap(); + save_active(root, &id).unwrap(); + assert_eq!(load_active(root), Some(id.clone())); + remove_account(root, &id).unwrap(); + assert!(load_active(root).is_none()); + assert!(list_accounts(root).is_empty()); + } + #[test] fn drafts_round_trip_through_the_sidecar() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("drafts.txt"); let drafts = vec![ Draft { - id: draft_id(), + id: random_id(), to: "smol://alice@example.org/KEY".into(), subject: "line breaks\nand \\backslashes\r".into(), body: "a draft\n\nwith paragraphs\nand a \\ literal".into(), reply_to: Some("ab".repeat(32)), + // Rows return as typed: colons and separators included. + headers: vec![ + "Urgency: high".into(), + "Note: a: value: with: colons".into(), + String::from_utf8_lossy(&[0x1f, b's', b'e', b'p']).into_owned(), + String::new(), + ], at: now(), }, Draft { - id: draft_id(), + id: random_id(), to: "bob@example.org".into(), subject: "no reply".into(), body: String::new(), reply_to: None, + headers: Vec::new(), at: now(), }, ]; @@ -671,6 +1154,94 @@ mod tests { let torn = text.lines().take(6).collect::>().join("\n") + "\n"; std::fs::write(&path, torn).unwrap(); assert_eq!(load_drafts(&path).len(), 1); + + // The old four-line records, written before header rows existed, + // still read as drafts with no headers. + let legacy = format!( + "draft {} {} {}\n{}\n{}\n{}\n", + "0f".repeat(8), + 100, + "-", + line("carol@example.org"), + line("before headers"), + line("an old body"), + ); + std::fs::write(&path, legacy).unwrap(); + let loaded = load_drafts(&path); + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].to, "carol@example.org"); + assert!(loaded[0].headers.is_empty()); + } + + #[test] + fn header_rows_follow_the_frontmatter_rules() { + // The allowed forms: a pair, and the empty row a send skips. + assert_eq!( + header_row("Urgency: high"), + Ok(Some(("Urgency".into(), "high".into()))) + ); + assert_eq!( + header_row(" spaced-key : trimmed value "), + Ok(Some(("spaced-key".into(), "trimmed value".into()))) + ); + assert_eq!(header_row(""), Ok(None)); + assert_eq!(header_row(" "), Ok(None)); + + // Everything the reader would reject the whole block for. + assert!(header_row("no colon").is_err()); + assert!(header_row(": value").is_err()); + assert!(header_row("bad key: v").is_err()); + assert!(header_row("ke\ty: v").is_err()); + assert!(header_row(&format!("{}: v", "k".repeat(65))).is_err()); + // A trailing newline is trimmed out of the key; an inner one is + // not, and the row is rejected. + assert_eq!( + header_row("value\n: v"), + Ok(Some(("value".into(), "v".into()))) + ); + assert!(header_row("multi\nline: v").is_err()); + // The client's own fields would be shadowed by a copy. + for reserved in [ + "Subject: x", + "subject: x", + "Reply-To: x", + "In-Reply-To: x", + "accept: x", + ] { + assert!(header_row(reserved).is_err(), "{reserved}"); + } + + // Across rows: keys are case-insensitive and must be unique. + assert_eq!( + validate_headers(&[("Urgency".into(), "high".into())]), + Ok(()) + ); + assert!(validate_headers(&[ + ("Urgency".into(), "high".into()), + ("urgency".into(), "low".into()), + ]) + .is_err()); + // And the whole block stays inside the reader's budget. + let big = "v".repeat(1024); + let many: Vec<(String, String)> = + (0..5).map(|i| (format!("X-Key{i}"), big.clone())).collect(); + assert!(validate_headers(&many).is_err()); + } + + #[test] + fn reply_rows_drop_what_a_reply_sets_itself() { + // Only the sender's own, writable fields carry over; the reserved + // ones — threading included — are the reply's own context. + let rows = reply_rows(&[ + ("priority".to_string(), "high".to_string()), + ("in-reply-to".to_string(), "ab".repeat(32)), + ("subject".to_string(), "shadow".to_string()), + ("accept".to_string(), "token".to_string()), + ]); + assert_eq!(rows, ["priority: high"]); + // A mail whose only extra field is the threading id carries + // nothing to ask about. + assert!(reply_rows(&[("in-reply-to".to_string(), "ab".repeat(32))]).is_empty()); } fn master() -> [u8; KEY_LEN] { @@ -685,6 +1256,22 @@ mod tests { Store::open_in_memory().expect("in-memory store") } + /// Fluent wraps every interpolated value in invisible bidi-isolation + /// marks by default; disabled in `i18n::bundle()` because this app + /// has one left-to-right locale and those marks would otherwise leak + /// into copy/paste, the clipboard and plain string comparisons. + #[test] + fn interpolated_messages_carry_no_bidi_isolation_marks() { + let mut args = fluent_bundle::FluentArgs::new(); + args.set("total", 5i64); + args.set("stored", 5i64); + args.set("rejected", 0i64); + assert_eq!( + i18n::t_args("fetch-result-note-plain", Some(&args)), + "5 fetched, 5 stored" + ); + } + #[test] fn seed_round_trips_through_base32_and_hex() { let m = master(); @@ -695,13 +1282,6 @@ mod tests { assert!(parse_seed(&hex[..63]).is_err()); } - #[test] - fn key_parsing_round_trips() { - let m = master(); - assert_eq!(parse_key(&b32(&m)).unwrap(), m); - assert!(parse_key("short").is_err()); - } - /// A sealed self-copy in the store surfaces as a row, opens with its /// frontmatter split, and flips to read against the marks set. #[test] @@ -713,7 +1293,12 @@ mod tests { store.set_account(&addr).unwrap(); let body = build_frontmatter( - &[("Subject", "hello"), ("Reply-To", &addr.uri(&me.me().pk()))], + &[ + ("Subject", "hello"), + ("Reply-To", &addr.uri(&me.me().pk())), + ("Urgency", "high"), + ("X-Source", "nightly build"), + ], "the body text", ); let envelope = seal(me.me(), &me.me().pk(), body.as_bytes(), now(), true).unwrap(); @@ -735,6 +1320,15 @@ mod tests { assert_eq!(opened.subject, "hello"); assert_eq!(opened.body, "the body text"); assert!(opened.reply_to.is_some()); + // The sender's own fields come through; the ones carrier already + // consumes do not. + assert_eq!( + opened.headers, + [ + ("urgency".to_string(), "high".to_string()), + ("x-source".to_string(), "nightly build".to_string()), + ] + ); let mut read = HashSet::new(); read.insert(id_hex); @@ -773,8 +1367,11 @@ mod tests { .store_inbox(&id, &envelope, now(), false, false) .unwrap(); - let (path, text) = export_backup(&store, &m, dir.path()).unwrap(); + let path = dir.path().join("backup.gsmol"); + let note = export_backup(&store, &m, &path).unwrap(); assert!(path.exists()); + assert!(note.contains(&path.display().to_string())); + let text = std::fs::read_to_string(&path).unwrap(); assert!(!text.is_empty()); let fresh = setup(); @@ -786,18 +1383,80 @@ mod tests { assert_eq!(folders[0][0].subject, "kept"); } + /// The detail pane says whether a contact's key could have come from + /// an unpinned server, so each row carries its server's pin state — + /// keyed by the same label pins use, non-default ports included. #[test] - fn unpin_splits_the_label() { + fn contacts_report_their_server_and_pin_state() { + let store = setup(); + let key = master(); + store.save_contact("bob@example.org", &key, false).unwrap(); + store + .save_contact("eve@example.org:1962", &key, false) + .unwrap(); + + let by_address = |all: Vec, address: &str| { + all.into_iter().find(|c| c.address == address).unwrap() + }; + let all = contacts(&store).unwrap(); + assert_eq!( + by_address(all.clone(), "bob@example.org").server, + "example.org" + ); + assert!(!by_address(all.clone(), "bob@example.org").pinned); + assert_eq!( + by_address(all, "eve@example.org:1962").server, + "example.org:1962" + ); + + store.pin_server("example.org", 1961, &key).unwrap(); + let all = contacts(&store).unwrap(); + assert!(by_address(all.clone(), "bob@example.org").pinned); + assert!( + !by_address(all, "eve@example.org:1962").pinned, + "a default-port pin must not cover another port" + ); + } + + #[test] + fn pin_lists_under_the_host_port_label() { let store = setup(); let addr = Address::parse("me@localhost:1962").unwrap(); let key = master(); - store.pin_server(&addr.host, addr.port, &key).unwrap(); assert_eq!(pin(&store, &addr, &key), Ok(())); let all = pins(&store).unwrap(); assert_eq!(all.len(), 1); assert_eq!(all[0].0, "localhost:1962"); - unpin(&store, "localhost:1962").unwrap(); - assert!(pins(&store).unwrap().is_empty()); + } + + /// The dev-build demo seed grows a mail that carries the sender's own + /// frontmatter, and it opens with those fields intact — the case the + /// message detail's header block is laid out around. + #[cfg(debug_assertions)] + #[test] + fn demo_seed_carries_a_mail_with_custom_fields() { + let dir = tempfile::tempdir().unwrap(); + crate::demo::seed(dir.path()); + let account = account_dir(dir.path(), "demo"); + let store = Store::open(&account.join("carrier.db")).unwrap(); + // The demo master is fixed bytes in demo.rs. + let master: [u8; KEY_LEN] = core::array::from_fn(|i| i as u8 + 1); + let empty = HashSet::new(); + + let folders = lists(&store, &master, &empty).unwrap(); + let row = folders[0] + .iter() + .find(|row| row.subject == "canary rollout report") + .expect("the custom-fields mail in the demo inbox"); + + let opened = open(&store, &master, &row.id, Folder::Inbox).unwrap(); + assert_eq!( + opened.headers, + [ + ("priority".to_string(), "high".to_string()), + ("x-stage".to_string(), "canary at 5%".to_string()), + ] + ); } #[test] diff --git a/src/view.rs b/src/view.rs index 03416ec..8ed9952 100644 --- a/src/view.rs +++ b/src/view.rs @@ -11,6 +11,7 @@ use std::sync::atomic::Ordering; use std::time::Duration; +use fumi_core::address::trust_label; use fumi_core::crypto::{b32, fingerprint, KEY_LEN}; use gtk::prelude::*; use gtk::{Align, Orientation, WrapMode}; @@ -19,7 +20,11 @@ use relm4::adw::prelude::*; use relm4::ComponentSender; use relm4::{Component, ComponentParts}; -use crate::app::{Carrier, Dialog, Message, OnboardMode, OpResult, Page, PendingOp}; +use crate::app::{ + AccountEntry, Carrier, Dialog, DialogKind, Message, OnboardMode, OpResult, Page, PendingOp, + SignupMode, SignupStep, +}; +use crate::i18n; use crate::ops::{self, Contact, Folder, Row}; use relm4::RelmApp; @@ -163,13 +168,40 @@ fn buffer_text(buffer: >k::TextBuffer) -> String { /// The contact's trust state as one word, the same vocabulary the sidebar, /// the detail pane and the contacts page all label it with. -fn contact_state(contact: &Contact) -> &'static str { - match contact.accepted { - Some(true) => "accepted", - Some(false) => "blocked", - None if contact.verified => "verified", - None => "trust on first use", - } +fn contact_state(contact: &Contact) -> String { + let id = match contact.accepted { + Some(true) => "contact-state-accepted", + Some(false) => "contact-state-blocked", + None if contact.verified => "contact-state-verified", + None => "contact-state-tofu", + }; + i18n::t(id) +} + +/// An account's address, or the not-registered label while it has none. +fn account_title(entry: &AccountEntry) -> String { + entry + .label + .clone() + .unwrap_or_else(|| i18n::t("account-not-registered-value")) +} + +/// One switcher row, named by account id; the active one carries a check. +fn account_row(entry: &AccountEntry, active: bool) -> gtk::ListBoxRow { + let line = gtk::Box::new(Orientation::Horizontal, 6); + line.set_margin_top(6); + line.set_margin_bottom(6); + let title = label(&account_title(entry), "mono"); + title.set_hexpand(true); + title.set_ellipsize(gtk::pango::EllipsizeMode::End); + line.append(&title); + let check = gtk::Image::from_icon_name("object-select-symbolic"); + check.set_opacity(if active { 1.0 } else { 0.0 }); + line.append(&check); + let row = gtk::ListBoxRow::new(); + row.set_widget_name(&entry.id); + row.set_child(Some(&line)); + row } #[derive(Debug, Clone)] @@ -193,22 +225,35 @@ pub struct CarrierWidgets { mail_list: gtk::ListBox, list_empty: adw::StatusPage, list_empty_fetch: gtk::Button, + list_empty_hint: gtk::Label, article_stack: gtk::Stack, article_subject: gtk::Label, article_meta: gtk::Label, + article_headers: gtk::Label, article_view: gtk::TextView, article_body: gtk::TextBuffer, actions: gtk::Box, // compose page compose_to: adw::EntryRow, + compose_headers: gtk::ListBox, compose_subject: adw::EntryRow, compose_body: gtk::TextBuffer, compose_send: adw::ButtonContent, + compose_pin_card: gtk::Box, + compose_pin_title: gtk::Label, + compose_pin_body: gtk::Label, + compose_pin_key: gtk::Label, + compose_pin_fingerprint: gtk::Label, + compose_pin_hint: gtk::Label, + compose_pin_button: gtk::Button, // sidebar bottom: own identity and the contact list sidebar_own: gtk::Label, sidebar_contacts: gtk::ListBox, + /// The account switcher beside the identity card, and its list. + accounts_menu: gtk::MenuButton, + accounts_list: gtk::ListBox, // the QR-only share popover on the detail view's header detail_share: gtk::MenuButton, @@ -216,21 +261,38 @@ pub struct CarrierWidgets { detail_qr: gtk::Image, // settings page - identity_values: Vec, - offer_group: adw::PreferencesGroup, - offer_row: adw::ActionRow, - pins_group: adw::PreferencesGroup, - pin_rows: Vec, + identity_rows: Vec, + secret_row: adw::ActionRow, + secret_reveal: gtk::Button, + host_row: adw::ActionRow, + public_key_row: adw::ActionRow, + rotations_value: gtk::Label, + keep_mail_check: gtk::CheckButton, + strict_check: gtk::CheckButton, timeout_row: adw::SpinRow, - backup_label: gtk::Label, // onboarding onboard_seed_label: gtk::Label, + onboard_seed_entry: adw::EntryRow, + onboard_reuse: gtk::Box, + onboard_reuse_list: gtk::ListBox, + onboard_cancel: gtk::Button, // signup - signup_back: gtk::Button, - signup_offer_list: gtk::ListBox, - signup_offer_row: adw::ActionRow, + signup_key_button: gtk::Button, + signup_key_card: gtk::Box, + signup_key_value: gtk::Label, + signup_key_fingerprint: gtk::Label, + signup_key_hint: gtk::Label, + signup_start_over: gtk::Button, + signup_step_back: gtk::Button, + signup_mode_new: gtk::ToggleButton, + signup_mode_existing: gtk::ToggleButton, + signup_host: adw::EntryRow, + signup_user: adw::EntryRow, + signup_invite: adw::EntryRow, + register_button: gtk::Button, + recall_button: gtk::Button, // status bar and dialogs spinner: gtk::Spinner, @@ -287,8 +349,16 @@ impl CarrierWidgets { // leave neither of them reading as the primary one. let sidebar_actions = gtk::Box::new(Orientation::Horizontal, 6); sidebar_actions.set_homogeneous(true); - let fetch_button = icon_label_button("mail-send-receive-symbolic", "Fetch", "accent"); - let write_button = icon_label_button("mail-message-new-symbolic", "Write", ""); + let fetch_button = icon_label_button( + "mail-send-receive-symbolic", + &i18n::t("mail-fetch-button"), + "accent", + ); + let write_button = icon_label_button( + "mail-message-new-symbolic", + &i18n::t("mail-write-button"), + "", + ); sidebar_actions.append(&fetch_button); sidebar_actions.append(&write_button); sidebar_top.append(&sidebar_actions); @@ -299,10 +369,10 @@ impl CarrierWidgets { folders.add_css_class("navigation-sidebar"); folders.set_selection_mode(gtk::SelectionMode::Single); let folder_rows = [ - nav_row("folder-download-symbolic", "Inbox"), - nav_row("contact-new-symbolic", "Requests"), - nav_row("mail-send-symbolic", "Sent"), - nav_row("document-edit-symbolic", "Drafts"), + nav_row("folder-download-symbolic", &i18n::t("folder-inbox")), + nav_row("contact-new-symbolic", &i18n::t("folder-requests")), + nav_row("mail-send-symbolic", &i18n::t("folder-sent")), + nav_row("document-edit-symbolic", &i18n::t("folder-drafts")), ]; let mut folder_counts = Vec::new(); let mut drafts_nav = None; @@ -329,7 +399,10 @@ impl CarrierWidgets { let settings_nav = gtk::ListBox::new(); settings_nav.add_css_class("navigation-sidebar"); settings_nav.set_selection_mode(gtk::SelectionMode::Single); - let (settings_row, _) = nav_row("preferences-system-symbolic", "Settings"); + let (settings_row, _) = nav_row( + "preferences-system-symbolic", + &i18n::t("settings-nav-label"), + ); settings_nav.append(&settings_row); sidebar_top.append(&settings_nav); @@ -341,7 +414,7 @@ impl CarrierWidgets { own_text.set_margin_top(8); own_text.set_margin_bottom(8); own_text.set_margin_start(12); - let own_caption = label("you", "caption"); + let own_caption = label(&i18n::t("identity-you-caption"), "caption"); let sidebar_own = label("", "mono heading"); // Not selectable: a selectable label eats clicks on the text with // its selection gesture, and the address is already copyable from @@ -351,22 +424,53 @@ impl CarrierWidgets { own_text.append(&sidebar_own); let own_row = gtk::Button::new(); own_row.add_css_class("card"); - own_row.set_halign(Align::Fill); - own_row.set_margin_top(6); + own_row.set_hexpand(true); own_row.set_child(Some(&own_text)); - sidebar_bottom.append(&own_row); + + // The account switcher sits beside the card: one list of accounts, + // the active one checked, and a way to add another. + let accounts_list = gtk::ListBox::new(); + accounts_list.add_css_class("navigation-sidebar"); + accounts_list.set_selection_mode(gtk::SelectionMode::None); + let add_account = icon_label_button( + "list-add-symbolic", + &i18n::t("accounts-add-button"), + "quiet", + ); + let accounts_box = gtk::Box::new(Orientation::Vertical, 6); + accounts_box.set_width_request(260); + accounts_box.append(&accounts_list); + accounts_box.append(&add_account); + let accounts_popover = gtk::Popover::new(); + accounts_popover.set_child(Some(&accounts_box)); + let accounts_menu = gtk::MenuButton::new(); + accounts_menu.set_icon_name("system-switch-user-symbolic"); + accounts_menu.add_css_class("flat"); + accounts_menu.add_css_class("circular"); + accounts_menu.set_valign(Align::Center); + accounts_menu.set_tooltip_text(Some(&i18n::t("accounts-menu-tooltip"))); + accounts_menu.set_popover(Some(&accounts_popover)); + let own_line = gtk::Box::new(Orientation::Horizontal, 6); + own_line.set_margin_top(6); + own_line.append(&own_row); + own_line.append(&accounts_menu); + sidebar_bottom.append(&own_line); // The list's header carries its one action: importing a // smol:// address, in a popover off a plain add button. let contacts_head = gtk::Box::new(Orientation::Horizontal, 6); - let contacts_caption = label("contacts", "caption"); + let contacts_caption = label(&i18n::t("contacts-caption"), "caption"); contacts_caption.set_hexpand(true); contacts_caption.set_valign(Align::Center); contacts_caption.set_margin_start(12); let contact_import = adw::EntryRow::builder() - .title("Import a smol:// address") + .title(i18n::t("contacts-import-placeholder")) .build(); - let import_button = icon_label_button("document-open-symbolic", "Import", "accent"); + let import_button = icon_label_button( + "document-open-symbolic", + &i18n::t("contacts-import-button"), + "accent", + ); import_button.set_valign(Align::Center); contact_import.add_suffix(&import_button); let import_list = boxed_list(); @@ -382,7 +486,7 @@ impl CarrierWidgets { add_contact.set_icon_name("list-add-symbolic"); add_contact.add_css_class("flat"); add_contact.add_css_class("circular"); - add_contact.set_tooltip_text(Some("Import a smol:// address")); + add_contact.set_tooltip_text(Some(&i18n::t("contacts-import-placeholder"))); add_contact.set_popover(Some(&import_popover)); contacts_head.append(&contacts_caption); contacts_head.append(&add_contact); @@ -410,9 +514,20 @@ impl CarrierWidgets { // An empty folder gets a status page rather than a stray line of // dim text, so the pane says what to do about it. let list_empty = adw::StatusPage::new(); - let list_empty_fetch = icon_label_button("mail-send-receive-symbolic", "Fetch", "pill"); + let list_empty_fetch = icon_label_button( + "mail-send-receive-symbolic", + &i18n::t("mail-fetch-button"), + "pill", + ); list_empty_fetch.set_halign(Align::Center); - list_empty.set_child(Some(&list_empty_fetch)); + let list_empty_hint = label(&i18n::t("mail-empty-hint"), "dim caption"); + list_empty_hint.set_wrap(true); + list_empty_hint.set_justify(gtk::Justification::Center); + list_empty_hint.set_halign(Align::Center); + let list_empty_box = gtk::Box::new(Orientation::Vertical, 8); + list_empty_box.append(&list_empty_fetch); + list_empty_box.append(&list_empty_hint); + list_empty.set_child(Some(&list_empty_box)); let list_stack = gtk::Stack::new(); list_stack.set_hhomogeneous(false); list_stack.set_vhomogeneous(false); @@ -445,13 +560,13 @@ impl CarrierWidgets { detail_share.set_icon_name("send-to-symbolic"); detail_share.add_css_class("flat"); detail_share.add_css_class("circular"); - detail_share.set_tooltip_text(Some("Show the address as a QR code")); + detail_share.set_tooltip_text(Some(&i18n::t("detail-qr-tooltip"))); detail_share.set_popover(Some(&detail_popover)); detail_share.set_valign(Align::Start); detail_share.set_visible(false); // Copies the address the header shows, so it serves the contact // and the own-identity detail alike. - let detail_copy = icon_button("edit-copy-symbolic", "Copy the address"); + let detail_copy = icon_button("edit-copy-symbolic", &i18n::t("detail-copy-tooltip")); detail_copy.set_valign(Align::Start); detail_copy.set_visible(false); let copy_source = article_subject.clone(); @@ -469,6 +584,15 @@ impl CarrierWidgets { article_meta.set_wrap(true); article_head.append(&subject_row); article_head.append(&article_meta); + // The sender's own frontmatter fields, when a mail carries any: + // envelope data, so it reads like the contact detail's key block + // rather than like body prose. + let article_headers = label("", "caption mono"); + article_headers.set_wrap(true); + article_headers.set_wrap_mode(gtk::pango::WrapMode::WordChar); + article_headers.set_selectable(true); + article_headers.set_visible(false); + article_head.append(&article_headers); article.append(&article_head); article.append(>k::Separator::new(Orientation::Horizontal)); let article_view = gtk::TextView::new(); @@ -494,8 +618,8 @@ impl CarrierWidgets { // No icon: the pane sits directly under the list's own empty page, // and two envelopes stacked up the window say nothing twice. let article_empty = adw::StatusPage::builder() - .title("No message selected") - .description("Pick a message from the list above to read it.") + .title(i18n::t("mail-empty-title")) + .description(i18n::t("mail-empty-description")) .build(); let article_stack = gtk::Stack::new(); article_stack.set_hhomogeneous(false); @@ -526,11 +650,69 @@ impl CarrierWidgets { compose.set_margin_start(12); compose.set_margin_end(12); let compose_fields = boxed_list(); - let compose_to = adw::EntryRow::builder().title("To").build(); - let compose_subject = adw::EntryRow::builder().title("Subject").build(); + let compose_to = adw::EntryRow::builder() + .title(i18n::t("compose-to-label")) + .build(); + let compose_subject = adw::EntryRow::builder() + .title(i18n::t("compose-subject-label")) + .build(); compose_fields.append(&compose_to); compose_fields.append(&compose_subject); compose.append(&compose_fields); + + // Shown when a send was refused because the recipient's key would + // have come from a server with no pin: the refusal and its fix in + // one place, since nowhere else in the app pins a correspondent's + // server. + let compose_pin_title = label("", "heading"); + compose_pin_title.set_wrap(true); + let compose_pin_body = label("", "dim"); + compose_pin_body.set_wrap(true); + let compose_pin_key = label("", "mono"); + compose_pin_key.set_selectable(true); + compose_pin_key.set_wrap(true); + compose_pin_key.set_wrap_mode(gtk::pango::WrapMode::Char); + let compose_pin_fingerprint = label("", "mono dim"); + compose_pin_fingerprint.set_selectable(true); + compose_pin_fingerprint.set_wrap(true); + let compose_pin_hint = label(&i18n::t("trust-fingerprint-hint"), "dim caption"); + compose_pin_hint.set_wrap(true); + let compose_pin_button = button("", "accent"); + compose_pin_button.set_halign(Align::Start); + compose_pin_button.set_margin_top(6); + let compose_pin_card = gtk::Box::new(Orientation::Vertical, 6); + compose_pin_card.add_css_class("card"); + compose_pin_card.set_visible(false); + for child in [&compose_pin_title, &compose_pin_body] { + child.set_margin_start(12); + child.set_margin_end(12); + } + compose_pin_title.set_margin_top(12); + for child in [ + &compose_pin_key, + &compose_pin_fingerprint, + &compose_pin_hint, + ] { + child.set_margin_start(12); + child.set_margin_end(12); + } + compose_pin_button.set_margin_start(12); + compose_pin_button.set_margin_bottom(12); + compose_pin_card.append(&compose_pin_title); + compose_pin_card.append(&compose_pin_body); + compose_pin_card.append(&compose_pin_key); + compose_pin_card.append(&compose_pin_fingerprint); + compose_pin_card.append(&compose_pin_hint); + compose_pin_card.append(&compose_pin_button); + compose.append(&compose_pin_card); + // Frontmatter rows: one `Key: value` entry each, plus a flat + // add button below. Rows are rebuilt in render on structural + // changes only, so the entries never lose focus while typing. + let compose_headers = boxed_list(); + compose.append(&compose_headers); + let add_header = button(&i18n::t("compose-add-header-button"), "quiet"); + add_header.set_halign(Align::Start); + compose.append(&add_header); let compose_view = gtk::TextView::new(); compose_view.set_wrap_mode(WrapMode::WordChar); compose_view.set_top_margin(8); @@ -546,10 +728,10 @@ impl CarrierWidgets { let compose_send_button = button("", "accent"); let compose_send = adw::ButtonContent::builder() .icon_name("mail-send-symbolic") - .label("Send") + .label(i18n::t("compose-send-button")) .build(); compose_send_button.set_child(Some(&compose_send)); - let compose_cancel = button("Cancel", "quiet"); + let compose_cancel = button(&i18n::t("action-cancel"), "quiet"); let compose_actions = gtk::Box::new(Orientation::Horizontal, 6); compose_actions.set_halign(Align::End); compose_actions.append(&compose_cancel); @@ -557,107 +739,236 @@ impl CarrierWidgets { compose.append(&compose_actions); stack.add_named(&compose, Some("compose")); - // settings: the preferences page every GNOME app shows, one group - // per concern, so scrolling, width and margins come for free. - let settings = adw::PreferencesPage::new(); + // settings: a tabbed preferences page — Identity, Server, Backup, + // Advanced — switched by an adw::ViewSwitcher over an + // adw::ViewStack, each tab its own PreferencesPage. + let settings_stack = adw::ViewStack::new(); - let identity_group = adw::PreferencesGroup::builder().title("Identity").build(); - let identity_actions = gtk::Box::new(Orientation::Horizontal, 6); - let rotate_button = icon_label_button("view-refresh-symbolic", "Rotate", ""); - let learn_button = button("Learn key", ""); - identity_actions.append(&learn_button); - identity_actions.append(&rotate_button); - identity_group.set_header_suffix(Some(&identity_actions)); - let mut identity_values = Vec::new(); - for title in ["Address", "Key", "Fingerprint", "Rotations"] { - let row = adw::ActionRow::builder().title(title).build(); - let value = label("", "mono dim"); - value.set_selectable(true); - value.set_ellipsize(gtk::pango::EllipsizeMode::End); - value.set_max_width_chars(48); - value.set_valign(Align::Center); - row.add_suffix(&value); + // Read-only values use Adwaita's "property" row: the field name + // sits small above the value it labels, which leaves the value + // itself room to wrap instead of being ellipsized into a suffix. + // Markup is off so the copy button can hand back exactly what is + // on screen. + // `id` is a message id (e.g. "settings-field-host"), not literal + // text, so both the title and its "Copy the …" tooltip come from + // the catalogue rather than one being built from the other. + let property_row = |id: &str| -> adw::ActionRow { + let title = i18n::t(id); + let row = adw::ActionRow::builder() + .title(&title) + .use_markup(false) + .subtitle_lines(0) + .subtitle_selectable(true) + .build(); + row.add_css_class("property"); + row.add_css_class("monospace"); + let copy = icon_button( + "edit-copy-symbolic", + &i18n::t1("property-row-copy-tooltip", "field", title.to_lowercase()), + ); + let copy_source = row.clone(); + copy.connect_clicked(move |_| { + if let Some(display) = gtk::gdk::Display::default() { + display + .clipboard() + .set_text(©_source.subtitle().unwrap_or_default()); + } + }); + row.add_suffix(©); + row + }; + + // -- Identity tab -------------------------------------------------- + // The switcher already names each page, so the first group on a + // page carries no title of its own. + let identity_page = adw::PreferencesPage::new(); + let identity_group = adw::PreferencesGroup::new(); + let mut identity_rows = Vec::new(); + for field in [ + "settings-field-address", + "settings-field-key", + "settings-field-fingerprint", + "settings-field-uri", + ] { + let row = property_row(field); identity_group.add(&row); - identity_values.push(value); + identity_rows.push(row); } - settings.add(&identity_group); + identity_page.add(&identity_group); - // The pin offer is a group that appears in place rather than a - // dialog: pinning is a decision about this host, taken next to the - // identity it belongs to. - let offer_group = adw::PreferencesGroup::builder() - .title("Server key offered") - .visible(false) + // The group header names this one, so the row carries only the + // secret — masked until the reveal button is pressed. + let secret_group = adw::PreferencesGroup::builder() + .title(i18n::t("settings-recovery-secret-title")) .build(); - let offer_row = adw::ActionRow::builder().title("").build(); - offer_row.add_css_class("monospace"); - offer_row.set_subtitle_lines(2); - let offer_pin = button("Pin", "accent"); - offer_pin.set_valign(Align::Center); - let offer_discard = button("Discard", ""); - offer_discard.set_valign(Align::Center); - offer_row.add_suffix(&offer_discard); - offer_row.add_suffix(&offer_pin); - offer_group.add(&offer_row); - settings.add(&offer_group); - - let pins_group = adw::PreferencesGroup::builder() - .title("Server keys") + let secret_row = adw::ActionRow::builder() + .use_markup(false) + .title_lines(0) + .title_selectable(true) .build(); - settings.add(&pins_group); + secret_row.add_css_class("monospace"); + let secret_reveal = icon_button( + "view-reveal-symbolic", + &i18n::t("settings-secret-reveal-tooltip"), + ); + let secret_copy = icon_button( + "edit-copy-symbolic", + &i18n::t("settings-secret-copy-tooltip"), + ); + secret_row.add_suffix(&secret_reveal); + secret_row.add_suffix(&secret_copy); + secret_group.add(&secret_row); + identity_page.add(&secret_group); + settings_stack.add_titled_with_icon( + &identity_page, + Some("identity"), + &i18n::t("settings-tab-identity"), + "avatar-default-symbolic", + ); - let network_group = adw::PreferencesGroup::builder().title("Network").build(); + // -- Server tab ---------------------------------------------------- + let server_page = adw::PreferencesPage::new(); + let server_group = adw::PreferencesGroup::builder() + .title(i18n::t("server-connection-title")) + .build(); + let host_row = property_row("settings-field-host"); + let public_key_row = property_row("settings-field-public-key"); + server_group.add(&host_row); + server_group.add(&public_key_row); let timeout_row = adw::SpinRow::with_range(1.0, 600.0, 1.0); - timeout_row.set_title("Timeout"); - timeout_row.set_subtitle("Seconds before a network call gives up"); - network_group.add(&timeout_row); - settings.add(&network_group); + timeout_row.set_title(&i18n::t("server-timeout-title")); + timeout_row.set_subtitle(&i18n::t("server-timeout-subtitle")); + server_group.add(&timeout_row); + server_page.add(&server_group); + let network_group = adw::PreferencesGroup::builder() + .title(i18n::t("server-fetching-title")) + .build(); + let keep_mail_row = adw::ActionRow::builder() + .title(i18n::t("server-leave-mail-title")) + .subtitle(i18n::t("server-leave-mail-subtitle")) + .subtitle_lines(0) + .activatable(true) + .build(); + let keep_mail_check = gtk::CheckButton::builder().valign(Align::Center).build(); + keep_mail_row.add_suffix(&keep_mail_check); + keep_mail_row.set_activatable_widget(Some(&keep_mail_check)); + network_group.add(&keep_mail_row); + server_page.add(&network_group); + settings_stack.add_titled_with_icon( + &server_page, + Some("server"), + &i18n::t("settings-tab-server"), + "network-server-symbolic", + ); + + // -- Backup tab ---------------------------------------------------- + let backup_page = adw::PreferencesPage::new(); let backup_group = adw::PreferencesGroup::builder() - .title("Backup") - .description( - "Sealed to a key derived from the seed, so it restores only where this\n identity already lives. The seed itself is never in the file.", - ) + .description(i18n::t("backup-page-description")) .build(); - let backup_actions = gtk::Box::new(Orientation::Horizontal, 6); - let export_button = icon_label_button("document-save-symbolic", "Export", ""); - let copy_export = icon_button("edit-copy-symbolic", "Copy the backup"); - backup_actions.append(©_export); - backup_actions.append(&export_button); - backup_group.set_header_suffix(Some(&backup_actions)); - let backup_label = label("", "mono caption"); - backup_label.set_wrap(true); - backup_label.set_wrap_mode(gtk::pango::WrapMode::Char); - backup_label.set_selectable(true); - let backup_scroll = gtk::ScrolledWindow::new(); - backup_scroll.add_css_class("card"); - backup_scroll.set_height_request(72); - backup_scroll.set_child(Some(&backup_label)); - backup_group.add(&backup_scroll); - settings.add(&backup_group); + let export_row = adw::ActionRow::builder() + .title(i18n::t("backup-export-title")) + .subtitle(i18n::t("backup-export-subtitle")) + .activatable(true) + .build(); + export_row.add_prefix(>k::Image::from_icon_name("document-save-symbolic")); + export_row.add_suffix(>k::Image::from_icon_name("go-next-symbolic")); + let import_row = adw::ActionRow::builder() + .title(i18n::t("backup-import-title")) + .subtitle(i18n::t("backup-import-subtitle")) + .activatable(true) + .build(); + import_row.add_prefix(>k::Image::from_icon_name("document-open-symbolic")); + import_row.add_suffix(>k::Image::from_icon_name("go-next-symbolic")); + backup_group.add(&export_row); + backup_group.add(&import_row); + backup_page.add(&backup_group); + settings_stack.add_titled_with_icon( + &backup_page, + Some("backup"), + &i18n::t("settings-tab-backup"), + "document-save-symbolic", + ); - let import_group = adw::PreferencesGroup::builder() - .title("Restore") - .description("Paste a gsmol backup to restore the contacts, pins and mail it carries.") + // -- Advanced tab -------------------------------------------------- + let advanced_page = adw::PreferencesPage::new(); + let rotations_group = adw::PreferencesGroup::builder() + .title(i18n::t("advanced-rotations-title")) + .description(i18n::t("advanced-rotations-description")) .build(); - let import_view = gtk::TextView::new(); - import_view.set_wrap_mode(WrapMode::WordChar); - import_view.set_top_margin(8); - import_view.set_bottom_margin(8); - import_view.set_left_margin(8); - import_view.set_right_margin(8); - import_view.add_css_class("monospace"); - let import_body = import_view.buffer(); - let import_scroll = gtk::ScrolledWindow::new(); - import_scroll.add_css_class("card"); - import_scroll.set_height_request(96); - import_scroll.set_child(Some(&import_view)); - import_group.add(&import_scroll); - let import_backup = icon_label_button("document-open-symbolic", "Restore", ""); - import_backup.set_halign(Align::End); - import_backup.set_margin_top(6); - import_group.add(&import_backup); - settings.add(&import_group); + // Both actions sit in their group's body, centred under the + // explanation: a long description wraps under the group title and + // would run straight into a header-suffix button. + let rotations_row = adw::ActionRow::builder() + .title(i18n::t("advanced-rotations-completed")) + .build(); + let rotations_value = label("", "dim numeric"); + rotations_value.set_valign(Align::Center); + rotations_row.add_suffix(&rotations_value); + rotations_group.add(&rotations_row); + let rotate_button = icon_label_button( + "view-refresh-symbolic", + &i18n::t("advanced-rotate-button"), + "", + ); + rotate_button.set_halign(Align::Center); + rotate_button.set_margin_top(12); + rotations_group.add(&rotate_button); + advanced_page.add(&rotations_group); + + let trust_group = adw::PreferencesGroup::builder() + .title(i18n::t("advanced-first-contact-title")) + .description(i18n::t("advanced-first-contact-description")) + .build(); + let strict_row = adw::ActionRow::builder() + .title(i18n::t("advanced-strict-pinning-title")) + .subtitle(i18n::t("advanced-strict-pinning-subtitle")) + .subtitle_lines(0) + .activatable(true) + .build(); + let strict_check = gtk::CheckButton::builder().valign(Align::Center).build(); + strict_row.add_suffix(&strict_check); + strict_row.set_activatable_widget(Some(&strict_check)); + trust_group.add(&strict_row); + advanced_page.add(&trust_group); + + // The log-out button is wide and destructive, so it sits in the + // group's body under the warning rather than squeezed beside the + // header where its label would crowd the title. + let logout_group = adw::PreferencesGroup::builder() + .title(i18n::t("advanced-logout-title")) + .description(i18n::t("advanced-logout-description")) + .build(); + let reset_button = icon_label_button( + "system-log-out-symbolic", + &i18n::t("advanced-logout-button"), + "danger", + ); + reset_button.set_halign(Align::Center); + reset_button.set_margin_top(12); + logout_group.add(&reset_button); + advanced_page.add(&logout_group); + settings_stack.add_titled_with_icon( + &advanced_page, + Some("advanced"), + &i18n::t("settings-tab-advanced"), + "emblem-system-symbolic", + ); + + // The switcher is a centred bar of its own above the pages, since + // the window's headerbar already carries the app name and address. + let settings_switcher = adw::ViewSwitcher::builder() + .stack(&settings_stack) + .policy(adw::ViewSwitcherPolicy::Wide) + .halign(Align::Center) + .build(); + let settings_switcher_bar = gtk::Box::new(Orientation::Vertical, 0); + settings_switcher_bar.add_css_class("toolbar"); + settings_switcher_bar.append(&settings_switcher); + let settings = gtk::Box::new(Orientation::Vertical, 0); + settings.append(&settings_switcher_bar); + settings.append(&settings_stack); stack.add_named(&settings, Some("settings")); @@ -677,23 +988,33 @@ impl CarrierWidgets { let title = label("carrier", "title"); title.set_halign(Align::Center); onboard_start.append(&title); - let tagline = label("smolmail: one seed, sealed mail, five operations", "dim"); + let tagline = label(&i18n::t("onboard-tagline"), "dim"); tagline.set_halign(Align::Center); tagline.set_margin_bottom(12); onboard_start.append(&tagline); - let create_button = button("Create an identity", "pill"); - let restore_button = button("Restore from a seed", "pill-quiet"); + let create_button = button(&i18n::t("onboard-create-button"), "pill"); + let restore_button = button(&i18n::t("onboard-restore-button"), "pill-quiet"); onboard_start.append(&create_button); onboard_start.append(&restore_button); + // Shown only while other accounts hold a secret: one row each. + let onboard_reuse = gtk::Box::new(Orientation::Vertical, 6); + onboard_reuse.set_margin_top(12); + onboard_reuse.append(&label(&i18n::t("onboard-reuse-title"), "heading")); + let reuse_description = label(&i18n::t("onboard-reuse-description"), "dim"); + reuse_description.set_wrap(true); + onboard_reuse.append(&reuse_description); + let onboard_reuse_list = boxed_list(); + onboard_reuse.append(&onboard_reuse_list); + onboard_start.append(&onboard_reuse); + let onboard_cancel = button(&i18n::t("accounts-add-cancel-button"), "pill-quiet"); + onboard_cancel.set_margin_top(12); + onboard_start.append(&onboard_cancel); stack.add_named(¢er(&onboard_start), Some("onboard")); let onboard_created = gtk::Box::new(Orientation::Vertical, 12); - let created_title = label("Write this seed down", "subtitle"); + let created_title = label(&i18n::t("onboard-created-title"), "subtitle"); onboard_created.append(&created_title); - onboard_created.append(&label( - "It is the only secret, and it is shown once.", - "dim", - )); + onboard_created.append(&label(&i18n::t("onboard-created-description"), "dim")); let onboard_seed_label = label("", "mono subtitle"); onboard_seed_label.set_selectable(true); onboard_seed_label.set_wrap(true); @@ -707,66 +1028,104 @@ impl CarrierWidgets { seed_card.add_css_class("card"); seed_card.append(&onboard_seed_label); onboard_created.append(&seed_card); - let saved_button = button("I saved it", "pill"); - let created_back = button("Back", "pill-quiet"); + let saved_button = button(&i18n::t("onboard-saved-button"), "pill"); + let created_back = button(&i18n::t("action-back"), "pill-quiet"); onboard_created.append(&saved_button); onboard_created.append(&created_back); stack.add_named(¢er(&onboard_created), Some("onboard-created")); let onboard_restore = gtk::Box::new(Orientation::Vertical, 12); - onboard_restore.append(&label("Restore from a seed", "subtitle")); + onboard_restore.append(&label(&i18n::t("onboard-restore-title"), "subtitle")); let restore_list = boxed_list(); let onboard_seed_entry = adw::EntryRow::builder() - .title("Seed — 32 bytes, base32 or hex") + .title(i18n::t("onboard-seed-entry-title")) .build(); restore_list.append(&onboard_seed_entry); onboard_restore.append(&restore_list); - let restore_go = button("Restore", "pill"); - let restore_back = button("Back", "pill-quiet"); + let restore_go = button(&i18n::t("onboard-restore-go-button"), "pill"); + let restore_back = button(&i18n::t("action-back"), "pill-quiet"); onboard_restore.append(&restore_go); onboard_restore.append(&restore_back); stack.add_named(¢er(&onboard_restore), Some("onboard-restore")); - // signup - let signup = gtk::Box::new(Orientation::Vertical, 12); - signup.append(&label("Set up the address", "subtitle")); - let signup_group = adw::PreferencesGroup::builder() - .description( - "The invite token and server key are only needed when the operator published them.", - ) + // signup: step 1 — the server this address lives on + let signup_server = gtk::Box::new(Orientation::Vertical, 12); + signup_server.append(&label(&i18n::t("signup-server-title"), "subtitle")); + let signup_server_group = adw::PreferencesGroup::new(); + let signup_host = adw::EntryRow::builder() + .title(i18n::t("settings-field-host")) .build(); - let signup_user = adw::EntryRow::builder().title("User").build(); - let signup_host = adw::EntryRow::builder().title("Host").build(); - let signup_invite = adw::EntryRow::builder().title("Invite token").build(); - let signup_key = adw::EntryRow::builder().title("Server key").build(); - for row in [&signup_user, &signup_host, &signup_invite, &signup_key] { - signup_group.add(row); - } - signup.append(&signup_group); - let signup_learn = button("Learn the server key and pin what it presents", ""); - signup.append(&signup_learn); - let signup_offer_list = boxed_list(); - signup_offer_list.set_visible(false); - let signup_offer_row = adw::ActionRow::builder() - .title("Server key offered") + signup_server_group.add(&signup_host); + signup_server.append(&signup_server_group); + + // Shown once a key has been fetched: the key and its fingerprint, + // prominent, plus the reminder to check it against what the + // operator published. Hidden otherwise. + let signup_key_value = label("", "mono"); + signup_key_value.set_selectable(true); + signup_key_value.set_wrap(true); + signup_key_value.set_margin_top(12); + signup_key_value.set_margin_start(12); + signup_key_value.set_margin_end(12); + let signup_key_fingerprint = label("", "mono dim"); + signup_key_fingerprint.set_selectable(true); + signup_key_fingerprint.set_wrap(true); + signup_key_fingerprint.set_margin_bottom(12); + signup_key_fingerprint.set_margin_start(12); + signup_key_fingerprint.set_margin_end(12); + let signup_key_card = gtk::Box::new(Orientation::Vertical, 4); + signup_key_card.add_css_class("card"); + signup_key_card.set_visible(false); + signup_key_card.append(&signup_key_value); + signup_key_card.append(&signup_key_fingerprint); + signup_server.append(&signup_key_card); + let signup_key_hint = label(&i18n::t("trust-fingerprint-hint"), "dim"); + signup_key_hint.set_wrap(true); + signup_key_hint.set_visible(false); + signup_server.append(&signup_key_hint); + + let signup_key_button = button(&i18n::t("signup-fetch-key-button"), "pill"); + let signup_start_over = button(&i18n::t("signup-start-over-button"), "pill-quiet"); + signup_server.append(&signup_key_button); + signup_server.append(&signup_start_over); + stack.add_named(¢er(&signup_server), Some("signup-server")); + + // signup: step 2 — bind a username, or recall an existing address + let signup_account = gtk::Box::new(Orientation::Vertical, 12); + signup_account.append(&label(&i18n::t("signup-account-title"), "subtitle")); + let signup_mode_new = gtk::ToggleButton::builder() + .label(i18n::t("signup-mode-new-label")) + .active(true) + .hexpand(true) .build(); - signup_offer_row.set_subtitle_lines(2); - let signup_offer_pin = button("Pin", "accent"); - signup_offer_pin.set_valign(Align::Center); - let signup_offer_discard = button("Discard", ""); - signup_offer_discard.set_valign(Align::Center); - signup_offer_row.add_suffix(&signup_offer_discard); - signup_offer_row.add_suffix(&signup_offer_pin); - signup_offer_list.append(&signup_offer_row); - signup.append(&signup_offer_list); - let register_button = button("Register", "pill"); - let recall_button = button("I already have this address", "pill-quiet"); - signup.append(®ister_button); - signup.append(&recall_button); - let signup_back = button("Back", "quiet"); - signup_back.set_visible(false); - signup.append(&signup_back); - stack.add_named(¢er(&signup), Some("signup")); + let signup_mode_existing = gtk::ToggleButton::builder() + .label(i18n::t("signup-mode-existing-label")) + .hexpand(true) + .build(); + signup_mode_existing.set_group(Some(&signup_mode_new)); + let signup_mode_box = gtk::Box::new(Orientation::Horizontal, 0); + signup_mode_box.add_css_class("linked"); + signup_mode_box.set_homogeneous(true); + signup_mode_box.append(&signup_mode_new); + signup_mode_box.append(&signup_mode_existing); + signup_account.append(&signup_mode_box); + let signup_account_group = adw::PreferencesGroup::new(); + let signup_user = adw::EntryRow::builder() + .title(i18n::t("signup-user-label")) + .build(); + let signup_invite = adw::EntryRow::builder() + .title(i18n::t("signup-invite-label")) + .build(); + signup_account_group.add(&signup_user); + signup_account_group.add(&signup_invite); + signup_account.append(&signup_account_group); + let register_button = button(&i18n::t("signup-register-button"), "pill"); + let recall_button = button(&i18n::t("signup-recall-button"), "pill"); + signup_account.append(®ister_button); + signup_account.append(&recall_button); + let signup_step_back = button(&i18n::t("action-back"), "quiet"); + signup_account.append(&signup_step_back); + stack.add_named(¢er(&signup_account), Some("signup-account")); // --- status bar ------------------------------------------------- // One fixed line at the bottom: the spinner and the running @@ -778,7 +1137,7 @@ impl CarrierWidgets { spinner.set_visible(false); let status_label = label("", "caption"); status_label.set_hexpand(true); - let cancel_button = button("Cancel", ""); + let cancel_button = button(&i18n::t("action-cancel"), ""); cancel_button.set_visible(false); status_bar.append(&spinner); status_bar.append(&status_label); @@ -890,7 +1249,10 @@ impl CarrierWidgets { gtk::glib::Propagation::Stop }); + add_header.connect_clicked(input(Message::ComposeHeaderAdded)); + compose_send_button.connect_clicked(input(Message::SendPressed)); + compose_pin_button.connect_clicked(input(Message::PinServerAction)); compose_cancel.connect_clicked(input(Message::ComposeClosed)); let to_sender = sender.clone(); compose_to.connect_changed(move |entry| { @@ -906,7 +1268,17 @@ impl CarrierWidgets { }); own_row.connect_clicked(input(Message::OwnSelected)); - copy_export.connect_clicked(input(Message::CopyExport)); + let switch_sender = sender.clone(); + let switch_popover = accounts_popover.clone(); + accounts_list.connect_row_activated(move |_, row| { + switch_popover.popdown(); + switch_sender.input(Message::AccountSwitch(row.widget_name().to_string())); + }); + let add_sender = sender.clone(); + add_account.connect_clicked(move |_| { + accounts_popover.popdown(); + add_sender.input(Message::AccountAdd); + }); import_button.connect_clicked(input(Message::ContactImportPressed)); let import_sender = sender.clone(); contact_import.connect_changed(move |entry| { @@ -918,24 +1290,73 @@ impl CarrierWidgets { }); rotate_button.connect_clicked(input(Message::RotatePressed)); - learn_button.connect_clicked(input(Message::SettingsLearnKey)); - offer_pin.connect_clicked(input(Message::PinAccept)); - signup_offer_pin.connect_clicked(input(Message::PinAccept)); - offer_discard.connect_clicked(input(Message::PinDiscard)); - signup_offer_discard.connect_clicked(input(Message::PinDiscard)); - export_button.connect_clicked(input(Message::ExportPressed)); - import_backup.connect_clicked(input(Message::ImportPressed)); + reset_button.connect_clicked(input(Message::ResetPressed)); + secret_reveal.connect_clicked(input(Message::SecretRevealToggled)); + secret_copy.connect_clicked(input(Message::CopySecret)); let timeout_sender = sender.clone(); timeout_row.connect_value_notify(move |row| { timeout_sender.input(Message::TimeoutChanged((row.value() as u64).to_string())) }); - let import_body_sender = sender.clone(); - import_body.connect_changed(move |buffer| { - import_body_sender.input(Message::ImportBodyChanged(buffer_text(buffer))) + let keep_mail_sender = sender.clone(); + keep_mail_check.connect_toggled(move |check| { + keep_mail_sender.input(Message::KeepMailChanged(check.is_active())) + }); + let strict_sender = sender.clone(); + strict_check.connect_toggled(move |check| { + strict_sender.input(Message::StrictPinningChanged(check.is_active())) + }); + // Export/Import go straight to a native file dialog rather than a + // Message — the chosen path only matters for this one call, and + // round-tripping it through the model would gain nothing. + let export_sender = sender.clone(); + let export_window = root.clone(); + export_row.connect_activated(move |_| { + let dialog = gtk::FileDialog::builder() + .title(i18n::t("backup-export-dialog-title")) + .initial_name("carrier-backup.gsmol") + .build(); + let sender = export_sender.clone(); + dialog.save( + Some(&export_window), + gtk::gio::Cancellable::NONE, + move |result| { + if let Ok(file) = result { + if let Some(path) = file.path() { + sender.input(Message::ExportBackupTo(path)); + } + } + }, + ); + }); + let backup_import_sender = sender.clone(); + let backup_import_window = root.clone(); + import_row.connect_activated(move |_| { + let dialog = gtk::FileDialog::builder() + .title(i18n::t("backup-import-dialog-title")) + .build(); + let sender = backup_import_sender.clone(); + dialog.open( + Some(&backup_import_window), + gtk::gio::Cancellable::NONE, + move |result| { + if let Ok(file) = result { + if let Some(path) = file.path() { + if let Ok(text) = std::fs::read_to_string(&path) { + sender.input(Message::ImportBackupFrom(text)); + } + } + } + }, + ); }); create_button.connect_clicked(input(Message::OnboardCreate)); restore_button.connect_clicked(input(Message::OnboardRestore)); + onboard_cancel.connect_clicked(input(Message::AccountAddCancelled)); + let reuse_sender = sender.clone(); + onboard_reuse_list.connect_row_activated(move |_, row| { + reuse_sender.input(Message::OnboardReuse(row.widget_name().to_string())); + }); restore_back.connect_clicked(input(Message::OnboardBack)); created_back.connect_clicked(input(Message::OnboardBack)); saved_button.connect_clicked(input(Message::OnboardSeedSaved)); @@ -961,14 +1382,23 @@ impl CarrierWidgets { signup_invite.connect_changed(move |entry| { invite_sender.input(Message::SignupInviteChanged(entry.text().to_string())) }); - let key_sender = sender.clone(); - signup_key.connect_changed(move |entry| { - key_sender.input(Message::SignupKeyChanged(entry.text().to_string())) - }); - signup_learn.connect_clicked(input(Message::SignupLearnKey)); + signup_key_button.connect_clicked(input(Message::SignupKeyAction)); + signup_start_over.connect_clicked(input(Message::SignupStartOver)); + signup_step_back.connect_clicked(input(Message::SignupStepBack)); register_button.connect_clicked(input(Message::SignupRegister)); recall_button.connect_clicked(input(Message::SignupRecall)); - signup_back.connect_clicked(input(Message::SignupBack)); + let mode_new_sender = sender.clone(); + signup_mode_new.connect_toggled(move |btn| { + if btn.is_active() { + mode_new_sender.input(Message::SignupModeChanged(SignupMode::New)); + } + }); + let mode_existing_sender = sender.clone(); + signup_mode_existing.connect_toggled(move |btn| { + if btn.is_active() { + mode_existing_sender.input(Message::SignupModeChanged(SignupMode::Existing)); + } + }); CarrierWidgets { window: root.clone(), @@ -984,32 +1414,61 @@ impl CarrierWidgets { mail_list, list_empty, list_empty_fetch, + list_empty_hint, article_stack, article_subject, article_meta, + article_headers, article_view, article_body, actions, compose_to, + compose_headers, compose_subject, compose_body, compose_send, + compose_pin_card, + compose_pin_title, + compose_pin_body, + compose_pin_key, + compose_pin_fingerprint, + compose_pin_hint, + compose_pin_button, sidebar_own, sidebar_contacts: contacts_list, + accounts_menu, + accounts_list, detail_share, detail_copy, detail_qr, - identity_values, - offer_group, - offer_row, - pins_group, - pin_rows: Vec::new(), + identity_rows, + secret_row, + secret_reveal, + host_row, + public_key_row, + rotations_value, + keep_mail_check, + strict_check, timeout_row, - backup_label, onboard_seed_label, - signup_back, - signup_offer_list, - signup_offer_row, + onboard_seed_entry, + onboard_reuse, + onboard_reuse_list, + onboard_cancel, + signup_key_button, + signup_key_card, + signup_key_value, + signup_key_fingerprint, + signup_key_hint, + signup_start_over, + signup_step_back, + signup_mode_new, + signup_mode_existing, + signup_host, + signup_user, + signup_invite, + register_button, + recall_button, spinner, status_label, cancel_button, @@ -1039,10 +1498,15 @@ impl Component for Carrier { sender: ComponentSender, ) -> ComponentParts { let (model, op) = Carrier::boot(init); - let widgets = CarrierWidgets::new(&root, &sender); + let mut widgets = CarrierWidgets::new(&root, &sender); if let Some(op) = op { spawn_op(&model, op, &sender); } + // `update_view` runs only after a message, and a clean install + // boots with none queued, so the first paint happens here — + // otherwise the stack sits on its default page until the first + // click flips it to the page the model opened with. + render(&model, &mut widgets, &sender); ComponentParts { model, widgets } } @@ -1075,31 +1539,27 @@ fn spawn_op(model: &Carrier, op: PendingOp, sender: &ComponentSender) { let store = model.store.clone(); let master = model.master.unwrap_or([0u8; KEY_LEN]); let timeout = model.timeout; + let keep_mail = model.keep_mail; match op { PendingOp::Snapshot { read } => sender.spawn_command(move |out| { let _ = out.send(OpResult::SnapshotLoaded(ops::snapshot( &store, &master, &read, ))); }), - PendingOp::Register { addr, invite, key } => sender.spawn_command(move |out| { - let res = if key.is_empty() { - ops::register(&store, &master, &addr, invite.as_deref(), timeout) - } else { - ops::parse_key(&key).and_then(|key| { - ops::pin(&store, &addr, &key)?; - ops::register(&store, &master, &addr, invite.as_deref(), timeout) - }) - }; - let _ = out.send(OpResult::Generic(res.map(|_| "registered".to_string()))); + PendingOp::Register { addr, invite } => sender.spawn_command(move |out| { + let res = ops::register(&store, &master, &addr, invite.as_deref(), timeout); + let _ = out.send(OpResult::Generic( + res.map(|_| i18n::t("status-registered-note")), + )); }), PendingOp::Restore { addr } => sender.spawn_command(move |out| { let res = ops::restore(&store, &master, &addr, timeout) - .map(|index| format!("restored at rotation {index}")); + .map(|index| i18n::t1("status-restored-note", "index", index as i64)); let _ = out.send(OpResult::Generic(res)); }), PendingOp::LearnKey { addr } => sender.spawn_command(move |out| { - let offered = - ops::learn_key(&store, &addr, 30).map(|key| key.map(|key| (addr.clone(), key))); + let offered = ops::learn_key(&store, &addr, timeout) + .map(|key| key.map(|key| (addr.clone(), key))); let _ = out.send(OpResult::PinOffered(offered)); }), PendingOp::Pin { addr, key } => sender.spawn_command(move |out| { @@ -1119,7 +1579,7 @@ fn spawn_op(model: &Carrier, op: PendingOp, sender: &ComponentSender) { }); sender.spawn_command(move |out| { let _ = out.send(OpResult::Generic(ops::fetch( - &store, &master, cancel, timeout, + &store, &master, cancel, keep_mail, timeout, ))); }); } @@ -1128,6 +1588,7 @@ fn spawn_op(model: &Carrier, op: PendingOp, sender: &ComponentSender) { subject, body, reply_to, + headers, } => sender.spawn_command(move |out| { let res = ops::send( &store, @@ -1140,6 +1601,7 @@ fn spawn_op(model: &Carrier, op: PendingOp, sender: &ComponentSender) { }, &body, reply_to.as_deref(), + &headers, timeout, ); let _ = out.send(OpResult::Generic(res)); @@ -1150,42 +1612,42 @@ fn spawn_op(model: &Carrier, op: PendingOp, sender: &ComponentSender) { everywhere, } => sender.spawn_command(move |out| { let res = ops::delete(&store, &master, &id, folder, everywhere, timeout) - .map(|_| "deleted".to_string()); + .map(|_| i18n::t("status-deleted-note")); let _ = out.send(OpResult::Generic(res)); }), PendingOp::Accept { address, identity } => sender.spawn_command(move |out| { let res = ops::accept_contact(&store, &master, &address, &identity, timeout) - .map(|_| format!("accepted {address}")); + .map(|_| i18n::t1("status-accepted-note", "address", address.clone())); let _ = out.send(OpResult::Generic(res)); }), PendingOp::Block { address } => sender.spawn_command(move |out| { let res = ops::block_contact(&store, &master, &address, timeout).map(|blocked| { if blocked { - format!("blocked {address}") + i18n::t1("status-blocked-note", "address", address.clone()) } else { - format!("{address} was not blocked") + i18n::t1("status-not-blocked-note", "address", address.clone()) } }); let _ = out.send(OpResult::Generic(res)); }), PendingOp::ImportContact { uri } => sender.spawn_command(move |out| { let res = ops::import_contact(&store, &uri) - .map(|(address, _)| format!("imported {address} (verified)")); + .map(|(address, _)| i18n::t1("status-imported-note", "address", address)); let _ = out.send(OpResult::Generic(res)); }), PendingOp::Rotate => sender.spawn_command(move |out| { - let res = ops::rotate(&store, &master, timeout) - .map(|(index, key)| format!("rotated to index {index}; new key {}…", &key[..12])); + let res = ops::rotate(&store, &master, timeout).map(|(index, key)| { + let mut args = fluent_bundle::FluentArgs::new(); + args.set("index", index as i64); + args.set("key_prefix", key[..12].to_string()); + i18n::t_args("status-rotated-note", Some(&args)) + }); let _ = out.send(OpResult::Generic(res)); }), - PendingOp::Unpin { label } => sender.spawn_command(move |out| { - let res = ops::unpin(&store, &label).map(|_| format!("unpinned {label}")); - let _ = out.send(OpResult::Generic(res)); - }), - PendingOp::Export { dir } => sender.spawn_command(move |out| { - let exported = ops::export_backup(&store, &master, &dir) - .map(|(path, text)| (format!("backup written to {}", path.display()), text)); - let _ = out.send(OpResult::Exported(exported)); + PendingOp::Export { path } => sender.spawn_command(move |out| { + let _ = out.send(OpResult::Generic(ops::export_backup( + &store, &master, &path, + ))); }), PendingOp::ImportBackup { text } => sender.spawn_command(move |out| { let _ = out.send(OpResult::Generic(ops::import_backup( @@ -1203,15 +1665,87 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender model only, so the view never fights the user. + // Prefill entries once after a reply, write or draft reopen; + // afterwards typing flows entry -> model only, so the view never + // fights the user. The fresh flag also rebuilds the header rows, + // which otherwise sync on count changes alone. + let mut compose_fresh = false; if model.compose_fresh.take() { + compose_fresh = true; if let Some(compose) = &model.compose { w.compose_to.set_text(&compose.to); w.compose_subject.set_text(&compose.subject); w.compose_body.set_text(&compose.body); } } + let rows = model.compose.as_ref().map_or(0, |c| c.headers.len()); + let mut current = 0; + let mut child = w.compose_headers.first_child(); + while let Some(item) = child { + current += 1; + child = item.next_sibling(); + } + if compose_fresh || current != rows { + let added = rows > current; + clear_list(&w.compose_headers); + if let Some(compose) = &model.compose { + let mut last_entry = None; + for (index, text) in compose.headers.iter().enumerate() { + let (row, entry) = compose_header_row(index, text, sender); + last_entry = Some(entry); + w.compose_headers.append(&row); + } + // A freshly appended row is the one being typed into. + if added { + if let Some(entry) = last_entry { + entry.grab_focus(); + } + } + } + } + + // The pin card follows the recipient: a prompt armed for a different + // address simply isn't shown, so editing To retires it with no + // explicit clearing. + let compose_prompt = model.compose.as_ref().and_then(|compose| { + let typed = ops::parse_address(compose.to.trim()).ok()?.short(); + model + .pin_prompt + .as_ref() + .filter(|prompt| prompt.addr.short() == typed) + }); + w.compose_pin_card.set_visible(compose_prompt.is_some()); + if let Some(prompt) = compose_prompt { + w.compose_pin_title.set_text(&i18n::t1( + "compose-pin-title", + "host", + trust_label(&prompt.addr.host, prompt.addr.port), + )); + w.compose_pin_body.set_text(&i18n::t1( + "compose-pin-body", + "address", + prompt.addr.short(), + )); + match prompt.offered { + Some(key) => { + w.compose_pin_key.set_text(&b32(&key)); + w.compose_pin_fingerprint.set_text(&fingerprint(&key)); + w.compose_pin_button + .set_label(&i18n::t("compose-pin-button-send")); + } + None => w + .compose_pin_button + .set_label(&i18n::t("compose-pin-button-fetch")), + } + let fetched = prompt.offered.is_some(); + for line in [ + &w.compose_pin_key, + &w.compose_pin_fingerprint, + &w.compose_pin_hint, + ] { + line.set_visible(fetched); + } + } // Header and sidebar identity. let address = model @@ -1267,7 +1801,10 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender "onboard-created", OnboardMode::Restore => "onboard-restore", }, - Page::Signup => "signup", + Page::Signup => match model.signup.step { + SignupStep::Server => "signup-server", + SignupStep::Account => "signup-account", + }, Page::Mail => "mail", Page::Settings => "settings", } @@ -1277,33 +1814,35 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender ( - "mail-read-symbolic", - "Inbox is empty", - "Fetch to check the mailbox.", + None, + "mail-inbox-empty-title", + "mail-inbox-empty-description", ), Folder::Requests => ( - "contact-new-symbolic", - "No requests", - "Mail from senders you have not accepted yet arrives here.", + Some("contact-new-symbolic"), + "mail-requests-empty-title", + "mail-requests-empty-description", ), Folder::Sent => ( - "mail-send-symbolic", - "Nothing sent yet", - "Messages you send keep a sealed copy here.", + Some("mail-send-symbolic"), + "mail-sent-empty-title", + "mail-sent-empty-description", ), Folder::Drafts => ( - "document-edit-symbolic", - "No drafts", - "A compose closed from the sidebar is kept here.", + Some("document-edit-symbolic"), + "mail-drafts-empty-title", + "mail-drafts-empty-description", ), }; - w.list_empty.set_icon_name(Some(icon)); - w.list_empty.set_title(title); - w.list_empty.set_description(Some(description)); - w.list_empty_fetch - .set_visible(model.folder == Folder::Inbox); + w.list_empty.set_icon_name(icon); + w.list_empty.set_title(&i18n::t(title_id)); + w.list_empty.set_description(Some(&i18n::t(description_id))); + let inbox_empty = model.folder == Folder::Inbox; + w.list_empty_fetch.set_visible(inbox_empty); + w.list_empty_hint + .set_visible(inbox_empty && !model.keep_mail); w.list_stack .set_visible_child_name(if rows.is_empty() { "empty" } else { "list" }); let mut selected_row = None; @@ -1345,8 +1884,11 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender { - let block = icon_label_button("action-unavailable-symbolic", "Block", "danger"); + let block = icon_label_button( + "action-unavailable-symbolic", + &i18n::t("action-block"), + "danger", + ); let msg = Message::ContactBlock(contact.address.clone()); let block_sender = sender.clone(); block.connect_clicked(move |_| block_sender.input(msg.clone())); w.actions.append(&block); } Some(false) => { - let unblock = icon_label_button("object-select-symbolic", "Unblock", "accent"); + let unblock = icon_label_button( + "object-select-symbolic", + &i18n::t("action-unblock"), + "accent", + ); let msg = Message::ContactUnblock(contact.address.clone()); let unblock_sender = sender.clone(); unblock.connect_clicked(move |_| unblock_sender.input(msg.clone())); w.actions.append(&unblock); } None => { - let accept = icon_label_button("object-select-symbolic", "Accept", "accent"); + let accept = icon_label_button( + "object-select-symbolic", + &i18n::t("action-accept"), + "accent", + ); let msg = Message::ContactAccept(contact.address.clone(), contact.key.clone()); let accept_sender = sender.clone(); accept.connect_clicked(move |_| accept_sender.input(msg.clone())); @@ -1412,16 +2017,16 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender{address}") + let from = if known { + format!("{address}") } else { - format!("{label} {address}") + address }; - meta.push_str(&format!(" · {} UTC", escape(&ops::when(msg.time)))); - meta.push_str(&format!(" · id {}…", &msg.id[..msg.id.len().min(8)])); - if msg.kept { - meta.push_str(" · a server copy still exists"); - } + let mail_meta_id = if msg.kept { + "mail-meta-line-yes" + } else { + "mail-meta-line-no" + }; + let mut meta_args = fluent_bundle::FluentArgs::new(); + meta_args.set("label", label); + meta_args.set("from", from); + meta_args.set("time", escape(&ops::when(msg.time))); + meta_args.set("id", msg.id[..msg.id.len().min(8)].to_string()); + let meta = i18n::t_args(mail_meta_id, Some(&meta_args)); w.article_meta.set_markup(&meta); + let headers: Vec = msg + .headers + .iter() + .map(|(key, value)| format!("{key}: {value}")) + .collect(); + w.article_headers.set_visible(!headers.is_empty()); + w.article_headers.set_text(&headers.join("\n")); w.article_body.set_text(&msg.body); clear(&w.actions); - let reply = icon_label_button("mail-reply-sender-symbolic", "Reply", ""); + let reply = + icon_label_button("mail-reply-sender-symbolic", &i18n::t("action-reply"), ""); reply.connect_clicked(input(Message::ReplyPressed)); w.actions.append(&reply); if *folder == Folder::Requests { if msg.reply_to.is_some() { - let accept = icon_label_button("object-select-symbolic", "Accept", "accent"); + let accept = icon_label_button( + "object-select-symbolic", + &i18n::t("action-accept"), + "accent", + ); accept.connect_clicked(input(Message::AcceptPressed)); - let block = icon_label_button("action-unavailable-symbolic", "Block", "danger"); + let block = icon_label_button( + "action-unavailable-symbolic", + &i18n::t("action-block"), + "danger", + ); block.connect_clicked(input(Message::BlockPressed)); w.actions.append(&accept); w.actions.append(&block); } else { w.actions.append(&crate::view::label( - "no reply address: cannot accept or block", + &i18n::t("mail-no-reply-address"), "caption", )); } @@ -1464,7 +2091,8 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender()) - .unwrap_or_default(); - w.backup_label.set_text(&backup_text); // Onboarding. if model.onboard.mode == OnboardMode::Created { @@ -1580,29 +2240,71 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender Some edge: `render` // runs after every message and an alert dialog is modal, so presenting // again would stack a second copy over the first. match (&model.dialog, w.dialog.is_some()) { (Some(dialog), false) => { - let rotating = matches!(dialog, Dialog::Rotate); + let kind = dialog.kind(); let alert = match dialog { Dialog::Delete { kept, .. } => { let alert = adw::AlertDialog::new( - Some("Delete this message?"), - Some(if *kept { - "Deleting it here leaves the server's copy in place. Deleting it everywhere asks the server to drop that copy too." + Some(&i18n::t("delete-dialog-title")), + Some(&i18n::t(if *kept { + "delete-dialog-body-kept" } else { - "The sealed copy in the local store is removed." - }), + "delete-dialog-body-gone" + })), ); - alert.add_response("cancel", "Cancel"); - alert.add_response("here", "Delete"); + alert.add_response("cancel", &i18n::t("action-cancel")); + alert.add_response("here", &i18n::t("action-delete")); alert.set_response_appearance("here", adw::ResponseAppearance::Destructive); if *kept { - alert.add_response("everywhere", "Delete Everywhere"); + alert.add_response( + "everywhere", + &i18n::t("delete-dialog-everywhere-button"), + ); alert.set_response_appearance( "everywhere", adw::ResponseAppearance::Destructive, @@ -1612,25 +2314,86 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender { let alert = adw::AlertDialog::new( - Some("Rotate the identity?"), - Some("The old key stays derivable from the seed, but the rotation index never moves back."), + Some(&i18n::t("rotate-dialog-title")), + Some(&i18n::t("advanced-rotations-description")), ); - alert.add_response("cancel", "Cancel"); - alert.add_response("rotate", "Rotate"); + alert.add_response("cancel", &i18n::t("action-cancel")); + alert.add_response("rotate", &i18n::t("advanced-rotate-button")); alert.set_response_appearance("rotate", adw::ResponseAppearance::Destructive); alert } + Dialog::Reset => { + let alert = adw::AlertDialog::new( + Some(&i18n::t("reset-dialog-title")), + Some(&i18n::t("advanced-logout-description")), + ); + alert.add_response("cancel", &i18n::t("action-cancel")); + alert.add_response("reset", &i18n::t("advanced-logout-button")); + alert.set_response_appearance("reset", adw::ResponseAppearance::Destructive); + alert + } + Dialog::Reply { rows, .. } => { + let list = rows + .iter() + .map(String::as_str) + .collect::>() + .join("\n"); + let alert = adw::AlertDialog::new( + Some(&i18n::t("reply-dialog-title")), + Some(&i18n::t1("reply-dialog-body", "list", list)), + ); + alert.add_response("cancel", &i18n::t("reply-dialog-cancel-button")); + alert.add_response("without", &i18n::t("reply-dialog-without-button")); + alert.add_response("copy", &i18n::t("reply-dialog-copy-button")); + alert.set_response_appearance("copy", adw::ResponseAppearance::Suggested); + alert + } + Dialog::KeyChange { + address, + known_fingerprint, + offered_fingerprint, + .. + } => { + let mut args = fluent_bundle::FluentArgs::new(); + args.set("address", address.clone()); + args.set("known_fingerprint", known_fingerprint.clone()); + args.set("offered_fingerprint", offered_fingerprint.clone()); + let alert = adw::AlertDialog::new( + Some(&i18n::t("key-change-dialog-title")), + Some(&i18n::t_args("key-change-dialog-body", Some(&args))), + ); + alert.add_response("cancel", &i18n::t("action-cancel")); + alert.add_response("replace", &i18n::t("key-change-dialog-replace-button")); + alert.set_response_appearance("replace", adw::ResponseAppearance::Destructive); + alert + } + }; + // The reply dialog carries its own default: Enter answers the + // question instead of cancelling the reply the user asked for. + let close_default = if kind == DialogKind::Reply { + "without" + } else { + "cancel" }; alert.set_close_response("cancel"); - alert.set_default_response(Some("cancel")); + alert.set_default_response(Some(close_default)); let response_sender = sender.clone(); alert.connect_response(None, move |_, response| { - response_sender.input(match (rotating, response) { - (true, "rotate") => Message::RotateConfirmed, - (true, _) => Message::RotateCancelled, - (false, "here") => Message::DeleteConfirmed(false), - (false, "everywhere") => Message::DeleteConfirmed(true), - (false, _) => Message::DeleteCancelled, + // Anything that is not an explicit confirmation — a + // Cancel, Escape, or the close response — cancels. + response_sender.input(match (kind, response) { + (DialogKind::Delete, "here") => Message::DeleteConfirmed(false), + (DialogKind::Delete, "everywhere") => Message::DeleteConfirmed(true), + (DialogKind::Delete, _) => Message::DeleteCancelled, + (DialogKind::Rotate, "rotate") => Message::RotateConfirmed, + (DialogKind::Rotate, _) => Message::RotateCancelled, + (DialogKind::Reset, "reset") => Message::ResetConfirmed, + (DialogKind::Reset, _) => Message::ResetCancelled, + (DialogKind::Reply, "copy") => Message::ReplyConfirmed(true), + (DialogKind::Reply, "without") => Message::ReplyConfirmed(false), + (DialogKind::Reply, _) => Message::ReplyCancelled, + (DialogKind::KeyChange, "replace") => Message::KeyChangeConfirmed, + (DialogKind::KeyChange, _) => Message::KeyChangeCancelled, }); }); alert.present(Some(&w.window)); @@ -1658,9 +2421,15 @@ fn render(model: &Carrier, w: &mut CarrierWidgets, sender: &ComponentSender { let inbox = model.lists.first().map(|rows| rows.len()).unwrap_or(0); - format!("fetching… {inbox} in inbox") + i18n::t1("status-fetching-progress", "count", inbox as i64) } - (Some(busy), false) => format!("{busy}…"), + (Some(busy), false) => match busy.as_str() { + "fetching" => i18n::t("status-busy-fetching"), + "refreshing" => i18n::t("status-busy-refreshing"), + "registering" => i18n::t("status-busy-registering"), + "restoring" => i18n::t("status-busy-restoring"), + other => format!("{other}…"), + }, (None, _) => model.status.clone().unwrap_or_default(), }); let errored = model.status_error && model.busy.is_none(); @@ -1683,7 +2452,7 @@ fn mail_row(folder: Folder, row: &Row) -> adw::ActionRow { "mail-read-symbolic" })); let subject = if row.subject.is_empty() { - "(no subject)".to_string() + i18n::t("mail-no-subject") } else { row.subject.clone() }; @@ -1711,6 +2480,60 @@ fn mail_row(folder: Folder, row: &Row) -> adw::ActionRow { item } +/// One compose header row: a `Key: value` entry plus a remove button. +/// The row carries its own validation state — anything the send would +/// reject is tinted and explained right where it is typed, and the +/// empty rows the send skips are left quiet. +fn compose_header_row<'a>( + index: usize, + text: &str, + sender: &ComponentSender, +) -> (gtk::ListBoxRow, gtk::Entry) { + let entry = gtk::Entry::new(); + entry.set_hexpand(true); + entry.set_placeholder_text(Some(&i18n::t("compose-header-placeholder"))); + entry.set_text(text); + let style = |entry: >k::Entry, text: &str| match crate::ops::header_row(text) { + Err(reason) => { + entry.add_css_class("error"); + entry.set_tooltip_text(Some(&reason)); + } + Ok(_) => { + entry.remove_css_class("error"); + entry.set_tooltip_text(None); + } + }; + style(&entry, text); + let change_sender = sender.clone(); + let style_entry = entry.clone(); + entry.connect_changed(move |changed| { + let text = changed.text().to_string(); + style(&style_entry, &text); + change_sender.input(Message::ComposeHeaderChanged(index, text)); + }); + + let remove = icon_button( + "user-trash-symbolic", + &i18n::t("compose-header-remove-tooltip"), + ); + let remove_sender = sender.clone(); + remove.connect_clicked(move |_| { + remove_sender.input(Message::ComposeHeaderRemoved(index)); + }); + + let line = gtk::Box::new(Orientation::Horizontal, 6); + line.set_margin_top(6); + line.set_margin_bottom(6); + line.set_margin_start(12); + line.set_margin_end(6); + line.append(&entry); + line.append(&remove); + + let row = gtk::ListBoxRow::new(); + row.set_child(Some(&line)); + (row, entry) +} + /// One contact in the sidebar's bottom panel: the address over its trust /// state; activating it opens the detail pane. fn sidebar_contact_row(contact: &Contact) -> adw::ActionRow { @@ -1728,7 +2551,11 @@ fn sidebar_contact_row(contact: &Contact) -> adw::ActionRow { /// The detail view's body: the three lines an address is made of, in /// the column-aligned form a key block wants. fn detail_body(address: &str, key: &str, fingerprint: &str) -> String { - format!("key {key}\nfingerprint {fingerprint}\nsmol://{address}/{key}") + format!( + "{:<14}{key}\n{:<14}{fingerprint}\nsmol://{address}/{key}", + i18n::t("detail-key-label"), + i18n::t("detail-fingerprint-label"), + ) } /// Puts one URI's QR code into the detail header's share popover. A diff --git a/windows/bundle.sh b/windows/bundle.sh new file mode 100644 index 0000000..c8ac496 --- /dev/null +++ b/windows/bundle.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Build carrier and bundle the result: carrier.exe plus the GTK runtime +# into dist/, then dist/ into carrier-windows-.zip. +# +# Run from the carrier checkout inside the MSYS2 MINGW64 shell (or with +# the MINGW64 toolchain on PATH — windows/setup.sh installs the deps, +# and the forgejo Windows runner host already carries them). +set -euo pipefail + +say() { printf '\n==> %s\n' "$*"; } +die() { printf '\n!! %s\n' "$*" >&2; exit 1; } + +say "building carrier (release; the first build takes a while)" +cargo build --release --locked || die "cargo build failed" + +say "bundling the runtime" +rm -rf dist +mkdir -p dist/share/glib-2.0/schemas \ + dist/share/icons/hicolor/512x512/apps \ + dist/share/icons/hicolor/256x256/apps \ + dist/share/icons/hicolor/128x128/apps +cp target/release/carrier.exe dist/ +for dll in $(ldd target/release/carrier.exe | awk '/mingw64/ {print $3}'); do + cp "$dll" dist/ || die "copying $dll failed" +done +[ "$(ls dist/*.dll | wc -l)" -gt 0 ] || die "no DLLs collected — ldd found none under /mingw64" +cp /mingw64/share/glib-2.0/schemas/* dist/share/glib-2.0/schemas/ +glib-compile-schemas dist/share/glib-2.0/schemas/ +cp -r /mingw64/share/icons/Adwaita dist/share/icons/ +cp -r /mingw64/share/icons/hicolor dist/share/icons/ +cp data/icons/com.randogoth.carrier.png dist/share/icons/hicolor/512x512/apps/ +cp data/icons/com.randogoth.carrier-256.png dist/share/icons/hicolor/256x256/apps/ +cp data/icons/com.randogoth.carrier-128.png dist/share/icons/hicolor/128x128/apps/ + +say "zipping" +version=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1) +rm -f "carrier-windows-$version.zip" +(cd dist && zip -qr "../carrier-windows-$version.zip" .) diff --git a/windows/carrier.iss b/windows/carrier.iss new file mode 100644 index 0000000..e9fc5cb --- /dev/null +++ b/windows/carrier.iss @@ -0,0 +1,42 @@ +; carrier Windows installer. Packs the same portable bundle windows/ +; bundle.sh produces (dist/) into a classic setup.exe: Program Files, +; Start Menu shortcut, optional desktop icon, Apps & Features uninstall +; entry. Built by windows/installer.sh, which passes /DVersion= from +; Cargo.toml. +; +; Not yet wired into the forgejo release job - deliberately local until +; the experience is signed off. + +#ifndef Version + #error Pass the version: ISCC /DVersion=0.2.0 windows/carrier.iss +#endif + +[Setup] +AppId={{345BADA4-146B-4F57-B7D3-E9FD5D664F4B} +AppName=carrier +AppVersion={#Version} +AppPublisher=randogoth +DefaultDirName={autopf}\carrier +DefaultGroupName=carrier +; Next to the portable zip (paths relative to this script's directory). +OutputDir=.. +OutputBaseFilename=carrier-windows-{#Version}-setup +Compression=lzma2/max +SolidCompression=yes +WizardStyle=modern +ArchitecturesInstallIn64BitMode=x64compatible +UninstallDisplayName=carrier + +[Tasks] +Name: "desktopicon"; Description: "Create a &desktop icon"; GroupDescription: "Additional icons:" + +[Files] +Source: "..\dist\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion + +[Icons] +; Shortcut icons come from carrier.exe's embedded .ico resource. +Name: "{group}\carrier"; Filename: "{app}\carrier.exe" +Name: "{autodesktop}\carrier"; Filename: "{app}\carrier.exe"; Tasks: desktopicon + +[Run] +Filename: "{app}\carrier.exe"; Description: "Launch carrier"; Flags: nowait postinstall skipifsilent diff --git a/windows/installer.sh b/windows/installer.sh new file mode 100644 index 0000000..906b8ef --- /dev/null +++ b/windows/installer.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Pack the dist/ bundle into carrier-windows--setup.exe. +# +# Run from the carrier checkout after windows/bundle.sh has produced +# dist/. Requires Inno Setup 7 (per-user install, which its own +# installer's "just me" option produces). +set -euo pipefail + +say() { printf '\n==> %s\n' "$*"; } +die() { printf '\n!! %s\n' "$*" >&2; exit 1; } + +# MSYS2's login shells prune LOCALAPPDATA from the environment, so fall +# back to cygpath (CSIDL 28 = local AppData of the current user). +if [ -n "${LOCALAPPDATA:-}" ]; then + appdata=$(cygpath -u "$LOCALAPPDATA") +else + appdata=$(cygpath -F 28) +fi +ISCC="$appdata/Programs/Inno Setup 7/ISCC.exe" +[ -f "$ISCC" ] || die "Inno Setup not found at $ISCC — install it from https://jrsoftware.org/isdl.php" + +[ -d dist ] || die "no dist/ bundle — run windows/bundle.sh first" + +version=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1) + +say "compiling the installer" +# MSYS2_ARG_CONV_EXCL stops MSYS2 mangling /DVersion into a path. +MSYS2_ARG_CONV_EXCL="*" "$ISCC" /DVersion="$version" windows/carrier.iss \ + || die "ISCC failed" + +say "done — carrier-windows-$version-setup.exe (in the checkout root)" diff --git a/windows/setup.sh b/windows/setup.sh new file mode 100755 index 0000000..f6a591d --- /dev/null +++ b/windows/setup.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Windows build in one command. Run inside the MSYS2 MINGW64 shell from +# the carrier checkout: it installs the dependencies into MSYS2, clones +# fumi next to carrier if missing, builds, and bundles carrier plus the +# GTK runtime into dist/ and carrier-windows.zip. +# +# If MSYS2 updates its own core mid-run the shell may die — just rerun. +# Building and bundling live in windows/bundle.sh, shared with the +# forgejo Windows release job. +set -euo pipefail + +say() { printf '\n==> %s\n' "$*"; } +die() { printf '\n!! %s\n' "$*" >&2; exit 1; } + +[ -d ../fumi/core ] || { + say "fumi not found next to carrier — cloning it" + git clone ssh://git@code.randogoth.com:2222/randogoth/fumi.git ../fumi \ + || die "cloning fumi failed — check your SSH key in ~/.ssh" +} + +say "installing dependencies (first run downloads several hundred MB)" +pacman -Syu --noconfirm || die "pacman update failed — reopen the shell and rerun this script" +pacman -S --noconfirm --needed \ + mingw-w64-x86_64-gtk4 \ + mingw-w64-x86_64-libadwaita \ + mingw-w64-x86_64-adwaita-icon-theme \ + mingw-w64-x86_64-toolchain \ + mingw-w64-x86_64-rust \ + mingw-w64-x86_64-git \ + zip \ + || die "installing the build stack failed" + +pkg-config --exists gtk4 libadwaita-1 \ + || die "gtk4/libadwaita invisible to pkg-config — are you in the MINGW64 shell?" + +bash windows/bundle.sh + +say "done — test with ./dist/carrier.exe (SmartScreen may ask once)"