From b67395bb94beb0a585303cd7dd51a32d01c072ff Mon Sep 17 00:00:00 2001 From: Jason Alexander Date: Tue, 13 Oct 2026 16:48:39 -0700 Subject: [PATCH] Remove retired Qt app and make Rust the only implementation --- .github/workflows/ci.yml | 94 +- .github/workflows/release.yml | 65 +- CHANGELOG.md | 10 + CMakeLists.txt | 41 - README.md | 341 +--- SECURITY.md | 25 +- crates/notes-ui/assets/NOTICE.md | 5 +- docs/arch-release.md | 106 +- docs/gpui-preview.md | 108 +- docs/index.html | 76 +- docs/migrating.md | 79 +- docs/performance.md | 8 +- docs/rust-data-ownership.md | 5 +- docs/rust-edition.md | 300 ++-- docs/rust-release-notes.md | 15 +- docs/rust-release.md | 55 +- install.sh | 87 +- packaging/arch/PKGBUILD-rust.in | 2 +- packaging/arch/PKGBUILD.in | 34 - .../desktop/org.omarchy.Notes.desktop.in | 21 - packaging/icons/org.omarchy.Notes.svg | 11 - packaging/man/omarchy-notes-rust.1 | 10 +- packaging/man/omarchy-notes.1 | 58 - .../org.omarchy.Notes.Rust.metainfo.xml | 4 +- .../metainfo/org.omarchy.Notes.metainfo.xml | 42 - packaging/prepare-release.py | 55 +- src/app/AppController.cpp | 68 - src/app/AppController.h | 50 - src/app/AppLibrary.cpp | 971 ---------- src/app/AppLibrary.h | 325 ---- src/app/BlobImageProvider.cpp | 26 - src/app/BlobImageProvider.h | 20 - src/app/CMakeLists.txt | 80 - src/app/EditorController.cpp | 1596 ----------------- src/app/EditorController.h | 316 ---- src/app/HyprlandSetup.cpp | 143 -- src/app/HyprlandSetup.h | 14 - src/app/InstanceChannel.cpp | 61 - src/app/InstanceChannel.h | 33 - src/app/ThemeController.cpp | 69 - src/app/ThemeController.h | 83 - src/app/icons/all-notes.svg | 1 - src/app/icons/attach.svg | 1 - src/app/icons/back.svg | 1 - src/app/icons/bullets.svg | 1 - src/app/icons/checklist.svg | 1 - src/app/icons/close.svg | 1 - src/app/icons/compose.svg | 1 - src/app/icons/folder-new.svg | 1 - src/app/icons/folder.svg | 1 - src/app/icons/gallery.svg | 1 - src/app/icons/highlight.svg | 1 - src/app/icons/image.svg | 1 - src/app/icons/link.svg | 1 - src/app/icons/list.svg | 1 - src/app/icons/more.svg | 1 - src/app/icons/note.svg | 1 - src/app/icons/numbers.svg | 1 - src/app/icons/pin.svg | 1 - src/app/icons/recover.svg | 1 - src/app/icons/search.svg | 1 - src/app/icons/share.svg | 1 - src/app/icons/sidebar.svg | 1 - src/app/icons/smart-folder.svg | 1 - src/app/icons/table.svg | 1 - src/app/icons/tag.svg | 1 - src/app/icons/trash.svg | 1 - src/app/main.cpp | 238 --- src/app/qml/AttachmentsView.qml | 222 --- src/app/qml/ConfirmDialog.qml | 58 - src/app/qml/EditorPane.qml | 616 ------- src/app/qml/FolderNameDialog.qml | 100 -- src/app/qml/Main.qml | 527 ------ src/app/qml/MoveNoteDialog.qml | 79 - src/app/qml/NoteLinkPicker.qml | 72 - src/app/qml/NoteList.qml | 515 ------ src/app/qml/NoteMenu.qml | 50 - src/app/qml/QuickNoteWindow.qml | 116 -- src/app/qml/Sidebar.qml | 234 --- src/app/qml/SmartFolderDialog.qml | 201 --- src/app/qml/StartupError.qml | 74 - src/app/qml/Toast.qml | 45 - src/app/qml/ToolIcon.qml | 40 - src/core/BlobStore.cpp | 175 -- src/core/BlobStore.h | 45 - src/core/CMakeLists.txt | 21 - src/core/Database.cpp | 225 --- src/core/Database.h | 91 - src/core/DocumentConverter.cpp | 648 ------- src/core/DocumentConverter.h | 93 - src/core/LibraryBackup.cpp | 277 --- src/core/LibraryBackup.h | 31 - src/core/LibraryPaths.cpp | 49 - src/core/LibraryPaths.h | 24 - src/core/LibraryService.cpp | 316 ---- src/core/LibraryService.h | 112 -- src/core/NoteExchange.cpp | 490 ----- src/core/NoteExchange.h | 51 - src/core/NoteStore.cpp | 1230 ------------- src/core/NoteStore.h | 268 --- src/core/RichDocument.cpp | 547 ------ src/core/RichDocument.h | 142 -- src/core/SampleLibrary.cpp | 216 --- src/core/SampleLibrary.h | 31 - src/core/ThemePalette.cpp | 325 ---- src/core/ThemePalette.h | 68 - tests/CMakeLists.txt | 34 - tests/bench_library.cpp | 170 -- tests/check-arch-package.sh | 33 - tests/crash_helper.cpp | 54 - tests/fixtures/README.md | 59 +- tests/qt-backup-probe.cpp | 33 - tests/qt-organization-probe.cpp | 58 - tests/qt-table-probe.cpp | 49 - tests/rust-compatibility-probe.cpp | 40 - tests/test-installer-package.sh | 66 - tests/test-package-install.sh | 45 - tests/test-release-metadata.sh | 21 - tests/test-rust-backups.py | 60 +- tests/test-rust-compatibility.py | 75 +- tests/test-rust-installer-package.sh | 6 +- tests/test-rust-organization.py | 56 +- tests/test-rust-tables.py | 48 +- tests/test_installer.py | 114 +- tests/test_rust_release.py | 53 +- tests/tst_document.cpp | 332 ---- tests/tst_editor.cpp | 929 ---------- tests/tst_exchange.cpp | 235 --- tests/tst_launch.cpp | 206 --- tests/tst_store.cpp | 760 -------- tests/tst_theme.cpp | 147 -- tools/capture-qt-fixture.py | 90 - tools/capture-screenshots.sh | 31 - 133 files changed, 757 insertions(+), 17247 deletions(-) delete mode 100644 CMakeLists.txt delete mode 100644 packaging/arch/PKGBUILD.in delete mode 100644 packaging/desktop/org.omarchy.Notes.desktop.in delete mode 100644 packaging/icons/org.omarchy.Notes.svg delete mode 100644 packaging/man/omarchy-notes.1 delete mode 100644 packaging/metainfo/org.omarchy.Notes.metainfo.xml delete mode 100644 src/app/AppController.cpp delete mode 100644 src/app/AppController.h delete mode 100644 src/app/AppLibrary.cpp delete mode 100644 src/app/AppLibrary.h delete mode 100644 src/app/BlobImageProvider.cpp delete mode 100644 src/app/BlobImageProvider.h delete mode 100644 src/app/CMakeLists.txt delete mode 100644 src/app/EditorController.cpp delete mode 100644 src/app/EditorController.h delete mode 100644 src/app/HyprlandSetup.cpp delete mode 100644 src/app/HyprlandSetup.h delete mode 100644 src/app/InstanceChannel.cpp delete mode 100644 src/app/InstanceChannel.h delete mode 100644 src/app/ThemeController.cpp delete mode 100644 src/app/ThemeController.h delete mode 100644 src/app/icons/all-notes.svg delete mode 100644 src/app/icons/attach.svg delete mode 100644 src/app/icons/back.svg delete mode 100644 src/app/icons/bullets.svg delete mode 100644 src/app/icons/checklist.svg delete mode 100644 src/app/icons/close.svg delete mode 100644 src/app/icons/compose.svg delete mode 100644 src/app/icons/folder-new.svg delete mode 100644 src/app/icons/folder.svg delete mode 100644 src/app/icons/gallery.svg delete mode 100644 src/app/icons/highlight.svg delete mode 100644 src/app/icons/image.svg delete mode 100644 src/app/icons/link.svg delete mode 100644 src/app/icons/list.svg delete mode 100644 src/app/icons/more.svg delete mode 100644 src/app/icons/note.svg delete mode 100644 src/app/icons/numbers.svg delete mode 100644 src/app/icons/pin.svg delete mode 100644 src/app/icons/recover.svg delete mode 100644 src/app/icons/search.svg delete mode 100644 src/app/icons/share.svg delete mode 100644 src/app/icons/sidebar.svg delete mode 100644 src/app/icons/smart-folder.svg delete mode 100644 src/app/icons/table.svg delete mode 100644 src/app/icons/tag.svg delete mode 100644 src/app/icons/trash.svg delete mode 100644 src/app/main.cpp delete mode 100644 src/app/qml/AttachmentsView.qml delete mode 100644 src/app/qml/ConfirmDialog.qml delete mode 100644 src/app/qml/EditorPane.qml delete mode 100644 src/app/qml/FolderNameDialog.qml delete mode 100644 src/app/qml/Main.qml delete mode 100644 src/app/qml/MoveNoteDialog.qml delete mode 100644 src/app/qml/NoteLinkPicker.qml delete mode 100644 src/app/qml/NoteList.qml delete mode 100644 src/app/qml/NoteMenu.qml delete mode 100644 src/app/qml/QuickNoteWindow.qml delete mode 100644 src/app/qml/Sidebar.qml delete mode 100644 src/app/qml/SmartFolderDialog.qml delete mode 100644 src/app/qml/StartupError.qml delete mode 100644 src/app/qml/Toast.qml delete mode 100644 src/app/qml/ToolIcon.qml delete mode 100644 src/core/BlobStore.cpp delete mode 100644 src/core/BlobStore.h delete mode 100644 src/core/CMakeLists.txt delete mode 100644 src/core/Database.cpp delete mode 100644 src/core/Database.h delete mode 100644 src/core/DocumentConverter.cpp delete mode 100644 src/core/DocumentConverter.h delete mode 100644 src/core/LibraryBackup.cpp delete mode 100644 src/core/LibraryBackup.h delete mode 100644 src/core/LibraryPaths.cpp delete mode 100644 src/core/LibraryPaths.h delete mode 100644 src/core/LibraryService.cpp delete mode 100644 src/core/LibraryService.h delete mode 100644 src/core/NoteExchange.cpp delete mode 100644 src/core/NoteExchange.h delete mode 100644 src/core/NoteStore.cpp delete mode 100644 src/core/NoteStore.h delete mode 100644 src/core/RichDocument.cpp delete mode 100644 src/core/RichDocument.h delete mode 100644 src/core/SampleLibrary.cpp delete mode 100644 src/core/SampleLibrary.h delete mode 100644 src/core/ThemePalette.cpp delete mode 100644 src/core/ThemePalette.h delete mode 100644 tests/CMakeLists.txt delete mode 100644 tests/bench_library.cpp delete mode 100755 tests/check-arch-package.sh delete mode 100644 tests/crash_helper.cpp delete mode 100644 tests/qt-backup-probe.cpp delete mode 100644 tests/qt-organization-probe.cpp delete mode 100644 tests/qt-table-probe.cpp delete mode 100644 tests/rust-compatibility-probe.cpp delete mode 100755 tests/test-installer-package.sh delete mode 100755 tests/test-package-install.sh delete mode 100755 tests/test-release-metadata.sh delete mode 100644 tests/tst_document.cpp delete mode 100644 tests/tst_editor.cpp delete mode 100644 tests/tst_exchange.cpp delete mode 100644 tests/tst_launch.cpp delete mode 100644 tests/tst_store.cpp delete mode 100644 tests/tst_theme.cpp delete mode 100644 tools/capture-qt-fixture.py delete mode 100755 tools/capture-screenshots.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8664fb5..0890db0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,13 +5,13 @@ on: pull_request: jobs: - rust-preview: + rust: runs-on: ubuntu-latest container: archlinux:latest timeout-minutes: 30 steps: - name: Install native build dependencies - run: pacman -Syu --noconfirm base-devel clang cmake git pkgconf rustup python qt6-base sqlite cairo pango noto-fonts noto-fonts-cjk noto-fonts-emoji ttf-liberation poppler qpdf fontconfig freetype2 libxkbcommon libxcb wayland vulkan-headers vulkan-icd-loader + run: pacman -Syu --noconfirm base-devel clang cmake git pkgconf rustup python cairo pango noto-fonts noto-fonts-cjk noto-fonts-emoji ttf-liberation poppler qpdf fontconfig freetype2 libxkbcommon libxcb wayland vulkan-headers vulkan-icd-loader - uses: actions/checkout@v4 - name: Create unprivileged build user run: | @@ -27,13 +27,13 @@ jobs: runuser -u builder -- cargo test --workspace --locked runuser -u builder -- cargo test -p accesskit_unix --lib --locked runuser -u builder -- cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - - name: Check Qt-free PDF structure and content + - name: Check PDF structure and content env: CARGO_BUILD_JOBS: 4 run: | runuser -u builder -- cargo build -p notes-export --example pdf-check --locked runuser -u builder -- python tests/test-rust-pdf.py target/debug/examples/pdf-check - - name: Check Rust and Qt storage compatibility + - name: Check Rust storage and backups env: CARGO_BUILD_JOBS: 4 run: | @@ -44,18 +44,14 @@ jobs: runuser -u builder -- python tests/test-rust-backups.py target/debug/omarchy-notes-preview --quote-driver target/debug/examples/quote-upgrade runuser -u builder -- cargo build -p notes-storage --example organization-roundtrip --locked runuser -u builder -- python tests/test-rust-organization.py target/debug/examples/organization-roundtrip + runuser -u builder -- cargo build -p notes-storage --example table-roundtrip --locked + runuser -u builder -- python tests/test-rust-tables.py target/debug/examples/table-roundtrip - name: Check durable capture and instance protocol without a display env: CARGO_BUILD_JOBS: 4 run: | runuser -u builder -- cargo build -p notes-platform --example instance-owner --locked runuser -u builder -- python tests/test-rust-capture.py target/debug/omarchy-notes-preview target/debug/examples/instance-owner - - name: Check editable table compatibility with Qt - env: - CARGO_BUILD_JOBS: 4 - run: | - runuser -u builder -- cargo build -p notes-storage --example table-roundtrip --locked - runuser -u builder -- python tests/test-rust-tables.py target/debug/examples/table-roundtrip installer: runs-on: ubuntu-latest @@ -63,7 +59,7 @@ jobs: timeout-minutes: 5 steps: - name: Install installer test tools - run: pacman -Syu --noconfirm bash curl python ripgrep shellcheck sudo util-linux + run: pacman -Syu --noconfirm bash curl git python ripgrep shellcheck sudo util-linux - uses: actions/checkout@v4 - name: Create unprivileged test user run: | @@ -71,70 +67,12 @@ jobs: chown -R builder:builder "$GITHUB_WORKSPACE" - name: Check installer syntax and lint run: | - bash -n install.sh tests/test-installer.sh tests/test-installer-package.sh - shellcheck install.sh tests/test-installer.sh tests/test-installer-package.sh + bash -n install.sh tests/test-installer.sh tests/check-rust-arch-package.sh tests/test-rust-installer-package.sh + shellcheck install.sh tests/test-installer.sh tests/check-rust-arch-package.sh tests/test-rust-installer-package.sh - name: Test installer without network or system changes run: runuser -u builder -- ./tests/test-installer.sh - - name: Check separate Rust identity and immutable preparation - run: | - pacman -S --noconfirm --needed git - runuser -u builder -- python3 tests/test_rust_release.py - - build-and-test: - runs-on: ubuntu-latest - container: archlinux:latest - timeout-minutes: 30 - steps: - - name: Install build dependencies - run: pacman -Syu --noconfirm appstream base-devel cmake desktop-file-utils git ninja qt6-base qt6-declarative qt6-svg sqlite ttf-dejavu - - uses: actions/checkout@v4 - - name: Create unprivileged test user - run: | - useradd --create-home builder - chown -R builder:builder "$GITHUB_WORKSPACE" - - name: Check release metadata - run: runuser -u builder -- ./tests/test-release-metadata.sh - - name: Verify production install tree - run: runuser -u builder -- ./tests/test-package-install.sh - - name: Build and test - run: | - runuser -u builder -- cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release - runuser -u builder -- cmake --build build - runuser -u builder -- env QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software \ - ctest --test-dir build --output-on-failure --timeout 300 - - name: Keep editor screenshots - if: always() - uses: actions/upload-artifact@v4 - with: - name: editor-screenshots - path: build/screenshots - if-no-files-found: ignore - - arch-package: - runs-on: ubuntu-latest - container: archlinux:latest - timeout-minutes: 30 - steps: - - name: Install packaging tools - run: pacman -Syu --noconfirm base-devel curl git namcap python ripgrep sudo util-linux - - uses: actions/checkout@v4 - - name: Prepare source and AUR files - run: | - useradd --create-home builder - echo 'builder ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/builder - chmod 440 /etc/sudoers.d/builder - chown -R builder:builder "$GITHUB_WORKSPACE" - runuser -u builder -- git config --global --add safe.directory "$GITHUB_WORKSPACE" - runuser -u builder -- python3 packaging/prepare-release.py --ref HEAD --output build-aur-ci - # A systemd-nspawn chroot (extra-x86_64-build) can't run inside the - # job container; the container itself is fresh, and --syncdeps installs - # only the dependencies the PKGBUILD declares. - - name: Build the package from the AUR files - run: runuser -u builder -- bash -c 'cd build-aur-ci/aur && makepkg --syncdeps --noconfirm --cleanbuild' - - name: Validate package contents and dependencies - run: ./tests/check-arch-package.sh build-aur-ci/aur - - name: Install and verify through the installer in the disposable container - run: runuser -u builder -- ./tests/test-installer-package.sh build-aur-ci/aur + - name: Check Rust identity and immutable preparation + run: runuser -u builder -- python3 tests/test_rust_release.py rust-arch-candidate: runs-on: ubuntu-latest @@ -144,19 +82,19 @@ jobs: - name: Install Rust packaging tools run: pacman -Syu --noconfirm appstream base-devel clang cmake curl desktop-file-utils git namcap pkgconf python ripgrep rustup shellcheck sudo util-linux - uses: actions/checkout@v4 - - name: Prepare immutable separate Rust candidate + - name: Prepare immutable Rust candidate run: | useradd --create-home builder echo 'builder ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/builder chmod 440 /etc/sudoers.d/builder chown -R builder:builder "$GITHUB_WORKSPACE" runuser -u builder -- git config --global --add safe.directory "$GITHUB_WORKSPACE" - runuser -u builder -- python3 packaging/prepare-release.py --edition rust --candidate --ref HEAD --output build-rust-ci - - name: Build from the archived Rust recipe and locked dependencies + runuser -u builder -- python3 packaging/prepare-release.py --candidate --ref HEAD --output build-rust-ci + - name: Build from the archived recipe and locked dependencies run: runuser -u builder -- bash -c 'cd build-rust-ci/aur && makepkg --syncdeps --noconfirm --cleanbuild' - - name: Validate separate package metadata and files + - name: Validate package metadata and files run: ./tests/check-rust-arch-package.sh build-rust-ci/aur - - name: Verify actual Rust install, alias, headless capture and retained data on removal + - name: Verify install, alias, headless capture and retained data on removal run: runuser -u builder -- ./tests/test-rust-installer-package.sh build-rust-ci/aur - name: Retain exact candidate identity uses: actions/upload-artifact@v4 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 179b69a..c37dc68 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,68 +2,19 @@ name: Release on: push: - tags: ["v*", "rust-v*"] + tags: ["rust-v*"] permissions: contents: write jobs: - release: - if: startsWith(github.ref, 'refs/tags/v') - runs-on: ubuntu-latest - container: archlinux:latest - timeout-minutes: 40 - steps: - - name: Install release dependencies - run: pacman -Syu --noconfirm appstream base-devel cmake curl desktop-file-utils git github-cli namcap ninja python qt6-base qt6-declarative qt6-svg shellcheck sqlite sudo util-linux - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - name: Create unprivileged build user - run: | - useradd --create-home builder - chown -R builder:builder "$GITHUB_WORKSPACE" - runuser -u builder -- git config --global --add safe.directory "$GITHUB_WORKSPACE" - # gh (run as root below) also reads the checkout, now owned by builder. - git config --global --add safe.directory "$GITHUB_WORKSPACE" - - name: Verify tag and release metadata - run: runuser -u builder -- env GITHUB_REF_NAME="$GITHUB_REF_NAME" GITHUB_REF_TYPE="$GITHUB_REF_TYPE" ./tests/test-release-metadata.sh - - name: Verify production install - run: runuser -u builder -- ./tests/test-package-install.sh - - name: Verify installer - run: | - bash -n install.sh tests/test-installer.sh tests/test-installer-package.sh - shellcheck install.sh tests/test-installer.sh tests/test-installer-package.sh - runuser -u builder -- ./tests/test-installer.sh - - name: Prepare and validate release artifacts - run: | - runuser -u builder -- python3 packaging/prepare-release.py --ref "$GITHUB_REF_NAME" --output dist - runuser -u builder -- bash -c 'cd dist/aur && makepkg --noconfirm --cleanbuild' - ./tests/check-arch-package.sh dist/aur - cp dist/aur/omarchy-notes-*.pkg.tar.zst dist/ - cp install.sh dist/install.sh - cd dist - sha256sum ./*.tar.gz ./*.pkg.tar.zst install.sh SOURCE_REVISION > SHA256SUMS - - name: Write release notes from the changelog - run: | - version="${GITHUB_REF_NAME#v}" - awk -v v="$version" '$0 ~ "^## \\[" v "\\]" {on=1; next} /^## \[/ {on=0} on' CHANGELOG.md > dist/NOTES.md - test -s dist/NOTES.md - - name: Create draft GitHub release - env: - GH_TOKEN: ${{ github.token }} - run: >- - gh release create "$GITHUB_REF_NAME" dist/*.tar.gz dist/*.pkg.tar.zst - dist/install.sh dist/SHA256SUMS dist/SOURCE_REVISION --title "Omarchy Notes ${GITHUB_REF_NAME}" - --notes-file dist/NOTES.md --verify-tag --draft - rust-release: if: startsWith(github.ref, 'refs/tags/rust-v') runs-on: ubuntu-latest container: archlinux:latest timeout-minutes: 90 steps: - - name: Install separate Rust release dependencies + - name: Install Rust release dependencies run: pacman -Syu --noconfirm appstream base-devel clang cmake curl desktop-file-utils git github-cli namcap pkgconf python ripgrep rustup shellcheck sudo util-linux - uses: actions/checkout@v4 with: @@ -76,15 +27,15 @@ jobs: chown -R builder:builder "$GITHUB_WORKSPACE" runuser -u builder -- git config --global --add safe.directory "$GITHUB_WORKSPACE" git config --global --add safe.directory "$GITHUB_WORKSPACE" - - name: Verify immutable Rust metadata and installer + - name: Verify immutable metadata and installer run: | runuser -u builder -- python3 tests/test_rust_release.py - bash -n install.sh tests/check-rust-arch-package.sh tests/test-rust-installer-package.sh - shellcheck install.sh tests/check-rust-arch-package.sh tests/test-rust-installer-package.sh + bash -n install.sh tests/test-installer.sh tests/check-rust-arch-package.sh tests/test-rust-installer-package.sh + shellcheck install.sh tests/test-installer.sh tests/check-rust-arch-package.sh tests/test-rust-installer-package.sh runuser -u builder -- ./tests/test-installer.sh - - name: Prepare stable Rust artifacts from the exact Rust tag + - name: Prepare stable artifacts from the exact Rust tag run: | - runuser -u builder -- python3 packaging/prepare-release.py --edition rust --ref "$GITHUB_REF_NAME" --output dist-rust + runuser -u builder -- python3 packaging/prepare-release.py --ref "$GITHUB_REF_NAME" --output dist-rust runuser -u builder -- bash -c 'cd dist-rust/aur && makepkg --syncdeps --noconfirm --cleanbuild' ./tests/check-rust-arch-package.sh dist-rust/aur runuser -u builder -- ./tests/test-rust-installer-package.sh dist-rust/aur @@ -102,7 +53,7 @@ jobs: exit 1 fi cp docs/rust-release-notes.md dist-rust/NOTES.md - - name: Create separate draft Rust release + - name: Create draft Rust release env: GH_TOKEN: ${{ github.token }} run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 698fae2..647514f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,16 @@ All notable changes to Omarchy Notes are documented here. The project uses ## [Unreleased] +### Changed + +- Rust/GPUI is now the only app implementation and installer target. Existing + Rust executable names and data directories remain unchanged. + +### Removed + +- Retired Qt/C++/QML app, CMake build, Qt packages and live Qt test probes. + Frozen legacy library fixtures remain for Rust migration regression tests. + ### Added - Command-line installer with formatted progress, verified Arch release diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 7f3ff90..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,41 +0,0 @@ -cmake_minimum_required(VERSION 3.24) - -project(omarchy-notes - VERSION 1.0.0 - DESCRIPTION "Native notes for Omarchy" - LANGUAGES CXX) - -# Working name; the application ID is what desktop files, Hyprland rules and -# D-Bus activation will key on, so it lives in exactly one place. -set(ONOTES_APP_ID "org.omarchy.Notes" CACHE STRING "Reverse-DNS application ID") -set(ONOTES_BINARY_NAME "omarchy-notes") - -set(CMAKE_CXX_STANDARD 20) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - -# Qt 6.8 is the LTS floor; the editor relies on TextEdit.textDocument (6.7+). -find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Network Qml Quick QuickControls2 Test) -find_package(PkgConfig REQUIRED) -pkg_check_modules(SQLITE3 REQUIRED IMPORTED_TARGET sqlite3>=3.35) - -qt_standard_project_setup(REQUIRES 6.8) -include(GNUInstallDirs) -# Packages install into system paths; no runtime library search paths. -set(CMAKE_SKIP_INSTALL_RPATH ON) - -add_compile_options(-Wall -Wextra -Wpedantic) - -add_subdirectory(src/core) -add_subdirectory(src/app) - -include(CTest) -if(BUILD_TESTING) - add_subdirectory(tests) -endif() - -# Documentation, license and man page. -install(FILES README.md CHANGELOG.md SECURITY.md DESTINATION ${CMAKE_INSTALL_DOCDIR}) -install(FILES LICENSE DESTINATION ${CMAKE_INSTALL_DATADIR}/licenses/${ONOTES_BINARY_NAME}) -install(FILES packaging/man/omarchy-notes.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1) diff --git a/README.md b/README.md index b468f49..0a88304 100644 --- a/README.md +++ b/README.md @@ -4,318 +4,149 @@ **Local, offline notes for [Omarchy](https://omarchy.org).** -Two native editions: **Rust 1.0 with GPUI**, and the existing **Qt edition**. -Rich notes stay on your machine, with no account required. +A native app built with **Rust and GPUI**. Rich notes stay on your machine, +with no account required. Rust is the only maintained implementation. [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Rust 1.0](https://img.shields.io/badge/Rust-1.0.0-2d4f8e?logo=rust)](https://github.com/last-refuge/omarchy-notes/releases/tag/rust-v1.0.0) -![Qt 6.8+](https://img.shields.io/badge/Qt-6.8%2B-41cd52?logo=qt&logoColor=white) ![SQLite](https://img.shields.io/badge/SQLite-FTS5-003b57?logo=sqlite&logoColor=white) ![Wayland](https://img.shields.io/badge/Wayland-native-ffbc00) Omarchy Notes Rust 1.0 writing view in a dark theme -[Download Rust 1.0](https://github.com/last-refuge/omarchy-notes/releases/tag/rust-v1.0.0) · [Qt edition](#qt-edition) +[Download Rust 1.0](https://github.com/last-refuge/omarchy-notes/releases/tag/rust-v1.0.0) -## Rust 1.0 +## What’s included -The separate Rust edition ships for **x86_64 Arch/Omarchy on Wayland/Hyprland**. -It includes rich writing, headings, lists, checklists, basic tables, links, -images and files; autosave and recovery; Quick Note and durable CLI capture; -nested folders, pins, sorting, prefix search and Recently Deleted. +Omarchy Notes ships for **x86_64 Arch/Omarchy on Wayland/Hyprland**. It includes +rich writing, headings, lists, checklists, basic tables, links, images and files; +autosave and recovery; Quick Note and durable CLI capture; nested folders, pins, +sorting, prefix search and Recently Deleted. -**Settings → Data** provides reviewed Markdown/text file or folder imports, -Markdown/HTML note exports, library Markdown with assets, complete backups, -inspection and restore into a new library. Export a note as PDF from the toolbar -or with **Ctrl+Shift+P**. Portable exports are useful copies; use a library backup -when you need exact preservation. +**Settings → Your notes and files → Import, export & backups** provides reviewed +Markdown/text file or folder imports, Markdown/HTML note exports, library Markdown +with assets, complete backups, inspection and restore into a new library. Export +a note as PDF from the toolbar or with **Ctrl+Shift+P**. Portable exports are useful +copies; use a library backup when you need exact preservation. -| Workflow | Rust 1.0 | Qt edition | -|---|---|---| -| Rich notes, basic tables, images and files | Available; existing merged cells are preserved | Available | -| Folders, pins, search, sorting and deletion recovery | Available | Available | -| Quick Note, import/export and library backups | Available | Available | -| Tags and Smart Folders | Interfaces deferred; existing metadata preserved | Available | -| Gallery and library-wide attachment browser | Deferred | Available | -| Automatic Hyprland Quick Note setup | Desktop action or a distinct manual binding | Optional setup command | +**Scope limits:** Tags/Smart Folder interfaces, advanced table operations (including +new merges), gallery, library-wide attachment browsing, drag filing, bulk +organization and browsable revision history are deferred. Existing metadata, +merged tables and revisions are preserved. Automatic Hyprland shortcut setup is +not implemented. X11 and other architectures are not advertised as tested. -Rust is a separate edition, not a complete replacement for Qt. See the -[Rust release notes](docs/rust-release-notes.md) for scope and recorded follow-up, -and the [installation and recovery guide](docs/rust-release.md) for details. +The Qt app is **retired**, not a current install, build or support option. Legacy +Qt data compatibility remains for [migration](docs/migrating.md); retirement does +not imply full parity with its former features. See the +[release notes](docs/rust-release-notes.md) for remaining native/package and human +usability verification gaps. -### Install Rust 1.0 +## Install -Download the **published Rust release installer** and inspect it before running: +Download the **published Rust 1.0 release installer** and inspect it before +running. That release's installer requires `--edition rust`: ```bash curl -fsSL https://github.com/last-refuge/omarchy-notes/releases/download/rust-v1.0.0/install.sh -o install.sh +less install.sh bash install.sh --edition rust --version rust-v1.0.0 --dry-run bash install.sh --edition rust --version rust-v1.0.0 --no-quick-note ``` +The `install.sh` in this repository is now Rust-only: omit `--edition rust` +when using that version. Qt releases are no longer installation targets. + The installer verifies the release checksum and package identity, then uses pacman. Open **Omarchy Notes (Rust)** from your launcher, or run `omarchy-notes-rust`. The `omarchy-notes-preview` compatibility launcher forwards to Rust; an older manual preview earlier on `PATH` may need moving aside. +The binary and Arch package remain `omarchy-notes-rust`, and the desktop ID remains +`org.omarchy.Notes.Rust`. -Choose **Rust Quick Note** from the desktop launcher's actions, run -`omarchy-notes-rust --quick-note`, or press **Ctrl+Shift+N** inside Rust. -**Ctrl+Shift+O** moves Quick Note into the main window. Use a distinct compositor -binding if you want a global shortcut; Rust does not run Qt's automatic setup. - -Rust keeps notes in `~/.local/share/omarchy-notes-gpui/` and preferences in -`~/.config/omarchy-notes-gpui/` (or the corresponding XDG locations). Qt uses -separate directories. Removing `omarchy-notes-rust` retains your data. -Use copies and verified backups when opening Qt libraries. Quotation/schema-3 -libraries require Rust; returning to Qt uses the pre-upgrade backup and excludes -later Rust edits. Keep the newer library and export or back it up before rollback. - -### Rust screenshots - -The dark writing view is shown above. These are screenshots of the released -Rust 1.0 application, using a sample library. - -| Light writing | Quick Note | -|---|---| -| [![Rust light writing](docs/images/rust-v1-writing-light.png)](docs/images/rust-v1-writing-light.png) | [![Rust Quick Note](docs/images/rust-v1-quick-note.png)](docs/images/rust-v1-quick-note.png) | -| **Folders** | **Data and backups** | -| [![Rust folders](docs/images/rust-v1-folders.png)](docs/images/rust-v1-folders.png) | [![Rust data and backups](docs/images/rust-v1-portability.png)](docs/images/rust-v1-portability.png) | - -[![Rust Recently Deleted](docs/images/rust-v1-recovery.png)](docs/images/rust-v1-recovery.png) - -## Qt edition - -Qt remains available as `omarchy-notes`, with its own library and desktop -identity. It supports tags, Smart Folders, gallery and the attachment browser, -in addition to the writing workflows below. The installer **defaults to Qt**; -Rust always requires explicit edition selection. - -
-Qt features - -- ⚡ **Start typing right away.** Notes save automatically, usually within a second. "Saved" only appears once your note is actually on disk. -- ✍️ **Format like you'd expect:** title, heading and subheading styles, plus bold, italic, underline, strikethrough, highlight and monospace. -- ✅ **Checklists and lists.** Bulleted, numbered and checklist items, nested as deep as you like. Click a checkbox to tick it off. -- 📊 **Tables.** Tab moves between cells, and Tab in the last cell adds a new row. -- 🖼️ **Images and attachments.** Add images from the toolbar or paste them in, and attach PDFs or any other file. Double-click one to open it in its usual app. -- 🔗 **Link notes together.** Ctrl+L links to another note, and Ctrl+click follows a link. -- 🗂️ **Folders.** Nest folders as deep as you like, move notes between them, and use All Notes to see everything at once. -- 🏷️ **Tags.** Type `#anything` in a note and it becomes a tag, listed in the sidebar with a count. Ctrl+click a tag to see every note that has it. -- ✨ **Smart Folders.** Save a filter, like "tagged #work, has a checklist, edited this week", and it stays up to date by itself. -- 🖼️ **Gallery and attachments.** Flip the note list to a gallery of cards with image previews, or browse every image and file across all your notes in one place. -- ⚡ **Quick Note.** A small window for jotting something down without opening the whole app. It's in the launcher menu, and you can bind it to a key (see below). -- 🔍 **Search everything.** Results appear as you type, with the matching words in bold. Partial words work too: "bench" finds "benchmark". Ctrl+F finds text inside the note you're reading. -- 📤 **Your notes aren't locked in.** Import Markdown and text files (including their images), export any note as Markdown, HTML or PDF, or export everything as a folder of Markdown files. -- 📌 **Pin what matters.** Pinned notes stay at the top. Sort the rest by date edited, date created or title. -- 🗑️ **Undo a delete.** Deleted notes wait in Recently Deleted for 30 days before they're gone for good. Deleting a folder moves its notes there too. -- 💾 **Backups you can trust.** One click saves a complete copy of your library, attachments included. Restoring checks the backup first and keeps your current notes aside, so you can always go back. -- 📋 **Copy and paste that behaves.** Copying between notes keeps everything intact. Text pasted from the web gets tidied into clean note formatting, and anything that can't come along, like images from other sites, gets a heads-up instead of vanishing silently. -- 🎨 **Matches your theme.** Colours come from your active Omarchy theme and are adjusted automatically when they'd be hard to read. -- 🌐 **Every language.** Emoji, right-to-left scripts, CJK and input methods (IME) all work. -- 🛟 **Hard to lose work.** If a save fails, your text stays on screen with Retry and Export buttons, and the app won't quit until your changes are safe or you choose to discard them. - -
- -
-Qt edition screenshots - -![Qt dark writing view](docs/images/screenshot-dark.png) - -![Qt light writing view](docs/images/screenshot-light.png) - -![Qt gallery view](docs/images/screenshot-gallery.png) - -
- -### Install Qt - -The published edition-aware installer supports both apps. Without -`--edition rust`, it selects Qt; these commands pin the existing Qt release: - -```bash -curl -fsSL https://github.com/last-refuge/omarchy-notes/releases/download/rust-v1.0.0/install.sh -o install.sh -bash install.sh --version v1.0.0 -``` - -After installation, open **Omarchy Notes** from your launcher. To preview, build -from source, or request Qt's optional Quick Note setup: - -```bash -bash install.sh --version v1.0.0 --dry-run -bash install.sh --version v1.0.0 --source -bash install.sh --version v1.0.0 --quick-note -``` - -`--yes` accepts package installation, but does not enable Quick Note by itself. -`--no-quick-note` skips setup. `NO_COLOR=1` disables colour and animation. -Downloads never switch to a source build automatically. Run the installer again -to update, then close and reopen the app normally. Removing Qt keeps its notes: - -```bash -sudo pacman -R omarchy-notes -``` - -### Qt package installation - -You can also install the **v1.0.0 x86_64 package** directly: +Run the installer again to update, then close and reopen the app normally. +Downloads do not silently fall back to source builds. Removing the package with +`sudo pacman -R omarchy-notes-rust` retains your notes and preferences. +See the [build, install and recovery guide](docs/rust-release.md). -```bash -sudo pacman -U https://github.com/last-refuge/omarchy-notes/releases/download/v1.0.0/omarchy-notes-1.0.0-1-x86_64.pkg.tar.zst -``` - -### Building Qt from source - -For a Qt release package on Arch, use `bash install.sh --version v1.0.0 --source`. To build a user-local -copy yourself, follow the steps below. Other Linux systems need equivalent build -tools, Qt 6.8 or newer, and SQLite. - -**1. Install the build tools:** - -```bash -sudo pacman -S --needed qt6-base qt6-declarative qt6-wayland qt6-svg sqlite cmake ninja gcc pkgconf -``` - -**2. Build and install it for your user:** - -```bash -git clone https://github.com/last-refuge/omarchy-notes.git -cd omarchy-notes -cmake -S . -B build-release -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$HOME/.local" -cmake --build build-release -cmake --install build-release -``` - -That puts `omarchy-notes` in `~/.local/bin` and adds it to your app launcher. - -> [!TIP] -> If it doesn't show up in the launcher right away, run `omarchy restart shell` so the launcher picks up the new app. - -To update later, `git pull` and run the last two `cmake` commands again. Your notes aren't touched. +### Quick Note -### Qt Quick Note on a key (optional) - -Let the app set it up. It checks your existing bindings (and Omarchy's) first, never overwrites a key that's taken, and backs up anything it changes: +Choose **Rust Quick Note** from the desktop launcher's actions, run +`omarchy-notes-rust --quick-note`, or press **Ctrl+Shift+N** inside the app. +**Ctrl+Shift+O** moves Quick Note into the main window. Use a distinct, unused +compositor binding if you want a global shortcut; automatic setup is unavailable. ```bash -omarchy-notes --setup-hyprland +printf 'A thought to keep\nSome details.' | omarchy-notes-rust --capture - ``` -Or do it by hand. Add a binding to `~/.config/hypr/bindings.lua`. Super Alt N is free in a default Omarchy setup: +Capture supports durable receipts and safe retry with `--request-id UUID` and +`--capture-status UUID`; see the [writing and capture guide](docs/gpui-preview.md). -```lua -o.bind("SUPER + ALT + N", "Quick Note", { launch = "omarchy-notes --quick-note" }) -``` +### Data and migration -To make the Quick Note window float, add this to `~/.config/hypr/hyprland.lua`: - -```lua -o.window({ class = "^org\\.omarchy\\.Notes$", title = "^Quick Note$" }, { tag = "+floating-window" }) -``` +Notes remain in `~/.local/share/omarchy-notes-gpui/` and preferences in +`~/.config/omarchy-notes-gpui/` (or the corresponding XDG locations). These +historical profile names are unchanged. Data and backups are not encrypted. -### Qt data and backups +Use copies and verified backups when bringing in retired Qt libraries; the original +library is never selected automatically. Quotation/schema-3 libraries require +Rust. A legacy rollback can only use the pre-upgrade backup and excludes later +Rust edits; preserve the newer library and export or back it up first. +See [migration](docs/migrating.md) and [data ownership](docs/rust-data-ownership.md). -Everything is stored in `~/.local/share/omarchy-notes/`: an SQLite database for your notes, plus a folder of attached files. Reinstalling or removing the app never touches it. +## Screenshots -To back up, click **⋯** at the bottom of the folder list and choose **Back Up Library…**. You get a normal folder with a consistent copy of everything, which is safe to make while you're writing. **Restore from Backup…** in the same menu checks a backup before using it and sets your current notes aside next to the library, so nothing is lost if you change your mind. +These are screenshots of the released Rust 1.0 application using a sample library. -Coming from Apple Notes, Obsidian or another app? See [moving your notes in](docs/migrating.md). - -Want a sandbox to play in? Point the app at a different folder and fill it with sample notes: - -```bash -omarchy-notes --data-dir /tmp/notes-playground --samples -``` - -
-All command-line options - -| Option | What it does | +| Light writing | Quick Note | |---|---| -| `--data-dir ` | Use a notes library in a different folder | -| `--new` | Start with a fresh note | -| `--note ` | Open a specific note | -| `--quick-note` | Open a Quick Note window | -| `--capture ` | Save text as a new note without opening a window (use `-` to read from a pipe, like `echo "idea" \| omarchy-notes --capture -`) | -| `--setup-hyprland` | Add a Quick Note key (Super+Alt+N) and floating rule to Hyprland, if the key is free | -| `--samples` | Fill an empty library with example notes (a meeting note with a table, image and PDF, some research links, and a grocery list) | -| `--simulate-save-failure` | Make saves fail on purpose, to see how the app handles it. Ctrl+Alt+Shift+F toggles this while running | +| [![Rust light writing](docs/images/rust-v1-writing-light.png)](docs/images/rust-v1-writing-light.png) | [![Rust Quick Note](docs/images/rust-v1-quick-note.png)](docs/images/rust-v1-quick-note.png) | +| **Folders** | **Data and backups** | +| [![Rust folders](docs/images/rust-v1-folders.png)](docs/images/rust-v1-folders.png) | [![Rust data and backups](docs/images/rust-v1-portability.png)](docs/images/rust-v1-portability.png) | -
+[![Rust Recently Deleted](docs/images/rust-v1-recovery.png)](docs/images/rust-v1-recovery.png) -### Qt keyboard shortcuts +## Development -| | Shortcut | -|---|---| -| New note · New folder | Ctrl N · Ctrl Shift N | -| Search all notes · Find in note | Ctrl Shift F · Ctrl F (then F3 / Enter for the next match) | -| Delete the selected note | Delete (in the note list) | -| Duplicate note | Ctrl D | -| Show or hide folders | Ctrl Shift S | -| Bold · Italic · Underline | Ctrl B · Ctrl I · Ctrl U | -| Strikethrough · Highlight · Monospace | Ctrl Shift X · Ctrl Shift Y · Ctrl E | -| Title · Heading · Subheading · Body | Ctrl Shift + T · H · J · B | -| Checklist · Tick an item | Ctrl Shift L · Ctrl Shift U | -| Bulleted · Numbered list | Ctrl Shift 8 · Ctrl Shift 7 | -| Indent · Outdent a list item | Tab · Shift Tab | -| Insert a table | Ctrl Alt T | -| Attach a file · Link to a note | Ctrl Shift A · Ctrl L | -| Follow a link or #tag · Open an attachment | Ctrl + click · double-click (or Ctrl Enter next to it) | - -### Qt roadmap - -| | Milestone | What it brings | -|---|---|---| -| ✅ | **Editor & storage** | Rich editing, autosave, crash-safe storage, theme support | -| ✅ | **Daily-use alpha** | Delete & trash, folders, pinning, search, backup & restore | -| ✅ | **Local beta** | Tags, Smart Folders, gallery view, import/export, Quick Note, find in note | -| ✅ | **1.0** | Arch package, accessibility polish, performance targets met ([numbers](docs/performance.md)) | -| 💭 | **After 1.0** | Locked notes, OCR, audio, sync between devices, sharing | - -The Qt plan is in [`llm-docs/omarchy-notes-plan.md`](llm-docs/omarchy-notes-plan.md), with a visual version in [`llm-docs/roadmap.html`](llm-docs/roadmap.html) (download it and open it in a browser). Big technical decisions are written up in [`docs/decisions/`](docs/decisions/). - -## 🛠️ Hacking on it - -For Rust development, see the [Rust build guide](docs/rust-release.md) and the -[`crates/`](crates/) workspace. The Cargo package retains its historical name; -the application executable is `omarchy-notes-rust`. +See the [Rust build guide](docs/rust-release.md), +[writing guide](docs/gpui-preview.md), [performance diagnostics](docs/rust-performance.md) +and [native acceptance guide](docs/rust-native-acceptance.md). +Build with Cargo using the pinned toolchain in `rust-toolchain.toml`. See the +build guide for native system dependencies. There is no Qt or CMake app build. +The Cargo package retains its historical name, `omarchy-notes-preview`; the +executable is `omarchy-notes-rust`: ```bash -cargo run --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust -cargo test --workspace --locked +cargo build --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust +./target/release/omarchy-notes-rust ``` -For Qt development, build a debug version and run the tests: +Run the Rust checks: ```bash -cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -cmake --build build -ctest --test-dir build --output-on-failure +cargo test --workspace --locked +cargo fmt --all --check +cargo clippy --workspace --all-targets --all-features --locked -- -D warnings ``` -The Qt editor tests drive the real app off-screen and save screenshots to `build/screenshots/`, which is handy for checking what changed visually. `tests/bench_library` measures the performance targets, and [docs/arch-release.md](docs/arch-release.md) explains how releases are made. +Frozen legacy Qt library fixtures remain for migration regression tests; the +Qt source, QML, packaging and live Qt test probes have been removed. -| Folder | What's inside | +| Folder | Contents | |---|---| -| [`crates`](crates) | Rust core, editor, UI, platform, storage and import/export libraries. | -| [`src/core`](src/core) | The engine: the note format, saving to SQLite, attachment storage and theme colours. There's no UI code in here. | -| [`src/app`](src/app) | The app itself: the editor logic and the Qt Quick (QML) interface. | -| [`tests`](tests) | Round-trip, storage (including a "kill it mid-save" durability test), theme contrast, end-to-end editor and launch tests, plus packaging checks. | -| [`packaging`](packaging) | Desktop entry, icon, AppStream metadata, man page and the AUR recipe template. | - -Found a bug or have an idea? [Open an issue](https://github.com/last-refuge/omarchy-notes/issues). It's early days, so feedback shapes where this goes. +| [`crates`](crates) | Rust core, editor, UI, platform, storage and import/export libraries | +| [`packaging`](packaging) | Package recipes, desktop metadata, icons and man pages | +| [`tests`](tests) | Storage, editor, native acceptance, migration and packaging checks | +| [`docs/decisions`](docs/decisions) | Historical architecture decisions, not current installation guidance | +| [`llm-docs`](llm-docs) | Historical plans and evidence ledgers; old Qt support/default statements are superseded | -## 🔒 Security +Found a bug or idea? [Open an issue](https://github.com/last-refuge/omarchy-notes/issues). -If you find a security issue, please **don't** open a public issue. Report it privately by following the steps in [SECURITY.md](SECURITY.md). - -## 📄 License +## Security and license +Report security issues privately via [SECURITY.md](SECURITY.md). Omarchy Notes is released under the [MIT License](LICENSE). ---- - -
-Made for Omarchy 🖤 · Not affiliated with Apple or the Omarchy project -
+Not affiliated with Apple or the Omarchy project. diff --git a/SECURITY.md b/SECURITY.md index eaac7ae..477d83d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,9 @@ ## Supported versions -Security fixes are provided for the latest published Omarchy Notes release. +Security fixes are provided for the latest published Rust Omarchy Notes release +(`rust-v*`, package/executable `omarchy-notes-rust`). The Qt app is retired and no +longer supported; legacy format compatibility is for migration only. Pre-release builds from `master` receive fixes as they are developed, but are not supported releases. @@ -20,10 +22,17 @@ investigate it, and coordinate disclosure and a fixed release with the reporter. ## Data and storage -Omarchy Notes works offline and has no accounts, sync or network access. Notes -are stored locally in SQLite under `$XDG_DATA_HOME/omarchy-notes`, with -attachments kept as files beside the database. Neither is encrypted by the app, -so they're protected only by your user account and any disk encryption on your -system. Backups made with **Back Up Library…** are plain, unencrypted copies of -that data; store them somewhere you trust. Encrypted locked notes are planned but -not yet available. +Omarchy Notes works offline and has no accounts or sync. Notes are stored locally +in SQLite under `$XDG_DATA_HOME/omarchy-notes-gpui` (by default +`~/.local/share/omarchy-notes-gpui`), with attachments beside the database. +Preferences remain under `$XDG_CONFIG_HOME/omarchy-notes-gpui`. `--data-dir` can +select a different library. Neither notes nor attachments are encrypted by the +app; protection depends on your user account and any system disk encryption. +Backups made through Settings → Your notes and files are plain, unencrypted +copies; store them somewhere trusted. Encrypted locked notes are not available. + +Imported files are untrusted input. Review import warnings; external links and +attachments can open other applications whose network and security behavior is +outside the notes app. Installation and dependency fetching require network +access. Preserve original legacy Qt data and verified backups when migrating; +see [migration guidance](docs/migrating.md). diff --git a/crates/notes-ui/assets/NOTICE.md b/crates/notes-ui/assets/NOTICE.md index 68b74cd..284f6ee 100644 --- a/crates/notes-ui/assets/NOTICE.md +++ b/crates/notes-ui/assets/NOTICE.md @@ -7,8 +7,9 @@ https://github.com/notofonts/latin-greek-cyrillic/blob/main/OFL.txt. They were copied from the installed Arch `noto-fonts` package; the embedded license was checked independently of the package's aggregate license file. -Existing line icons were adapted from this project's `src/app/icons/`, under the -repository MIT license, changing black strokes to `currentColor`. The additional +Existing line icons were adapted from the retired Qt app's `src/app/icons/` +(preserved in Git history), under the repository MIT license, changing black +strokes to `currentColor`. The additional simple geometric icons were authored for this preview under the same license. The search adapter's input-handler and custom paint integration follows the GPUI diff --git a/docs/arch-release.md b/docs/arch-release.md index c24b997..327b136 100644 --- a/docs/arch-release.md +++ b/docs/arch-release.md @@ -1,98 +1,14 @@ -# Releasing Omarchy Notes +# Arch releases -Releases follow the same flow as Omarchy Calendar. `packaging/arch/PKGBUILD.in` is a template, -not an AUR submission: release preparation generates `PKGBUILD` and `.SRCINFO` with the checksum -of the exact source archive users will download. +Omarchy Notes now ships only the Rust app. The Qt release route is retired; +old Qt release plans and ADRs are historical records, not current build or +publication instructions. -## 1. Prepare the version +Use [Building and installing Omarchy Notes (Rust)](rust-release.md) for candidate +source preparation, Arch packaging, installer verification and release freeze. +The package/executable remains `omarchy-notes-rust`, desktop ID remains +`org.omarchy.Notes.Rust`, and release tags remain `rust-vVERSION`. +Do not reuse the retired Qt `vVERSION` tags or replace published archives. -Update the version in `CMakeLists.txt` (`project(omarchy-notes VERSION …)`), -`packaging/arch/PKGBUILD.in`, `packaging/metainfo/org.omarchy.Notes.metainfo.xml`, -`packaging/man/omarchy-notes.1` and `CHANGELOG.md`, then check them together: - -```bash -shellcheck install.sh tests/test-installer.sh tests/test-installer-package.sh -./tests/test-installer.sh -./tests/test-release-metadata.sh -./tests/test-package-install.sh -``` - -## 2. Build and check the package locally (optional) - -Commit first: the generator archives a committed revision, not the working tree. It never -creates tags, pushes, or publishes anything. - -```bash -python3 packaging/prepare-release.py --ref HEAD --output build-aur-release -cd build-aur-release/aur && makepkg --cleanbuild && cd ../.. -./tests/check-arch-package.sh build-aur-release/aur -``` - -For a clean-chroot build, use `extra-x86_64-build` instead of `makepkg` (needs `devtools`). -CI builds with `makepkg --syncdeps` in a fresh container, since a chroot can't run inside it. -CI also runs `tests/test-installer-package.sh` as the build user in that disposable -container: it checks a dry run, installs the real package through the installer, -and verifies a repeat run. Only release transport is replaced with local artifacts. - -## 3. Tag and publish - -```bash -git tag v1.0.0 && git push origin v1.0.0 -``` - -The Release workflow checks the metadata, builds and validates the package, and creates a -**draft** GitHub release with: - -- `omarchy-notes-VERSION.tar.gz`: the source archive the AUR package downloads -- `omarchy-notes-VERSION-aur.tar.gz`: `aur/PKGBUILD` and `aur/.SRCINFO` -- the built package, `SHA256SUMS` and `SOURCE_REVISION` -- `install.sh`, also covered by `SHA256SUMS` - -Review the draft: confirm `install.sh` is attached and its checksum is present. -Publish it, then check the AUR files fetch the published archive: - -```bash -tar xf omarchy-notes-1.0.0-aur.tar.gz && cd aur && makepkg --verifysource -``` - -Verify the installer in a disposable Arch system as an unprivileged user, using -the version just published: - -```bash -curl -fsSL https://github.com/last-refuge/omarchy-notes/releases/latest/download/install.sh -o install.sh -less install.sh -bash install.sh --version vVERSION --dry-run -bash install.sh --version vVERSION --no-quick-note -``` - -Before the first release containing an installer, keep the README and website's -primary command pointing at the existing package. After publishing and checking -the installer asset, update both primary commands to: - -```bash -curl -fsSL https://github.com/last-refuge/omarchy-notes/releases/latest/download/install.sh | bash -``` - -Keep the download-and-inspect instructions, direct package command, and CMake -build instructions available. The old v1.0.0 release does not contain an installer; -do not replace its published archives to add one. - -## 4. Submit to the AUR - -The first time, create the package on the AUR by pushing to a new repo: - -```bash -git clone ssh://aur@aur.archlinux.org/omarchy-notes.git aur-omarchy-notes -cp aur/PKGBUILD aur/.SRCINFO aur-omarchy-notes/ -cd aur-omarchy-notes -git add PKGBUILD .SRCINFO && git commit -m "omarchy-notes 1.0.0" && git push -``` - -Only commit `PKGBUILD` and `.SRCINFO`. Never upload the source archive, binaries or -`PKGBUILD.in`. Don't replace a published source archive in place: any change needs a new -version (or `pkgrel` bump) and freshly generated checksums. - -## Screenshots - -`tools/capture-screenshots.sh BUILD_DIR` regenerates the website and README images from the -real app with the sample library, in stock Omarchy themes. +See [release identity](rust-edition.md), [dependency notices](rust-v1-dependency-inventory.md) +and [release notes](rust-release-notes.md) for scope and remaining acceptance work. diff --git a/docs/gpui-preview.md b/docs/gpui-preview.md index b8bcdc1..f3590bb 100644 --- a/docs/gpui-preview.md +++ b/docs/gpui-preview.md @@ -1,11 +1,17 @@ -# Rust / GPUI writing preview +# Rust / GPUI writing and capture guide + +Omarchy Notes is Rust-only; Qt is retired and mentioned below only for legacy +format migration. This guide retains incremental screenshots and verification +notes from development. Old milestone gates are historical, not current support +policy. For current release scope and unverified acceptance items, see the +[release notes](rust-release-notes.md). The Rust edition creates, edits and saves real notes with inline images, attachment cards, rich clipboard exchange and carefully typeset PDF export. It pairs a quiet, serif writing surface with graphite/champagne and warm-paper appearances, selection-aware formatting controls, focus mode and layouts down to 420 logical -pixels. **This is early access.** The Qt app remains the supported release and -installer; the complete rebuild feasibility gate is still open. +pixels. The current installer defaults to Rust. Retirement of Qt does not close +the native/package or human usability verification gaps. ![Images and attachment cards in the real GPUI editor](images/gpui-media-dark.png) @@ -24,16 +30,16 @@ uses installed fonts: `noto-fonts` is recommended, with `noto-fonts-cjk`, `noto-fonts-emoji` and fonts for the languages you write in. Do not run Cargo as root. ```sh -cargo run --release -p omarchy-notes-preview -- --reference -cargo run --release -p omarchy-notes-preview -- --light +cargo run --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust -- --reference +cargo run --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust -- --light # Choose a new library explicitly: -cargo run --release -p omarchy-notes-preview -- --data-dir /tmp/my-rust-notebook +cargo run --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust -- --data-dir /tmp/my-rust-notebook # The original disposable design sample remains opt-in: -cargo run --release -p omarchy-notes-preview -- --demo --reference +cargo run --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust -- --demo --reference ``` Normal launches use `$XDG_DATA_HOME/omarchy-notes-gpui`, falling back to -`~/.local/share/omarchy-notes-gpui`. The installed Qt library is never selected +`~/.local/share/omarchy-notes-gpui`. The retired Qt library is never selected automatically. `--data-dir` can open a compatible library; use a consistent backup/copy for compatibility testing, and close the other edition first. The editions exclude each other through the same `.lock` protocol. Rust forwards @@ -121,8 +127,9 @@ acknowledgement; errors keep your input ready to correct and retry. Filing keeps your current text, caret and undo/redo history and returns you to the editor. Existing rich documents and the Qt-compatible schema are preserved. -Folder deletion, trash, drag-and-drop filing, persistent expansion state and -complete keyboard tree navigation remain pending. See +Folder deletion, Recently Deleted and keyboard tree navigation are available. +Drag-and-drop filing remains deferred; folder deletion Undo restores notes unfiled +rather than rebuilding the deleted folders. See [ADR 0016](decisions/0016-folders-and-filing.md). ## Make yourself at home @@ -234,8 +241,9 @@ path and database digest, but cannot protect a backup that is later moved or del JSON and rich clipboard preserve quotation blocks. HTML uses `blockquote`, and the Markdown conversion backend uses `>`. Pasting a quote into prose keeps its boundaries; nested HTML/Markdown quotes flatten with an explicit warning. PDF -preserves the inset rule across page breaks. Full Markdown file import/export and -media packaging remain pending; the conversion backend is not yet a file UI. +preserves the inset rule across page breaks. Reviewed Markdown/text file import +and portable Markdown/HTML exports with assets are available through Settings; +see [data ownership](rust-data-ownership.md). ## Connect a thought @@ -358,7 +366,7 @@ other Wayland clipboard protocols remain pending. Headless capture, help and version do not initialize a window or GPU: ```sh -printf 'A thought to keep\nSome details.' | cargo run --release -p omarchy-notes-preview -- --capture - +printf 'A thought to keep\nSome details.' | omarchy-notes-rust --capture - ``` Capture now also works while the Rust app owns that library. The note appears in @@ -389,7 +397,7 @@ Use **Ctrl+Shift+N** or the notebook icon beside New Note to open Quick Note. Start directly in its compact writing window, or reach the existing Quick Note: ```sh -cargo run --release -p omarchy-notes-preview -- --reference --quick-note +cargo run --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust -- --reference --quick-note ``` Quick Note has the same rich formatting, images, files and clipboard as the main @@ -416,9 +424,9 @@ It preserves the current note and caret. These options work at startup and when that Rust library is already open: ```sh -target/release/omarchy-notes-preview --new -target/release/omarchy-notes-preview --note NOTE_UUID -target/release/omarchy-notes-preview --quick-note +omarchy-notes-rust --new +omarchy-notes-rust --note NOTE_UUID +omarchy-notes-rust --quick-note ``` Add `--data-dir PATH` when using a different library. `--new` creates and opens @@ -482,15 +490,15 @@ blocks creation. Never use your only copy of a library for fault testing. ### Full-library backups and safe restore -Close the edition using the source library, then use the preview's headless +Close the writer using the source library, then use the Rust app's headless commands. The destination's parent must exist; its final folder must be new. ```sh # Replace the example paths with your library, backup and recovery locations. -target/release/omarchy-notes-preview --data-dir /path/to/library --backup /path/to/new-backup -target/release/omarchy-notes-preview --inspect-backup /path/to/new-backup -target/release/omarchy-notes-preview --restore /path/to/new-backup --data-dir /path/to/new-restored-library -target/release/omarchy-notes-preview --data-dir /path/to/new-restored-library --reference +omarchy-notes-rust --data-dir /path/to/library --backup /path/to/new-backup +omarchy-notes-rust --inspect-backup /path/to/new-backup +omarchy-notes-rust --restore /path/to/new-backup --data-dir /path/to/new-restored-library +omarchy-notes-rust --data-dir /path/to/new-restored-library --reference ``` These commands need no display or running app. Backup takes the shared library @@ -521,15 +529,17 @@ such a directory as a completed backup. An error syncing the parent after publication preserves the completed destination and names it for inspection. The commands refuse missing/damaged assets and unsupported future formats. -Actual Qt backup creation → Rust restore and Rust backup → Qt inspection/open -pass in the scratch-library oracle. SIGKILL tests cover snapshot, blob, manifest +Historical Qt backup creation → Rust restore and Rust backup → Qt inspection/open +passed in the scratch-library oracle. SIGKILL tests cover snapshot, blob, manifest and publication boundaries; injected write failures cover ENOSPC paths. Physical disk-full, sudden power loss, network filesystems and production-scale timing are not verified. The quote-upgrade panel uses this backup path with progress and -cancellation. General in-app backup/restore and Settings routes remain pending. -Schema-3 backups restore in Rust; Qt rejects them. Actual Qt refusal and restoring -the pre-upgrade schema-2 backup are covered by the cross-edition oracle; see -[ADR 0011](decisions/0011-backups-and-quote-migration.md). +cancellation. General in-app backup/restore and Settings routes are now available; +see [data ownership](rust-data-ownership.md). +Schema-3 backups restore in Rust. Historical cross-edition checks verified that +Qt rejected them and could reopen the restored pre-upgrade schema-2 backup; see +[ADR 0011](decisions/0011-backups-and-quote-migration.md). Current regressions use +Rust and frozen legacy fixtures; the live Qt oracle has been retired. ## A page worth sharing @@ -576,17 +586,18 @@ large-document performance guarantees. ## Remaining work -New table merges, trash and folder deletion, tags/Smart Folders, -remaining library views, non-PDF import/export and the in-app backup/restore workflow -remain pending. Personal writing/appearance Settings are available; their -remaining library-action routes still need implementation. Window forwarding, Quick Note and headless verified -backup/restore commands are available. -Library search uses loaded text; SQLite FTS is maintained for compatibility but -is not yet the search backend. Large-document layout and undo memory have not -been optimized or benchmarked. Loaded documents and undo snapshots are in memory. - -The input adapter implements UTF-16 ranges, marked text and caret geometry, with -composition logic tested through GPUI. **Real IME and Orca are not verified.** +New table merges and advanced table operations, tags/Smart Folder interfaces, +gallery and library-wide attachment browsing, drag filing, bulk organization and +browsable revision history remain deferred. Trash, folder deletion, prefix search +with snippets, reviewed imports, portable exports and in-app backup/restore are +implemented. Editor retention and layout have bounded implementations and measured +CPU budgets; broader native fairness/performance acceptance remains follow-up. + +The input adapter implements UTF-16 ranges, marked text and caret geometry. +Release checks recorded actual CJK composition and silent Orca processing, but +**complete human accessibility usability is unverified**. The native Unicode +editing/undo test stopped on stale accessible node traversal; see the +[release notes](rust-release-notes.md) for the evidence boundary. The installed AT-SPI client reports cache-signature warnings and can retain closed-window nodes; the multi-window oracle explicitly selects the active window's accessibility frame. Screen-reader behavior across handoff still needs @@ -601,7 +612,8 @@ geometry need deeper coverage. The pinned Linux AccessKit adapter exposes `Text`, but not AT-SPI `EditableText`; editing uses the keyboard after accessible caret/selection changes. X11 runtime, mixed-DPI, suspend/resume and long-session behavior remain unverified. -These gaps keep M2 open and prevent installer cutover. +These were open M2 gates. Rust is now the installer default, but retirement does +not establish that these checks passed; consult the current release evidence. ## Development checks @@ -625,17 +637,10 @@ cargo run -p notes-ui --example pdf-ui-check --features visual-tests -- target/p # PDF checks also require Poppler and qpdf; --output must name a new directory: cargo build -p notes-export --example pdf-check --locked python tests/test-rust-pdf.py target/debug/examples/pdf-check --output target/pdf-review -# Cross-version checks additionally require Qt6Core, sqlite3, Python and g++: -cargo build --release -p omarchy-notes-preview --locked -cargo build -p notes-storage --example compatibility-edit --locked -python tests/test-rust-compatibility.py target/release/omarchy-notes-preview target/debug/examples/compatibility-edit -cargo build -p notes-storage --example quote-upgrade --locked -python tests/test-rust-backups.py target/release/omarchy-notes-preview --quote-driver target/debug/examples/quote-upgrade -cargo build -p notes-storage --example organization-roundtrip --locked -python tests/test-rust-organization.py target/debug/examples/organization-roundtrip # Durable capture and local Unix IPC, with no graphical session: +cargo build --release -p omarchy-notes-preview --bin omarchy-notes-rust --locked cargo build -p notes-platform --example instance-owner --locked -python tests/test-rust-capture.py target/release/omarchy-notes-preview target/debug/examples/instance-owner +python tests/test-rust-capture.py target/release/omarchy-notes-rust target/debug/examples/instance-owner ``` The writing harness routes real GPUI input through the rich editor and storage @@ -648,8 +653,9 @@ The media harness imports images/files through the real writer queue, checks cached image rendering, removal/undo, stale-cursor confirmation, cancellation, failed import and compact reopen. Storage tests also verify exact portable bytes, remapped ownership, corrupt/missing files, size limits and nonblocking rejection -of special files. The compatibility probe uses the actual Qt document reader and `QLockFile` APIs -against scratch copies; it checks both lock directions and unchanged blob hashes. +of special files. Historical legacy migration oracles used the actual Qt document +reader and `QLockFile` APIs against scratch copies to check both lock directions +and unchanged blob hashes. Those results are migration evidence, not Qt support. For opt-in desktop clipboard/input checks (Hyprland, `wtype`, `wl-clipboard`): diff --git a/docs/index.html b/docs/index.html index b7b4ca8..9d76942 100644 --- a/docs/index.html +++ b/docs/index.html @@ -4,10 +4,10 @@ Omarchy Notes - + - + @@ -208,20 +208,20 @@
- For Omarchy · Native Qt · Free and open source + For Omarchy · Native Rust / GPUI · Free and open source

Notes that feel at home on Omarchy.

-

Apple Notes' easy capture, rebuilt as a fast native app for your desktop. Start typing and it's saved: checklists, tables, images, #tags and search, stored on your machine and dressed in your theme.

+

Local, offline notes in a native Rust app. Rich writing, checklists, basic tables, images, Quick Note and search, stored on your machine with no account required.

- $sudo pacman -U https://github.com/last-refuge/omarchy-notes/releases/download/v1.0.0/omarchy-notes-1.0.0-1-x86_64.pkg.tar.zst + $bash install.sh --version rust-v1.0.0 --no-quick-note
- Other ways to install + Download and inspect the installer
-

Coming soon to the AUR, once it reopens new account sign-ups.

+

x86_64 Arch/Omarchy · Wayland/Hyprland. Qt is retired; legacy migration only.

- Omarchy Notes in the Kanagawa theme: a folder sidebar with tags, a note list, and a meeting note with headings, round checkboxes and a table + Omarchy Notes Rust 1.0 dark writing view
@@ -234,10 +234,10 @@

Everything you reach for, nothing you don't.

Write, it's saved

Autosave confirms "Saved" only once your words are really on disk. If saving ever fails, your text stays put with Retry and Export.

Checklists and tables

Nested checklists with round checkboxes, numbered and bulleted lists, and tables where Tab moves between cells.

-

Images and files

Paste images, attach PDFs and anything else, and browse every attachment across your notes in one place.

-

Folders, tags, Smart Folders

Nest folders, type #work to tag, and save filters like "tagged #work with an open checklist" that stay current.

+

Images and files

Paste images and attach files to notes. Existing merged tables and rich documents are preserved.

+

Folders and filing

Nested folders, pins, sorting and Recently Deleted. Tag/Smart Folder interfaces, gallery and library-wide attachment browsing remain deferred.

Find anything

Search all notes as you type with Ctrl Shift F, or find inside a note with Ctrl F.

-

Quick Note

A small capture window on a key of your choice, plus omarchy-notes --capture "idea" from any terminal.

+

Quick Note

A small capture window on a key of your choice, plus omarchy-notes-rust --capture "idea" from any terminal.

@@ -245,16 +245,16 @@

Everything you reach for, nothing you don't.

Theming

It wears whatever theme you do.

-

Colours come straight from your active Omarchy theme and change the moment you switch, with automatic fixes when a palette would be hard to read.

+

The initial appearance follows supported Omarchy theme settings. Settings remembers your palette, writing font, size and pane preferences.

- A note in the Catppuccin Latte theme -
Catppuccin Latte
+ Rust writing view in a light palette +
Light writing
- The gallery view in the Rosé Pine theme, with an image preview card -
Rosé Pine, gallery view
+ Rust Quick Note window +
Quick Note
@@ -264,12 +264,12 @@

It wears whatever theme you do.

Yours to keep

No account. No cloud. No lock-in.

-

Your library is a folder in ~/.local/share/omarchy-notes: one SQLite database and your attachments.

+

Your library is a folder in ~/.local/share/omarchy-notes-gpui: one SQLite database and your attachments.

@@ -283,32 +283,28 @@

Up and running in a minute.

-

From the latest release

-

On Omarchy or any Arch system, install the package from GitHub Releases:

-
$sudo pacman -U https://github.com/last-refuge/omarchy-notes/releases/download/v1.0.0/omarchy-notes-1.0.0-1-x86_64.pkg.tar.zst
-

Coming soon to the AUR. The AUR has paused new account sign-ups while it deals with a wave of automated registrations. Omarchy Notes will be published there as soon as registration reopens, and then yay -S omarchy-notes will work too.

+

Download and inspect

+

Use the published Rust 1.0 release installer on x86_64 Arch/Omarchy, as your normal user:

+
curl -fsSL https://github.com/last-refuge/omarchy-notes/releases/download/rust-v1.0.0/install.sh -o install.sh
+less install.sh
+bash install.sh --version rust-v1.0.0 --dry-run
+bash install.sh --version rust-v1.0.0 --no-quick-note
+

The current installer installs Rust by default and needs no edition selector. Older edition-aware installers require --edition rust. Checksums and package identity are verified before pacman installation. Run it again to update; data is retained. Binary/package remains omarchy-notes-rust, desktop ID org.omarchy.Notes.Rust.

-

Install with guided progress

-

The checkout installer checks release checksums, shows progress, and offers optional Quick Note setup. Download and inspect it, then run it as your normal user:

-
curl -fsSL https://raw.githubusercontent.com/last-refuge/omarchy-notes/master/install.sh -o install.sh
-less install.sh
-bash install.sh --dry-run
-bash install.sh
-

Run it again to update. Use --version v1.0.0 to choose a release or --source to build with makepkg. --yes accepts package installation; Quick Note requires --quick-note for unattended runs. Your notes are kept. The v1.0.0 release has no installer asset yet.

+

Open and capture

+

Search your launcher for Omarchy Notes (Rust). Use its Rust Quick Note action, omarchy-notes-rust --quick-note, or Ctrl Shift N in the app. A global shortcut needs a manual unused compositor binding; automatic setup is not implemented.

-

Then open it

-

Press Super Space and search for Omarchy Notes. Optional: put Quick Note on Super Alt N. This checks your existing key bindings first and never overwrites one:

-
$omarchy-notes --setup-hyprland
+

Build from source

+

Install the pinned Rust toolchain and native dependencies from the Rust build guide. The Cargo package name is historical:

+
cargo run --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust
+cargo test --workspace --locked
-

Or build it yourself

-

You'll need Qt 6.8 or newer, SQLite, CMake and Ninja.

-
git clone https://github.com/last-refuge/omarchy-notes.git
-cd omarchy-notes
-cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$HOME/.local"
-cmake --build build && cmake --install build
+

Scope and migration

+

Advanced table operations, drag filing, bulk organization and browsable revision history are deferred. X11 and other architectures are not advertised. Native/package and human usability checks still have gaps; see release notes.

+

Qt is retired, not a current install or support option. Migrate copies with verified backups; schema-3 quotation libraries require Rust. See migration and data and backups. Profile names remain unchanged; data and backups are unencrypted.

diff --git a/docs/migrating.md b/docs/migrating.md index 94947e6..852933d 100644 --- a/docs/migrating.md +++ b/docs/migrating.md @@ -1,43 +1,66 @@ # Moving your notes into Omarchy Notes -Omarchy Notes imports Markdown (`.md`) and plain-text (`.txt`) files, one at a time or as whole -folders. Folders become folders, checklists stay checklists, tables stay tables, and images a -note points to are copied into your library. Anything that can't come across (for example -images hosted on the web) is listed after the import, never silently dropped. +The current app is Rust-only. Qt is retired; compatibility with its library and +backup formats exists for legacy migration, not as a supported installation route. -Both options are in the **⋯** menu at the bottom of the folder list: +## Markdown and text imports -- **Import Markdown or Text…** for individual files -- **Import a Folder of Notes…** for a whole exported library +Open **Settings → Your notes and files → Import, export & backups** and choose +Markdown/text files or a folder. Sources are never edited. Review counts and +warnings before **Accept & import**. Folder structure and links between imported +notes receive new identities; supported local assets are copied. -## From Apple Notes +Imports are bounded to 1,000 text files and 64 MiB of text and unique asset bytes. +Symbolic links are refused, and local resources must be within the selected folder +or file's parent. Missing/remote assets and unsupported formatting are reported +before copying. Quotation content requires an explicit format upgrade with a +verified backup. See [data ownership](rust-data-ownership.md) for exact boundaries. -Apple Notes can't export to Markdown by itself, so use an exporter on your Mac first: +### From Apple Notes -1. Install **Exporter** (free) from the Mac App Store. -2. Export all folders as **Markdown**. Exporter writes one folder per Notes folder, with - images alongside. -3. Copy the exported folder to your Omarchy machine. -4. In Omarchy Notes choose **Import a Folder of Notes…** and pick it. +Use a Markdown exporter on your Mac, then copy its exported folders and assets to +your Omarchy machine and import the folder. Exporter output varies: review warnings +and check important notes after import. Unlock protected notes before export; +drawings or scans need an exporter that includes their image files. -Locked (password-protected) notes can't be exported by any tool; unlock them in Apple Notes -first. Drawings and scanned documents come across as images. +### From Obsidian, Logseq, Bear, Joplin and others -## From Obsidian, Logseq, Bear or any Markdown folder +Export to Markdown or select a copy of the Markdown folder. For Joplin, use +**File → Export all → MD – Markdown**. Application-specific metadata and wiki links +may not transfer as functional structures. Tags and Smart Folder interfaces are +not implemented in Rust; do not expect `#tags` to create browsable tag filters. +Review the supported formatting and asset warnings rather than assuming parity +with the source app. -Choose **Import a Folder of Notes…** and pick your vault or export folder. Front matter at the -top of files is skipped, `#tags` in the text become tags, and GitHub-style task lists -(`- [ ]`) become checklists. Wiki links (`[[Note]]`) come across as plain text. +## From the retired Qt app -## From Joplin, Standard Notes and others +The former default library is `~/.local/share/omarchy-notes/`; the Rust profile +remains `~/.local/share/omarchy-notes-gpui/`. Corresponding XDG overrides apply. +Rust does not automatically open, rename or upgrade the former library, and does +not import Qt's `settings.ini` as Rust preferences. -Export to Markdown from the app (Joplin: **File → Export all → MD – Markdown**), then import the -folder. +1. Close any legacy app using the library and preserve a consistent copy plus a + verified backup. Never experiment on the only original. +2. Open the copied compatible library with **Open Library** in Settings, or + `omarchy-notes-rust --data-dir /path/to/copied-library`. For a format-1 backup, + use **Inspect Backup**, then restore into a new directory. +3. Check notes and assets. Existing tags/Smart Folder metadata, merged tables and + revisions are preserved, but their deferred interfaces do not become available. +4. Enabling quotations explicitly upgrades to schema 3 and creates a verified + pre-upgrade backup. Legacy Qt cannot read the upgraded library. A legacy rollback + uses that backup and excludes later Rust edits; preserve the newer library and + back it up or export before any rollback. + +Only Rust owners provide the durable Rust capture/launch protocol. A legacy owner +must close before Rust can acquire the same library. Legacy media clipboard data +requires referenced assets already in the receiving library; cross-library rich +media exchange with Qt is not supported. ## Leaving again -You're never locked in. Use **Export All Notes as Markdown…** in the same menu to get a folder -of Markdown files that mirrors your folders. Images and attachments are included, and links -between notes become relative links. To move to another machine running Omarchy Notes, use -**Back Up Library…** and **Restore from Backup…** instead: that keeps everything exactly as it -is, including pins, Smart Folders and history. +Use Settings to export a note as Markdown/HTML, or a library as Markdown with +assets. PDF is a separate snapshot export and does not include attached file bytes. +Portable formats cannot preserve every application attribute or revision history. +For an exact move to another Rust installation, **Back Up Library**, inspect the +backup, and restore into a new library. The source backup and current notebook +remain intact. Backups are unencrypted; store them somewhere trusted. diff --git a/docs/performance.md b/docs/performance.md index 3eaac29..455050b 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -1,7 +1,9 @@ -# Performance +# Historical Qt performance report -Release gate results for Omarchy Notes 1.0.0, from `tests/bench_library` (build it, then run -`./tests/bench_library 10000 1024` in the build directory). +> Qt is retired. These recorded measurements describe the former Qt 1.0.0 app, +> not the current Rust app. See [Rust performance diagnostics](rust-performance.md). + +Historical release gate results from `tests/bench_library` on the Qt build. The benchmark builds a library of 10,000 generated notes (3–15 paragraphs each, with checklists and #tags mixed in) and 1 GB of image attachments. It then measures storage and diff --git a/docs/rust-data-ownership.md b/docs/rust-data-ownership.md index a9ccf74..f09412d 100644 --- a/docs/rust-data-ownership.md +++ b/docs/rust-data-ownership.md @@ -1,5 +1,8 @@ # Rust notes: import, export and backups +Omarchy Notes is Rust-only. Qt is retired; references to it below describe legacy +migration compatibility, not current support. + Open **Settings → Your notes and files → Import, export & backups**. These routes are implemented in the release branch; final native/package acceptance is still pending. @@ -59,7 +62,7 @@ required before the app reports success. Current main and Quick Note drafts stay available, including when verification or opening fails. Close the old window when convenient; its ordinary save/recovery guards still apply. Opening an already owned Rust library routes to its existing window. A Qt owner must close -before the separate Rust edition can acquire that library. +before the Rust app can acquire that library. See [migration](migrating.md). Use copies and verified backups when moving Qt data. A quotation-format upgrade requires Rust; the pre-upgrade backup is the rollback boundary for Qt. diff --git a/docs/rust-edition.md b/docs/rust-edition.md index bed291c..23dc56b 100644 --- a/docs/rust-edition.md +++ b/docs/rust-edition.md @@ -1,197 +1,105 @@ -# Rust edition: release identity and compatibility contract - -Discovery recorded 13 October 2026 for R0 of the -[Rust v1 release plan](../llm-docs/rust-v1-release-plan.md). -This is the release contract and implementation map for Rust **1.0.0**. -The owner directed release of the implemented build on 13 October 2026. -The evidence ledger records completed checks and remaining follow-up; -the study and five-day trial also follow after release. -R4 source now provides the separate Rust executable/package, compatibility -launcher and metadata, candidate preparation, edition-filtered installer and -CI routes. Focused identity/installer checks pass; clean package builds, -installed/native matrices and the complete license audit remain acceptance work. - -## Separate editions - -| Identity | Supported Qt edition | Planned stable Rust edition | -|---|---|---| -| Arch package / executable | `omarchy-notes` | `omarchy-notes-rust` | -| Desktop / AppStream ID | `org.omarchy.Notes` | `org.omarchy.Notes.Rust` | -| Release tag | `v1.0.0` | `rust-v1.0.0` | -| Default library | `$XDG_DATA_HOME/omarchy-notes` | `$XDG_DATA_HOME/omarchy-notes-gpui` | -| Preferences | `$XDG_CONFIG_HOME/omarchy-notes/settings.ini` | `$XDG_CONFIG_HOME/omarchy-notes-gpui/preferences.json` | -| Initial advertised platform | Existing Qt contract | x86_64 Arch/Omarchy, Wayland/Hyprland | - -The XDG fallbacks are `~/.local/share` and `~/.config`. Stable Rust retains the -preview library and preference locations. The Rust instance protocol already -uses a private `$XDG_RUNTIME_DIR/omarchy-notes-rust` directory; retaining that -protocol and its library-specific identity prevents a preview/stable process -from independently writing the same library. - -Keep the Qt installer as the default. Select Rust explicitly with an edition -option and the Rust tag; do not infer the edition from version `1.0.0`. Rust -must not provide, conflict with, overwrite or silently replace the Qt package. -Desktop names and icons must allow a person to distinguish both editions. - -For the preview executable transition, install an `omarchy-notes-preview` -compatibility launcher that executes the stable Rust binary with the same -arguments and exit status. It should report the Rust executable and version, -preserve the preview data/preferences locations, and never invoke Qt. Test both -direct and compatibility launch paths, including capture without a display. -An older manually installed preview earlier on `PATH` requires a clear warning -and instructions to move that specific old executable aside. - -Availability checks on 13 October 2026: - -- AUR's public RPC for `omarchy-notes-rust` returned `resultcount: 0`. This is - an absence check, not reservation of the name. [AUR lookup](https://aur.archlinux.org/rpc/v5/info?arg%5B%5D=omarchy-notes-rust). -- `git ls-remote --tags origin rust-v1.0.0 rust-v1.0.0-rc.1` returned no refs. - Local Git contains the existing Qt `v1.0.0` tag. Recheck before publishing. -- `org.omarchy.Notes.Rust` is distinct from the Qt and preview IDs in this - repository. Desktop IDs have no central reservation mechanism; this audit - does not claim a global registry check. - -## Feature boundary - -The full port remains larger than the first stable Rust release. The following -comparison is a target scope statement; the release evidence ledger determines -whether each Rust requirement is complete. - -| Workflow | Qt | Rust v1 requirement / limitation | -|---|---|---| -| Rich writing, lists, checks, links, images/files | Available | Required | -| Basic tables and existing merged tables | Available | Basic editing required; preserve and display existing merges; new merges deferred | -| Autosave, conflict recovery, undo/redo | Available | Required | -| Quick Note and installed launch actions | Available | Required | -| Folders, pins, duplication, sorting | Available | Required, including full keyboard tree navigation | -| Search | FTS prefix search | FTS prefix search/snippets, scope and stable keyboard selection required | -| Delete, undo, Recently Deleted, restore | Available | Required, including 30-day retention | -| Markdown/text import | Available | App file/folder routes required | -| Markdown/HTML/PDF export | Available | App per-note routes and library Markdown/assets export required | -| Exact backup, inspect, restore | App routes; restore sets the old library aside | App routes required; restore into a new verified library | -| Palettes, fonts, writing size, pane choices | Available | Existing Rust preferences required | -| Tags and Smart Folders | Available | UI deferred; preserve records and references | -| Gallery, library-wide attachment browser | Available | Deferred | -| Browsable revision history | Stored revisions; no browsable UI found | UI deferred; preserve revisions and referenced media | -| Drag filing, bulk organization, date groups | No corresponding shipped controls found | Deferred | - -Qt libraries are imported as copies with verified backups. Never select or -upgrade the original Qt library automatically. Schema-3 quotation libraries -require Rust; rollback to Qt uses the pre-upgrade backup and excludes later -Rust edits. Offer backup and portable export before rollback. Portable exports -may be lossy and must not be described as lossless backups. - -## Command routes - -These are the advertised Qt application options in `README.md`, its man page -and `src/app/main.cpp`, compared with `crates/omarchy-notes/src/main.rs`. - -| Advertised Qt option | Rust preview route | Stable Rust decision | -|---|---|---| -| `--help`, `--version` | Source builds provide both executable names; the installed alias reports Rust identity | Match Rust workspace/package version; no stable claim while version is 0.x | -| `--data-dir PATH` | Opens any compatible directory supplied by the caller | Retain; guide Qt imports to copies and verified backups | -| `--new` | Main-window launch/forwarding | Retain | -| `--note UUID` | Specific-note launch/forwarding | Retain | -| `--quick-note` | Quick-window launch/forwarding | Retain | -| `--capture TEXT`, stdin `-` | Durable capture/receipt | Retain; verify without display | -| `--setup-hyprland` | Absent | Implement edition-specific setup or an explicit supported installation route before advertising it | -| `--samples` | Absent; `--demo` opens disposable samples | Document distinct behavior; do not silently populate a real library | -| `--simulate-save-failure` | Implemented; developer fixture | Retain as testing option; no success claims on failed writes | - -Rust additionally implements `--request-id UUID` for safe capture retries, -`--capture-status UUID` for read-only receipt checks, `--backup PATH`, -`--inspect-backup PATH`, `--restore PATH --data-dir NEW`, `--reference`, -`--light` and `--demo`. These need Rust-specific help/man documentation. -CLI backup requires closing the writer. Settings → Data provides in-app import, -export, backup, inspection, restore and library opening. In-app backup waits for -pending edits and declares its committed revision boundary. No import/export -CLI is advertised by either edition. - -## Keyboard contracts - -| Advertised Qt action | Qt shortcut | Current Rust route | -|---|---|---| -| New note | Ctrl+N | Same | -| New folder | Ctrl+Shift+N | **Ctrl+Alt+N**; Ctrl+Shift+N opens Rust Quick Note | -| Library search | Ctrl+Shift+F | Same; Ctrl+K also focuses search | -| Find in note, next | Ctrl+F, F3 / Enter | Same | -| Delete selected note | Delete in note list | Keyboard-accessible Note actions → Delete; editor Delete remains text editing | -| Duplicate | Ctrl+D | Keyboard-accessible Note actions → Duplicate; Qt's Ctrl+D shortcut is not assigned | -| Show/hide folders | Ctrl+Shift+S | Absent; do not advertise until implemented | -| Bold / italic / underline | Ctrl+B / I / U | Same | -| Strikethrough / highlight / monospace | Ctrl+Shift+X / Y, Ctrl+E | Same | -| Title / heading / subheading / body | Ctrl+Shift+T / H / J / B | Same; Ctrl+Alt+1 / 2 / 3 / 0 are Rust aliases | -| Checklist / tick | Ctrl+Shift+L / U | Same; Ctrl+Shift+C is a Rust checklist alias | -| Bullet / numbered list | Ctrl+Shift+8 / 7 | Same, including shifted-symbol aliases | -| List indent / outdent | Tab / Shift+Tab | Same; Ctrl+] / [ also available | -| Insert table | Ctrl+Alt+T | Rust opens basic table tools; document that behavior | -| Attach / link note | Ctrl+Shift+A / Ctrl+L | Same | -| Open attachment / object | Double click / Ctrl+Enter | Ctrl+Enter implemented; verify installed cross-app opening | -| Follow link / tag | Ctrl+click | Links require native evidence; tags UI deferred | -| Developer save-failure toggle | Ctrl+Alt+Shift+F | No Rust runtime toggle; CLI fixture only | - -The New Folder / Quick Note collision is deliberate for the separate edition, -not a transparent Qt shortcut migration. Stable documentation and desktop -actions must expose the Rust keys. Additional Rust keys include Ctrl+Shift+O -for Quick-to-main handoff, Ctrl+, for Settings, Ctrl+Backslash for focus mode, -Ctrl+S for Save and Ctrl+Shift+P for PDF. Full folder and recovery keyboard -contracts are R2 work and need focused-context tests so editor keys are not -captured by the tree. - -## Packaging implementation map - -| Files / route | Required change and verification | +# Rust app: release identity and compatibility contract + +Omarchy Notes is a Rust-only app. Qt is retired and relevant only to legacy data +migration. Historical rebuild plans and ADRs record earlier decisions; their Qt +support and installer-default statements are not current policy. + +## Unchanged identity + +| Identity | Rust app | +|---|---| +| Arch package / executable | `omarchy-notes-rust` | +| Cargo application package | `omarchy-notes-preview` | +| Desktop / AppStream ID | `org.omarchy.Notes.Rust` | +| Release tag | `rust-v1.0.0` (future releases: `rust-vVERSION`) | +| Default library | `$XDG_DATA_HOME/omarchy-notes-gpui` | +| Preferences | `$XDG_CONFIG_HOME/omarchy-notes-gpui/preferences.json` | +| Runtime instance directory | `$XDG_RUNTIME_DIR/omarchy-notes-rust` | +| Advertised platform | x86_64 Arch/Omarchy, Wayland/Hyprland | + +The XDG fallbacks are `~/.local/share` and `~/.config`. Retirement does not rename +profiles, binaries or packages. The installed `omarchy-notes-preview` compatibility +launcher executes `omarchy-notes-rust` with the same arguments and exit status, +never Qt. An older manual preview earlier on `PATH` can shadow it; inspect and move +that specific old executable aside rather than deleting profiles. + +The current installer installs Rust by default and needs no edition selector. +Older edition-aware installers require `--edition rust`. Use Rust tags, not the retired `v1.0.0` tag. +Checksums, assets, package metadata and the package-owned executable must match +Rust identity. The package does not provide or conflict with the former +`omarchy-notes` package; retirement is not an automatic package or data replacement. +See [installation and release instructions](rust-release.md). + +## Scope and evidence + +Rich writing, basic tables, images/files, autosave, Quick Note, durable capture, +folders, pins, duplication, sorting, prefix search, Recently Deleted, reviewed +Markdown/text imports, portable exports and exact backup/restore are implemented. +Existing merged tables, tags/Smart Folder metadata and stored revisions are +preserved. New merges and other advanced table operations, tag/Smart Folder UI, +gallery, library-wide attachment browsing, browsable revisions, drag filing and +bulk organization remain deferred. + +Automatic `--setup-hyprland` and the old `--samples` option are not current app +routes. Use the desktop Quick Note action or a manual unused compositor binding; +`--demo` opens disposable samples. X11 and other architectures are not advertised. +Retirement does not resolve native performance/fairness, portal/scaling/suspend, +installed upgrade/rollback verification or human accessibility/usability gaps. +See the [release notes](rust-release-notes.md) and historical +[release evidence](../llm-docs/rust-v1-release-evidence.md) for exact results and limits. + +## Current command routes + +| Option | Behavior | +|---|---| +| `--help`, `--version` | Show Rust app help/version | +| `--data-dir PATH` | Open a selected compatible library | +| `--new`, `--note UUID` | Launch/forward a new or specific note | +| `--quick-note` | Launch/forward Quick Note | +| `--capture TEXT` (or `-` for stdin) | Durable text capture | +| `--request-id UUID`, `--capture-status UUID` | Safe capture retry and read-only receipt checks | +| `--backup PATH`, `--inspect-backup PATH` | Headless backup/inspection; close the writer for CLI backup | +| `--restore PATH --data-dir NEW` | Restore into a new library | +| `--reference`, `--light` | Launch palette overrides | +| `--demo` | Disposable design sample | +| `--simulate-save-failure` | Developer fixture, not a runtime keyboard toggle | + +Settings → Your notes and files supplies reviewed import/export, backup, +inspection, safe restore and library opening. No import/export CLI is advertised. +See [data ownership](rust-data-ownership.md) and the [writing guide](gpui-preview.md). + +## Keyboard routes + +| Action | Rust shortcut / route | |---|---| -| Workspace and `crates/omarchy-notes/Cargo.toml` | Stable executable/package identity; preserve compatibility launcher; align version only at final freeze | -| `notes-ui/src/lib.rs`, `quick_note.rs` | Use stable desktop ID for all windows; keep IDs distinct from Qt; update native tests that locate the launched test window | -| New Rust desktop, AppStream, man and icon metadata | Explicit Rust names, new/quick actions, stable app ID, help/version and target feature scope; validate desktop/AppStream syntax | -| New `packaging/arch/PKGBUILD-rust.in` | x86_64 only; pinned locked Cargo build; install app, alias, metadata, icon and all notices; no dependency on cached checkout | -| `packaging/prepare-release.py` | Explicit edition selection; version/tag checks per edition; immutable archive names and recipes; preserve Qt route | -| `install.sh` | Explicit opt-in edition; tag/asset/package/executable allowlists; separate dependency sets and default data paths; keep strict package identity checks | -| Installer latest route | GitHub `/releases/latest` can select either edition; select latest published release of the requested edition explicitly and test mixed ordering | -| `tests/test-release-metadata.sh`, package/installer tests | Preserve Qt checks; add Rust identity, cross-edition rejection, compatibility launch, capture and coexistence checks | -| `.github/workflows/ci.yml`, `release.yml` | Preserve Qt CI; add clean Rust packaging and `rust-v*` tag route; checksums/source hash and draft release from exact committed source | -| Rust release/build/rollback docs | Separate source build and installer commands, feature limits and actual screenshots; no untested X11/aarch64 claims | - -The installer now selects package, executable, tag and asset patterns from a -closed Qt/Rust allowlist; it rejects cross-edition names. Latest discovery filters -published release tags by edition. Rust Quick Note uses its desktop action or -the documented manual distinct-key route; automatic Qt setup is never invoked -for Rust. See [Rust release instructions](rust-release.md). - -## Runtime and license discovery - -The existing local release binary reports `omarchy-notes-preview 0.1.0`, is -285,223,488 bytes before stripping, and has SHA-256 -`295984b9066a78faf1ff84657f89324aabddd3fc06a971f9198f77eb36258ed0`. -It is a discovery artifact, not a reproducible release candidate. `readelf -d` -found no RPATH/RUNPATH and direct dependencies owned by Arch packages `glibc`, -`libgcc`, `glib2`, `libxcb`, `libxkbcommon`, `libxkbcommon-x11`, `pango` and -`cairo`; `ldd` resolved them on this developer machine. Wayland is loaded via -`dlopen` in pinned GPUI, so `ldd` alone is insufficient. Include Wayland, -Vulkan loader/driver, portal and attachment-launch requirements after testing -the candidate in a clean environment. Building with X11 support does not mean -X11 is advertised as tested. - -Toolchain discovery: rustc 1.99.0, x86_64; GPUI/platform pin -`a84689073d296dfd39987bc7dd478e43ef76d83a`. The current workspace declares both -Wayland and X11 features. Re-evaluate dependency declarations from the final -binary rather than this preliminary list. - -`cargo metadata --locked --offline` found 769 packages across all targets and -build/dev dependencies, with no missing Cargo license field. This is an -inventory starting point, not a redistribution-license audit. Optional -copyleft alternatives (`r-efi`, `self_cell`) also offer permissive choices; -MPL-2.0 appears on `cbindgen`, `dwrote` and `option-ext`. Determine which are -actually shipped, record selected licenses, gather required texts/notices, and -audit generated/bundled native code. Existing `notes-ui/assets/NOTICE.md`, -`GPUI-LICENSE` and Noto `fonts/OFL.txt` cover the bundled fonts/icon provenance -and GPUI source guidance. A release package must install these, the repository -MIT license and dependency notices. Runtime system libraries have their own -system packages and licensing. - -R4 remains blocked on a clean source-to-package build, disposable install / -preview transition / coexistence / upgrade / removal / rollback checks, -candidate runtime and license audit, native installed-launch/portal tests and -exact-source hosted CI evidence. R5 requires real participants and five actual -working days; no automated result substitutes for those gates. +| New note / folder | Ctrl+N / Ctrl+Alt+N | +| Quick Note / handoff to main | Ctrl+Shift+N / Ctrl+Shift+O | +| Library search / find in note | Ctrl+Shift+F or Ctrl+K / Ctrl+F | +| Next find match | F3 / Enter | +| Delete / duplicate note | Keyboard-accessible Note actions | +| Bold / italic / underline | Ctrl+B / I / U | +| Strikethrough / highlight / monospace | Ctrl+Shift+X / Y, Ctrl+E | +| Title / heading / subheading / body | Ctrl+Shift+T / H / J / B; Ctrl+Alt+1 / 2 / 3 / 0 | +| Checklist / tick | Ctrl+Shift+L / U; Ctrl+Shift+C checklist alias | +| Bullet / numbered list | Ctrl+Shift+8 / 7 | +| List indent / outdent | Tab / Shift+Tab; Ctrl+] / [ | +| Basic table tools | Ctrl+Alt+T | +| Attach file / link note | Ctrl+Shift+A / Ctrl+L | +| Open attachment / object | Ctrl+Enter | +| Settings / focus mode | Ctrl+, / Ctrl+Backslash | +| Save / PDF export | Ctrl+S / Ctrl+Shift+P | + +Qt shortcuts are not a transparent migration contract: Ctrl+Shift+N is now Quick +Note, Ctrl+D is not assigned to duplication, and Ctrl+Shift+S is not advertised +for hiding folders. Native cross-app opening and link behavior still need the +verification described in the acceptance record. + +## Legacy data boundary + +The retired Qt library was `$XDG_DATA_HOME/omarchy-notes`; its preferences were +`$XDG_CONFIG_HOME/omarchy-notes/settings.ini`. Neither is automatically selected, +renamed or upgraded. Close any legacy writer, migrate consistent copies with +verified backups, and preserve the originals. Schema-3 quotation libraries require +Rust. A rollback to a legacy reader uses the pre-upgrade backup and excludes later +Rust edits. Portable exports can be lossy; keep exact backups. +See [migration](migrating.md). diff --git a/docs/rust-release-notes.md b/docs/rust-release-notes.md index 280a189..0235db9 100644 --- a/docs/rust-release-notes.md +++ b/docs/rust-release-notes.md @@ -1,24 +1,26 @@ # Omarchy Notes Rust 1.0.0 -The first separate Rust edition provides an offline notes app with rich writing, +Omarchy Notes is now Rust-only; Qt is retired and retained only as a legacy +migration reference. The Rust 1.0 app provides offline notes with rich writing, Quick Note and durable command-line capture, nested keyboard-accessible folders, pinning, three sort modes, prefix search and snippets, duplication, Recently Deleted, Undo and recovery. Settings provides reviewed Markdown/text import, Markdown/HTML/PDF note export, library Markdown plus assets, exact backups, inspection, safe restore into a new library and library opening. -Install the x86_64 Arch/Omarchy edition explicitly: +Install on x86_64 Arch/Omarchy. The current installer installs Rust by default; +older edition-aware installers require `--edition rust`. ```sh -bash install.sh --edition rust --version rust-v1.0.0 --no-quick-note +bash install.sh --version rust-v1.0.0 --no-quick-note ``` The executable/package is `omarchy-notes-rust`, desktop identity is `org.omarchy.Notes.Rust`, and the `omarchy-notes-preview` compatibility launcher forwards to Rust. Existing Rust notes/preferences remain at `omarchy-notes-gpui`. -Qt remains available and remains the default installer edition. +Retirement changes neither Rust package identity nor its historical profile paths. -Use copies and verified backups for Qt libraries. Quotation/schema-3 libraries +Use copies and verified backups for retired Qt libraries; see [migration](migrating.md). Quotation/schema-3 libraries require Rust; return to Qt using the pre-upgrade backup, which excludes later Rust edits. Keep the newer library and export/backup before rollback. Folder deletion Undo restores notes unfiled; it does not rebuild deleted folders. @@ -27,7 +29,8 @@ Tags/Smart Folder interfaces, advanced table operations, gallery, drag filing, bulk organization and browsable revision history remain deferred; existing metadata and merged tables are preserved. X11 and other architectures are not advertised. Use the desktop Quick Note action or a distinct manual compositor -binding; the Rust installer does not alter the Qt shortcut. +binding; automatic compositor setup is not implemented and legacy bindings are +not altered. The implemented build was released at the owner's direction on 13 October 2026. Recorded checks include 171 Rust tests, six dependency tests, full Qt regression diff --git a/docs/rust-release.md b/docs/rust-release.md index 2bb83fc..62d7376 100644 --- a/docs/rust-release.md +++ b/docs/rust-release.md @@ -1,4 +1,4 @@ -# Building and installing the separate Rust edition +# Building and installing Omarchy Notes (Rust) The Rust workspace is **1.0.0**, released at the owner's direction on 13 October 2026. The evidence ledger distinguishes completed checks from @@ -6,9 +6,21 @@ remaining follow-up; no unverified check is presented as passed. The five-person first-use study and five-working-day trial also follow after release. Rust uses `omarchy-notes-rust`, desktop identity `org.omarchy.Notes.Rust`, and -the separate `rust-v1.0.0` tag. Qt remains the default installer route -and its `omarchy-notes` package remains available. Rust has no `provides` or -`conflicts` relationship with Qt. +the `rust-v1.0.0` tag. Omarchy Notes is Rust-only; Qt is retired and relevant +only for legacy migration. Binary/package/profile identity is unchanged. Rust +has no `provides` or `conflicts` relationship with the retired Qt package. + +## Run from source + +Install the toolchain in `rust-toolchain.toml` through rustup and the native +[development dependencies](gpui-preview.md#run-it). Do not run Cargo as root. + +```sh +cargo run --release --locked -p omarchy-notes-preview --bin omarchy-notes-rust +cargo test --workspace --locked +``` + +The Cargo package name is historical; it does not change the app identity. ## Candidate source and package @@ -17,7 +29,7 @@ revision, excluding dirty and untracked files, and refuses an existing output directory. Use a new directory per candidate: ```sh -python3 packaging/prepare-release.py --edition rust --candidate \ +python3 packaging/prepare-release.py --candidate \ --ref COMMIT_SHA --output build-rust-candidate cd build-rust-candidate/aur makepkg --syncdeps --cleanbuild @@ -55,15 +67,16 @@ this list does not claim that audit is complete. ## Published installer route After a Rust release is actually published, download and inspect its installer -before running it. Select Rust explicitly: +before running it. The current installer installs Rust by default and needs no +edition selector. Older edition-aware installers require `--edition rust`. ```sh -bash install.sh --edition rust --version rust-vVERSION --dry-run -bash install.sh --edition rust --version rust-vVERSION --no-quick-note +bash install.sh --version rust-vVERSION --dry-run +bash install.sh --version rust-vVERSION --no-quick-note ``` -Without `--edition rust`, the installer selects Qt. Its latest-release lookup -filters published, non-draft, non-prerelease tags by the chosen edition; if no +The installer selects Rust releases by default. Its latest-release lookup +filters published, non-draft, non-prerelease Rust tags; if no match occurs in the newest 100 releases, choose an explicit tag. Tags, assets, package metadata and the package-owned executable must all match that edition. The installer requires Python 3 for this JSON lookup, along with its existing @@ -79,14 +92,14 @@ on `PATH` may take precedence; move that specific executable aside after verifying the package-owned one. The installer reports such shadowing and does not delete manual copies. -## Quick Note and coexistence +## Quick Note Choose **Rust Quick Note** from the Rust desktop launcher's actions, run -`omarchy-notes-rust --quick-note`, or use Ctrl+Shift+N inside Rust. Qt and Rust -must use distinct global shortcut keys. For a compositor binding, choose an -unused key such as Super+Alt+Shift+N and execute the absolute Rust command above; -use `org.omarchy.Notes.Rust` when matching its windows. Keep the existing Qt -binding intact. Follow the configuration format used by your installed Omarchy +`omarchy-notes-rust --quick-note`, or use Ctrl+Shift+N inside Rust. For a +compositor binding, choose an unused key such as Super+Alt+Shift+N and execute +`/usr/bin/omarchy-notes-rust --quick-note`; use `org.omarchy.Notes.Rust` when +matching its windows. Do not overwrite a legacy binding during migration. +Follow the configuration format used by your installed Omarchy version; Lua and native Hyprland configuration are not interchangeable. Rust does not currently implement automatic `--setup-hyprland`. The installer's @@ -96,7 +109,8 @@ floating-rule and shortcut behavior still require the supported-platform matrix. ## Recovery and release freeze -Use copies and verified backups when bringing Qt libraries into Rust. Enabling +Use copies and verified backups when migrating retired Qt libraries into Rust; +see [migration](migrating.md). Enabling quotations creates schema-3 data requiring Rust; returning to Qt uses the pre-upgrade backup and excludes later Rust edits. Preserve the newer Rust library and export/backup before rollback. Restore into a new verified directory rather @@ -106,6 +120,7 @@ are useful copies, not lossless replacements for library backups. At the final freeze, align workspace, man page, AppStream and release versions, record every required gate on that exact revision, and use `rust-vVERSION`. Stable artifact preparation requires that exact Rust tag and refuses Qt tags. -The Rust release workflow creates a draft only; reviewing or publishing it and -changing the default edition are separate decisions. Never replace an existing -published archive or reuse Qt's tag. +The Rust release workflow creates a draft only; reviewing and publishing it are +separate decisions. The installer default is now Rust, not a reason to rename +packages or profiles. Never replace an existing published archive or reuse a +retired Qt tag. diff --git a/install.sh b/install.sh index 0886d09..5b71a4c 100755 --- a/install.sh +++ b/install.sh @@ -12,18 +12,17 @@ Omarchy Notes installer. A place for your thoughts. Installs a verified release package on Omarchy or Arch Linux. Run again to update. Your notes and running application are kept. - --version TAG select a published release (for example v1.0.0) - --edition qt|rust choose the edition (default: qt; Rust is separate) - --source build the selected release with makepkg as your user + --version TAG select a published Rust release (for example rust-v1.0.0) + --source build the selected Rust release with makepkg as your user --yes, -y accept package installation without confirmation --dry-run inspect the release and show the plan without installing - --quick-note opt in to the Quick Note key and floating window rule + --quick-note show manual Quick Note setup instructions --no-quick-note skip Quick Note setup --help, -h show this help Without a terminal, installation requires --yes and noninteractive sudo access. --yes alone never enables Quick Note. NO_COLOR disables color and animation. -Other Linux systems: see the README for building with CMake into ~/.local. +Other Linux systems: see the README for building with Cargo. USAGE } @@ -197,18 +196,18 @@ build_source() { } finish() { - local binary='' preview_alias='' package_name path count=0 alias_count=0 output shadow config data + local binary='' preview_alias='' package_name path count=0 alias_count=0 output shadow data pacman -Ql "$PACKAGE_NAME" "$WORK/installed-files" 2>>"$LOG" || die 'Installed package file list is unavailable.' while read -r package_name path; do if [[ $package_name == "$PACKAGE_NAME" && $path == /*/bin/"$EXECUTABLE" ]]; then binary=$path; count=$((count + 1)) fi - if [[ $EDITION == rust && $package_name == "$PACKAGE_NAME" && $path == /*/bin/omarchy-notes-preview ]]; then + if [[ $package_name == "$PACKAGE_NAME" && $path == /*/bin/omarchy-notes-preview ]]; then preview_alias=$path; alias_count=$((alias_count + 1)) fi done <"$WORK/installed-files" (( count == 1 )) && [[ -x $binary ]] || die 'The installed application executable is missing or ambiguous.' - output=$(env -u QT_QPA_PLATFORMTHEME QT_QPA_PLATFORM=offscreen "$binary" --version >"$LOG") || + output=$("$binary" --version >"$LOG") || die 'Package installed, but application verification failed. See the log before launching it.' [[ $output == "$EXECUTABLE $VERSION" ]] || die "Installed application reports an unexpected version: $output." ok "Application verified $BULLET $output" @@ -217,40 +216,18 @@ finish() { warn "An older or separate copy at $shadow takes precedence on PATH." note "Use $binary for the package version; move the older copy aside when ready." fi - if [[ $EDITION == rust ]]; then - (( alias_count == 1 )) && [[ -x $preview_alias ]] || die 'The package-owned preview compatibility launcher is missing or ambiguous.' - output=$("$preview_alias" --version >"$LOG") || die 'The preview compatibility launcher could not execute Rust.' - [[ $output == "$EXECUTABLE $VERSION" ]] || die "The preview compatibility launcher reports an unexpected version: $output." - shadow=$(command -v omarchy-notes-preview || true) - if [[ -n $shadow && $(readlink -f -- "$shadow") != "$(readlink -f -- "$preview_alias")" ]]; then - warn "An older preview at $shadow takes precedence on PATH; move that specific copy aside when ready." - fi + (( alias_count == 1 )) && [[ -x $preview_alias ]] || die 'The package-owned preview compatibility launcher is missing or ambiguous.' + output=$("$preview_alias" --version >"$LOG") || die 'The preview compatibility launcher could not execute Rust.' + [[ $output == "$EXECUTABLE $VERSION" ]] || die "The preview compatibility launcher reports an unexpected version: $output." + shadow=$(command -v omarchy-notes-preview || true) + if [[ -n $shadow && $(readlink -f -- "$shadow") != "$(readlink -f -- "$preview_alias")" ]]; then + warn "An older preview at $shadow takes precedence on PATH; move that specific copy aside when ready." fi - config=${XDG_CONFIG_HOME:-$HOME/.config} - if [[ $EDITION == rust ]]; then - if [[ $QUICK == yes ]]; then - note 'Rust Quick Note is available in the desktop launcher or with omarchy-notes-rust --quick-note.' - note 'Automatic Rust compositor setup is not implemented; use the distinct-key instructions in docs/rust-release.md. No bindings were changed.' - fi - elif (( IS_OMARCHY )) && [[ -f $config/hypr/bindings.lua && -f $config/hypr/hyprland.lua ]]; then - if [[ $QUICK == ask ]] && (( HAVE_TTY && ! YES )); then - if confirm 'Set up Quick Note with Super + Alt + N?' y/N; then QUICK=yes; fi - fi - if [[ $QUICK == yes ]]; then - if env -u QT_QPA_PLATFORMTHEME QT_QPA_PLATFORM=offscreen "$binary" --setup-hyprland "$WORK/quick-note" 2>>"$LOG"; then - ok 'Quick Note setup complete' - else - warn 'Notes is installed. Quick Note setup needs attention (the key may already be taken).' - RETAIN_LOG=1 - note "Setup log: $LOG" - fi - tee -a "$LOG" <"$WORK/quick-note" - fi - elif [[ $QUICK == yes ]]; then - warn 'Notes is installed. Quick Note setup requires compatible Omarchy Lua configuration.' + if [[ $QUICK == yes ]]; then + note 'Rust Quick Note is available in the desktop launcher or with omarchy-notes-rust --quick-note.' + note 'Automatic Rust compositor setup is not implemented; use the distinct-key instructions in docs/rust-release.md. No bindings were changed.' fi - if [[ $EDITION == rust ]]; then data=${XDG_DATA_HOME:-$HOME/.local/share}/omarchy-notes-gpui - else data=${OMARCHY_NOTES_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/omarchy-notes}; fi + data=${XDG_DATA_HOME:-$HOME/.local/share}/omarchy-notes-gpui [[ $data == /* ]] || data=$PWD/$data printf '\n %sReady to write%s\n' "$BOLD" "$RESET" if (( IS_OMARCHY )); then printf ' Super + Space, then type "%s"\n' "$DISPLAY_NAME"; fi @@ -265,7 +242,7 @@ finish() { main() { presentation - YES=0; DRY=0; SOURCE=0; QUICK=ask; TAG=''; EDITION=qt; WORK=''; LOG=''; ACTIVE_PID=''; RETAIN_LOG=0 + YES=0; DRY=0; SOURCE=0; QUICK=no; TAG=''; WORK=''; LOG=''; ACTIVE_PID=''; RETAIN_LOG=0 local quick_option='' option while (( $# )); do option=$1 @@ -274,8 +251,6 @@ main() { --yes|-y) YES=1 ;; --dry-run) DRY=1 ;; --source) SOURCE=1 ;; - --edition) shift; (( $# )) || die '--edition requires qt or rust.'; EDITION=$1 ;; - --edition=*) EDITION=${option#*=} ;; --version) shift; (( $# )) && [[ -n $1 ]] || die '--version requires a release tag.'; TAG=$1 ;; --version=*) TAG=${option#*=}; [[ -n $TAG ]] || die '--version requires a release tag.' ;; --quick-note|--no-quick-note) @@ -286,12 +261,8 @@ main() { esac shift done - case "$EDITION" in - qt) PACKAGE_NAME=omarchy-notes; EXECUTABLE=omarchy-notes; TAG_PREFIX=v; DISPLAY_NAME='Omarchy Notes' ;; - rust) PACKAGE_NAME=omarchy-notes-rust; EXECUTABLE=omarchy-notes-rust; TAG_PREFIX=rust-v; DISPLAY_NAME='Omarchy Notes (Rust)' ;; - *) die '--edition must be qt or rust.' ;; - esac - [[ -z $TAG || $TAG =~ ^${TAG_PREFIX}[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "--version must be a stable release tag for $EDITION such as ${TAG_PREFIX}1.0.0." + PACKAGE_NAME=omarchy-notes-rust; EXECUTABLE=omarchy-notes-rust; TAG_PREFIX=rust-v; DISPLAY_NAME='Omarchy Notes (Rust)' + [[ -z $TAG || $TAG =~ ^${TAG_PREFIX}[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "--version must be a stable Rust release tag such as ${TAG_PREFIX}1.0.0." HAVE_TTY=0 if ( : /dev/null; then HAVE_TTY=1; fi if (( ! DRY )); then @@ -301,10 +272,9 @@ main() { [[ $(uname -s) == Linux ]] || die 'This installer supports Linux. See the README for build instructions.' IS_OMARCHY=0 if [[ -d /usr/share/omarchy ]] || command -v omarchy >/dev/null 2>&1; then IS_OMARCHY=1; fi - [[ -f /etc/arch-release ]] || die 'This installer supports Omarchy and Arch Linux. See the README for a CMake build.' + [[ -f /etc/arch-release ]] || die 'This installer supports Omarchy and Arch Linux. See the README for a Cargo build.' ARCH=$(uname -m) - [[ $ARCH == x86_64 || $ARCH == aarch64 ]] || die "Unsupported architecture: $ARCH. See the README for building with CMake." - [[ $EDITION != rust || $ARCH == x86_64 ]] || die 'The Rust edition currently supports x86_64 only.' + [[ $ARCH == x86_64 ]] || die "Unsupported architecture: $ARCH. Rust currently supports x86_64 only." local tool for tool in curl sha256sum pacman setsid mktemp awk sed tail readlink python3; do command -v "$tool" >/dev/null || die "Missing prerequisite: $tool. Install it and try again." @@ -353,11 +323,8 @@ PY die "Could not download checksums for $TAG. Check that the release exists and the network is available." read_manifest PACMAN_FLAGS=(); (( ! YES )) || PACMAN_FLAGS+=(--noconfirm) - BUILD_DEPS=(base-devel cmake ninja pkgconf qt6-base qt6-declarative qt6-svg sqlite) - if [[ $EDITION == rust ]]; then - BUILD_DEPS=(base-devel rustup clang cmake pkgconf git vulkan-headers python glib2 cairo pango libxcb - libxkbcommon libxkbcommon-x11 wayland vulkan-icd-loader hicolor-icon-theme noto-fonts-cjk noto-fonts-emoji xdg-desktop-portal xdg-utils) - fi + BUILD_DEPS=(base-devel rustup clang cmake pkgconf git vulkan-headers python glib2 cairo pango libxcb + libxkbcommon libxkbcommon-x11 wayland vulkan-icd-loader hicolor-icon-theme noto-fonts-cjk noto-fonts-emoji xdg-desktop-portal xdg-utils) local recipe='' recipe_hash='' source='' source_hash='' installed='' if (( SOURCE )); then select_asset "^${PACKAGE_NAME}-${version_pattern}-aur\\.tar\\.gz$" 'AUR recipe' @@ -382,10 +349,8 @@ PY note "Would download and verify $ASSET, and check its package identity." fi if (( SOURCE )) || [[ $installed != "$PACKAGE_NAME $PACKAGE_VERSION" ]]; then note 'Would run sudo pacman -U .'; fi - note 'Would verify the package-owned executable with off-screen --version.' - if [[ $QUICK == yes && $EDITION == rust ]]; then note 'Would show the Rust desktop Quick Note action and manual distinct-key setup instructions.' - elif [[ $QUICK == yes ]]; then note 'Would set up Quick Note on compatible Omarchy configuration.' - elif [[ $EDITION == qt && $QUICK == ask ]] && (( IS_OMARCHY && ! YES )); then note 'Would offer optional Quick Note setup in an interactive terminal.'; fi + note 'Would verify the package-owned executable with --version.' + if [[ $QUICK == yes ]]; then note 'Would show the Rust desktop Quick Note action and manual distinct-key setup instructions.'; fi printf '\n'; return 0 fi if (( SOURCE )) || [[ $installed != "$PACKAGE_NAME $PACKAGE_VERSION" ]]; then diff --git a/packaging/arch/PKGBUILD-rust.in b/packaging/arch/PKGBUILD-rust.in index a292e65..fa7997c 100644 --- a/packaging/arch/PKGBUILD-rust.in +++ b/packaging/arch/PKGBUILD-rust.in @@ -1,5 +1,5 @@ # Maintainer: Jason Alexander -# Generated from an immutable revision. Rust remains separate from the Qt package. +# Generated from an immutable revision. Preserve the Rust executable identity. pkgname=omarchy-notes-rust pkgver=@RUST_VERSION@ pkgrel=1 diff --git a/packaging/arch/PKGBUILD.in b/packaging/arch/PKGBUILD.in deleted file mode 100644 index 418aede..0000000 --- a/packaging/arch/PKGBUILD.in +++ /dev/null @@ -1,34 +0,0 @@ -# Maintainer: Jason Alexander -# Generated with packaging/prepare-release.py; submit the generated copy to AUR. -pkgname=omarchy-notes -pkgver=1.0.0 -pkgrel=1 -pkgdesc='Fast, native notes for Omarchy, inspired by Apple Notes' -arch=('x86_64' 'aarch64') -url='https://lastrefuge.ai/projects/omarchy-notes' -license=('MIT') -depends=('glibc' 'hicolor-icon-theme' 'libgcc' 'libstdc++' 'qt6-base' 'qt6-declarative' 'qt6-svg' 'sqlite') -makedepends=('cmake' 'ninja' 'pkgconf') -optdepends=('qt6-wayland: native Wayland support' - 'qt6-imageformats: WebP, TIFF and other image formats in notes' - 'xdg-utils: open attachments in their default applications') -source=("https://github.com/last-refuge/omarchy-notes/releases/download/v${pkgver}/${pkgname}-${pkgver}.tar.gz") -b2sums=('@SOURCE_B2SUM@') - -build() { - cmake -S "$pkgname-$pkgver" -B build -G Ninja \ - -DCMAKE_BUILD_TYPE=None \ - -DCMAKE_INSTALL_PREFIX=/usr \ - -DCMAKE_INSTALL_LIBDIR=lib \ - -DBUILD_TESTING=OFF \ - -Wno-dev - cmake --build build -} - -check() { - QT_QPA_PLATFORM=offscreen "$srcdir/build/src/app/omarchy-notes" --version -} - -package() { - DESTDIR="$pkgdir" cmake --install build -} diff --git a/packaging/desktop/org.omarchy.Notes.desktop.in b/packaging/desktop/org.omarchy.Notes.desktop.in deleted file mode 100644 index 63a6fb3..0000000 --- a/packaging/desktop/org.omarchy.Notes.desktop.in +++ /dev/null @@ -1,21 +0,0 @@ -[Desktop Entry] -Type=Application -Name=Omarchy Notes -GenericName=Notes -Comment=Rich notes with checklists, tables and attachments -Exec=@ONOTES_BIN@ -Icon=@ONOTES_APP_ID@ -Terminal=false -Categories=Office; -Keywords=notes;notebook;checklist;todo;omarchy; -StartupNotify=true -StartupWMClass=@ONOTES_APP_ID@ -Actions=new-note;quick-note; - -[Desktop Action new-note] -Name=New Note -Exec=@ONOTES_BIN@ --new - -[Desktop Action quick-note] -Name=Quick Note -Exec=@ONOTES_BIN@ --quick-note diff --git a/packaging/icons/org.omarchy.Notes.svg b/packaging/icons/org.omarchy.Notes.svg deleted file mode 100644 index fbf3b43..0000000 --- a/packaging/icons/org.omarchy.Notes.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/packaging/man/omarchy-notes-rust.1 b/packaging/man/omarchy-notes-rust.1 index ff6872f..79a06c0 100644 --- a/packaging/man/omarchy-notes-rust.1 +++ b/packaging/man/omarchy-notes-rust.1 @@ -1,12 +1,12 @@ .TH OMARCHY-NOTES-RUST 1 "October 2026" "omarchy-notes-rust 1.0.0" "User Commands" .SH NAME -omarchy-notes-rust \- private local notes, separate Rust edition +omarchy-notes-rust \- private local notes .SH SYNOPSIS .B omarchy-notes-rust .RI [ options ] .SH DESCRIPTION -The Rust edition is separately installable from the supported Qt edition. -Version 1.0.0 is the first separate Rust release. +Omarchy Notes is a Rust application for private local notes. +Version 1.0.0 is the first Rust release. Its library and preferences retain the preview locations. The installed .B omarchy-notes-preview compatibility launcher executes the Rust application with unchanged arguments. @@ -52,7 +52,7 @@ Open disposable sample notes. Exercise recovery with a scratch library; not an ordinary writing option. .TP .B \-\-help, \-\-version -Show Rust edition help or version. +Show application help or version. .SH KEYBOARD Ctrl+N creates a note, Ctrl+S saves, Ctrl+K searches, Ctrl+, opens Settings, and Ctrl+Backslash toggles focus mode. Ctrl+Shift+N opens Quick Note; @@ -80,6 +80,4 @@ The desktop launcher has a Rust Quick Note action. Optional compositor shortcuts should use a distinct key and the org.omarchy.Notes.Rust application identity; the installer does not claim to modify Rust compositor bindings automatically. .SH SEE ALSO -.BR omarchy-notes (1) -.PP https://github.com/last-refuge/omarchy-notes diff --git a/packaging/man/omarchy-notes.1 b/packaging/man/omarchy-notes.1 deleted file mode 100644 index 76d8f9e..0000000 --- a/packaging/man/omarchy-notes.1 +++ /dev/null @@ -1,58 +0,0 @@ -.TH OMARCHY-NOTES 1 "September 2026" "omarchy-notes 1.0.0" "User Commands" -.SH NAME -omarchy-notes \- fast, native notes for Omarchy -.SH SYNOPSIS -.B omarchy-notes -[\fIOPTION\fR]... -.SH DESCRIPTION -Omarchy Notes is a local-first notes app with rich text, checklists, tables, -attachments, folders, tags, Smart Folders and search. Only one instance runs per -library: launching it again brings the open window forward and passes along -any request, such as a Quick Note or captured text. -.SH OPTIONS -.TP -.B \-\-new -Start a new note. -.TP -.B \-\-quick\-note -Open a small Quick Note window. -.TP -.BI \-\-capture " text" -Save \fItext\fR as a new note without opening a window. Use \fB\-\fR to read -the text from standard input. -.TP -.BI \-\-note " id" -Open the note with the given id. -.TP -.BI \-\-data\-dir " dir" -Use the library in \fIdir\fR instead of the default. -.TP -.B \-\-samples -Fill an empty library with sample notes. -.TP -.B \-\-setup\-hyprland -Add an optional Quick Note key binding (Super+Alt+N) and a floating window rule -to the Hyprland configuration, if they don't conflict with existing settings. -.TP -.B \-\-version -Show the version. -.TP -.B \-\-help -Show all options. -.SH FILES -.TP -.I $XDG_DATA_HOME/omarchy-notes/ -The notes library: an SQLite database and a folder of attachments. -Uninstalling the app never removes it. -.TP -.I $XDG_CONFIG_HOME/omarchy-notes/settings.ini -View preferences (sort order, last folder, gallery mode). -.SH EXAMPLES -.nf -omarchy-notes --capture "Call the plumber on Tuesday" -echo "idea" | omarchy-notes --capture - -.fi -.SH SEE ALSO -Project page: https://lastrefuge.ai/projects/omarchy-notes -.br -Source and issues: https://github.com/last-refuge/omarchy-notes diff --git a/packaging/metainfo/org.omarchy.Notes.Rust.metainfo.xml b/packaging/metainfo/org.omarchy.Notes.Rust.metainfo.xml index a20af66..fd406fa 100644 --- a/packaging/metainfo/org.omarchy.Notes.Rust.metainfo.xml +++ b/packaging/metainfo/org.omarchy.Notes.Rust.metainfo.xml @@ -6,14 +6,14 @@ CC0-1.0 MIT -

The separate Rust edition of Omarchy Notes keeps rich notes in a local SQLite library, without an account.

+

Omarchy Notes keeps rich notes in a local SQLite library, without an account.

  • Rich writing, headings, lists, checklists, basic tables, images and attached files
  • Nested folders, pinning, prefix search and recoverable deletion
  • Quick Note and durable command-line capture
  • Portable import/export and verified library backups
-

Rust uses its preview data directory and coexists with the Qt edition. Tags and Smart Folder interfaces are deferred; existing records remain preserved. Quotation libraries require Rust and returning to Qt uses a pre-upgrade backup.

+

The Rust application retains its preview data directory. Legacy Qt libraries can be migrated from verified backup copies. Tags and Smart Folder interfaces are deferred; existing records remain preserved. Quotation libraries require Rust and returning to Qt uses a pre-upgrade backup.

org.omarchy.Notes.Rust.desktop omarchy-notes-rust diff --git a/packaging/metainfo/org.omarchy.Notes.metainfo.xml b/packaging/metainfo/org.omarchy.Notes.metainfo.xml deleted file mode 100644 index f959250..0000000 --- a/packaging/metainfo/org.omarchy.Notes.metainfo.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - org.omarchy.Notes - Omarchy Notes - Fast, native notes for Omarchy - CC0-1.0 - MIT - -

Omarchy Notes is a native, local-first notes app inspired by Apple Notes. Open it, start typing, and your note is saved.

-
    -
  • Rich notes with headings, checklists, tables, images and file attachments
  • -
  • Folders, #tags, Smart Folders, pinning, and search as you type
  • -
  • Quick Note window and command-line capture
  • -
  • Import Markdown; export Markdown, HTML and PDF; full-library backups
  • -
-

It works offline with no account, keeps everything in a local SQLite library, and follows the active Omarchy theme.

-
- org.omarchy.Notes.desktop - - omarchy-notes - - https://lastrefuge.ai/projects/omarchy-notes - https://github.com/last-refuge/omarchy-notes/issues - https://github.com/last-refuge/omarchy-notes - - Omarchy Notes contributors - - - - A meeting note with checklists, a table, a chart and a PDF attachment - https://raw.githubusercontent.com/last-refuge/omarchy-notes/v1.0.0/docs/images/screenshot-dark.png - - - - - - -

First public release.

-
-
-
-
diff --git a/packaging/prepare-release.py b/packaging/prepare-release.py index 5c0d087..7c0dc74 100755 --- a/packaging/prepare-release.py +++ b/packaging/prepare-release.py @@ -36,9 +36,7 @@ def normalize(info): tar.add(root / name, arcname=name, filter=normalize) -def prepare(repo, ref, output, edition="qt", candidate=False): - if edition not in ("qt", "rust"): - raise ValueError("Edition must be qt or rust") +def prepare(repo, ref, output, candidate=False): revision = git(repo, "rev-parse", "--verify", f"{ref}^{{commit}}").decode().strip() epoch = int(git(repo, "show", "-s", "--format=%ct", revision)) if output.exists(): @@ -49,37 +47,23 @@ def prepare(repo, ref, output, edition="qt", candidate=False): tree.mkdir() with tarfile.open(fileobj=io.BytesIO(git(repo, "archive", revision))) as tar: tar.extractall(tree, filter="data") - if edition == "rust": - version = tomllib.loads((tree / "Cargo.toml").read_text())["workspace"]["package"]["version"] - if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version): - raise ValueError("Rust workspace must use a supported release version") - if ref.startswith("v") or (ref.startswith("rust-v") and ref != f"rust-v{version}"): - raise ValueError("Rust tag does not match the source version or edition") - if not candidate and (version.startswith("0.") or ref != f"rust-v{version}"): - raise ValueError("Unreleased Rust sources require --candidate; stable preparation requires the exact rust-vVERSION tag") - template = (tree / "packaging/arch/PKGBUILD-rust.in").read_text() - if template.count("@RUST_VERSION@") != 1: - raise ValueError("Rust PKGBUILD has no unique version placeholder") - template = template.replace("@RUST_VERSION@", version) - if not candidate: - template = template.replace(" (early access; v1 acceptance pending)", "") - source_name = f"omarchy-notes-rust-{version}" - kind = "candidate" if candidate else "stable" - (tree / "SOURCE_REVISION").write_text(revision + "\n") - (tree / "RELEASE_KIND").write_text(kind + "\n") - else: - if candidate: - raise ValueError("--candidate is specific to the separate Rust edition") - match = re.search(r"^project\(omarchy-notes\s+VERSION ([0-9]+\.[0-9]+\.[0-9]+)\b", - (tree / "CMakeLists.txt").read_text(), re.M) - if not match: - raise ValueError("Source revision has no supported release version") - version = match[1] - if ref.startswith("rust-v") or (ref.startswith("v") and ref != f"v{version}"): - raise ValueError("Tag does not match the source version or edition") - template = (tree / "packaging/arch/PKGBUILD.in").read_text() - source_name = f"omarchy-notes-{version}" - kind = "qt" + version = tomllib.loads((tree / "Cargo.toml").read_text())["workspace"]["package"]["version"] + if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version): + raise ValueError("Rust workspace must use a supported release version") + if ref.startswith("v") or (ref.startswith("rust-v") and ref != f"rust-v{version}"): + raise ValueError("Rust tag does not match the source version") + if not candidate and (version.startswith("0.") or ref != f"rust-v{version}"): + raise ValueError("Unreleased Rust sources require --candidate; stable preparation requires the exact rust-vVERSION tag") + template = (tree / "packaging/arch/PKGBUILD-rust.in").read_text() + if template.count("@RUST_VERSION@") != 1: + raise ValueError("Rust PKGBUILD has no unique version placeholder") + template = template.replace("@RUST_VERSION@", version) + if not candidate: + template = template.replace(" (early access; v1 acceptance pending)", "") + source_name = f"omarchy-notes-rust-{version}" + kind = "candidate" if candidate else "stable" + (tree / "SOURCE_REVISION").write_text(revision + "\n") + (tree / "RELEASE_KIND").write_text(kind + "\n") if f"pkgver={version}\n" not in template or template.count("@SOURCE_B2SUM@") != 1: raise ValueError("PKGBUILD template does not match the source version") source = work / source_name @@ -112,11 +96,10 @@ def prepare(repo, ref, output, edition="qt", candidate=False): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parent.parent) parser.add_argument("--ref", required=True, help="Committed revision or release tag") - parser.add_argument("--edition", choices=("qt", "rust"), default="qt", help="Separate edition; Qt remains the default") parser.add_argument("--candidate", action="store_true", help="Prepare unannounced Rust candidate artifacts without claiming a stable release") parser.add_argument("--output", required=True, type=Path, help="New output directory") args = parser.parse_args() try: - prepare(args.repo.resolve(), args.ref, args.output.resolve(), args.edition, args.candidate) + prepare(args.repo.resolve(), args.ref, args.output.resolve(), args.candidate) except (ValueError, OSError, subprocess.CalledProcessError) as error: parser.exit(1, f"Release preparation failed: {error}\n") diff --git a/src/app/AppController.cpp b/src/app/AppController.cpp deleted file mode 100644 index 46e973a..0000000 --- a/src/app/AppController.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include "AppController.h" - -#include "AppLibrary.h" -#include "DocumentConverter.h" - -#include -#include -#include -#include - -using namespace Qt::StringLiterals; - -namespace { -AppController *s_instance = nullptr; -} - -AppController::AppController(QObject *parent) : QObject(parent) {} - -AppController *AppController::create(QQmlEngine *, QJSEngine *) -{ - Q_ASSERT(s_instance); - QQmlEngine::setObjectOwnership(s_instance, QQmlEngine::CppOwnership); - return s_instance; -} - -void AppController::setInstance(AppController *instance) -{ - s_instance = instance; -} - -void AppController::activate(QWindow *window, const QString &token) -{ - if (!window) - return; - // Qt's Wayland client hands XDG_ACTIVATION_TOKEN to the compositor when - // activating, which is what lets another launch focus this window. - if (!token.isEmpty()) - qputenv("XDG_ACTIVATION_TOKEN", token.toUtf8()); - window->show(); - window->raise(); - window->requestActivate(); - // Without a token, Hyprland ignores activation requests; ask it directly. - if (token.isEmpty() && qEnvironmentVariableIsSet("HYPRLAND_INSTANCE_SIGNATURE")) { - QProcess::startDetached(u"hyprctl"_s, {u"dispatch"_s, u"focuswindow"_s, - u"title:^%1$"_s.arg(QRegularExpression::escape(window->title()))}); - } -} - -void AppController::handle(const QJsonObject &request) -{ - const QString action = request[u"action"].toString(); - const QString token = request[u"token"].toString(); - if (action == u"new") { - emit newNoteRequested(token); - } else if (action == u"quick-note") { - emit quickNoteRequested(token); - } else if (action == u"open") { - emit openNoteRequested(request[u"note"].toString(), token); - } else if (action == u"capture") { - // Captured text lands in Notes without disturbing the open window. - AppLibrary *library = qobject_cast(AppLibrary::create(nullptr, nullptr)); - const QString id = library ? library->captureText(request[u"text"].toString()) : QString(); - if (!id.isEmpty()) - emit captured(id); - } else { - emit activateRequested(token); - } -} diff --git a/src/app/AppController.h b/src/app/AppController.h deleted file mode 100644 index 4c0e7de..0000000 --- a/src/app/AppController.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -class QQmlEngine; -class QJSEngine; - -// Process-level requests for QML (`App`): what another launch asked for, -// and bringing windows forward on Wayland. -class AppController : public QObject -{ - Q_OBJECT - QML_NAMED_ELEMENT(App) - QML_SINGLETON - - Q_PROPERTY(bool startHidden READ startHidden CONSTANT) - Q_PROPERTY(bool startWithQuickNote READ startWithQuickNote CONSTANT) - -public: - // Not default-constructible on purpose: QML must use create(), which - // returns the one shared instance, rather than making its own. - explicit AppController(QObject *parent); - - static AppController *create(QQmlEngine *, QJSEngine *); - static void setInstance(AppController *instance); - - bool startHidden() const { return m_startWithQuickNote; } - bool startWithQuickNote() const { return m_startWithQuickNote; } - void setStartWithQuickNote(bool quickNote) { m_startWithQuickNote = quickNote; } - - // Shows and focuses `window`, using the launcher's activation token - // when there is one. - Q_INVOKABLE void activate(QWindow *window, const QString &token = {}); - - // Routes a request from InstanceChannel. - void handle(const QJsonObject &request); - -signals: - void activateRequested(const QString &token); - void newNoteRequested(const QString &token); - void quickNoteRequested(const QString &token); - void openNoteRequested(const QString ¬eId, const QString &token); - void captured(const QString ¬eId); - -private: - bool m_startWithQuickNote = false; -}; diff --git a/src/app/AppLibrary.cpp b/src/app/AppLibrary.cpp deleted file mode 100644 index ce17fdd..0000000 --- a/src/app/AppLibrary.cpp +++ /dev/null @@ -1,971 +0,0 @@ -#include "AppLibrary.h" - -#include "DocumentConverter.h" -#include "LibraryBackup.h" -#include "LibraryPaths.h" -#include "NoteExchange.h" -#include "RichDocument.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace Qt::StringLiterals; -using namespace onotes; - -namespace { - -AppLibrary *s_instance = nullptr; - -QString friendlyDate(qint64 ms) -{ - const QDateTime when = QDateTime::fromMSecsSinceEpoch(ms); - const QDate today = QDate::currentDate(); - const QLocale locale; - if (when.date() == today) - return locale.toString(when.time(), QLocale::ShortFormat); - if (when.date() == today.addDays(-1)) - return QObject::tr("Yesterday"); - if (when.date().daysTo(today) < 7) - return locale.dayName(when.date().dayOfWeek()); - return locale.toString(when.date(), QLocale::ShortFormat); -} - -// Search snippets mark matches with \x02..\x03; render them as bold in -// Qt's StyledText, escaping everything else. -QString styledSnippet(const QString &snippet) -{ - QString out = snippet.toHtmlEscaped(); - out.replace(QChar(2), u""_s); - out.replace(QChar(3), u""_s); - return out; -} - -QString safeFileName(const QString &name) -{ - QString out = QFileInfo(name).fileName(); - out.replace(u'/', u'_'); - if (out.isEmpty() || out == u"." || out == u"..") - out = u"attachment"_s; - return out; -} - -QVariantMap result(bool ok, const QString &error = {}) -{ - return {{u"ok"_s, ok}, {u"error"_s, error}}; -} - -} // namespace - -// ---------------------------------------------------------------- NotesModel - -int NotesModel::rowCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : int(m_notes.size()); -} - -QVariant NotesModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid() || index.row() >= m_notes.size()) - return {}; - const NoteSummary &n = m_notes.at(index.row()); - switch (role) { - case IdRole: return n.id; - case TitleRole: return n.title.isEmpty() ? tr("New Note") : n.title; - case SnippetRole: - if (m_search && !n.snippet.isEmpty()) - return styledSnippet(n.snippet); - return n.snippet.isEmpty() ? tr("No additional text") : n.snippet.toHtmlEscaped(); - case DateRole: return friendlyDate(m_trash ? n.deletedAt : n.updatedAt); - case PinnedRole: return n.pinned; - case HasAttachmentsRole: return n.hasAttachments; - case HasChecklistRole: return n.hasChecklist; - case FolderNameRole: return n.folderId.isEmpty() ? QString() : m_folderNames.value(n.folderId); - case ThumbnailRole: return n.thumbnail; - case SectionRole: - if (m_search || m_trash || !hasPinned()) - return QString(); - return n.pinned ? tr("Pinned") : tr("Notes"); - } - return {}; -} - -QHash NotesModel::roleNames() const -{ - return { - {IdRole, "noteId"}, - {TitleRole, "title"}, - {SnippetRole, "snippet"}, - {DateRole, "date"}, - {PinnedRole, "pinned"}, - {HasAttachmentsRole, "hasAttachments"}, - {HasChecklistRole, "hasChecklist"}, - {FolderNameRole, "folderName"}, - {SectionRole, "section"}, - {ThumbnailRole, "thumbnail"}, - }; -} - -bool NotesModel::hasPinned() const -{ - return std::any_of(m_notes.cbegin(), m_notes.cend(), [](const NoteSummary &n) { return n.pinned; }); -} - -void NotesModel::reset(const QList ¬es, bool searchResults, bool trash, - const QHash &folderNames) -{ - beginResetModel(); - m_notes = notes; - m_search = searchResults; - m_trash = trash; - m_folderNames = folderNames; - endResetModel(); - emit countChanged(); -} - -void NotesModel::applySaved(const QString &id, const RichDocument &body, qint64 updatedAt, bool moveToTop) -{ - const int row = indexOf(id); - if (row < 0) - return; - NoteSummary &n = m_notes[row]; - n.title = body.title(); - if (!m_search) - n.snippet = body.snippet(); - n.updatedAt = updatedAt; - n.hasAttachments = !body.referencedAttachments().isEmpty() || !body.referencedBlobs().isEmpty(); - emit dataChanged(index(row), index(row)); - if (!moveToTop) - return; - - // Most recently edited first, below pinned notes. - int target = 0; - while (target < m_notes.size() && m_notes[target].pinned && !n.pinned) - ++target; - if (target != row && beginMoveRows({}, row, row, {}, target > row ? target + 1 : target)) { - m_notes.move(row, target); - endMoveRows(); - } -} - -int NotesModel::indexOf(const QString &id) const -{ - for (int i = 0; i < m_notes.size(); ++i) { - if (m_notes[i].id == id) - return i; - } - return -1; -} - -QString NotesModel::idAt(int row) const -{ - return row >= 0 && row < m_notes.size() ? m_notes[row].id : QString(); -} - -QString NotesModel::titleOf(const QString &id) const -{ - const int row = indexOf(id); - return row < 0 ? QString() : data(index(row), TitleRole).toString(); -} - -bool NotesModel::isPinned(const QString &id) const -{ - const int row = indexOf(id); - return row >= 0 && m_notes[row].pinned; -} - -// ---------------------------------------------------------------- FoldersModel - -int FoldersModel::rowCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : int(m_rows.size()); -} - -QVariant FoldersModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid() || index.row() >= m_rows.size()) - return {}; - const Row &r = m_rows.at(index.row()); - switch (role) { - case KeyRole: return r.key; - case NameRole: return r.name; - case KindRole: return r.kind; - case DepthRole: return r.depth; - case CountRole: return r.count; - case FolderIdRole: return r.folderId; - case ParentIdRole: return r.parentId; - case SectionRole: return r.section; - } - return {}; -} - -QHash FoldersModel::roleNames() const -{ - return { - {KeyRole, "key"}, - {NameRole, "name"}, - {KindRole, "kind"}, - {DepthRole, "depth"}, - {CountRole, "count"}, - {FolderIdRole, "folderId"}, - {ParentIdRole, "parentId"}, - {SectionRole, "section"}, - }; -} - -void FoldersModel::reset(const QList &folders, int noteCount, int trashCount, int attachmentCount, - const QList &smartFolders, const QList &tags) -{ - QHash> children; - int filed = 0; - for (const FolderInfo &f : folders) { - children[f.parentId].append(f); - filed += f.noteCount; - } - - QList rows; - rows.append({u"all"_s, tr("All Notes"), u"all"_s, 0, noteCount, {}, {}, {}}); - rows.append({u"notes"_s, tr("Notes"), u"notes"_s, 0, noteCount - filed, {}, {}, {}}); - // Depth-first, keeping the store's alphabetical order among siblings. - std::function walk = [&](const QString &parent, int depth) { - for (const FolderInfo &f : children.value(parent)) { - rows.append({f.id, f.name, u"folder"_s, depth, f.noteCount, f.id, f.parentId, {}}); - walk(f.id, depth + 1); - } - }; - walk({}, 0); - rows.append({u"attachments"_s, tr("Attachments"), u"attachments"_s, 0, attachmentCount, {}, {}, {}}); - rows.append({u"trash"_s, tr("Recently Deleted"), u"trash"_s, 0, trashCount, {}, {}, {}}); - for (const SmartFolder &f : smartFolders) - rows.append({u"smart:"_s + f.id, f.name, u"smart"_s, 0, f.noteCount, f.id, {}, tr("Smart Folders")}); - for (const TagInfo &t : tags) - rows.append({u"tag:"_s + t.name, u"#"_s + t.name, u"tag"_s, 0, t.noteCount, {}, {}, tr("Tags")}); - - beginResetModel(); - m_rows = rows; - endResetModel(); -} - -QString FoldersModel::nameOf(const QString &key) const -{ - const int row = indexOfKey(key); - return row < 0 ? QString() : m_rows[row].name; -} - -int FoldersModel::indexOfKey(const QString &key) const -{ - for (int i = 0; i < m_rows.size(); ++i) { - if (m_rows[i].key == key) - return i; - } - return -1; -} - -// ---------------------------------------------------------------- AttachmentsModel - -int AttachmentsModel::rowCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : int(m_visible.size()); -} - -QVariant AttachmentsModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid() || index.row() >= m_visible.size()) - return {}; - const AttachmentItem &item = m_visible.at(index.row()); - switch (role) { - case IsImageRole: return item.isImage; - case BlobHashRole: return item.blobHash; - case AttachmentIdRole: return item.attachmentId; - case FileNameRole: return item.isImage ? tr("Image") : item.fileName; - case DetailRole: { - const QString size = QLocale().formattedDataSize(item.size); - if (item.isImage) - return size; - const QString kind = QMimeDatabase().mimeTypeForName(item.mimeType).comment(); - return kind.isEmpty() ? size : kind + u" · "_s + size; - } - case ExtensionRole: return QFileInfo(item.fileName).suffix().toUpper().left(4); - case NoteIdRole: return item.noteId; - case NoteTitleRole: return item.noteTitle.isEmpty() ? tr("New Note") : item.noteTitle; - } - return {}; -} - -QHash AttachmentsModel::roleNames() const -{ - return { - {IsImageRole, "isImage"}, - {BlobHashRole, "blobHash"}, - {AttachmentIdRole, "attachmentId"}, - {FileNameRole, "fileName"}, - {DetailRole, "detail"}, - {ExtensionRole, "extension"}, - {NoteIdRole, "noteId"}, - {NoteTitleRole, "noteTitle"}, - }; -} - -void AttachmentsModel::setFilter(int filter) -{ - if (filter == m_filter) - return; - m_filter = filter; - emit filterChanged(); - applyFilter(); -} - -void AttachmentsModel::reset(const QList &items) -{ - m_items = items; - applyFilter(); -} - -void AttachmentsModel::applyFilter() -{ - beginResetModel(); - m_visible.clear(); - for (const AttachmentItem &item : m_items) { - if (m_filter == All || (m_filter == Images) == item.isImage) - m_visible.append(item); - } - endResetModel(); - emit countChanged(); -} - -// ---------------------------------------------------------------- AppLibrary - -AppLibrary::AppLibrary(LibraryService *service, const QString &settingsFile, QObject *parent) - : QObject(parent), m_service(service) -{ - const QString file = settingsFile.isEmpty() - ? QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) - + u"/omarchy-notes/settings.ini"_s - : settingsFile; - m_settings = std::make_unique(file, QSettings::IniFormat); - m_sort = static_cast(std::clamp(m_settings->value(u"list/sort"_s, 0).toInt(), 0, 2)); - m_key = m_settings->value(u"list/view"_s, u"all"_s).toString(); - m_gallery = m_settings->value(u"list/gallery"_s, false).toBool(); - - m_searchDebounce.setSingleShot(true); - m_searchDebounce.setInterval(120); - connect(&m_searchDebounce, &QTimer::timeout, this, &AppLibrary::runSearch); - m_sidebarRefresh.setSingleShot(true); - m_sidebarRefresh.setInterval(800); - connect(&m_sidebarRefresh, &QTimer::timeout, this, [this] { - reloadFolders(); - // Membership of tag and Smart Folder views can change with an edit. - if (!searching() && (m_key.startsWith(u"tag:") || m_key.startsWith(u"smart:"))) - reloadNotes(); - }); - connect(m_service, &LibraryService::searchFinished, this, &AppLibrary::onSearchFinished); - connect(m_service, &LibraryService::notesChanged, this, &AppLibrary::refresh); - - reloadFolders(); - if (m_folders.indexOfKey(m_key) < 0) - m_key = u"all"_s; - reloadNotes(); -} - -AppLibrary *AppLibrary::create(QQmlEngine *, QJSEngine *) -{ - Q_ASSERT(s_instance); - QQmlEngine::setObjectOwnership(s_instance, QQmlEngine::CppOwnership); - return s_instance; -} - -void AppLibrary::setInstance(AppLibrary *instance) -{ - s_instance = instance; -} - -QString AppLibrary::viewTitle() const -{ - if (searching()) - return tr("Search"); - return m_folders.nameOf(m_key); -} - -void AppLibrary::setGalleryMode(bool gallery) -{ - if (gallery == m_gallery) - return; - m_gallery = gallery; - m_settings->setValue(u"list/gallery"_s, gallery); - emit galleryModeChanged(); -} - -QString AppLibrary::lastNoteId() const -{ - return m_settings->value(u"editor/lastNote"_s).toString(); -} - -void AppLibrary::setLastNoteId(const QString &id) -{ - if (id == lastNoteId()) - return; - m_settings->setValue(u"editor/lastNote"_s, id); - emit lastNoteIdChanged(); -} - -void AppLibrary::setSimulateSaveFailure(bool fail) -{ - if (fail == simulateSaveFailure()) - return; - m_service->setSimulatedSaveFailure(fail); - emit simulateSaveFailureChanged(); -} - -void AppLibrary::setSearchText(const QString &text) -{ - if (text == m_searchText) - return; - const bool wasSearching = searching(); - m_searchText = text; - emit searchTextChanged(); - if (searching()) { - m_searchDebounce.start(); - } else { - m_searchDebounce.stop(); - ++m_searchTicket; // ignore results still in flight - reloadNotes(); - } - if (wasSearching != searching()) - emit viewChanged(); -} - -void AppLibrary::setSortOrder(int order) -{ - const auto sort = static_cast(std::clamp(order, 0, 2)); - if (sort == m_sort) - return; - m_sort = sort; - m_settings->setValue(u"list/sort"_s, int(sort)); - emit sortOrderChanged(); - reloadNotes(); -} - -void AppLibrary::showKey(const QString &key) -{ - if (m_folders.indexOfKey(key) < 0) - return; - const bool changed = key != m_key || searching(); - m_key = key; - m_settings->setValue(u"list/view"_s, key); - if (searching()) { - m_searchText.clear(); - emit searchTextChanged(); - } - reloadNotes(); - if (changed) - emit viewChanged(); -} - -void AppLibrary::refresh() -{ - reloadFolders(); - if (m_folders.indexOfKey(m_key) < 0) { - m_key = u"all"_s; - emit viewChanged(); - } - if (searching()) - runSearch(); - else - reloadNotes(); -} - -void AppLibrary::reloadFolders() -{ - m_trashCount = m_service->trashCount(); - m_smartFolders = m_service->listSmartFolders(); - const QList tags = m_service->listTags(); - m_tags.clear(); - for (const TagInfo &t : tags) - m_tags << t.name; - const QList items = m_service->listAttachmentItems(); - m_folders.reset(m_service->listFolders(), m_service->noteCount(), m_trashCount, int(items.size()), - m_smartFolders, tags); - if (m_key == u"attachments") - m_attachments.reset(items); - emit countsChanged(); -} - -QHash AppLibrary::folderNames() const -{ - QHash names; - for (const FoldersModel::Row &row : m_folders.rows()) { - if (row.kind == u"folder") - names.insert(row.folderId, row.name); - } - return names; -} - -void AppLibrary::reloadNotes() -{ - if (searching()) - return; - NoteQuery query; - if (m_key == u"trash") { - query = NoteQuery::trash(); - } else if (m_key == u"attachments") { - m_attachments.reset(m_service->listAttachmentItems()); - m_notes.reset({}, false, false, {}); - return; - } else if (m_key.startsWith(u"tag:")) { - query = NoteQuery::tagged(m_key.mid(4), m_sort); - } else if (m_key.startsWith(u"smart:")) { - query = NoteQuery::all(m_sort); - for (const SmartFolder &f : m_smartFolders) { - if (f.id == m_key.mid(6)) - query = NoteQuery::smart(f.criteria, m_sort); - } - } else if (m_key == u"all") - query = NoteQuery::all(m_sort); - else if (m_key == u"notes") - query = NoteQuery::folder({}, m_sort); - else - query = NoteQuery::folder(m_key, m_sort); - m_notes.reset(m_service->listNotes(query), false, m_key == u"trash", folderNames()); -} - -void AppLibrary::runSearch() -{ - if (searching()) - m_searchTicket = m_service->search(m_searchText); -} - -void AppLibrary::onSearchFinished(quint64 ticket, const QList &results) -{ - if (ticket != m_searchTicket || !searching()) - return; - m_notes.reset(results, true, false, folderNames()); -} - -void AppLibrary::noteSaved(const QString ¬eId, const RichDocument &body, qint64 updatedAt) -{ - const bool moveToTop = m_sort == NoteSort::Edited && !searching() && m_key != u"trash"; - m_notes.applySaved(noteId, body, updatedAt, moveToTop); - m_sidebarRefresh.start(); -} - -bool AppLibrary::report(bool ok, const QString &error) -{ - if (!ok && !error.isEmpty()) - emit errorOccurred(error); - return ok; -} - -QString AppLibrary::createNote() -{ - const bool special = m_key == u"all" || m_key == u"notes" || m_key == u"trash" || m_key == u"attachments" - || m_key.startsWith(u"tag:") || m_key.startsWith(u"smart:"); - const QString folderId = special ? QString() : m_key; - RichDocument body{{Block::paragraph()}}; - // A note started from a tag carries the tag, so it shows up there. - if (m_key.startsWith(u"tag:") && !searching()) - body.blocks.append(Block::paragraph({Span::plain(u"#"_s + m_key.mid(4))})); - QString error; - const auto note = m_service->createNote(body, &error, folderId); - if (!note) { - emit errorOccurred(tr("Couldn't create a note: %1").arg(error)); - return {}; - } - // A new note should be visible in the list it was created from. - if (searching() || m_key == u"trash" || m_key == u"attachments" || m_key.startsWith(u"smart:")) { - m_searchText.clear(); - emit searchTextChanged(); - m_key = u"all"_s; - emit viewChanged(); - } - refresh(); - return note->id; -} - -QString AppLibrary::createQuickNote() -{ - QString error; - const auto note = m_service->createNote(RichDocument{{Block::paragraph()}}, &error); - if (!note) { - emit errorOccurred(tr("Couldn't create a note: %1").arg(error)); - return {}; - } - refresh(); - return note->id; -} - -bool AppLibrary::discardIfEmpty(const QString ¬eId) -{ - const auto note = m_service->loadNote(noteId); - if (!note || !note->body.plainText().trimmed().isEmpty() || !note->body.referencedBlobs().isEmpty() - || !note->body.referencedAttachments().isEmpty()) - return false; - const bool removed = m_service->trashNote(noteId) && m_service->deleteNotePermanently(noteId); - refresh(); - emit noteMetaChanged(noteId); - return removed; -} - -QString AppLibrary::captureText(const QString &text) -{ - if (text.trimmed().isEmpty()) - return {}; - QString error; - const auto note = m_service->createNote(DocumentConverter::fromPlainText(text.trimmed()), &error); - if (!note) { - emit errorOccurred(tr("Couldn't save the captured note: %1").arg(error)); - return {}; - } - refresh(); - return note->id; -} - -void AppLibrary::setPinned(const QString &id, bool pinned) -{ - if (report(m_service->setPinned(id, pinned), tr("Couldn't update the note."))) { - refresh(); - emit noteMetaChanged(id); - } -} - -bool AppLibrary::moveNote(const QString ¬eId, const QString &folderId) -{ - QString error; - if (!report(m_service->moveNote(noteId, folderId, &error), error)) - return false; - refresh(); - emit noteMetaChanged(noteId); - return true; -} - -QString AppLibrary::duplicateNote(const QString ¬eId) -{ - QString error; - const auto copy = m_service->duplicateNote(noteId, &error); - if (!report(copy.has_value(), error)) - return {}; - refresh(); - return copy->id; -} - -bool AppLibrary::trashNote(const QString ¬eId) -{ - QString error; - if (!report(m_service->trashNote(noteId, &error), error)) - return false; - refresh(); - emit noteMetaChanged(noteId); - return true; -} - -bool AppLibrary::recoverNote(const QString ¬eId) -{ - QString error; - if (!report(m_service->recoverNote(noteId, &error), error)) - return false; - refresh(); - emit noteMetaChanged(noteId); - return true; -} - -bool AppLibrary::deleteNotePermanently(const QString ¬eId) -{ - QString error; - if (!report(m_service->deleteNotePermanently(noteId, &error), error)) - return false; - refresh(); - emit noteMetaChanged(noteId); - return true; -} - -int AppLibrary::emptyTrash() -{ - const QList trashed = m_service->listNotes(NoteQuery::trash()); - QString error; - const int removed = m_service->emptyTrash(&error); - report(removed >= 0, error); - refresh(); - for (const NoteSummary &n : trashed) - emit noteMetaChanged(n.id); - return removed; -} - -QVariantMap AppLibrary::createFolder(const QString &name, const QString &parentId) -{ - QString error; - const auto folder = m_service->createFolder(name, parentId, &error); - if (!folder) - return result(false, error); - refresh(); - QVariantMap out = result(true); - out.insert(u"id"_s, folder->id); - return out; -} - -QVariantMap AppLibrary::renameFolder(const QString &id, const QString &name) -{ - QString error; - if (!m_service->renameFolder(id, name, &error)) - return result(false, error); - refresh(); - emit viewChanged(); // the title may be this folder's name - return result(true); -} - -bool AppLibrary::deleteFolder(const QString &id) -{ - // Notes inside are moved to Recently Deleted; tell open editors. - QStringList affected; - for (const NoteSummary &n : m_service->listNotes(NoteQuery::all())) - affected << n.id; - QString error; - if (!report(m_service->deleteFolder(id, &error), error)) - return false; - refresh(); - for (const QString ¬eId : affected) - emit noteMetaChanged(noteId); - return true; -} - -QString AppLibrary::folderName(const QString &id) const -{ - return id.isEmpty() ? tr("Notes") : m_folders.nameOf(id); -} - -int AppLibrary::folderNoteCount(const QString &id) const -{ - const int row = m_folders.indexOfKey(id); - return row < 0 ? 0 : m_folders.rows()[row].count; -} - -QVariantList AppLibrary::folderChoices() const -{ - QVariantList out; - out.append(QVariantMap{{u"id"_s, QString()}, {u"name"_s, tr("Notes")}, {u"depth"_s, 0}}); - for (const FoldersModel::Row &row : m_folders.rows()) { - if (row.kind == u"folder") - out.append(QVariantMap{{u"id"_s, row.folderId}, {u"name"_s, row.name}, {u"depth"_s, row.depth}}); - } - return out; -} - -QVariantMap AppLibrary::createSmartFolder(const QString &name, const QVariantMap &criteria) -{ - QString error; - const auto folder = m_service->createSmartFolder( - name, SmartCriteria::fromJson(QJsonObject::fromVariantMap(criteria)), &error); - if (!folder) - return result(false, error); - refresh(); - QVariantMap out = result(true); - out.insert(u"id"_s, u"smart:"_s + folder->id); - return out; -} - -QVariantMap AppLibrary::updateSmartFolder(const QString &id, const QString &name, const QVariantMap &criteria) -{ - QString error; - if (!m_service->updateSmartFolder(id, name, SmartCriteria::fromJson(QJsonObject::fromVariantMap(criteria)), &error)) - return result(false, error); - refresh(); - emit viewChanged(); - return result(true); -} - -bool AppLibrary::deleteSmartFolder(const QString &id) -{ - QString error; - if (!report(m_service->deleteSmartFolder(id, &error), error)) - return false; - refresh(); - return true; -} - -QVariantMap AppLibrary::smartFolder(const QString &id) const -{ - for (const SmartFolder &f : m_smartFolders) { - if (f.id == id) { - QVariantMap out = f.criteria.toJson().toVariantMap(); - out.insert(u"name"_s, f.name); - return out; - } - } - return {}; -} - -bool AppLibrary::openAttachment(const QString &attachmentId) -{ - const auto info = m_service->attachment(attachmentId); - const QString source = info ? m_service->blobPath(info->blobHash) : QString(); - if (!info || !QFileInfo::exists(source)) { - emit errorOccurred(tr("This attachment's data is missing from the library.")); - return false; - } - // External apps need a real file name; give them a read-only copy. - const QString dir = cacheDirectory() + u"/open/"_s + attachmentId; - QDir().mkpath(dir); - const QString target = dir + u'/' + safeFileName(info->fileName); - if (!QFileInfo::exists(target)) { - if (!QFile::copy(source, target)) { - emit errorOccurred(tr("Couldn't prepare the attachment for opening.")); - return false; - } - QFile::setPermissions(target, QFileDevice::ReadOwner | QFileDevice::ReadUser); - } - if (!QDesktopServices::openUrl(QUrl::fromLocalFile(target))) { - emit errorOccurred(tr("No application is set up to open %1.").arg(info->fileName)); - return false; - } - return true; -} - -bool AppLibrary::openImage(const QString &blobHash) -{ - const QString source = m_service->blobPath(blobHash); - if (source.isEmpty() || !QFileInfo::exists(source)) { - emit errorOccurred(tr("This image's data is missing from the library.")); - return false; - } - // Hand images to the desktop viewer through a named copy. - const QString dir = cacheDirectory() + u"/open/"_s + blobHash.left(16); - QDir().mkpath(dir); - const QString suffix = QMimeDatabase().mimeTypeForFile(source).preferredSuffix(); - const QString target = dir + u"/image."_s + (suffix.isEmpty() ? u"png"_s : suffix); - if (!QFileInfo::exists(target)) - QFile::copy(source, target); - return QDesktopServices::openUrl(QUrl::fromLocalFile(target)); -} - -QVariantMap AppLibrary::importFiles(const QList &files) -{ - QStringList paths; - for (const QUrl &url : files) - paths << url.toLocalFile(); - const bool special = m_key == u"all" || m_key == u"notes" || m_key == u"trash" || m_key == u"attachments" - || m_key.startsWith(u"tag:") || m_key.startsWith(u"smart:") || searching(); - const ImportReport report = onotes::importFiles(*m_service, paths, special ? QString() : m_key); - if (special) { - m_searchText.clear(); - emit searchTextChanged(); - m_key = u"all"_s; - emit viewChanged(); - } - refresh(); - QVariantMap out = result(!report.createdIds.isEmpty(), report.warnings.join(u'\n')); - out.insert(u"count"_s, report.createdIds.size()); - out.insert(u"first"_s, report.createdIds.value(0)); - out.insert(u"warnings"_s, report.warnings); - return out; -} - -QVariantMap AppLibrary::importFolder(const QUrl &folder) -{ - QString folderId; - const ImportReport report = onotes::importFolder(*m_service, folder.toLocalFile(), {}, &folderId); - m_searchText.clear(); - emit searchTextChanged(); - refresh(); - if (!folderId.isEmpty()) - showKey(folderId); - QVariantMap out = result(!report.createdIds.isEmpty(), report.warnings.join(u'\n')); - out.insert(u"count"_s, report.createdIds.size()); - out.insert(u"first"_s, report.createdIds.value(0)); - out.insert(u"warnings"_s, report.warnings); - return out; -} - -QString AppLibrary::exportFileName(const QString ¬eId, const QString &format) const -{ - const auto note = m_service->loadNote(noteId); - const QString base = fileNameForTitle(note ? note->body.title() : QString()); - const QString suffix = format == u"html" ? u".html"_s : format == u"pdf" ? u".pdf"_s : u".md"_s; - return base + suffix; -} - -QVariantMap AppLibrary::exportNote(const QString ¬eId, const QString &format, const QUrl &file) -{ - const ExportFormat f = format == u"html" ? ExportFormat::Html - : format == u"pdf" ? ExportFormat::Pdf - : ExportFormat::Markdown; - QString error; - if (!onotes::exportNote(*m_service, noteId, f, file.toLocalFile(), &error)) - return result(false, error); - QVariantMap out = result(true); - out.insert(u"path"_s, file.toLocalFile()); - return out; -} - -QVariantMap AppLibrary::exportAll(const QUrl &folder) -{ - QString error; - const auto root = exportLibraryAsMarkdown(*m_service, folder.toLocalFile(), &error); - if (!root) - return result(false, error); - QVariantMap out = result(true); - out.insert(u"path"_s, *root); - return out; -} - -QString AppLibrary::defaultBackupName() const -{ - return onotes::defaultBackupName(); -} - -QVariantMap AppLibrary::backupTo(const QUrl &parentFolder, const QString &name) -{ - const QString path = QDir(parentFolder.toLocalFile()).filePath(name.trimmed()); - QString error; - const auto manifest = m_service->backupTo(path, &error); - if (!manifest) - return result(false, error); - QVariantMap out = result(true); - out.insert(u"path"_s, manifest->path); - out.insert(u"notes"_s, manifest->notes); - out.insert(u"attachments"_s, manifest->blobs); - out.insert(u"size"_s, QLocale().formattedDataSize(manifest->bytes)); - return out; -} - -QVariantMap AppLibrary::inspectBackup(const QUrl &folder) -{ - QString error; - const auto manifest = m_service->inspectBackup(folder.toLocalFile(), &error); - if (!manifest) - return result(false, error); - QVariantMap out = result(true); - out.insert(u"path"_s, manifest->path); - out.insert(u"notes"_s, manifest->notes); - out.insert(u"attachments"_s, manifest->blobs); - out.insert(u"size"_s, QLocale().formattedDataSize(manifest->bytes)); - out.insert(u"created"_s, QLocale().toString(QDateTime::fromMSecsSinceEpoch(manifest->createdAt), - QLocale::LongFormat)); - return out; -} - -QVariantMap AppLibrary::restoreFrom(const QUrl &folder) -{ - QString safety; - QString error; - if (!m_service->restoreFrom(folder.toLocalFile(), &safety, &error)) - return result(false, error); - m_searchText.clear(); - emit searchTextChanged(); - m_key = u"all"_s; - refresh(); - emit viewChanged(); - emit libraryReplaced(); - QVariantMap out = result(true); - out.insert(u"previous"_s, safety); - return out; -} - -void AppLibrary::openLibraryFolder() const -{ - QDesktopServices::openUrl(QUrl::fromLocalFile(location())); -} diff --git a/src/app/AppLibrary.h b/src/app/AppLibrary.h deleted file mode 100644 index dd5aa0b..0000000 --- a/src/app/AppLibrary.h +++ /dev/null @@ -1,325 +0,0 @@ -#pragma once - -#include "LibraryService.h" - -#include -#include -#include -#include -#include -#include -#include - -#include - -class QQmlEngine; -class QJSEngine; - -class NotesModel : public QAbstractListModel -{ - Q_OBJECT - QML_ANONYMOUS - - Q_PROPERTY(int count READ count NOTIFY countChanged) - Q_PROPERTY(bool hasPinned READ hasPinned NOTIFY countChanged) - -public: - enum Role { - IdRole = Qt::UserRole + 1, - TitleRole, - SnippetRole, - DateRole, - PinnedRole, - HasAttachmentsRole, - HasChecklistRole, - FolderNameRole, - SectionRole, - ThumbnailRole, - }; - - using QAbstractListModel::QAbstractListModel; - - int rowCount(const QModelIndex &parent = {}) const override; - QVariant data(const QModelIndex &index, int role) const override; - QHash roleNames() const override; - - int count() const { return int(m_notes.size()); } - bool hasPinned() const; - - // `searchResults` switches the snippet to highlighted matches; `trash` - // shows the deletion date. - void reset(const QList ¬es, bool searchResults, bool trash, - const QHash &folderNames); - // Applies a saved note's new title/excerpt without re-querying storage. - void applySaved(const QString &id, const onotes::RichDocument &body, qint64 updatedAt, bool moveToTop); - Q_INVOKABLE int indexOf(const QString &id) const; - Q_INVOKABLE QString idAt(int row) const; - Q_INVOKABLE QString titleOf(const QString &id) const; - Q_INVOKABLE bool isPinned(const QString &id) const; - -signals: - void countChanged(); - -private: - QList m_notes; - QHash m_folderNames; - bool m_search = false; - bool m_trash = false; -}; - -// Sidebar rows: All Notes, Notes, the folder tree (flattened, with depth), -// and Recently Deleted. -class FoldersModel : public QAbstractListModel -{ - Q_OBJECT - QML_ANONYMOUS - -public: - enum Role { - KeyRole = Qt::UserRole + 1, - NameRole, - KindRole, - DepthRole, - CountRole, - FolderIdRole, - ParentIdRole, - SectionRole, - }; - - struct Row { - // "all", "notes", "attachments", "trash", a folder id, - // "smart:" or "tag:" - QString key; - QString name; - QString kind; // "all", "notes", "folder", "attachments", "trash", "smart", "tag" - int depth = 0; - int count = 0; - QString folderId; // folder or Smart Folder id - QString parentId; - QString section; // "" for the library, then "Smart Folders", "Tags" - }; - - using QAbstractListModel::QAbstractListModel; - - int rowCount(const QModelIndex &parent = {}) const override; - QVariant data(const QModelIndex &index, int role) const override; - QHash roleNames() const override; - - void reset(const QList &folders, int noteCount, int trashCount, int attachmentCount, - const QList &smartFolders, const QList &tags); - const QList &rows() const { return m_rows; } - QString nameOf(const QString &key) const; - Q_INVOKABLE int indexOfKey(const QString &key) const; - -private: - QList m_rows; -}; - -// Every image and file across notes, for the attachment browser. -class AttachmentsModel : public QAbstractListModel -{ - Q_OBJECT - QML_ANONYMOUS - - Q_PROPERTY(int count READ count NOTIFY countChanged) - Q_PROPERTY(int filter READ filter WRITE setFilter NOTIFY filterChanged) - -public: - enum Filter { All, Images, Files }; - Q_ENUM(Filter) - - enum Role { - IsImageRole = Qt::UserRole + 1, - BlobHashRole, - AttachmentIdRole, - FileNameRole, - DetailRole, - ExtensionRole, - NoteIdRole, - NoteTitleRole, - }; - - using QAbstractListModel::QAbstractListModel; - - int rowCount(const QModelIndex &parent = {}) const override; - QVariant data(const QModelIndex &index, int role) const override; - QHash roleNames() const override; - - int count() const { return int(m_visible.size()); } - int filter() const { return m_filter; } - void setFilter(int filter); - void reset(const QList &items); - -signals: - void countChanged(); - void filterChanged(); - -private: - void applyFilter(); - - QList m_items; - QList m_visible; - int m_filter = All; -}; - -// QML-facing wrapper around the LibraryService: `Library` in QML. It owns -// what the note list shows (a folder, all notes, the trash, or search -// results) and every library-level action. -class AppLibrary : public QObject -{ - Q_OBJECT - QML_NAMED_ELEMENT(Library) - QML_SINGLETON - - Q_PROPERTY(NotesModel *notes READ notes CONSTANT) - Q_PROPERTY(FoldersModel *folders READ folders CONSTANT) - Q_PROPERTY(AttachmentsModel *attachments READ attachments CONSTANT) - Q_PROPERTY(bool galleryMode READ galleryMode WRITE setGalleryMode NOTIFY galleryModeChanged) - Q_PROPERTY(bool inAttachments READ inAttachments NOTIFY viewChanged) - Q_PROPERTY(QStringList allTags READ allTags NOTIFY countsChanged) - Q_PROPERTY(QString currentKey READ currentKey NOTIFY viewChanged) - Q_PROPERTY(QString viewTitle READ viewTitle NOTIFY viewChanged) - Q_PROPERTY(bool inTrash READ inTrash NOTIFY viewChanged) - Q_PROPERTY(QString searchText READ searchText WRITE setSearchText NOTIFY searchTextChanged) - Q_PROPERTY(bool searching READ searching NOTIFY searchTextChanged) - Q_PROPERTY(int sortOrder READ sortOrder WRITE setSortOrder NOTIFY sortOrderChanged) - Q_PROPERTY(int trashCount READ trashCount NOTIFY countsChanged) - Q_PROPERTY(QString location READ location CONSTANT) - Q_PROPERTY(QString lastNoteId READ lastNoteId WRITE setLastNoteId NOTIFY lastNoteIdChanged) - Q_PROPERTY(bool simulateSaveFailure READ simulateSaveFailure WRITE setSimulateSaveFailure NOTIFY simulateSaveFailureChanged) - -public: - enum SortOrder { SortEdited = int(onotes::NoteSort::Edited), SortCreated, SortTitle }; - Q_ENUM(SortOrder) - - // `settingsFile` stores view preferences; empty uses - // $XDG_CONFIG_HOME/omarchy-notes/settings.ini. - explicit AppLibrary(onotes::LibraryService *service, const QString &settingsFile = {}, - QObject *parent = nullptr); - - static AppLibrary *create(QQmlEngine *, QJSEngine *); - static void setInstance(AppLibrary *instance); - - onotes::LibraryService *service() const { return m_service; } - NotesModel *notes() { return &m_notes; } - FoldersModel *folders() { return &m_folders; } - AttachmentsModel *attachments() { return &m_attachments; } - bool galleryMode() const { return m_gallery; } - void setGalleryMode(bool gallery); - bool inAttachments() const { return m_key == u"attachments" && m_searchText.isEmpty(); } - QStringList allTags() const { return m_tags; } - QString currentKey() const { return m_key; } - QString viewTitle() const; - bool inTrash() const { return m_key == u"trash" && m_searchText.isEmpty(); } - QString searchText() const { return m_searchText; } - void setSearchText(const QString &text); - bool searching() const { return !m_searchText.trimmed().isEmpty(); } - int sortOrder() const { return int(m_sort); } - void setSortOrder(int order); - int trashCount() const { return m_trashCount; } - QString location() const { return m_service->paths().root; } - QString lastNoteId() const; - void setLastNoteId(const QString &id); - - bool simulateSaveFailure() const { return m_service->simulatedSaveFailure(); } - void setSimulateSaveFailure(bool fail); - - // Called by the editor after an acknowledged save. - void noteSaved(const QString ¬eId, const onotes::RichDocument &body, qint64 updatedAt); - - // Views: "all", "notes", "trash", or a folder id. - Q_INVOKABLE void showKey(const QString &key); - Q_INVOKABLE void refresh(); - - // Notes. createNote files the note in the folder being viewed. - Q_INVOKABLE QString createNote(); - // A Quick Note always starts in Notes, whatever is being viewed. - Q_INVOKABLE QString createQuickNote(); - // Removes a note that was never written in (an abandoned Quick Note). - Q_INVOKABLE bool discardIfEmpty(const QString ¬eId); - // Saves text as a new note in Notes (command-line capture). - QString captureText(const QString &text); - Q_INVOKABLE void setPinned(const QString &id, bool pinned); - Q_INVOKABLE bool moveNote(const QString ¬eId, const QString &folderId); - Q_INVOKABLE QString duplicateNote(const QString ¬eId); - Q_INVOKABLE bool trashNote(const QString ¬eId); - Q_INVOKABLE bool recoverNote(const QString ¬eId); - Q_INVOKABLE bool deleteNotePermanently(const QString ¬eId); - Q_INVOKABLE int emptyTrash(); - - // Folders. Results are {ok, id, error} maps so dialogs can show errors inline. - Q_INVOKABLE QVariantMap createFolder(const QString &name, const QString &parentId); - Q_INVOKABLE QVariantMap renameFolder(const QString &id, const QString &name); - Q_INVOKABLE bool deleteFolder(const QString &id); - Q_INVOKABLE QString folderName(const QString &id) const; - Q_INVOKABLE int folderNoteCount(const QString &id) const; - // Destinations for "Move to": [{id, name, depth}], "Notes" first (id ""). - Q_INVOKABLE QVariantList folderChoices() const; - - // Smart Folders. Criteria maps use SmartCriteria's JSON keys. - Q_INVOKABLE QVariantMap createSmartFolder(const QString &name, const QVariantMap &criteria); - Q_INVOKABLE QVariantMap updateSmartFolder(const QString &id, const QString &name, const QVariantMap &criteria); - Q_INVOKABLE bool deleteSmartFolder(const QString &id); - Q_INVOKABLE QVariantMap smartFolder(const QString &id) const; - - // Opening files with the desktop's default apps. - Q_INVOKABLE bool openAttachment(const QString &attachmentId); - Q_INVOKABLE bool openImage(const QString &blobHash); - - // Import and export. Results are maps with ok/error plus details. - Q_INVOKABLE QVariantMap importFiles(const QList &files); - // Imports a folder tree as folders and notes; shows the new folder. - Q_INVOKABLE QVariantMap importFolder(const QUrl &folder); - Q_INVOKABLE QString exportFileName(const QString ¬eId, const QString &format) const; - Q_INVOKABLE QVariantMap exportNote(const QString ¬eId, const QString &format, const QUrl &file); - Q_INVOKABLE QVariantMap exportAll(const QUrl &folder); - - // Backup. Results are maps with ok/error plus details. - Q_INVOKABLE QString defaultBackupName() const; - Q_INVOKABLE QVariantMap backupTo(const QUrl &parentFolder, const QString &name); - Q_INVOKABLE QVariantMap inspectBackup(const QUrl &folder); - // Close the open note (after flushing it) before restoring: its id may - // not exist in the backup. libraryReplaced() follows a successful restore. - Q_INVOKABLE QVariantMap restoreFrom(const QUrl &folder); - Q_INVOKABLE void openLibraryFolder() const; - -signals: - void viewChanged(); - void searchTextChanged(); - void sortOrderChanged(); - void galleryModeChanged(); - void countsChanged(); - void lastNoteIdChanged(); - void simulateSaveFailureChanged(); - // A note's pinned/deleted state changed, or it was removed. - void noteMetaChanged(const QString ¬eId); - // The whole library was replaced (restore); reopen from scratch. - void libraryReplaced(); - void errorOccurred(const QString &message); - -private: - void reloadNotes(); - void reloadFolders(); - void runSearch(); - void onSearchFinished(quint64 ticket, const QList &results); - QHash folderNames() const; - bool report(bool ok, const QString &error); - - onotes::LibraryService *m_service; - std::unique_ptr m_settings; - NotesModel m_notes; - FoldersModel m_folders; - AttachmentsModel m_attachments; - QStringList m_tags; - QList m_smartFolders; - bool m_gallery = false; - QString m_key = QStringLiteral("all"); - QString m_searchText; - QTimer m_searchDebounce; - // Saves can change tags, Smart Folder matches and attachments; the - // sidebar catches up shortly after typing pauses. - QTimer m_sidebarRefresh; - quint64 m_searchTicket = 0; - onotes::NoteSort m_sort = onotes::NoteSort::Edited; - int m_trashCount = 0; -}; diff --git a/src/app/BlobImageProvider.cpp b/src/app/BlobImageProvider.cpp deleted file mode 100644 index 75ad217..0000000 --- a/src/app/BlobImageProvider.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "BlobImageProvider.h" - -#include "LibraryService.h" - -#include - -BlobImageProvider::BlobImageProvider(onotes::LibraryService *service) - : QQuickImageProvider(QQuickImageProvider::Image, QQmlImageProviderBase::ForceAsynchronousImageLoading) - , m_service(service) -{ -} - -QImage BlobImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) -{ - // blobPath() validates the hash, so ids can't reach other files. - QImageReader reader(m_service->blobPath(id)); - reader.setAutoTransform(true); - const QSize original = reader.size(); - if (size) - *size = original; - // Never decode more than a thumbnail needs (and cap unbounded requests). - const QSize bound = requestedSize.isValid() && !requestedSize.isEmpty() ? requestedSize : QSize(1024, 1024); - if (original.isValid() && (original.width() > bound.width() || original.height() > bound.height())) - reader.setScaledSize(original.scaled(bound, Qt::KeepAspectRatioByExpanding)); - return reader.read(); -} diff --git a/src/app/BlobImageProvider.h b/src/app/BlobImageProvider.h deleted file mode 100644 index b9633cb..0000000 --- a/src/app/BlobImageProvider.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include - -namespace onotes { -class LibraryService; -} - -// Serves stored images to QML as image://blob/, decoded off the UI -// thread and scaled to the requested size (thumbnails in the gallery and -// attachment browser). -class BlobImageProvider : public QQuickImageProvider -{ -public: - explicit BlobImageProvider(onotes::LibraryService *service); - QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override; - -private: - onotes::LibraryService *m_service; -}; diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt deleted file mode 100644 index 42143a4..0000000 --- a/src/app/CMakeLists.txt +++ /dev/null @@ -1,80 +0,0 @@ -qt_add_library(notes_app_lib STATIC) - -qt_add_qml_module(notes_app_lib - URI OmarchyNotes - VERSION 1.0 - OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/qml/OmarchyNotes - SOURCES - AppController.cpp AppController.h - AppLibrary.cpp AppLibrary.h - HyprlandSetup.cpp HyprlandSetup.h - InstanceChannel.cpp InstanceChannel.h - BlobImageProvider.cpp BlobImageProvider.h - EditorController.cpp EditorController.h - ThemeController.cpp ThemeController.h - QML_FILES - qml/Main.qml - qml/NoteList.qml - qml/EditorPane.qml - qml/ToolIcon.qml - qml/NoteLinkPicker.qml - qml/Toast.qml - qml/Sidebar.qml - qml/FolderNameDialog.qml - qml/ConfirmDialog.qml - qml/MoveNoteDialog.qml - qml/SmartFolderDialog.qml - qml/NoteMenu.qml - qml/AttachmentsView.qml - qml/QuickNoteWindow.qml - qml/StartupError.qml - RESOURCES - icons/compose.svg - icons/bullets.svg - icons/numbers.svg - icons/checklist.svg - icons/table.svg - icons/image.svg - icons/attach.svg - icons/link.svg - icons/highlight.svg - icons/back.svg - icons/pin.svg - icons/trash.svg - icons/folder.svg - icons/folder-new.svg - icons/all-notes.svg - icons/note.svg - icons/search.svg - icons/sidebar.svg - icons/more.svg - icons/recover.svg - icons/close.svg - icons/smart-folder.svg - icons/tag.svg - icons/gallery.svg - icons/list.svg - icons/share.svg -) - -target_include_directories(notes_app_lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -target_link_libraries(notes_app_lib PUBLIC - notes_core Qt6::Quick Qt6::Qml Qt6::QuickControls2 Qt6::Network) - -qt_add_executable(${ONOTES_BINARY_NAME} main.cpp) -target_link_libraries(${ONOTES_BINARY_NAME} PRIVATE notes_app_lib notes_app_libplugin) -set_target_properties(${ONOTES_BINARY_NAME} PROPERTIES OUTPUT_NAME ${ONOTES_BINARY_NAME}) - -install(TARGETS ${ONOTES_BINARY_NAME} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) - -set(ONOTES_BIN "${CMAKE_INSTALL_FULL_BINDIR}/${ONOTES_BINARY_NAME}") -configure_file(${PROJECT_SOURCE_DIR}/packaging/desktop/org.omarchy.Notes.desktop.in - ${CMAKE_CURRENT_BINARY_DIR}/${ONOTES_APP_ID}.desktop @ONLY) -install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${ONOTES_APP_ID}.desktop - DESTINATION ${CMAKE_INSTALL_DATADIR}/applications) -install(FILES ${PROJECT_SOURCE_DIR}/packaging/icons/org.omarchy.Notes.svg - DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps - RENAME ${ONOTES_APP_ID}.svg) -install(FILES ${PROJECT_SOURCE_DIR}/packaging/metainfo/org.omarchy.Notes.metainfo.xml - DESTINATION ${CMAKE_INSTALL_DATADIR}/metainfo - RENAME ${ONOTES_APP_ID}.metainfo.xml) diff --git a/src/app/EditorController.cpp b/src/app/EditorController.cpp deleted file mode 100644 index 2949aeb..0000000 --- a/src/app/EditorController.cpp +++ /dev/null @@ -1,1596 +0,0 @@ -#include "EditorController.h" - -#include "AppLibrary.h" -#include "LibraryPaths.h" -#include "ThemeController.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace Qt::StringLiterals; -using namespace onotes; - -namespace { - -constexpr auto kFragmentMime = "application/x-omarchy-notes-fragment+json"; -constexpr char16_t kObjectReplacement = 0xFFFC; -constexpr int kMaxIndent = 8; - -ListKind kindOfList(const QTextList *list) -{ - const QTextListFormat lf = list->format(); - if (lf.hasProperty(TextProperty::ListKind)) - return static_cast(lf.intProperty(TextProperty::ListKind)); - switch (lf.style()) { - case QTextListFormat::ListDecimal: - case QTextListFormat::ListLowerAlpha: - case QTextListFormat::ListUpperAlpha: - case QTextListFormat::ListLowerRoman: - case QTextListFormat::ListUpperRoman: - return ListKind::Ordered; - default: - return ListKind::Bullet; - } -} - -int indentOfList(const QTextList *list) -{ - return std::max(0, list->format().indent() - 1); -} - -// Blocks in different table cells (or a cell and the body) never share a list. -bool sameContainer(const QTextBlock &a, const QTextBlock &b) -{ - QTextCursor ca(a); - QTextCursor cb(b); - if (ca.currentFrame() != cb.currentFrame()) - return false; - if (QTextTable *table = ca.currentTable()) - return table->cellAt(a.position()) == table->cellAt(b.position()); - return true; -} - -// Removes one mark from a format without disturbing the others. -void clearMark(QTextCharFormat &fmt, quint32 mark) -{ - switch (mark) { - case Bold: fmt.setFontWeight(QFont::Normal); break; - case Italic: fmt.setFontItalic(false); break; - case Underline: fmt.setFontUnderline(false); break; - case Strikethrough: fmt.setFontStrikeOut(false); break; - case Highlight: - fmt.clearBackground(); - fmt.clearProperty(TextProperty::Highlight); - break; - case Code: - fmt.clearProperty(QTextFormat::FontFamilies); - fmt.clearProperty(QTextFormat::FontFixedPitch); - fmt.clearProperty(TextProperty::Code); - break; - } -} - -template -void forEachFragment(QTextDocument *doc, int start, int end, Fn fn) -{ - for (QTextBlock block = doc->findBlock(start); block.isValid() && block.position() <= end; - block = block.next()) { - for (auto it = block.begin(); !it.atEnd(); ++it) { - const QTextFragment fragment = it.fragment(); - const int fs = std::max(start, fragment.position()); - const int fe = std::min(end, fragment.position() + fragment.length()); - if (fs < fe) - fn(fs, fe, fragment.charFormat()); - } - } -} - -} // namespace - -EditorController::EditorController(QObject *parent) : QObject(parent) -{ - m_idleTimer.setSingleShot(true); - m_idleTimer.setInterval(IdleSaveMs); - connect(&m_idleTimer, &QTimer::timeout, this, &EditorController::saveNow); - // Saves during continuous typing so edits never wait longer than the cap. - m_capTimer.setSingleShot(true); - m_capTimer.setInterval(MaxUnsavedMs); - connect(&m_capTimer, &QTimer::timeout, this, &EditorController::saveNow); - m_retryTimer.setSingleShot(true); - connect(&m_retryTimer, &QTimer::timeout, this, &EditorController::saveNow); - // Decorations follow edits on the next turn of the event loop, after - // the text edit has finished its own update. - m_decorateTimer.setSingleShot(true); - m_decorateTimer.setInterval(0); - connect(&m_decorateTimer, &QTimer::timeout, this, [this] { - if (!m_findText.isEmpty()) - recountMatches(); - decorate(m_decorateFrom, m_decorateTo); - m_decorateFrom = m_decorateTo = -1; - rebuildOverlays(); - }); - - if (ThemeController *theme = ThemeController::instance()) - connect(theme, &ThemeController::changed, this, &EditorController::reloadPresentation); -} - -EditorController::~EditorController() -{ - flush(); -} - -void EditorController::setLibrary(AppLibrary *library) -{ - if (m_library == library) - return; - if (m_library) { - disconnect(m_library->service(), nullptr, this, nullptr); - disconnect(m_library, nullptr, this, nullptr); - } - m_library = library; - if (m_library) { - connect(m_library->service(), &LibraryService::saveFinished, this, &EditorController::onSaveFinished); - connect(m_library, &AppLibrary::noteMetaChanged, this, &EditorController::onLibraryNoteChanged); - } - emit libraryChanged(); - if (!m_pendingNoteId.isEmpty() && m_doc) - openNote(std::exchange(m_pendingNoteId, {})); -} - -void EditorController::setDocument(QQuickTextDocument *document) -{ - if (m_quickDocument == document) - return; - m_quickDocument = document; - setTextDocument(document ? document->textDocument() : nullptr); - emit documentChanged(); -} - -void EditorController::setTextDocument(QTextDocument *doc) -{ - disconnect(m_docConnection); - m_doc = doc; - m_loadedResources.clear(); - if (m_doc) { - m_docConnection = connect(m_doc, &QTextDocument::contentsChange, this, - &EditorController::onContentsChange); - if (!m_pendingNoteId.isEmpty() && m_library) - openNote(std::exchange(m_pendingNoteId, {})); - } -} - -void EditorController::setCursorPosition(int position) -{ - if (m_cursorPosition == position) - return; - m_cursorPosition = position; - if (position != m_pendingPosition) { - m_pendingPosition = -1; // moving the cursor drops a pending format - m_pendingSet = m_pendingClear = 0; - } - emit cursorPositionChanged(); - updateFormatState(); -} - -void EditorController::setSelectionStart(int position) -{ - if (m_selectionStart == position) - return; - m_selectionStart = position; - emit selectionChanged(); - updateFormatState(); -} - -void EditorController::setSelectionEnd(int position) -{ - if (m_selectionEnd == position) - return; - m_selectionEnd = position; - emit selectionChanged(); - updateFormatState(); -} - -void EditorController::setBodyPixelSize(qreal size) -{ - if (qFuzzyCompare(m_bodyPixelSize, size) || size <= 0) - return; - m_bodyPixelSize = size; - emit styleChanged(); - reloadPresentation(); -} - -void EditorController::setDevicePixelRatio(qreal ratio) -{ - if (qFuzzyCompare(m_devicePixelRatio, ratio) || ratio <= 0) - return; - m_devicePixelRatio = ratio; - emit styleChanged(); - reloadPresentation(); -} - -void EditorController::setMaxImageWidth(int width) -{ - width = std::max(120, width); - if (m_maxImageWidth == width) - return; - m_maxImageWidth = width; - emit styleChanged(); - reloadPresentation(); -} - -QString EditorController::editedText() const -{ - if (!m_updatedAt) - return {}; - const QDateTime when = QDateTime::fromMSecsSinceEpoch(m_updatedAt); - const QLocale locale; - return tr("%1 at %2").arg(locale.toString(when.date(), QLocale::LongFormat), - locale.toString(when.time(), QLocale::ShortFormat)); -} - -DocumentStyle EditorController::style() const -{ - DocumentStyle s; - s.bodyPixelSize = m_bodyPixelSize; - s.maxImageWidth = m_maxImageWidth; - if (ThemeController *theme = ThemeController::instance()) { - s.link = theme->link(); - s.highlight = theme->highlight(); - s.tableBorder = theme->tableBorder(); - } - return s; -} - -// ---------------------------------------------------------------- notes - -bool EditorController::openNote(const QString &id) -{ - if (!m_doc || !m_library) { - m_pendingNoteId = id; - return true; - } - if (id == m_noteId) - return true; - if (!m_noteId.isEmpty() && !flush()) { - emit notice(tr("This note has changes that couldn't be saved. Retry or export them first.")); - return false; - } - - QString error; - const auto record = m_library->service()->loadNote(id, &error); - if (!record) { - emit notice(tr("Couldn't open the note: %1").arg(error)); - return false; - } - m_noteId = id; - m_revision = record->revision; - m_updatedAt = record->updatedAt; - m_deletedAt = record->deletedAt; - m_pinned = record->pinned; - m_retryTimer.stop(); - m_retryCount = 0; - loadBody(record->body); - setSaveState(Saved); - emit noteChanged(); - emit noteMetaChanged(); - emit savedChanged(); - // Notes open at the top, like Notes; an empty new note is ready to type. - emit cursorRequested(0); - m_library->setLastNoteId(id); - return true; -} - -void EditorController::closeNote() -{ - m_idleTimer.stop(); - m_capTimer.stop(); - m_retryTimer.stop(); - m_ticket = 0; // a late acknowledgement belongs to a note no longer shown - m_noteId.clear(); - m_revision = m_updatedAt = m_deletedAt = 0; - m_pinned = false; - if (m_doc) - loadBody(RichDocument{{Block::paragraph()}}); - setSaveState(Saved); - emit noteChanged(); - emit noteMetaChanged(); - emit savedChanged(); -} - -void EditorController::setPinned(bool pinned) -{ - if (m_library && !m_noteId.isEmpty() && pinned != m_pinned) - m_library->setPinned(m_noteId, pinned); -} - -// Pinning, moving, deleting or recovering happened in the library; pick up -// the note's new state, or let go of it if it's gone. -void EditorController::onLibraryNoteChanged(const QString ¬eId) -{ - if (noteId != m_noteId || !m_library) - return; - const auto record = m_library->service()->loadNote(noteId); - if (!record) { - closeNote(); - return; - } - m_revision = std::max(m_revision, record->revision); - m_pinned = record->pinned; - m_deletedAt = record->deletedAt; - emit noteMetaChanged(); -} - -void EditorController::loadBody(const RichDocument &body) -{ - m_pendingPosition = -1; - m_pendingSet = m_pendingClear = 0; - m_loading = true; - m_loadedResources.clear(); - DocumentConverter::load(body, m_doc, style()); - ensureResources(); - m_loading = false; - m_savedGeneration = m_generation; - if (!m_findText.isEmpty()) - recountMatches(); - decorateAll(); - rebuildOverlays(); - updateFormatState(); -} - -// Rebuilds the document with the current theme/font. Content is unchanged; -// undo history is reset because formats are recreated. -void EditorController::reloadPresentation() -{ - if (!m_doc || m_noteId.isEmpty()) - return; - const RichDocument body = DocumentConverter::read(m_doc); - const int position = m_cursorPosition; - const quint64 generation = m_generation; - const quint64 saved = m_savedGeneration; - loadBody(body); - m_generation = generation; - m_savedGeneration = saved; - emit cursorRequested(std::clamp(position, 0, m_doc->characterCount() - 1)); -} - -void EditorController::onContentsChange(int position, int removed, int added) -{ - if (m_decorating) - return; // our own re-layout, not an edit - if (m_loading || m_noteId.isEmpty() || readOnly() || (removed == 0 && added == 0)) - return; - if (m_applyingPending) - return; // counted with the insertion it formats - if (m_pendingPosition >= 0 && position == m_pendingPosition && removed == 0 && added > 0) - applyPendingFormat(position, position + added); - ++m_generation; - if (m_saveState == Saved) - setSaveState(Edited); - scheduleDecorate(position, position + std::max(added, 1)); - // Save once typing pauses, and at the latest when the cap expires. - m_idleTimer.start(); - if (!m_capTimer.isActive()) - m_capTimer.start(); - QMetaObject::invokeMethod(this, &EditorController::updateFormatState, Qt::QueuedConnection); -} - -QTextCharFormat EditorController::pendingFormatAt(const QTextCursor &cursor) const -{ - QTextCharFormat fmt = cursor.charFormat(); - if (fmt.isImageFormat()) - fmt = baseFormatFor(cursor.block()); - for (quint32 mark = 1; mark <= Code; mark <<= 1) { - if (m_pendingClear & mark) - clearMark(fmt, mark); - } - DocumentConverter::applyMarks(fmt, m_pendingSet, {}, style()); - return fmt; -} - -bool EditorController::typeWithPendingFormat(const QString &text) -{ - if (!m_doc || !hasPendingFormat()) - return false; - QTextCursor cursor = textCursor(); - const QTextCharFormat fmt = pendingFormatAt(cursor); - m_applyingPending = true; // the insertion already carries the format - cursor.insertText(text, fmt); - m_applyingPending = false; - m_pendingPosition = -1; - m_pendingSet = m_pendingClear = 0; - // The edit still counts as a change for autosave. - onContentsChange(cursor.position() - int(text.size()), 0, int(text.size())); - emit cursorRequested(cursor.position()); - updateFormatState(); - return true; -} - -// Fallback for text that arrives without a key event (input method -// commits): format it after insertion, as a separate undo step. -void EditorController::applyPendingFormat(int start, int end) -{ - m_applyingPending = true; - QTextCursor range(m_doc); - range.setPosition(start); - range.setPosition(end, QTextCursor::KeepAnchor); - QTextCursor before(m_doc); - before.setPosition(start); - range.setCharFormat(pendingFormatAt(before)); - m_applyingPending = false; - // Following text inherits the format from the characters before it. - m_pendingPosition = -1; - m_pendingSet = m_pendingClear = 0; -} - -void EditorController::saveNow() -{ - m_idleTimer.stop(); - if (!m_library || !m_doc || m_noteId.isEmpty() || !isDirty()) - return; - if (m_ticket || m_saveState == Conflict) - return; // a save is in flight; its completion schedules the next one - - m_inFlightBody = DocumentConverter::read(m_doc); - m_inFlightGeneration = m_generation; - m_capTimer.stop(); - m_ticket = m_library->service()->saveNote({m_noteId, m_revision, m_inFlightBody}); - if (m_saveState != Failed) - setSaveState(Saving); -} - -void EditorController::onSaveFinished(quint64 ticket, const QString ¬eId, const SaveResult &result) -{ - if (ticket != m_ticket) - return; - m_ticket = 0; - - switch (result.status) { - case SaveResult::Status::Saved: - m_retryCount = 0; - if (m_library) - m_library->noteSaved(noteId, m_inFlightBody, result.updatedAt); - if (noteId != m_noteId) - return; - m_revision = result.revision; - m_updatedAt = result.updatedAt; - m_savedGeneration = m_inFlightGeneration; - emit savedChanged(); - if (isDirty()) { - setSaveState(Edited); - m_idleTimer.start(); - } else { - setSaveState(Saved); - } - return; - case SaveResult::Status::Conflict: - m_conflictRevision = result.revision; - setSaveState(Conflict, result.error); - return; - case SaveResult::Status::Failed: { - // Keep the draft in the editor and retry with backoff. - setSaveState(Failed, result.error); - static constexpr int backoff[] = {2000, 5000, 15000, 30000}; - m_retryTimer.start(backoff[std::min(m_retryCount++, std::size(backoff) - 1)]); - return; - } - } -} - -bool EditorController::flush() -{ - if (!m_library || m_noteId.isEmpty()) - return true; - m_retryTimer.stop(); - // Each round queues a save if needed and waits for its acknowledgement; - // edits made while a save was in flight need a second round. - for (int round = 0; round < 3; ++round) { - if (m_saveState == Conflict) - return false; - if (!m_ticket) { - if (!isDirty()) - return true; - saveNow(); - } - m_library->service()->deliverPendingResults(); - if (m_saveState == Failed) - return false; - } - return !isDirty() && !m_ticket; -} - -void EditorController::retrySave() -{ - m_retryTimer.stop(); - m_retryCount = 0; - saveNow(); -} - -void EditorController::keepMyVersion() -{ - if (m_saveState != Conflict) - return; - m_revision = m_conflictRevision; - setSaveState(Edited); - saveNow(); -} - -bool EditorController::exportDraft(const QUrl &file) -{ - if (!m_doc) - return false; - QSaveFile out(file.toLocalFile()); - if (!out.open(QIODevice::WriteOnly)) { - emit notice(tr("Couldn't export: %1").arg(out.errorString())); - return false; - } - out.write(m_doc->toMarkdown().toUtf8()); - if (!out.commit()) { - emit notice(tr("Couldn't export: %1").arg(out.errorString())); - return false; - } - return true; -} - -void EditorController::setSaveState(SaveState state, const QString &error) -{ - if (m_saveState == state && m_saveError == error) - return; - m_saveState = state; - m_saveError = error; - emit saveStateChanged(); -} - -// ---------------------------------------------------------------- resources - -void EditorController::ensureResources() -{ - if (!m_doc || !m_library) - return; - bool added = false; - for (QTextBlock block = m_doc->begin(); block.isValid(); block = block.next()) { - for (auto it = block.begin(); !it.atEnd(); ++it) { - const QTextCharFormat cf = it.fragment().charFormat(); - if (!cf.isImageFormat()) - continue; - const QTextImageFormat fmt = cf.toImageFormat(); - const QString name = fmt.name(); - if (m_loadedResources.contains(name)) - continue; - m_loadedResources.insert(name); - - QImage image; - if (const QString hash = DocumentConverter::blobHashFromResource(name); !hash.isEmpty()) { - const QSize logical(qRound(fmt.width()), qRound(fmt.height())); - QImageReader reader(m_library->service()->blobPath(hash)); - reader.setAutoTransform(true); - const QSize source = reader.size(); - const QSize target = logical.isValid() && !logical.isEmpty() - ? (logical * m_devicePixelRatio).boundedTo(source.isValid() ? source : QSize(8192, 8192)) - : QSize(); - if (target.isValid() && source.isValid() && target != source) - reader.setScaledSize(source.scaled(target, Qt::KeepAspectRatio)); - image = reader.read(); - if (image.isNull()) { - image = renderMissingImage(logical.isEmpty() ? QSize(240, 120) : logical); - } else { - image.setDevicePixelRatio(double(image.width()) / std::max(1, logical.width())); - } - } else if (const QString id = DocumentConverter::attachmentIdFromResource(name); !id.isEmpty()) { - image = renderAttachmentChip(id); - } else { - continue; - } - m_doc->addResource(QTextDocument::ImageResource, QUrl(name), image); - added = true; - } - } - if (added) { - const bool wasLoading = std::exchange(m_loading, true); - m_doc->markContentsDirty(0, m_doc->characterCount()); - m_loading = wasLoading; - } -} - -QImage EditorController::renderAttachmentChip(const QString &attachmentId) const -{ - const DocumentStyle s = style(); - const QSize logical = s.attachmentChipSize; - QImage image(logical * m_devicePixelRatio, QImage::Format_ARGB32_Premultiplied); - image.setDevicePixelRatio(m_devicePixelRatio); - image.fill(Qt::transparent); - - const auto info = m_library ? m_library->service()->attachment(attachmentId) : std::nullopt; - const bool available = info && QFileInfo::exists(m_library->service()->blobPath(info->blobHash)); - ThemeController *theme = ThemeController::instance(); - const QColor surface = theme ? theme->raised() : QColor(0xee, 0xee, 0xee); - const QColor border = theme ? theme->divider() : QColor(0xcc, 0xcc, 0xcc); - const QColor text = theme ? theme->text() : Qt::black; - const QColor secondary = theme ? theme->secondaryText() : Qt::darkGray; - const QColor badge = available ? (theme ? theme->accent() : Qt::blue) : (theme ? theme->error() : Qt::red); - const QColor badgeText = theme ? theme->accentText() : Qt::white; - - QPainter p(&image); - p.setRenderHint(QPainter::Antialiasing); - p.setPen(QPen(border, 1)); - p.setBrush(surface); - p.drawRoundedRect(QRectF(0.5, 0.5, logical.width() - 1, logical.height() - 1), 8, 8); - - const QString extension = info ? QFileInfo(info->fileName).suffix().toUpper().left(4) : u"?"_s; - const QRectF badgeRect(8, 8, 40, logical.height() - 16); - p.setPen(Qt::NoPen); - p.setBrush(badge); - p.drawRoundedRect(badgeRect, 5, 5); - QFont font = QGuiApplication::font(); - font.setPixelSize(10); - font.setBold(true); - p.setFont(font); - p.setPen(badgeText); - p.drawText(badgeRect, Qt::AlignCenter, extension.isEmpty() ? u"FILE"_s : extension); - - const qreal textX = badgeRect.right() + 10; - const qreal textWidth = logical.width() - textX - 10; - font.setPixelSize(13); - font.setBold(false); - font.setWeight(QFont::DemiBold); - p.setFont(font); - p.setPen(text); - const QString title = info ? info->fileName : tr("Missing attachment"); - p.drawText(QRectF(textX, 8, textWidth, 18), Qt::AlignLeft | Qt::AlignVCenter, - QFontMetrics(font).elidedText(title, Qt::ElideMiddle, int(textWidth))); - - font.setWeight(QFont::Normal); - font.setPixelSize(12); - p.setFont(font); - p.setPen(available ? secondary : badge); - QString subtitle; - if (!info) - subtitle = tr("Not found in this library"); - else if (!available) - subtitle = tr("File data is missing"); - else - subtitle = u"%1 · %2"_s.arg(QMimeDatabase().mimeTypeForName(info->mimeType).comment(), - QLocale().formattedDataSize(info->size)); - p.drawText(QRectF(textX, 27, textWidth, 16), Qt::AlignLeft | Qt::AlignVCenter, - QFontMetrics(font).elidedText(subtitle, Qt::ElideRight, int(textWidth))); - return image; -} - -QImage EditorController::renderMissingImage(QSize logical) const -{ - QImage image(logical * m_devicePixelRatio, QImage::Format_ARGB32_Premultiplied); - image.setDevicePixelRatio(m_devicePixelRatio); - image.fill(Qt::transparent); - ThemeController *theme = ThemeController::instance(); - QPainter p(&image); - p.setRenderHint(QPainter::Antialiasing); - p.setPen(QPen(theme ? theme->divider() : Qt::gray, 1, Qt::DashLine)); - p.drawRoundedRect(QRectF(0.5, 0.5, logical.width() - 1, logical.height() - 1), 8, 8); - p.setPen(theme ? theme->secondaryText() : Qt::darkGray); - p.drawText(QRectF(QPointF(0, 0), logical), Qt::AlignCenter, tr("Image unavailable")); - return image; -} - -// ---------------------------------------------------------------- state - -QTextCursor EditorController::textCursor() const -{ - QTextCursor cursor(m_doc); - const int last = m_doc->characterCount() - 1; - if (m_selectionStart != m_selectionEnd) { - cursor.setPosition(std::clamp(m_selectionStart, 0, last)); - cursor.setPosition(std::clamp(m_selectionEnd, 0, last), QTextCursor::KeepAnchor); - } else { - cursor.setPosition(std::clamp(m_cursorPosition, 0, last)); - } - return cursor; -} - -QList EditorController::selectedBlocks() const -{ - const QTextCursor cursor = textCursor(); - QList blocks; - for (QTextBlock b = m_doc->findBlock(cursor.selectionStart()); - b.isValid() && b.position() <= cursor.selectionEnd(); b = b.next()) { - blocks.append(b); - } - return blocks; -} - -void EditorController::updateFormatState() -{ - if (!m_doc) - return; - QTextCursor cursor = textCursor(); - // With a selection, report the format of its first character. - if (cursor.hasSelection()) - cursor.setPosition(std::min(cursor.selectionStart() + 1, m_doc->characterCount() - 1)); - const QTextBlock block = cursor.block(); - const int heading = std::min(block.blockFormat().headingLevel(), 3); - - quint32 marks = DocumentConverter::marksOf(cursor.charFormat(), heading > 0); - if (!cursor.hasSelection() && cursor.position() == m_pendingPosition) - marks = (marks | m_pendingSet) & ~m_pendingClear; - const int list = int(DocumentConverter::listKindOf(block)); - const bool table = cursor.currentTable() != nullptr; - if (marks == m_marks && heading == m_blockStyle && list == m_listKind && table == m_inTable) - return; - m_marks = marks; - m_blockStyle = heading; - m_listKind = list; - m_inTable = table; - emit formatChanged(); -} - -// ---------------------------------------------------------------- formatting - -bool EditorController::toggleMark(int mark) -{ - if (!m_doc) - return false; - QTextCursor cursor = textCursor(); - if (!cursor.hasSelection()) { - // Inside a word, act on the word; at a boundary, set the format for - // the text typed next. - QTextCursor word = cursor; - word.select(QTextCursor::WordUnderCursor); - if (!word.hasSelection() || word.selectionStart() == cursor.position() - || word.selectionEnd() == cursor.position()) { - if (m_pendingPosition != cursor.position()) { - m_pendingSet = m_pendingClear = 0; - m_pendingPosition = cursor.position(); - } - const bool on = m_marks & quint32(mark); - if (on) { - m_pendingClear |= quint32(mark); - m_pendingSet &= ~quint32(mark); - } else { - m_pendingSet |= quint32(mark); - m_pendingClear &= ~quint32(mark); - } - updateFormatState(); - return true; - } - cursor = word; - } - const int start = cursor.selectionStart(); - const int end = cursor.selectionEnd(); - const bool inHeading = cursor.block().blockFormat().headingLevel() > 0; - - bool allHave = true; - forEachFragment(m_doc, start, end, [&](int, int, const QTextCharFormat &fmt) { - if (!fmt.isImageFormat() && !(DocumentConverter::marksOf(fmt, inHeading) & quint32(mark))) - allHave = false; - }); - - cursor.beginEditBlock(); - if (allHave) { - forEachFragment(m_doc, start, end, [&](int fs, int fe, QTextCharFormat fmt) { - if (fmt.isImageFormat()) - return; - clearMark(fmt, quint32(mark)); - QTextCursor range(m_doc); - range.setPosition(fs); - range.setPosition(fe, QTextCursor::KeepAnchor); - range.setCharFormat(fmt); - }); - } else { - QTextCharFormat add; - DocumentConverter::applyMarks(add, quint32(mark), {}, style()); - cursor.mergeCharFormat(add); - } - cursor.endEditBlock(); - updateFormatState(); - return true; -} - -QTextCharFormat EditorController::baseFormatFor(const QTextBlock &block) const -{ - Block shape; - const int heading = block.blockFormat().headingLevel(); - if (heading > 0) { - shape.type = Block::Type::Heading; - shape.level = std::min(heading, 3); - } - return DocumentConverter::charFormatForBlock(shape, style()); -} - -void EditorController::applyBlockStyle(QTextBlock block, int level) -{ - if (level > 0 && block.textList()) - removeFromList(block); - - QTextCursor cursor(block); - QTextBlockFormat bf = block.blockFormat(); - bf.setHeadingLevel(level); - bf.setTopMargin(level == 0 ? 0 : (level == 1 ? 4 : 10)); - bf.setBottomMargin(level == 0 ? 0 : 4); - cursor.setBlockFormat(bf); - - const qreal size = style().headingPixelSize(level); - auto restyle = [&](QTextCharFormat fmt) { - if (level > 0) { - fmt.setProperty(QTextFormat::FontPixelSize, int(size)); - fmt.setFontWeight(QFont::Bold); - } else { - fmt.clearProperty(QTextFormat::FontPixelSize); - fmt.clearProperty(QTextFormat::FontWeight); - } - return fmt; - }; - for (auto it = block.begin(); !it.atEnd(); ++it) { - const QTextFragment fragment = it.fragment(); - QTextCursor range(m_doc); - range.setPosition(fragment.position()); - range.setPosition(fragment.position() + fragment.length(), QTextCursor::KeepAnchor); - range.setCharFormat(restyle(fragment.charFormat())); - } - cursor.setBlockCharFormat(restyle(cursor.blockCharFormat())); -} - -void EditorController::setBlockStyle(int headingLevel) -{ - if (!m_doc) - return; - headingLevel = std::clamp(headingLevel, 0, 3); - QTextCursor cursor = textCursor(); - cursor.beginEditBlock(); - for (const QTextBlock &block : selectedBlocks()) - applyBlockStyle(block, headingLevel); - cursor.endEditBlock(); - updateFormatState(); -} - -void EditorController::removeFromList(QTextBlock block) -{ - if (QTextList *list = block.textList()) - list->remove(block); - QTextBlockFormat bf = block.blockFormat(); - bf.setIndent(0); - bf.setMarker(QTextBlockFormat::MarkerType::NoMarker); - bf.setObjectIndex(-1); - QTextCursor(block).setBlockFormat(bf); -} - -void EditorController::attachToList(QTextBlock block, ListKind kind, int indent) -{ - if (QTextList *current = block.textList()) { - if (kindOfList(current) == kind && indentOfList(current) == indent) - return; - current->remove(block); - } - - // Join the nearest list at the same depth and kind, looking past deeper - // nested items, so numbering continues across sub-lists. - auto search = [&](bool forward) -> QTextList * { - for (QTextBlock b = forward ? block.next() : block.previous(); b.isValid(); - b = forward ? b.next() : b.previous()) { - QTextList *list = b.textList(); - if (!list || !sameContainer(b, block)) - return nullptr; - const int depth = indentOfList(list); - if (depth == indent && kindOfList(list) == kind) - return list; - if (depth < indent) - return nullptr; - } - return nullptr; - }; - if (QTextList *list = search(false)) - list->add(block); - else if (QTextList *list = search(true)) - list->add(block); - else - QTextCursor(block).createList(DocumentConverter::listFormat(kind, indent)); -} - -void EditorController::makeListItem(QTextBlock block, ListKind kind, int indent) -{ - if (block.blockFormat().headingLevel() > 0) - applyBlockStyle(block, 0); - block = m_doc->findBlock(block.position()); - QTextBlockFormat bf = block.blockFormat(); - const bool wasChecked = bf.marker() == QTextBlockFormat::MarkerType::Checked; - bf.setMarker(kind == ListKind::Check ? (wasChecked ? QTextBlockFormat::MarkerType::Checked - : QTextBlockFormat::MarkerType::Unchecked) - : QTextBlockFormat::MarkerType::NoMarker); - QTextCursor(block).setBlockFormat(bf); - attachToList(block, kind, indent); -} - -void EditorController::toggleList(int kindValue) -{ - if (!m_doc) - return; - const auto kind = static_cast(std::clamp(kindValue, 1, 3)); - const QList blocks = selectedBlocks(); - const bool all = std::all_of(blocks.begin(), blocks.end(), [&](const QTextBlock &b) { - return DocumentConverter::listKindOf(b) == kind; - }); - - QTextCursor cursor = textCursor(); - cursor.beginEditBlock(); - for (const QTextBlock &block : blocks) { - if (all) { - removeFromList(block); - } else { - const int indent = block.textList() ? indentOfList(block.textList()) : 0; - makeListItem(block, kind, indent); - } - } - cursor.endEditBlock(); - updateFormatState(); -} - -void EditorController::setListIndent(int delta) -{ - QTextCursor cursor = textCursor(); - cursor.beginEditBlock(); - for (const QTextBlock &block : selectedBlocks()) { - QTextList *list = block.textList(); - if (!list) - continue; - const int depth = indentOfList(list) + delta; - if (depth < 0) - removeFromList(block); - else - attachToList(block, DocumentConverter::listKindOf(block), std::min(depth, kMaxIndent)); - } - cursor.endEditBlock(); - updateFormatState(); -} - -void EditorController::indent() -{ - if (m_doc) - setListIndent(+1); -} - -void EditorController::outdent() -{ - if (m_doc) - setListIndent(-1); -} - -// ---------------------------------------------------------------- keys - -bool EditorController::handleReturn() -{ - if (!m_doc) - return false; - QTextCursor cursor = textCursor(); - if (cursor.hasSelection()) - return false; - const QTextBlock block = cursor.block(); - - if (QTextList *list = block.textList()) { - if (block.length() <= 1) { - // Return on an empty item steps out one level, then out of the list. - cursor.beginEditBlock(); - if (indentOfList(list) > 0) - attachToList(block, DocumentConverter::listKindOf(block), indentOfList(list) - 1); - else - removeFromList(block); - cursor.endEditBlock(); - updateFormatState(); - return true; - } - cursor.beginEditBlock(); - cursor.insertBlock(); - // New checklist items start unchecked. - QTextBlockFormat bf = cursor.blockFormat(); - if (bf.marker() == QTextBlockFormat::MarkerType::Checked) { - bf.setMarker(QTextBlockFormat::MarkerType::Unchecked); - cursor.setBlockFormat(bf); - } - cursor.endEditBlock(); - emit cursorRequested(cursor.position()); - return true; - } - - if (block.blockFormat().headingLevel() > 0 && cursor.atBlockEnd()) { - // Headings are followed by body text, like Notes' title. - const QTextBlockFormat body = style().bodyBlockFormat(); - cursor.beginEditBlock(); - cursor.insertBlock(body, baseFormatFor(QTextBlock())); - cursor.endEditBlock(); - emit cursorRequested(cursor.position()); - return true; - } - return false; -} - -bool EditorController::handleTab(bool backward) -{ - if (!m_doc) - return false; - QTextCursor cursor = textCursor(); - if (QTextTable *table = cursor.currentTable()) { - const QTextTableCell cell = table->cellAt(cursor); - int row = cell.row(); - int column = cell.column() + (backward ? -1 : cell.columnSpan()); - if (column >= table->columns()) { - column = 0; - ++row; - } else if (column < 0) { - column = table->columns() - 1; - --row; - } - if (row < 0) - return true; - if (row >= table->rows()) { - // Tab from the last cell adds a row. - table->appendRows(1); - } - const QTextTableCell next = table->cellAt(row, column); - emit selectionRequested(next.firstCursorPosition().position(), next.lastCursorPosition().position()); - return true; - } - if (cursor.block().textList()) { - setListIndent(backward ? -1 : +1); - return true; - } - return false; -} - -bool EditorController::handleBackspace() -{ - if (!m_doc) - return false; - const QTextCursor cursor = textCursor(); - if (cursor.hasSelection() || !cursor.atBlockStart()) - return false; - const QTextBlock block = cursor.block(); - if (QTextList *list = block.textList()) { - QTextCursor edit = cursor; - edit.beginEditBlock(); - if (indentOfList(list) > 0) - attachToList(block, DocumentConverter::listKindOf(block), indentOfList(list) - 1); - else - removeFromList(block); - edit.endEditBlock(); - updateFormatState(); - return true; - } - if (block.blockFormat().headingLevel() > 0 && block.length() <= 1) { - setBlockStyle(0); - return true; - } - return false; -} - -// ---------------------------------------------------------------- objects - -void EditorController::toggleCheckAtCursor() -{ - if (m_doc) - toggleCheckAt(textCursor().position()); -} - -void EditorController::toggleCheckAt(int position) -{ - if (!m_doc || readOnly()) - return; - const QTextBlock block = m_doc->findBlock(position); - QTextBlockFormat bf = block.blockFormat(); - if (bf.marker() == QTextBlockFormat::MarkerType::NoMarker) - return; - bf.setMarker(bf.marker() == QTextBlockFormat::MarkerType::Checked - ? QTextBlockFormat::MarkerType::Unchecked - : QTextBlockFormat::MarkerType::Checked); - QTextCursor(block).setBlockFormat(bf); - updateFormatState(); -} - -bool EditorController::activateObjectAt(int position) -{ - if (!m_doc) - return false; - // The object may be just before or after the hit position. - for (int p : {position, position - 1}) { - if (p < 0 || p >= m_doc->characterCount() - 1 || m_doc->characterAt(p) != QChar(kObjectReplacement)) - continue; - QTextCursor c(m_doc); - c.setPosition(p + 1); - const QTextCharFormat cf = c.charFormat(); - if (!cf.isImageFormat()) - continue; - const QString name = cf.toImageFormat().name(); - if (const QString id = DocumentConverter::attachmentIdFromResource(name); !id.isEmpty()) - return m_library->openAttachment(id); - if (const QString hash = DocumentConverter::blobHashFromResource(name); !hash.isEmpty()) - return m_library->openImage(hash); - } - return false; -} - -void EditorController::openLink(const QString &href) -{ - if (href.startsWith(u"note://")) { - emit openNoteRequested(href.mid(7)); - return; - } - if (DocumentConverter::isAllowedLink(href)) - QDesktopServices::openUrl(QUrl(href)); -} - -// ---------------------------------------------------------------- insertions - -void EditorController::insertTable(int rows, int columns) -{ - if (!m_doc) - return; - QTextCursor cursor = textCursor(); - cursor.clearSelection(); - cursor.beginEditBlock(); - if (cursor.block().length() > 1) - cursor.movePosition(QTextCursor::EndOfBlock); - QTextTable *table = cursor.insertTable(std::max(1, rows), std::max(1, columns), - DocumentConverter::tableFormat(style())); - cursor.endEditBlock(); - emit cursorRequested(table->cellAt(0, 0).firstCursorPosition().position()); -} - -void EditorController::addTableRow() -{ - QTextCursor cursor = textCursor(); - if (QTextTable *table = cursor.currentTable()) { - const QTextTableCell cell = table->cellAt(cursor); - table->insertRows(cell.row() + cell.rowSpan(), 1); - } -} - -void EditorController::addTableColumn() -{ - QTextCursor cursor = textCursor(); - if (QTextTable *table = cursor.currentTable()) { - const QTextTableCell cell = table->cellAt(cursor); - table->insertColumns(cell.column() + cell.columnSpan(), 1); - } -} - -void EditorController::removeTableRow() -{ - QTextCursor cursor = textCursor(); - if (QTextTable *table = cursor.currentTable()) { - if (table->rows() > 1) - table->removeRows(table->cellAt(cursor).row(), 1); - } -} - -void EditorController::removeTableColumn() -{ - QTextCursor cursor = textCursor(); - if (QTextTable *table = cursor.currentTable()) { - if (table->columns() > 1) - table->removeColumns(table->cellAt(cursor).column(), 1); - } -} - -void EditorController::insertImage(QTextCursor &cursor, const QString &hash, QSize logicalSize) -{ - QTextImageFormat fmt; - fmt.setName(DocumentConverter::imageResourceName(hash)); - QSizeF display = logicalSize; - if (display.width() > m_maxImageWidth) - display = display.scaled(m_maxImageWidth, 1e6, Qt::KeepAspectRatio); - fmt.setWidth(display.width()); - fmt.setHeight(display.height()); - fmt.setProperty(TextProperty::ImageLogicalSize, logicalSize); - cursor.insertImage(fmt); -} - -bool EditorController::insertImageFile(const QUrl &file) -{ - if (!m_doc || !m_library) - return false; - const QString path = file.toLocalFile(); - QImageReader reader(path); - reader.setAutoTransform(true); - const QSize size = reader.size(); - if (!size.isValid()) { - emit notice(tr("%1 isn't an image this app can show.").arg(QFileInfo(path).fileName())); - return false; - } - QString error; - const auto hash = m_library->service()->addImageFile(path, &error); - if (!hash) { - emit notice(error); - return false; - } - QTextCursor cursor = textCursor(); - insertImage(cursor, *hash, size); - ensureResources(); - return true; -} - -bool EditorController::attachFile(const QUrl &file) -{ - if (!m_doc || !m_library || m_noteId.isEmpty()) - return false; - QString error; - const auto info = m_library->service()->addAttachment(m_noteId, file.toLocalFile(), &error); - if (!info) { - emit notice(error); - return false; - } - QTextImageFormat fmt; - fmt.setName(DocumentConverter::attachmentResourceName(info->id)); - const QSize chip = style().attachmentChipSize; - fmt.setWidth(chip.width()); - fmt.setHeight(chip.height()); - fmt.setVerticalAlignment(QTextCharFormat::AlignMiddle); - QTextCursor cursor = textCursor(); - cursor.insertImage(fmt); - ensureResources(); - return true; -} - -void EditorController::insertNoteLink(const QString ¬eId) -{ - if (!m_doc || !m_library) - return; - QString title = m_library->notes()->titleOf(noteId); - if (title.isEmpty()) - title = tr("Untitled note"); - QTextCursor cursor = textCursor(); - const QTextCharFormat base = baseFormatFor(cursor.block()); - QTextCharFormat link = base; - DocumentConverter::applyMarks(link, 0, u"note://"_s + noteId, style()); - cursor.beginEditBlock(); - cursor.insertText(title, link); - // End the link so typing continues as plain text. - cursor.insertText(u" "_s, base); - cursor.endEditBlock(); - emit cursorRequested(cursor.position()); -} - -// ---------------------------------------------------------------- decorations and find - -void EditorController::scheduleDecorate(int from, int to) -{ - m_decorateFrom = m_decorateFrom < 0 ? from : std::min(m_decorateFrom, from); - m_decorateTo = std::max(m_decorateTo, to); - m_decorateTimer.start(); -} - -void EditorController::decorateAll() -{ - if (m_doc) - decorate(0, m_doc->characterCount()); -} - -void EditorController::decorate(int from, int to) -{ - if (!m_doc || from < 0) - return; - ThemeController *theme = ThemeController::instance(); - QTextCharFormat tagFormat; - tagFormat.setForeground(theme ? theme->accent() : QColor(0x2f, 0x6f, 0xd0)); - QTextCharFormat matchFormat; - QColor highlight = theme ? theme->highlight() : QColor(255, 204, 0, 110); - matchFormat.setBackground(highlight); - QTextCharFormat currentFormat; - QColor current = theme ? theme->accent() : QColor(0x2f, 0x6f, 0xd0); - current.setAlphaF(0.45f); - currentFormat.setBackground(current); - const int currentStart = m_findCurrent >= 0 ? m_matchStarts.value(m_findCurrent, -1) : -1; - - to = std::min(to, m_doc->characterCount()); - for (QTextBlock block = m_doc->findBlock(from); block.isValid() && block.position() <= to; - block = block.next()) { - QList ranges; - const QString text = block.text(); - for (const TagMatch &m : findTags(text)) { - // Tags aren't tags inside code or links (see RichDocument::tags). - QTextCursor at(block); - at.setPosition(block.position() + int(m.start) + 1); - const QTextCharFormat cf = at.charFormat(); - if (cf.isAnchor() || cf.boolProperty(TextProperty::Code)) - continue; - ranges.append({int(m.start), int(m.length), tagFormat}); - } - if (!m_findText.isEmpty()) { - for (qsizetype i = text.indexOf(m_findText, 0, Qt::CaseInsensitive); i >= 0; - i = text.indexOf(m_findText, i + m_findText.size(), Qt::CaseInsensitive)) { - const bool isCurrent = block.position() + int(i) == currentStart; - ranges.append({int(i), int(m_findText.size()), isCurrent ? currentFormat : matchFormat}); - } - } - if (ranges.isEmpty() && block.layout()->formats().isEmpty()) - continue; - block.layout()->setFormats(ranges); - m_decorating = true; - m_doc->markContentsDirty(block.position(), block.length()); - m_decorating = false; - } -} - -void EditorController::setFindText(const QString &text) -{ - if (text == m_findText) - return; - m_findText = text; - recountMatches(); - // Jump to the first match from the cursor, like typing into a find bar. - m_findCurrent = -1; - for (int i = 0; i < m_matchStarts.size(); ++i) { - if (m_matchStarts[i] >= m_cursorPosition - int(text.size())) { - m_findCurrent = i; - break; - } - } - if (m_findCurrent < 0 && !m_matchStarts.isEmpty()) - m_findCurrent = 0; - decorateAll(); - if (m_findCurrent >= 0) - selectMatch(m_findCurrent); - emit findChanged(); -} - -void EditorController::recountMatches() -{ - const int previous = m_findCurrent >= 0 ? m_matchStarts.value(m_findCurrent, -1) : -1; - m_matchStarts.clear(); - if (m_doc && !m_findText.isEmpty()) { - for (QTextBlock block = m_doc->begin(); block.isValid(); block = block.next()) { - const QString text = block.text(); - for (qsizetype i = text.indexOf(m_findText, 0, Qt::CaseInsensitive); i >= 0; - i = text.indexOf(m_findText, i + m_findText.size(), Qt::CaseInsensitive)) - m_matchStarts.append(block.position() + int(i)); - } - } - // Keep the current match if it still exists. - m_findCurrent = previous >= 0 ? int(m_matchStarts.indexOf(previous)) : -1; - if (m_findCurrent < 0 && !m_matchStarts.isEmpty() && previous >= 0) - m_findCurrent = 0; - emit findChanged(); -} - -void EditorController::selectMatch(int index) -{ - if (index < 0 || index >= m_matchStarts.size()) - return; - const int old = m_findCurrent >= 0 ? m_matchStarts.value(m_findCurrent, -1) : -1; - m_findCurrent = index; - const int start = m_matchStarts[index]; - if (old >= 0) - decorate(old, old + 1); - decorate(start, start + 1); - emit selectionRequested(start, start + int(m_findText.size())); - emit findChanged(); -} - -void EditorController::findNext() -{ - if (!m_matchStarts.isEmpty()) - selectMatch((m_findCurrent + 1) % int(m_matchStarts.size())); -} - -void EditorController::findPrevious() -{ - if (!m_matchStarts.isEmpty()) - selectMatch((m_findCurrent - 1 + int(m_matchStarts.size())) % int(m_matchStarts.size())); -} - -QString EditorController::tagAt(int position) const -{ - if (!m_doc) - return {}; - const QTextBlock block = m_doc->findBlock(position); - const int offset = position - block.position(); - for (const TagMatch &m : findTags(block.text())) { - if (offset >= m.start && offset <= m.start + m.length) - return m.tag; - } - return {}; -} - -// ---------------------------------------------------------------- overlays - -void EditorController::rebuildOverlays() -{ - QVariantList next; - if (m_doc) { - for (QTextBlock block = m_doc->begin(); block.isValid(); block = block.next()) { - const auto marker = block.blockFormat().marker(); - if (marker != QTextBlockFormat::MarkerType::NoMarker && block.textList()) { - QString label = block.text().trimmed(); - label.remove(QChar(kObjectReplacement)); - next.append(QVariantMap{{u"kind"_s, u"check"_s}, - {u"position"_s, block.position()}, - {u"checked"_s, marker == QTextBlockFormat::MarkerType::Checked}, - {u"name"_s, label.isEmpty() ? tr("Checklist item") : label}}); - } - for (auto it = block.begin(); !it.atEnd(); ++it) { - const QTextFragment fragment = it.fragment(); - if (!fragment.charFormat().isImageFormat()) - continue; - const QTextImageFormat fmt = fragment.charFormat().toImageFormat(); - const QString resource = fmt.name(); - QString kind; - QString name; - if (const QString id = DocumentConverter::attachmentIdFromResource(resource); !id.isEmpty()) { - kind = u"attachment"_s; - if (!m_attachmentNames.contains(id) && m_library) { - const auto info = m_library->service()->attachment(id); - m_attachmentNames.insert(id, info ? info->fileName : tr("missing file")); - } - name = tr("Attachment: %1").arg(m_attachmentNames.value(id)); - } else if (!DocumentConverter::blobHashFromResource(resource).isEmpty()) { - kind = u"image"_s; - const QString alt = fmt.property(QTextFormat::ImageAltText).toString(); - name = alt.isEmpty() ? tr("Image") : tr("Image: %1").arg(alt); - } else { - continue; - } - for (int i = 0; i < fragment.length(); ++i) { - next.append(QVariantMap{{u"kind"_s, kind}, - {u"position"_s, fragment.position() + i}, - {u"checked"_s, false}, - {u"name"_s, name}}); - } - } - } - } - if (next != m_overlays) { - m_overlays = next; - emit overlaysChanged(); - } - ++m_layoutRevision; - emit layoutRevisionChanged(); -} - -// ---------------------------------------------------------------- clipboard - -void EditorController::copy() -{ - if (!m_doc) - return; - const QTextCursor cursor = textCursor(); - if (!cursor.hasSelection()) - return; - const RichDocument part = DocumentConverter::readSelection(cursor); - const QTextDocumentFragment fragment = cursor.selection(); - auto *mime = new QMimeData; - mime->setData(QString::fromLatin1(kFragmentMime), part.toJsonBytes()); - QString plain = fragment.toPlainText(); - plain.remove(QChar(kObjectReplacement)); - mime->setText(plain); - mime->setHtml(fragment.toHtml()); - QGuiApplication::clipboard()->setMimeData(mime); -} - -void EditorController::cut() -{ - if (!m_doc) - return; - QTextCursor cursor = textCursor(); - if (!cursor.hasSelection()) - return; - copy(); - cursor.removeSelectedText(); - emit cursorRequested(cursor.position()); -} - -void EditorController::insertRich(const RichDocument &doc, QTextCursor &cursor) -{ - const Block &first = doc.blocks.first(); - const bool inline_ = doc.blocks.size() == 1 && first.type == Block::Type::Paragraph; - if (!inline_) { - DocumentConverter::insert(doc, cursor, style()); - return; - } - // A single paragraph flows into the current block and takes its style - // (e.g. pasting a word into a heading keeps the heading look). - const QTextCharFormat base = baseFormatFor(cursor.block()); - for (const Span &span : first.spans) { - switch (span.kind) { - case Span::Kind::Text: { - QTextCharFormat fmt = base; - DocumentConverter::applyMarks(fmt, span.marks, span.href, style()); - QString text = span.text; - text.replace(u'\n', QChar::LineSeparator); - cursor.insertText(text, fmt); - break; - } - case Span::Kind::Image: - insertImage(cursor, span.ref, QSize(span.width, span.height)); - break; - case Span::Kind::Attachment: { - QTextImageFormat fmt; - fmt.setName(DocumentConverter::attachmentResourceName(span.ref)); - fmt.setWidth(style().attachmentChipSize.width()); - fmt.setHeight(style().attachmentChipSize.height()); - fmt.setVerticalAlignment(QTextCharFormat::AlignMiddle); - cursor.insertImage(fmt); - break; - } - } - } -} - -void EditorController::paste() -{ - if (!m_doc || !m_library) - return; - const QMimeData *mime = QGuiApplication::clipboard()->mimeData(); - if (!mime) - return; - - QTextCursor cursor = textCursor(); - ConversionReport report; - std::optional content; - - if (mime->hasFormat(QString::fromLatin1(kFragmentMime))) { - content = RichDocument::fromJsonBytes(mime->data(QString::fromLatin1(kFragmentMime))); - } - if (!content && mime->hasUrls()) { - // Files copied from a file manager: images inline, others attached. - const QList urls = mime->urls(); - if (std::all_of(urls.begin(), urls.end(), [](const QUrl &u) { return u.isLocalFile(); })) { - cursor.beginEditBlock(); - for (const QUrl &url : urls) { - if (QImageReader(url.toLocalFile()).canRead()) - insertImageFile(url); - else - attachFile(url); - } - cursor.endEditBlock(); - return; - } - } - if (!content && mime->hasImage()) { - const QImage image = qvariant_cast(mime->imageData()); - QByteArray png; - QBuffer buffer(&png); - buffer.open(QIODevice::WriteOnly); - image.save(&buffer, "PNG"); - QString error; - const auto hash = m_library->service()->addImage(png, &error); - if (!hash) { - emit notice(error); - return; - } - cursor.beginEditBlock(); - cursor.removeSelectedText(); - insertImage(cursor, *hash, (QSizeF(image.size()) / image.devicePixelRatio()).toSize()); - cursor.endEditBlock(); - ensureResources(); - return; - } - if (!content && mime->hasHtml()) - content = DocumentConverter::fromHtml(mime->html(), &report); - if (!content && mime->hasText()) - content = DocumentConverter::fromPlainText(mime->text()); - if (!content || content->blocks.isEmpty()) - return; - - cursor.beginEditBlock(); - cursor.removeSelectedText(); - insertRich(*content, cursor); - cursor.endEditBlock(); - ensureResources(); - emit cursorRequested(cursor.position()); - if (!report.warnings.isEmpty()) - emit notice(report.warnings.join(u' ')); -} diff --git a/src/app/EditorController.h b/src/app/EditorController.h deleted file mode 100644 index 7ed6d6e..0000000 --- a/src/app/EditorController.h +++ /dev/null @@ -1,316 +0,0 @@ -#pragma once - -#include "AppLibrary.h" -#include "DocumentConverter.h" -#include "NoteStore.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -class QTextDocument; -class QTextList; - -// Drives a TextEdit's QTextDocument: loading and saving notes, formatting -// commands, lists, tables, media and clipboard conversion. It only touches the -// QTextDocument and a cursor position, so the same controller could drive a -// QTextEdit if the QML editor fails the feasibility gate. -class EditorController : public QObject -{ - Q_OBJECT - QML_NAMED_ELEMENT(NoteEditor) - - Q_PROPERTY(AppLibrary *library READ library WRITE setLibrary NOTIFY libraryChanged) - Q_PROPERTY(QQuickTextDocument *document READ document WRITE setDocument NOTIFY documentChanged) - Q_PROPERTY(int cursorPosition READ cursorPosition WRITE setCursorPosition NOTIFY cursorPositionChanged) - Q_PROPERTY(int selectionStart READ selectionStart WRITE setSelectionStart NOTIFY selectionChanged) - Q_PROPERTY(int selectionEnd READ selectionEnd WRITE setSelectionEnd NOTIFY selectionChanged) - Q_PROPERTY(qreal bodyPixelSize READ bodyPixelSize WRITE setBodyPixelSize NOTIFY styleChanged) - Q_PROPERTY(qreal devicePixelRatio READ devicePixelRatio WRITE setDevicePixelRatio NOTIFY styleChanged) - Q_PROPERTY(int maxImageWidth READ maxImageWidth WRITE setMaxImageWidth NOTIFY styleChanged) - - Q_PROPERTY(QString noteId READ noteId NOTIFY noteChanged) - Q_PROPERTY(bool hasNote READ hasNote NOTIFY noteChanged) - // Notes in Recently Deleted open read-only until recovered. - Q_PROPERTY(bool readOnly READ readOnly NOTIFY noteMetaChanged) - Q_PROPERTY(bool pinned READ pinned NOTIFY noteMetaChanged) - Q_PROPERTY(QString editedText READ editedText NOTIFY savedChanged) - Q_PROPERTY(SaveState saveState READ saveState NOTIFY saveStateChanged) - Q_PROPERTY(QString saveError READ saveError NOTIFY saveStateChanged) - - Q_PROPERTY(bool bold READ bold NOTIFY formatChanged) - Q_PROPERTY(bool italic READ italic NOTIFY formatChanged) - Q_PROPERTY(bool underline READ underline NOTIFY formatChanged) - Q_PROPERTY(bool strikethrough READ strikethrough NOTIFY formatChanged) - Q_PROPERTY(bool highlight READ highlight NOTIFY formatChanged) - Q_PROPERTY(bool code READ code NOTIFY formatChanged) - Q_PROPERTY(int blockStyle READ blockStyle NOTIFY formatChanged) - Q_PROPERTY(int listKind READ listKind NOTIFY formatChanged) - Q_PROPERTY(bool inTable READ inTable NOTIFY formatChanged) - Q_PROPERTY(bool inHeading READ inHeading NOTIFY formatChanged) - Q_PROPERTY(bool hasPendingFormat READ hasPendingFormat NOTIFY formatChanged) - - // Find in note. Matches are highlighted; findIndex is 1-based (0: none). - Q_PROPERTY(QString findText READ findText WRITE setFindText NOTIFY findChanged) - Q_PROPERTY(int findCount READ findCount NOTIFY findChanged) - Q_PROPERTY(int findIndex READ findIndex NOTIFY findChanged) - - // Things drawn over the text: round checkboxes for checklist items and - // accessible stand-ins for images and attachments. Each entry has - // kind ("check", "image", "attachment"), position, checked and name. - Q_PROPERTY(QVariantList overlays READ overlays NOTIFY overlaysChanged) - // Bumped whenever text layout may have moved, so overlay positions refresh. - Q_PROPERTY(int layoutRevision READ layoutRevision NOTIFY layoutRevisionChanged) - -public: - enum SaveState { Saved, Edited, Saving, Failed, Conflict }; - Q_ENUM(SaveState) - - // Mirrors onotes::Mark so QML can pass NoteEditor.Bold etc. - enum MarkType { - Bold = onotes::Bold, - Italic = onotes::Italic, - Underline = onotes::Underline, - Strikethrough = onotes::Strikethrough, - Highlight = onotes::Highlight, - Code = onotes::Code, - }; - Q_ENUM(MarkType) - - enum ListType { NoList = 0, BulletList, OrderedList, CheckList }; - Q_ENUM(ListType) - - // Longest time typed text may stay unsaved while typing continues. - static constexpr int MaxUnsavedMs = 3000; - static constexpr int IdleSaveMs = 700; - - explicit EditorController(QObject *parent = nullptr); - ~EditorController() override; - - AppLibrary *library() const { return m_library; } - void setLibrary(AppLibrary *library); - QQuickTextDocument *document() const { return m_quickDocument; } - void setDocument(QQuickTextDocument *document); - // Direct QTextDocument access, for tests and a possible Widgets frontend. - QTextDocument *textDocument() const { return m_doc; } - void setTextDocument(QTextDocument *doc); - - int cursorPosition() const { return m_cursorPosition; } - void setCursorPosition(int position); - int selectionStart() const { return m_selectionStart; } - void setSelectionStart(int position); - int selectionEnd() const { return m_selectionEnd; } - void setSelectionEnd(int position); - - qreal bodyPixelSize() const { return m_bodyPixelSize; } - void setBodyPixelSize(qreal size); - qreal devicePixelRatio() const { return m_devicePixelRatio; } - void setDevicePixelRatio(qreal ratio); - int maxImageWidth() const { return m_maxImageWidth; } - void setMaxImageWidth(int width); - - QString noteId() const { return m_noteId; } - bool hasNote() const { return !m_noteId.isEmpty(); } - bool readOnly() const { return m_deletedAt != 0; } - bool pinned() const { return m_pinned; } - QString editedText() const; - SaveState saveState() const { return m_saveState; } - QString saveError() const { return m_saveError; } - - bool bold() const { return m_marks & onotes::Bold; } - bool italic() const { return m_marks & onotes::Italic; } - bool underline() const { return m_marks & onotes::Underline; } - bool strikethrough() const { return m_marks & onotes::Strikethrough; } - bool highlight() const { return m_marks & onotes::Highlight; } - bool code() const { return m_marks & onotes::Code; } - int blockStyle() const { return m_blockStyle; } - int listKind() const { return m_listKind; } - bool inTable() const { return m_inTable; } - bool inHeading() const { return m_blockStyle > 0; } - bool hasPendingFormat() const { return m_pendingPosition >= 0 && m_pendingPosition == m_cursorPosition; } - - QString findText() const { return m_findText; } - void setFindText(const QString &text); - int findCount() const { return int(m_matchStarts.size()); } - int findIndex() const { return m_findCurrent + 1; } - QVariantList overlays() const { return m_overlays; } - int layoutRevision() const { return m_layoutRevision; } - - onotes::DocumentStyle style() const; - bool isDirty() const { return m_generation != m_savedGeneration; } - - // Notes - Q_INVOKABLE bool openNote(const QString &id); - // Leaves the editor empty. Call flush() first to keep changes. - Q_INVOKABLE void closeNote(); - Q_INVOKABLE void setPinned(bool pinned); - // Saves outstanding changes and waits for the result; false if they - // could not be saved (the draft stays in the editor). - Q_INVOKABLE bool flush(); - Q_INVOKABLE void retrySave(); - Q_INVOKABLE void keepMyVersion(); - Q_INVOKABLE bool exportDraft(const QUrl &file); - - // Formatting. With a selection (or inside a word) marks apply to that - // text; at a bare insertion point they apply to what is typed next. - Q_INVOKABLE bool toggleMark(int mark); - // Inserts typed text in the pending format, so the rest of the run - // continues in it and undoes as one step with it. - Q_INVOKABLE bool typeWithPendingFormat(const QString &text); - Q_INVOKABLE void setBlockStyle(int headingLevel); - Q_INVOKABLE void toggleList(int kind); - Q_INVOKABLE void indent(); - Q_INVOKABLE void outdent(); - - // Keys the editor handles itself; each returns true if it consumed the key. - Q_INVOKABLE bool handleReturn(); - Q_INVOKABLE bool handleTab(bool backward); - Q_INVOKABLE bool handleBackspace(); - - // Checklist items toggle natively on click; this is the keyboard path. - Q_INVOKABLE void toggleCheckAtCursor(); - Q_INVOKABLE void toggleCheckAt(int position); - Q_INVOKABLE bool activateObjectAt(int position); - Q_INVOKABLE void openLink(const QString &href); - // The #tag at a document position, if any (for Ctrl+click). - Q_INVOKABLE QString tagAt(int position) const; - - Q_INVOKABLE void findNext(); - Q_INVOKABLE void findPrevious(); - - // Insertions - Q_INVOKABLE void insertTable(int rows, int columns); - Q_INVOKABLE void addTableRow(); - Q_INVOKABLE void addTableColumn(); - Q_INVOKABLE void removeTableRow(); - Q_INVOKABLE void removeTableColumn(); - Q_INVOKABLE bool insertImageFile(const QUrl &file); - Q_INVOKABLE bool attachFile(const QUrl &file); - Q_INVOKABLE void insertNoteLink(const QString ¬eId); - - // Clipboard - Q_INVOKABLE void copy(); - Q_INVOKABLE void cut(); - Q_INVOKABLE void paste(); - -signals: - void libraryChanged(); - void documentChanged(); - void cursorPositionChanged(); - void selectionChanged(); - void styleChanged(); - void noteChanged(); - void noteMetaChanged(); - void savedChanged(); - void saveStateChanged(); - void formatChanged(); - void findChanged(); - void overlaysChanged(); - void layoutRevisionChanged(); - - // Requests for the view, which owns the visible cursor. - void cursorRequested(int position); - void selectionRequested(int start, int end); - void openNoteRequested(const QString ¬eId); - // Short user-facing message (e.g. content that could not be pasted). - void notice(const QString &message); - -private: - void onContentsChange(int position, int removed, int added); - void onSaveFinished(quint64 ticket, const QString ¬eId, const onotes::SaveResult &result); - void onLibraryNoteChanged(const QString ¬eId); - void saveNow(); - void applyPendingFormat(int start, int end); - QTextCharFormat pendingFormatAt(const QTextCursor &cursor) const; - void setSaveState(SaveState state, const QString &error = {}); - void loadBody(const onotes::RichDocument &body); - void reloadPresentation(); - void ensureResources(); - void updateFormatState(); - - // Presentation-only formats on the text layout (tag colour, find - // highlights): never part of the document, its undo history or saves. - void decorate(int from, int to); - void decorateAll(); - void scheduleDecorate(int from, int to); - void recountMatches(); - void selectMatch(int index); - void rebuildOverlays(); - - QTextCursor textCursor() const; - QList selectedBlocks() const; - void applyBlockStyle(QTextBlock block, int level); - void makeListItem(QTextBlock block, onotes::ListKind kind, int indent); - void attachToList(QTextBlock block, onotes::ListKind kind, int indent); - void removeFromList(QTextBlock block); - void setListIndent(int delta); - QTextCharFormat baseFormatFor(const QTextBlock &block) const; - void insertRich(const onotes::RichDocument &doc, QTextCursor &cursor); - void insertImage(QTextCursor &cursor, const QString &hash, QSize logicalSize); - QImage renderAttachmentChip(const QString &attachmentId) const; - QImage renderMissingImage(QSize logicalSize) const; - - QPointer m_library; - QPointer m_quickDocument; - QPointer m_doc; - QMetaObject::Connection m_docConnection; - - int m_cursorPosition = 0; - int m_selectionStart = 0; - int m_selectionEnd = 0; - qreal m_bodyPixelSize = 15; - qreal m_devicePixelRatio = 1; - int m_maxImageWidth = 640; - - QString m_noteId; - QString m_pendingNoteId; // requested before the document was attached - qint64 m_revision = 0; - qint64 m_updatedAt = 0; - qint64 m_deletedAt = 0; - bool m_pinned = false; - bool m_loading = false; - - // Autosave bookkeeping: every edit bumps m_generation; a save snapshots - // it, and the note is clean once an acknowledged save matches it. - quint64 m_generation = 0; - quint64 m_savedGeneration = 0; - quint64 m_inFlightGeneration = 0; - quint64 m_ticket = 0; - onotes::RichDocument m_inFlightBody; - qint64 m_conflictRevision = 0; - QTimer m_idleTimer; - QTimer m_capTimer; - QTimer m_retryTimer; - int m_retryCount = 0; - SaveState m_saveState = Saved; - QString m_saveError; - - QSet m_loadedResources; - - bool m_decorating = false; - QTimer m_decorateTimer; - int m_decorateFrom = -1; - int m_decorateTo = -1; - QString m_findText; - QList m_matchStarts; - int m_findCurrent = -1; - QVariantList m_overlays; - int m_layoutRevision = 0; - QHash m_attachmentNames; - - // Marks to set/clear on the next text typed at m_pendingPosition. - int m_pendingPosition = -1; - quint32 m_pendingSet = 0; - quint32 m_pendingClear = 0; - bool m_applyingPending = false; - - quint32 m_marks = 0; - int m_blockStyle = 0; - int m_listKind = 0; - bool m_inTable = false; -}; diff --git a/src/app/HyprlandSetup.cpp b/src/app/HyprlandSetup.cpp deleted file mode 100644 index 16047b5..0000000 --- a/src/app/HyprlandSetup.cpp +++ /dev/null @@ -1,143 +0,0 @@ -#include "HyprlandSetup.h" - -#include -#include -#include -#include -#include -#include -#include - -using namespace Qt::StringLiterals; - -namespace { - -QString read(const QString &path) -{ - QFile file(path); - return file.open(QIODevice::ReadOnly) ? QString::fromUtf8(file.readAll()) : QString(); -} - -QString normalizeKeys(QString keys) -{ - return keys.toUpper().remove(u' '); -} - -// Every "MODS + KEY" string bound with o.bind or hl.bind in `text`. -QStringList boundKeys(const QString &text) -{ - static const QRegularExpression bind(uR"re((?:o|hl)\.bind\(\s*"([^"]+)")re"_s); - QStringList out; - for (auto it = bind.globalMatch(text); it.hasNext();) - out << normalizeKeys(it.next().captured(1)); - return out; -} - -// Keys the user explicitly unbound (hl.unbind) are free again. -QStringList unboundKeys(const QString &text) -{ - static const QRegularExpression unbind(uR"re(hl\.unbind\(\s*"([^"]+)")re"_s); - QStringList out; - for (auto it = unbind.globalMatch(text); it.hasNext();) - out << normalizeKeys(it.next().captured(1)); - return out; -} - -bool append(const QString &path, const QString &lines, QStringList *backups) -{ - const QString backup = path + u".bak."_s + QString::number(QDateTime::currentSecsSinceEpoch()); - if (QFile::exists(path) && !QFile::copy(path, backup)) - return false; - if (QFile::exists(backup)) - backups->append(backup); - QFile file(path); - if (!file.open(QIODevice::Append)) - return false; - file.write(lines.toUtf8()); - return true; -} - -} // namespace - -HyprlandSetupResult setUpHyprland(const QString &keys) -{ - HyprlandSetupResult result; - const QString hypr = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + u"/hypr"_s; - const QString bindings = hypr + u"/bindings.lua"_s; - const QString main = hypr + u"/hyprland.lua"_s; - if (!QFile::exists(bindings) || !QFile::exists(main)) { - result.messages << u"This doesn't look like an Omarchy setup (no %1 or %2). " - "See the README for doing this by hand."_s.arg(bindings, main); - return result; - } - - const QString userBindings = read(bindings); - const QString userMain = read(main); - const bool haveBinding = userBindings.contains(u"omarchy-notes --quick-note"_s); - const bool haveRule = userMain.contains(u"org\\\\.omarchy\\\\.Notes"_s) || userMain.contains(u"org.omarchy.Notes"_s); - - QString additions; - if (haveBinding) { - result.messages << u"The Quick Note key binding is already set up."_s; - } else { - // Omarchy's own bindings count unless the user unbound them. - QString defaults; - const QString omarchy = qEnvironmentVariable("OMARCHY_PATH", u"/usr/share/omarchy"_s); - QDirIterator it(omarchy + u"/default/hypr"_s, {u"*.lua"_s}, QDir::Files, QDirIterator::Subdirectories); - while (it.hasNext()) - defaults += read(it.next()) + u'\n'; - const QString wanted = normalizeKeys(keys); - const bool takenByDefault = boundKeys(defaults).contains(wanted) && !unboundKeys(userBindings).contains(wanted); - if (boundKeys(userBindings).contains(wanted) || takenByDefault) { - result.messages << u"%1 is already bound, so nothing was changed. Pick another key and add the " - "binding by hand (see the README)."_s.arg(keys); - return result; - } - additions = u"\n-- Added by omarchy-notes --setup-hyprland\n" - "o.bind(\"%1\", \"Quick Note\", { launch = \"omarchy-notes --quick-note\" })\n"_s.arg(keys); - } - - QStringList backups; - if (!additions.isEmpty()) { - if (!append(bindings, additions, &backups)) { - result.messages << u"Couldn't update %1."_s.arg(bindings); - return result; - } - result.messages << u"Added %1 for Quick Note to %2."_s.arg(keys, bindings); - } - if (haveRule) { - result.messages << u"The Quick Note window rule is already set up."_s; - } else { - const QString rule = u"\n-- Added by omarchy-notes --setup-hyprland: float the Quick Note window\n" - "o.window({ class = \"^org\\\\.omarchy\\\\.Notes$\", title = \"^Quick Note$\" }, " - "{ tag = \"+floating-window\" })\n"_s; - if (!append(main, rule, &backups)) { - result.messages << u"Couldn't update %1."_s.arg(main); - return result; - } - result.messages << u"Added a rule to %1 so Quick Note floats."_s.arg(main); - } - - // Let Hyprland check the result; undo if it objects. - if (qEnvironmentVariableIsSet("HYPRLAND_INSTANCE_SIGNATURE") && !backups.isEmpty()) { - QProcess::execute(u"hyprctl"_s, {u"reload"_s}); - QProcess check; - check.start(u"hyprctl"_s, {u"configerrors"_s}); - check.waitForFinished(5000); - const QString errors = QString::fromUtf8(check.readAllStandardOutput()).trimmed(); - if (!errors.isEmpty() && !errors.contains(u"no errors"_s, Qt::CaseInsensitive)) { - for (const QString &backup : backups) { - const QString original = backup.section(u".bak."_s, 0, 0); - QFile::remove(original); - QFile::copy(backup, original); - } - QProcess::execute(u"hyprctl"_s, {u"reload"_s}); - result.messages << u"Hyprland reported a problem, so the changes were undone:"_s << errors; - return result; - } - } - if (!backups.isEmpty()) - result.messages << u"Backups: %1"_s.arg(backups.join(u", "_s)); - result.ok = true; - return result; -} diff --git a/src/app/HyprlandSetup.h b/src/app/HyprlandSetup.h deleted file mode 100644 index 0d6399f..0000000 --- a/src/app/HyprlandSetup.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include - -// Optional Omarchy/Hyprland integration, run only on request -// (omarchy-notes --setup-hyprland): a Quick Note key binding and a rule that -// floats the Quick Note window. Conflicting bindings are never overwritten. -struct HyprlandSetupResult { - bool ok = false; - QStringList messages; // what happened, one line each -}; - -HyprlandSetupResult setUpHyprland(const QString &keys = QStringLiteral("SUPER + ALT + N")); diff --git a/src/app/InstanceChannel.cpp b/src/app/InstanceChannel.cpp deleted file mode 100644 index 54aa62e..0000000 --- a/src/app/InstanceChannel.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "InstanceChannel.h" - -#include "LibraryPaths.h" - -#include -#include -#include -#include -#include - -using namespace Qt::StringLiterals; - -QString InstanceChannel::socketPath(const onotes::LibraryPaths &paths) -{ - QString runtime = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation); - if (runtime.isEmpty()) - runtime = QDir::tempPath(); - const QByteArray key = QCryptographicHash::hash(paths.root.toUtf8(), QCryptographicHash::Sha256).toHex().left(12); - return runtime + u"/omarchy-notes-"_s + QString::fromLatin1(key) + u".sock"_s; -} - -bool InstanceChannel::send(const QString &socketPath, const QJsonObject &request, int timeoutMs) -{ - QLocalSocket socket; - socket.connectToServer(socketPath); - if (!socket.waitForConnected(timeoutMs)) - return false; - socket.write(QJsonDocument(request).toJson(QJsonDocument::Compact) + '\n'); - if (!socket.waitForBytesWritten(timeoutMs)) - return false; - return socket.waitForReadyRead(timeoutMs) && socket.readAll().startsWith("ok"); -} - -bool InstanceChannel::listen(const QString &socketPath, QString *error) -{ - // Only called while holding the library lock, so a leftover socket file - // belongs to a process that's gone. - QLocalServer::removeServer(socketPath); - m_server.setSocketOptions(QLocalServer::UserAccessOption); - if (!m_server.listen(socketPath)) { - if (error) - *error = m_server.errorString(); - return false; - } - connect(&m_server, &QLocalServer::newConnection, this, [this] { - while (QLocalSocket *socket = m_server.nextPendingConnection()) { - connect(socket, &QLocalSocket::disconnected, socket, &QObject::deleteLater); - connect(socket, &QLocalSocket::readyRead, this, [this, socket] { - if (!socket->canReadLine()) - return; - const QJsonObject request = QJsonDocument::fromJson(socket->readLine()).object(); - socket->write("ok\n"); - socket->flush(); - socket->disconnectFromServer(); - if (!request.isEmpty()) - emit requestReceived(request); - }); - } - }); - return true; -} diff --git a/src/app/InstanceChannel.h b/src/app/InstanceChannel.h deleted file mode 100644 index 554010a..0000000 --- a/src/app/InstanceChannel.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace onotes { -struct LibraryPaths; -} - -// Lets a second launch hand its request to the running instance instead of -// opening the library twice. One JSON object per connection, answered "ok". -class InstanceChannel : public QObject -{ - Q_OBJECT - -public: - using QObject::QObject; - - // A socket in $XDG_RUNTIME_DIR, one per library. - static QString socketPath(const onotes::LibraryPaths &paths); - // Delivers `request` to a running instance. False if none answered. - static bool send(const QString &socketPath, const QJsonObject &request, int timeoutMs = 1500); - - bool listen(const QString &socketPath, QString *error); - -signals: - void requestReceived(const QJsonObject &request); - -private: - QLocalServer m_server; -}; diff --git a/src/app/ThemeController.cpp b/src/app/ThemeController.cpp deleted file mode 100644 index 861fd09..0000000 --- a/src/app/ThemeController.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include "ThemeController.h" - -#include -#include -#include - -using namespace Qt::StringLiterals; - -namespace { -ThemeController *s_instance = nullptr; -} - -ThemeController::ThemeController(QObject *parent) - : QObject(parent), m_palette(onotes::ThemePalette::loadActive()) -{ - // Theme switches rewrite several files; coalesce them into one reload. - m_debounce.setSingleShot(true); - m_debounce.setInterval(150); - connect(&m_debounce, &QTimer::timeout, this, &ThemeController::reload); - connect(&m_watcher, &QFileSystemWatcher::directoryChanged, &m_debounce, qOverload<>(&QTimer::start)); - connect(&m_watcher, &QFileSystemWatcher::fileChanged, &m_debounce, qOverload<>(&QTimer::start)); - rearmWatcher(); -} - -ThemeController *ThemeController::create(QQmlEngine *, QJSEngine *) -{ - Q_ASSERT(s_instance); - QQmlEngine::setObjectOwnership(s_instance, QQmlEngine::CppOwnership); - return s_instance; -} - -void ThemeController::setInstance(ThemeController *instance) -{ - s_instance = instance; -} - -ThemeController *ThemeController::instance() -{ - return s_instance; -} - -void ThemeController::reload() -{ - onotes::ThemePalette next = onotes::ThemePalette::loadActive(); - rearmWatcher(); - if (next == m_palette) - return; - m_palette = std::move(next); - emit changed(); -} - -void ThemeController::rearmWatcher() -{ - if (!m_watcher.files().isEmpty()) - m_watcher.removePaths(m_watcher.files()); - if (!m_watcher.directories().isEmpty()) - m_watcher.removePaths(m_watcher.directories()); - - QStringList paths; - for (const QString &dir : onotes::ThemePalette::candidateDirectories()) { - const QString parent = QFileInfo(dir).absolutePath(); - for (const QString &path : {parent, dir, dir + u"/colors.toml"_s, dir + u"/alacritty.toml"_s}) { - if (QFileInfo::exists(path) && !paths.contains(path)) - paths << path; - } - } - if (!paths.isEmpty()) - m_watcher.addPaths(paths); -} diff --git a/src/app/ThemeController.h b/src/app/ThemeController.h deleted file mode 100644 index 4755cfa..0000000 --- a/src/app/ThemeController.h +++ /dev/null @@ -1,83 +0,0 @@ -#pragma once - -#include "ThemePalette.h" - -#include -#include -#include -#include -#include - -class QQmlEngine; -class QJSEngine; - -// Exposes the active Omarchy palette to QML as `Theme` and follows theme -// switches live. Omarchy replaces the whole current/theme directory when the -// theme changes, so the parent directory is watched as well as the files. -class ThemeController : public QObject -{ - Q_OBJECT - QML_NAMED_ELEMENT(Theme) - QML_SINGLETON - - Q_PROPERTY(QString name READ name NOTIFY changed) - Q_PROPERTY(QString source READ source NOTIFY changed) - Q_PROPERTY(bool dark READ dark NOTIFY changed) - Q_PROPERTY(QColor canvas READ canvas NOTIFY changed) - Q_PROPERTY(QColor sidebar READ sidebar NOTIFY changed) - Q_PROPERTY(QColor raised READ raised NOTIFY changed) - Q_PROPERTY(QColor divider READ divider NOTIFY changed) - Q_PROPERTY(QColor text READ text NOTIFY changed) - Q_PROPERTY(QColor secondaryText READ secondaryText NOTIFY changed) - Q_PROPERTY(QColor selection READ selection NOTIFY changed) - Q_PROPERTY(QColor selectionText READ selectionText NOTIFY changed) - Q_PROPERTY(QColor accent READ accent NOTIFY changed) - Q_PROPERTY(QColor accentText READ accentText NOTIFY changed) - Q_PROPERTY(QColor focus READ focus NOTIFY changed) - Q_PROPERTY(QColor link READ link NOTIFY changed) - Q_PROPERTY(QColor error READ error NOTIFY changed) - Q_PROPERTY(QColor highlight READ highlight NOTIFY changed) - Q_PROPERTY(QColor tableBorder READ tableBorder NOTIFY changed) - -public: - // Not default-constructible on purpose: QML must use create(), which - // returns the one shared instance, rather than making its own. - explicit ThemeController(QObject *parent); - - static ThemeController *create(QQmlEngine *, QJSEngine *); - static void setInstance(ThemeController *instance); - static ThemeController *instance(); - - const onotes::ThemePalette &palette() const { return m_palette; } - - QString name() const { return m_palette.name; } - QString source() const { return m_palette.source; } - bool dark() const { return m_palette.dark; } - QColor canvas() const { return m_palette.canvas; } - QColor sidebar() const { return m_palette.sidebar; } - QColor raised() const { return m_palette.raised; } - QColor divider() const { return m_palette.divider; } - QColor text() const { return m_palette.text; } - QColor secondaryText() const { return m_palette.secondaryText; } - QColor selection() const { return m_palette.selection; } - QColor selectionText() const { return m_palette.selectionText; } - QColor accent() const { return m_palette.accent; } - QColor accentText() const { return m_palette.accentText; } - QColor focus() const { return m_palette.focus; } - QColor link() const { return m_palette.link; } - QColor error() const { return m_palette.error; } - QColor highlight() const { return m_palette.highlight; } - QColor tableBorder() const { return m_palette.tableBorder; } - - Q_INVOKABLE void reload(); - -signals: - void changed(); - -private: - void rearmWatcher(); - - onotes::ThemePalette m_palette; - QFileSystemWatcher m_watcher; - QTimer m_debounce; -}; diff --git a/src/app/icons/all-notes.svg b/src/app/icons/all-notes.svg deleted file mode 100644 index 7d1580b..0000000 --- a/src/app/icons/all-notes.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/attach.svg b/src/app/icons/attach.svg deleted file mode 100644 index 7b868f9..0000000 --- a/src/app/icons/attach.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/back.svg b/src/app/icons/back.svg deleted file mode 100644 index 8614da3..0000000 --- a/src/app/icons/back.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/bullets.svg b/src/app/icons/bullets.svg deleted file mode 100644 index 3f0c09e..0000000 --- a/src/app/icons/bullets.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/checklist.svg b/src/app/icons/checklist.svg deleted file mode 100644 index aaf0c7e..0000000 --- a/src/app/icons/checklist.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/close.svg b/src/app/icons/close.svg deleted file mode 100644 index 7182981..0000000 --- a/src/app/icons/close.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/compose.svg b/src/app/icons/compose.svg deleted file mode 100644 index 33704a8..0000000 --- a/src/app/icons/compose.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/folder-new.svg b/src/app/icons/folder-new.svg deleted file mode 100644 index 3e4dcfe..0000000 --- a/src/app/icons/folder-new.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/folder.svg b/src/app/icons/folder.svg deleted file mode 100644 index 7726523..0000000 --- a/src/app/icons/folder.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/gallery.svg b/src/app/icons/gallery.svg deleted file mode 100644 index ec9cb8c..0000000 --- a/src/app/icons/gallery.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/highlight.svg b/src/app/icons/highlight.svg deleted file mode 100644 index 62d2bf2..0000000 --- a/src/app/icons/highlight.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/image.svg b/src/app/icons/image.svg deleted file mode 100644 index 2ea365d..0000000 --- a/src/app/icons/image.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/link.svg b/src/app/icons/link.svg deleted file mode 100644 index de3564b..0000000 --- a/src/app/icons/link.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/list.svg b/src/app/icons/list.svg deleted file mode 100644 index 059a1ad..0000000 --- a/src/app/icons/list.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/more.svg b/src/app/icons/more.svg deleted file mode 100644 index 948fc58..0000000 --- a/src/app/icons/more.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/note.svg b/src/app/icons/note.svg deleted file mode 100644 index 9a4851d..0000000 --- a/src/app/icons/note.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/numbers.svg b/src/app/icons/numbers.svg deleted file mode 100644 index 1fab612..0000000 --- a/src/app/icons/numbers.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/pin.svg b/src/app/icons/pin.svg deleted file mode 100644 index 09e9567..0000000 --- a/src/app/icons/pin.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/recover.svg b/src/app/icons/recover.svg deleted file mode 100644 index 77c4145..0000000 --- a/src/app/icons/recover.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/search.svg b/src/app/icons/search.svg deleted file mode 100644 index e6edbc0..0000000 --- a/src/app/icons/search.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/share.svg b/src/app/icons/share.svg deleted file mode 100644 index 224df43..0000000 --- a/src/app/icons/share.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/sidebar.svg b/src/app/icons/sidebar.svg deleted file mode 100644 index 3bc0b48..0000000 --- a/src/app/icons/sidebar.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/smart-folder.svg b/src/app/icons/smart-folder.svg deleted file mode 100644 index 1e16881..0000000 --- a/src/app/icons/smart-folder.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/table.svg b/src/app/icons/table.svg deleted file mode 100644 index cc6fac3..0000000 --- a/src/app/icons/table.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/tag.svg b/src/app/icons/tag.svg deleted file mode 100644 index 58e6009..0000000 --- a/src/app/icons/tag.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/icons/trash.svg b/src/app/icons/trash.svg deleted file mode 100644 index 6f3377b..0000000 --- a/src/app/icons/trash.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/app/main.cpp b/src/app/main.cpp deleted file mode 100644 index 8217267..0000000 --- a/src/app/main.cpp +++ /dev/null @@ -1,238 +0,0 @@ -#include "AppController.h" -#include "DocumentConverter.h" -#include "HyprlandSetup.h" -#include "AppLibrary.h" -#include "InstanceChannel.h" -#include "BlobImageProvider.h" -#include "LibraryService.h" -#include "SampleLibrary.h" -#include "ThemeController.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -Q_IMPORT_QML_PLUGIN(OmarchyNotesPlugin) - -using namespace Qt::StringLiterals; - -namespace { - -// Test, benchmark and documentation hooks: -// ONOTES_EXIT_AFTER_FIRST_FRAME=1 report the first rendered frame, then quit -// ONOTES_SCREENSHOT= save the window once images have loaded, then quit -void exitAfterFirstFrame(QQmlApplicationEngine &engine, const QElapsedTimer &sinceStart) -{ - const QString screenshot = qEnvironmentVariable("ONOTES_SCREENSHOT"); - if ((!qEnvironmentVariableIsSet("ONOTES_EXIT_AFTER_FIRST_FRAME") && screenshot.isEmpty()) - || engine.rootObjects().isEmpty()) - return; - auto *window = qobject_cast(engine.rootObjects().constFirst()); - if (!window) - return; - QObject::connect(window, &QQuickWindow::frameSwapped, window, [window, sinceStart, screenshot] { - std::printf("first-frame %lld ms: %s\n", static_cast(sinceStart.elapsed()), - qPrintable(window->title())); - std::fflush(stdout); - if (screenshot.isEmpty()) { - QCoreApplication::quit(); - return; - } - QTimer::singleShot(1200, window, [window, screenshot] { - window->grabWindow().save(screenshot); - QCoreApplication::quit(); - }); - }, Qt::SingleShotConnection); -} - -// Shows why the library can't be used, in a window, since a launch from the -// app launcher has no terminal to print to. -int showStartupError(QGuiApplication &app, const QString &heading, const QString &message, - const QString &location, const QElapsedTimer &sinceStart) -{ - std::fprintf(stderr, "%s %s\n", qPrintable(heading), qPrintable(message)); - ThemeController theme(nullptr); - ThemeController::setInstance(&theme); - QQuickStyle::setStyle(u"Basic"_s); - QQmlApplicationEngine engine; - engine.setInitialProperties({{u"heading"_s, heading}, {u"message"_s, message}, {u"location"_s, location}}); - engine.loadFromModule("OmarchyNotes", "StartupError"); - exitAfterFirstFrame(engine, sinceStart); - app.exec(); - return 1; -} - -} // namespace - -int main(int argc, char *argv[]) -{ - QElapsedTimer sinceStart; - sinceStart.start(); - QGuiApplication app(argc, argv); - QGuiApplication::setApplicationName(u"omarchy-notes"_s); - QGuiApplication::setApplicationDisplayName(u"Omarchy Notes"_s); - QGuiApplication::setApplicationVersion(QStringLiteral(ONOTES_VERSION)); - QGuiApplication::setDesktopFileName(QStringLiteral(ONOTES_APP_ID)); - - QCommandLineParser parser; - parser.setApplicationDescription(u"Notes for Omarchy"_s); - parser.addHelpOption(); - parser.addVersionOption(); - const QCommandLineOption dataDir(u"data-dir"_s, u"Use the library in ."_s, u"dir"_s); - const QCommandLineOption newNote(u"new"_s, u"Start with a new note."_s); - const QCommandLineOption openNote(u"note"_s, u"Open the note with ."_s, u"id"_s); - const QCommandLineOption quickNote(u"quick-note"_s, u"Open a Quick Note window."_s); - const QCommandLineOption capture(u"capture"_s, u"Save as a new note (\"-\" reads standard input)."_s, - u"text"_s); - const QCommandLineOption samples(u"samples"_s, u"Add sample notes if the library is empty."_s); - const QCommandLineOption setupHyprland(u"setup-hyprland"_s, - u"Add a Quick Note key (Super+Alt+N) and floating rule to Hyprland."_s); - const QCommandLineOption failSaves(u"simulate-save-failure"_s, - u"Make saves fail (for testing failure handling)."_s); - parser.addOptions({dataDir, newNote, openNote, quickNote, capture, samples, setupHyprland, failSaves}); - parser.process(app); - - if (parser.isSet(setupHyprland)) { - const HyprlandSetupResult setup = setUpHyprland(); - for (const QString &line : setup.messages) - std::printf("%s\n", qPrintable(line)); - return setup.ok ? 0 : 1; - } - - const onotes::LibraryPaths paths = parser.isSet(dataDir) - ? onotes::LibraryPaths::at(parser.value(dataDir)) - : onotes::LibraryPaths::standard(); - - // What this launch is asking for. - QString captured; - if (parser.isSet(capture)) { - captured = parser.value(capture); - if (captured == u"-") { - QFile in; - if (in.open(stdin, QIODevice::ReadOnly)) - captured = QString::fromUtf8(in.readAll()); - } - if (captured.trimmed().isEmpty()) { - std::fprintf(stderr, "Nothing to capture.\n"); - return 1; - } - } - QJsonObject request{{u"token"_s, qEnvironmentVariable("XDG_ACTIVATION_TOKEN")}}; - if (parser.isSet(capture)) - request[u"action"_s] = u"capture"_s, request[u"text"_s] = captured; - else if (parser.isSet(quickNote)) - request[u"action"_s] = u"quick-note"_s; - else if (parser.isSet(newNote)) - request[u"action"_s] = u"new"_s; - else if (parser.isSet(openNote)) - request[u"action"_s] = u"open"_s, request[u"note"_s] = parser.value(openNote); - else - request[u"action"_s] = u"activate"_s; - - // One process owns a library: hand the request to it if it's running. - const QString socket = InstanceChannel::socketPath(paths); - auto delivered = [&] { - if (!InstanceChannel::send(socket, request)) - return false; - if (parser.isSet(capture)) - std::printf("Saved to Omarchy Notes.\n"); - return true; - }; - if (delivered()) - return 0; - QDir().mkpath(paths.root); - QLockFile lock(paths.root + u"/.lock"_s); - const bool locked = lock.tryLock(200); - if (!locked && lock.error() != QLockFile::LockFailedError) { - // Not "someone else has it": the folder itself is unusable. - const QString why = QObject::tr("Omarchy Notes can't write to its library at %1. Check that the folder " - "and its files belong to you and aren't read-only.").arg(paths.root); - if (parser.isSet(capture)) { - std::fprintf(stderr, "%s\n", qPrintable(why)); - return 1; - } - return showStartupError(app, QObject::tr("Omarchy Notes can't open your notes."), why, paths.root, - sinceStart); - } - if (!locked) { - // Another instance is starting up; give it a moment to listen. - for (int attempt = 0; attempt < 20; ++attempt) { - QThread::msleep(150); - if (delivered()) - return 0; - } - if (parser.isSet(capture)) { - std::fprintf(stderr, "Omarchy Notes is running for %s but isn't responding.\n", qPrintable(paths.root)); - return 1; - } - return showStartupError(app, QObject::tr("Omarchy Notes is already running but isn't responding."), - QObject::tr("Close the other Omarchy Notes window, or end it from a terminal " - "with \u201cpkill omarchy-notes\u201d, then open it again."), - paths.root, sinceStart); - } - - onotes::LibraryService service(paths); - QString error; - if (!service.start(&error)) { - if (parser.isSet(capture)) { - std::fprintf(stderr, "Could not open the notes library: %s\n", qPrintable(error)); - return 1; - } - return showStartupError(app, QObject::tr("Omarchy Notes can't open your notes."), error, paths.root, - sinceStart); - } - // Capturing without a running app needs no window. - if (parser.isSet(capture)) { - const auto note = service.createNote(onotes::DocumentConverter::fromPlainText(captured.trimmed()), &error); - if (!note) { - std::fprintf(stderr, "Could not save the note: %s\n", qPrintable(error)); - return 1; - } - std::printf("Saved to Omarchy Notes.\n"); - return 0; - } - if (parser.isSet(samples) && service.listNotes().isEmpty()) { - if (onotes::SampleLibrary::seed(service, &error).isEmpty()) - std::fprintf(stderr, "Could not add sample notes: %s\n", qPrintable(error)); - } - service.setSimulatedSaveFailure(parser.isSet(failSaves)); - - ThemeController theme(nullptr); - ThemeController::setInstance(&theme); - AppLibrary library(&service); - AppLibrary::setInstance(&library); - AppController controller(nullptr); - controller.setStartWithQuickNote(parser.isSet(quickNote)); - AppController::setInstance(&controller); - InstanceChannel channel; - QString listenError; - if (!channel.listen(socket, &listenError)) - std::fprintf(stderr, "Other launches won't reach this window: %s\n", qPrintable(listenError)); - QObject::connect(&channel, &InstanceChannel::requestReceived, &controller, &AppController::handle); - - QString initialNote = parser.value(openNote); - if (parser.isSet(newNote)) - initialNote = library.createNote(); - - QQuickStyle::setStyle(u"Basic"_s); - QQmlApplicationEngine engine; - engine.addImageProvider(u"blob"_s, new BlobImageProvider(&service)); - engine.setInitialProperties({{u"initialNoteId"_s, initialNote}}); - QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, &app, - [] { QCoreApplication::exit(1); }, Qt::QueuedConnection); - engine.loadFromModule("OmarchyNotes", "Main"); - exitAfterFirstFrame(engine, sinceStart); - return app.exec(); -} diff --git a/src/app/qml/AttachmentsView.qml b/src/app/qml/AttachmentsView.qml deleted file mode 100644 index 9289c5c..0000000 --- a/src/app/qml/AttachmentsView.qml +++ /dev/null @@ -1,222 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Controls.impl -import QtQuick.Layouts -import OmarchyNotes - -// Every image and file across your notes. Click shows the note it's in; -// double-click opens the file itself. -Rectangle { - id: root - - property bool showSidebarButton: false - signal noteChosen(string noteId) - signal sidebarToggled() - - function focusGrid() { grid.forceActiveFocus() } - - color: Theme.sidebar - - ColumnLayout { - anchors.fill: parent - spacing: 0 - - RowLayout { - Layout.fillWidth: true - Layout.preferredHeight: 52 - Layout.leftMargin: root.showSidebarButton ? 8 : 16 - Layout.rightMargin: 12 - spacing: 8 - ToolIcon { - visible: root.showSidebarButton - iconName: "sidebar" - text: qsTr("Show folders") - onClicked: root.sidebarToggled() - } - Label { - text: qsTr("Attachments") - color: Theme.text - font.pixelSize: 17 - font.weight: Font.DemiBold - Accessible.role: Accessible.Heading - } - Label { - text: Library.attachments.count - color: Theme.secondaryText - } - Item { Layout.fillWidth: true } - Repeater { - model: [qsTr("All"), qsTr("Images"), qsTr("Files")] - delegate: ToolIcon { - required property int index - required property string modelData - text: modelData - active: Library.attachments.filter === index - onClicked: Library.attachments.filter = index - } - } - } - - GridView { - id: grid - objectName: "attachmentGrid" - Layout.fillWidth: true - Layout.fillHeight: true - Layout.leftMargin: 10 - clip: true - model: Library.attachments - keyNavigationEnabled: true - activeFocusOnTab: true - boundsBehavior: Flickable.StopAtBounds - readonly property int columns: Math.max(1, Math.floor(width / 200)) - cellWidth: Math.floor(width / columns) - cellHeight: 212 - Accessible.role: Accessible.List - Accessible.name: qsTr("Attachments") - ScrollBar.vertical: ScrollBar {} - Keys.onReturnPressed: if (currentItem) currentItem.open() - Keys.onSpacePressed: if (currentItem) root.noteChosen(currentItem.noteId) - - delegate: Item { - id: tile - - required property int index - required property bool isImage - required property string blobHash - required property string attachmentId - required property string fileName - required property string detail - required property string extension - required property string noteId - required property string noteTitle - - function open() { - if (isImage) - Library.openImage(blobHash) - else - Library.openAttachment(attachmentId) - } - - width: GridView.view.cellWidth - height: GridView.view.cellHeight - Accessible.role: Accessible.ListItem - Accessible.name: fileName + ", " + qsTr("in %1").arg(noteTitle) - Accessible.description: detail - - Rectangle { - anchors.fill: parent - anchors.margins: 7 - radius: 10 - color: Theme.canvas - clip: true - border.width: tile.GridView.isCurrentItem && tile.GridView.view.activeFocus ? 2 : 1 - border.color: tile.GridView.isCurrentItem && tile.GridView.view.activeFocus - ? Theme.focus : (hover.hovered ? Theme.tableBorder : Theme.divider) - - Item { - id: preview - anchors.left: parent.left - anchors.right: parent.right - anchors.top: parent.top - anchors.margins: 1 - height: 120 - Image { - anchors.fill: parent - visible: tile.isImage - source: tile.isImage ? "image://blob/" + tile.blobHash : "" - sourceSize: Qt.size(400, 240) - fillMode: Image.PreserveAspectCrop - asynchronous: true - } - Rectangle { - visible: !tile.isImage - anchors.centerIn: parent - width: 64 - height: 76 - radius: 8 - color: Theme.accent - Label { - anchors.centerIn: parent - text: tile.extension || qsTr("FILE") - color: Theme.accentText - font.bold: true - } - } - Rectangle { - anchors.bottom: parent.bottom - width: parent.width - height: 1 - color: Theme.divider - } - } - ColumnLayout { - anchors.left: parent.left - anchors.right: parent.right - anchors.top: preview.bottom - anchors.margins: 10 - spacing: 1 - Label { - Layout.fillWidth: true - text: tile.fileName - elide: Text.ElideMiddle - font.weight: Font.DemiBold - color: Theme.text - } - Label { - Layout.fillWidth: true - text: tile.detail - elide: Text.ElideRight - font.pixelSize: 12 - color: Theme.secondaryText - } - RowLayout { - spacing: 4 - IconImage { - source: "qrc:/qt/qml/OmarchyNotes/icons/note.svg" - sourceSize: Qt.size(12, 12) - color: Theme.secondaryText - } - Label { - Layout.fillWidth: true - text: tile.noteTitle - elide: Text.ElideRight - font.pixelSize: 11 - color: Theme.secondaryText - } - } - } - } - HoverHandler { id: hover } - TapHandler { - onTapped: { - tile.GridView.view.currentIndex = tile.index - root.noteChosen(tile.noteId) - } - onDoubleTapped: tile.open() - } - } - - ColumnLayout { - anchors.centerIn: parent - width: parent.width - 48 - visible: grid.count === 0 - spacing: 8 - Label { - Layout.fillWidth: true - horizontalAlignment: Text.AlignHCenter - text: qsTr("No attachments yet") - font.weight: Font.DemiBold - color: Theme.text - } - Label { - Layout.fillWidth: true - horizontalAlignment: Text.AlignHCenter - wrapMode: Text.Wrap - text: qsTr("Images and files you add to notes appear here.") - font.pixelSize: 12 - color: Theme.secondaryText - } - } - } - } -} diff --git a/src/app/qml/ConfirmDialog.qml b/src/app/qml/ConfirmDialog.qml deleted file mode 100644 index 1e5f01d..0000000 --- a/src/app/qml/ConfirmDialog.qml +++ /dev/null @@ -1,58 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Layouts -import OmarchyNotes - -// Asks before something that can't be undone. The action button names -// exactly what happens ("Delete Permanently", not "OK"). -Dialog { - id: dialog - - property string message - property string confirmText: qsTr("OK") - property bool destructive: false - property var callback: null - - function ask(titleText, messageText, confirmLabel, isDestructive, done) { - title = titleText - message = messageText - confirmText = confirmLabel - destructive = isDestructive - dialog.callback = done - open() - } - - modal: true - anchors.centerIn: Overlay.overlay - width: Math.min(420, Overlay.overlay ? Overlay.overlay.width - 32 : 420) - background: Rectangle { radius: 10; color: Theme.canvas; border.color: Theme.divider } - onOpened: confirmButton.forceActiveFocus() - - Label { - width: parent.width - text: dialog.message - wrapMode: Text.Wrap - color: Theme.text - } - - footer: DialogButtonBox { - background: null - Button { - text: qsTr("Cancel") - DialogButtonBox.buttonRole: DialogButtonBox.RejectRole - } - Button { - id: confirmButton - text: dialog.confirmText - DialogButtonBox.buttonRole: DialogButtonBox.ActionRole - palette.buttonText: dialog.destructive ? Theme.error : Theme.text - Keys.onReturnPressed: clicked() - onClicked: { - const callback = dialog.callback - dialog.close() - if (callback) - callback() - } - } - } -} diff --git a/src/app/qml/EditorPane.qml b/src/app/qml/EditorPane.qml deleted file mode 100644 index c3c141b..0000000 --- a/src/app/qml/EditorPane.qml +++ /dev/null @@ -1,616 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Dialogs -import QtQuick.Layouts -import QtQuick.Window -import QtCore -import OmarchyNotes - -Rectangle { - id: root - objectName: "editorPane" - - property alias editor: editor - property alias textArea: textArea - property bool narrow: false - signal backRequested() - signal openNoteRequested(string noteId) - signal newNoteRequested() - signal deleteRequested() - signal recoverRequested() - signal deleteForeverRequested() - signal notice(string message) - signal tagRequested(string tag) - - function openFind() { - findBar.visible = true - findField.forceActiveFocus() - findField.selectAll() - if (findField.text) - editor.findText = findField.text - } - function closeFind() { - findBar.visible = false - editor.findText = "" - focusEditor() - } - - function focusEditor() { textArea.forceActiveFocus() } - - function exportAs(format) { - noteExportDialog.format = format - noteExportDialog.nameFilters = [format === "pdf" ? qsTr("PDF (*.pdf)") - : format === "html" ? qsTr("Web page (*.html)") - : qsTr("Markdown (*.md)")] - noteExportDialog.defaultSuffix = format - noteExportDialog.selectedFile = noteExportDialog.currentFolder + "/" - + encodeURIComponent(Library.exportFileName(editor.noteId, format)) - noteExportDialog.open() - } - - function toggleMark(mark) { - editor.toggleMark(mark) - } - - color: Theme.canvas - - NoteEditor { - id: editor - objectName: "noteEditor" - library: Library - document: textArea.textDocument - cursorPosition: textArea.cursorPosition - selectionStart: textArea.selectionStart - selectionEnd: textArea.selectionEnd - bodyPixelSize: 15 - devicePixelRatio: Screen.devicePixelRatio - maxImageWidth: Math.min(640, Math.max(160, textArea.width - textArea.leftPadding - textArea.rightPadding - 8)) - - onCursorRequested: position => textArea.cursorPosition = position - onSelectionRequested: (start, end) => textArea.select(start, end) - onOpenNoteRequested: noteId => root.openNoteRequested(noteId) - onNotice: message => root.notice(message) - } - - ColumnLayout { - anchors.fill: parent - spacing: 0 - - // ------------------------------------------------------------ toolbar - RowLayout { - Layout.fillWidth: true - Layout.leftMargin: 10 - Layout.rightMargin: 10 - Layout.topMargin: 8 - Layout.bottomMargin: 8 - spacing: 2 - - ToolIcon { - Layout.alignment: Qt.AlignTop - visible: root.narrow - iconName: "back" - text: qsTr("Back to notes") - onClicked: root.backRequested() - } - - Flow { - id: toolbar - readonly property bool editable: editor.hasNote && !editor.readOnly - Layout.fillWidth: true - spacing: 2 - enabled: editable - opacity: editable ? 1 : 0.35 - Accessible.role: Accessible.ToolBar - Accessible.name: qsTr("Formatting") - - ToolIcon { - id: styleButton - text: [qsTr("Body"), qsTr("Title"), qsTr("Heading"), qsTr("Subheading")][editor.blockStyle] + " ▾" - font.pixelSize: 13 - width: 104 - onClicked: styleMenu.popup(styleButton, 0, styleButton.height) - Menu { - id: styleMenu - MenuItem { text: qsTr("Title"); checkable: true; checked: editor.blockStyle === 1; onTriggered: editor.setBlockStyle(1) } - MenuItem { text: qsTr("Heading"); checkable: true; checked: editor.blockStyle === 2; onTriggered: editor.setBlockStyle(2) } - MenuItem { text: qsTr("Subheading"); checkable: true; checked: editor.blockStyle === 3; onTriggered: editor.setBlockStyle(3) } - MenuItem { text: qsTr("Body"); checkable: true; checked: editor.blockStyle === 0; onTriggered: editor.setBlockStyle(0) } - } - } - - ToolSeparator {} - - ToolIcon { - text: qsTr("Bold"); shortcutHint: "Ctrl+B" - font.bold: true; font.pixelSize: 15 - active: editor.bold - display: AbstractButton.TextOnly - contentItem: Text { text: "B"; font.bold: true; font.pixelSize: 15; color: Theme.text; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter } - onClicked: root.toggleMark(NoteEditor.Bold) - } - ToolIcon { - text: qsTr("Italic"); shortcutHint: "Ctrl+I" - active: editor.italic - contentItem: Text { text: "I"; font.italic: true; font.pixelSize: 15; font.family: "serif"; color: Theme.text; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter } - onClicked: root.toggleMark(NoteEditor.Italic) - } - ToolIcon { - text: qsTr("Underline"); shortcutHint: "Ctrl+U" - active: editor.underline - contentItem: Text { text: "U"; font.underline: true; font.pixelSize: 15; color: Theme.text; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter } - onClicked: root.toggleMark(NoteEditor.Underline) - } - ToolIcon { - text: qsTr("Strikethrough"); shortcutHint: "Ctrl+Shift+X" - active: editor.strikethrough - contentItem: Text { text: "S"; font.strikeout: true; font.pixelSize: 15; color: Theme.text; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter } - onClicked: root.toggleMark(NoteEditor.Strikethrough) - } - ToolIcon { - iconName: "highlight"; text: qsTr("Highlight"); shortcutHint: "Ctrl+Shift+Y" - active: editor.highlight - onClicked: root.toggleMark(NoteEditor.Highlight) - } - - ToolSeparator {} - - ToolIcon { - iconName: "bullets"; text: qsTr("Bulleted list"); shortcutHint: "Ctrl+Shift+8" - active: editor.listKind === NoteEditor.BulletList - onClicked: editor.toggleList(NoteEditor.BulletList) - } - ToolIcon { - iconName: "numbers"; text: qsTr("Numbered list"); shortcutHint: "Ctrl+Shift+7" - active: editor.listKind === NoteEditor.OrderedList - onClicked: editor.toggleList(NoteEditor.OrderedList) - } - ToolIcon { - iconName: "checklist"; text: qsTr("Checklist"); shortcutHint: "Ctrl+Shift+L" - active: editor.listKind === NoteEditor.CheckList - onClicked: editor.toggleList(NoteEditor.CheckList) - } - - ToolSeparator {} - - ToolIcon { - id: tableButton - iconName: "table" - text: editor.inTable ? qsTr("Table options") : qsTr("Insert table") - shortcutHint: editor.inTable ? "" : "Ctrl+Alt+T" - active: editor.inTable - onClicked: editor.inTable ? tableMenu.popup(tableButton, 0, tableButton.height) - : editor.insertTable(2, 2) - Menu { - id: tableMenu - MenuItem { text: qsTr("Add Row Below"); onTriggered: editor.addTableRow() } - MenuItem { text: qsTr("Add Column After"); onTriggered: editor.addTableColumn() } - MenuSeparator {} - MenuItem { text: qsTr("Delete Row"); onTriggered: editor.removeTableRow() } - MenuItem { text: qsTr("Delete Column"); onTriggered: editor.removeTableColumn() } - } - } - ToolIcon { - iconName: "image"; text: qsTr("Insert image") - onClicked: imageDialog.open() - } - ToolIcon { - iconName: "attach"; text: qsTr("Attach file"); shortcutHint: "Ctrl+Shift+A" - onClicked: attachDialog.open() - } - ToolIcon { - iconName: "link"; text: qsTr("Link to note"); shortcutHint: "Ctrl+L" - onClicked: linkPicker.open() - } - - ToolSeparator {} - - ToolIcon { - id: noteMenuButton - objectName: "noteMenuButton" - iconName: "more" - text: qsTr("Note actions") - onClicked: noteMenu.popup(noteMenuButton, 0, noteMenuButton.height) - Menu { - id: noteMenu - MenuItem { - text: editor.pinned ? qsTr("Unpin Note") : qsTr("Pin Note") - onTriggered: editor.setPinned(!editor.pinned) - } - MenuSeparator {} - MenuItem { text: qsTr("Export as Markdown…"); onTriggered: root.exportAs("md") } - MenuItem { text: qsTr("Export as HTML…"); onTriggered: root.exportAs("html") } - MenuItem { text: qsTr("Export as PDF…"); onTriggered: root.exportAs("pdf") } - MenuSeparator {} - MenuItem { text: qsTr("Delete Note"); onTriggered: root.deleteRequested() } - } - } - } - } - - Rectangle { - Layout.fillWidth: true - Layout.preferredHeight: 1 - color: Theme.divider - } - - // Find in note. - Rectangle { - id: findBar - objectName: "findBar" - visible: false - Layout.fillWidth: true - Layout.preferredHeight: 44 - color: Theme.raised - RowLayout { - anchors.fill: parent - anchors.leftMargin: 12 - anchors.rightMargin: 8 - spacing: 6 - TextField { - id: findField - objectName: "findField" - Layout.fillWidth: true - Layout.maximumWidth: 360 - placeholderText: qsTr("Find in note") - placeholderTextColor: Theme.secondaryText - color: Theme.text - selectionColor: Theme.selection - selectedTextColor: Theme.selectionText - Accessible.name: qsTr("Find in note") - onTextEdited: editor.findText = text - Keys.onReturnPressed: event => { - if (event.modifiers & Qt.ShiftModifier) - editor.findPrevious() - else - editor.findNext() - } - Keys.onEscapePressed: root.closeFind() - background: Rectangle { - radius: 6 - color: Theme.canvas - border.width: findField.activeFocus ? 2 : 1 - border.color: findField.text && editor.findCount === 0 ? Theme.error - : findField.activeFocus ? Theme.focus : Theme.divider - } - } - Label { - text: !findField.text ? "" - : editor.findCount === 0 ? qsTr("No matches") - : qsTr("%1 of %2").arg(editor.findIndex).arg(editor.findCount) - color: editor.findCount === 0 && findField.text ? Theme.error : Theme.secondaryText - font.pixelSize: 12 - Accessible.role: Accessible.StaticText - Accessible.name: text - } - ToolIcon { text: "\u2191"; Accessible.name: qsTr("Previous match"); enabled: editor.findCount > 0; onClicked: editor.findPrevious() } - ToolIcon { text: "\u2193"; Accessible.name: qsTr("Next match"); enabled: editor.findCount > 0; onClicked: editor.findNext() } - Item { Layout.fillWidth: true } - ToolIcon { text: qsTr("Done"); onClicked: root.closeFind() } - } - } - - // Notes in Recently Deleted open read-only. - Rectangle { - visible: editor.readOnly - Layout.fillWidth: true - Layout.preferredHeight: banner.implicitHeight + 16 - color: Theme.raised - RowLayout { - id: banner - anchors.fill: parent - anchors.leftMargin: 16 - anchors.rightMargin: 10 - spacing: 8 - Label { - Layout.fillWidth: true - text: qsTr("This note is in Recently Deleted. Recover it to make changes.") - wrapMode: Text.Wrap - color: Theme.text - } - ToolIcon { iconName: "recover"; text: qsTr("Recover"); display: AbstractButton.TextBesideIcon; implicitWidth: implicitContentWidth + 20; onClicked: root.recoverRequested() } - ToolIcon { text: qsTr("Delete Permanently…"); onClicked: root.deleteForeverRequested() } - } - } - - // ------------------------------------------------------------ document - ScrollView { - id: scroller - Layout.fillWidth: true - Layout.fillHeight: true - contentWidth: availableWidth - visible: editor.hasNote - - TextArea { - id: textArea - objectName: "noteText" - - readonly property int column: 720 - - textFormat: TextEdit.RichText - wrapMode: TextEdit.Wrap - readOnly: editor.readOnly || !editor.hasNote - selectByMouse: true - persistentSelection: true - focus: true - color: Theme.text - selectionColor: Theme.selection - selectedTextColor: Theme.selectionText - placeholderTextColor: Theme.secondaryText - font.pixelSize: editor.bodyPixelSize - topPadding: 52 - bottomPadding: 96 - leftPadding: Math.max(24, (width - column) / 2) - rightPadding: leftPadding - background: null - Accessible.name: qsTr("Note") - Accessible.description: qsTr("Rich text note editor") - - Label { - id: editedLabel - y: 20 - width: parent.width - horizontalAlignment: Text.AlignHCenter - text: editor.editedText - color: Theme.secondaryText - font.pixelSize: 12 - } - - Keys.onPressed: event => { - const plain = !(event.modifiers & (Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier)) - if (event.matches(StandardKey.Copy)) { - editor.copy(); event.accepted = true - } else if (event.matches(StandardKey.Cut)) { - editor.cut(); event.accepted = true - } else if (event.matches(StandardKey.Paste)) { - editor.paste(); event.accepted = true - } else if ((event.key === Qt.Key_Return || event.key === Qt.Key_Enter) && plain - && !(event.modifiers & Qt.ShiftModifier)) { - event.accepted = editor.handleReturn() - } else if (event.key === Qt.Key_Tab && plain) { - event.accepted = editor.handleTab(false) - } else if (event.key === Qt.Key_Backtab) { - editor.handleTab(true); event.accepted = true - } else if (event.key === Qt.Key_Backspace && plain) { - event.accepted = editor.handleBackspace() - } else if (editor.hasPendingFormat && plain && event.text.length > 0 - && event.text.charCodeAt(0) >= 32) { - event.accepted = editor.typeWithPendingFormat(event.text) - } - } - - // Round checkboxes over the text engine's box glyphs, and - // accessible stand-ins for images and attachments. - Repeater { - model: editor.overlays - delegate: Item { - id: overlay - - required property var modelData - readonly property bool isCheck: modelData.kind === "check" - // Re-evaluated whenever the layout may have moved. - readonly property rect at: { - editor.layoutRevision - textArea.width - textArea.contentHeight - return textArea.positionToRectangle(modelData.position) - } - - x: isCheck ? at.x - 21 : at.x - y: isCheck ? at.y + (at.height - height) / 2 : at.y - width: isCheck ? 20 : 1 - height: isCheck ? 20 : Math.max(1, at.height) - Accessible.role: isCheck ? Accessible.CheckBox - : modelData.kind === "image" ? Accessible.Graphic : Accessible.Button - Accessible.name: modelData.name - Accessible.checkable: isCheck - Accessible.checked: modelData.checked - Accessible.onToggleAction: editor.toggleCheckAt(modelData.position) - Accessible.onPressAction: isCheck ? editor.toggleCheckAt(modelData.position) - : editor.activateObjectAt(modelData.position) - - Rectangle { - visible: overlay.isCheck - anchors.centerIn: parent - width: 20 - height: 20 - radius: 10 - color: Theme.canvas // hides the glyph underneath - Rectangle { - anchors.centerIn: parent - width: 16 - height: 16 - radius: 8 - color: overlay.modelData.checked ? Theme.accent : "transparent" - border.width: overlay.modelData.checked ? 0 : 1.5 - border.color: Theme.secondaryText - Text { - anchors.centerIn: parent - visible: overlay.modelData.checked - text: "\u2713" - color: Theme.accentText - font.pixelSize: 11 - font.bold: true - } - } - } - MouseArea { - anchors.fill: parent - enabled: overlay.isCheck && !editor.readOnly - cursorShape: Qt.PointingHandCursor - onClicked: editor.toggleCheckAt(overlay.modelData.position) - } - } - } - - // Checkbox markers toggle natively on click (and undo). - // Double-click opens attachments and images. - TapHandler { - acceptedModifiers: Qt.NoModifier - onDoubleTapped: eventPoint => { - const p = eventPoint.position - editor.activateObjectAt(textArea.positionAt(p.x, p.y)) - } - } - // Ctrl+click follows links and opens #tags. - TapHandler { - acceptedModifiers: Qt.ControlModifier - onTapped: eventPoint => { - const p = eventPoint.position - const link = textArea.linkAt(p.x, p.y) - if (link) { - editor.openLink(link) - return - } - const tag = editor.tagAt(textArea.positionAt(p.x, p.y)) - if (tag) - root.tagRequested(tag) - } - } - HoverHandler { - cursorShape: textArea.hoveredLink ? Qt.PointingHandCursor : Qt.IBeamCursor - } - } - } - - // Nothing open (empty folder, or the note was deleted). - ColumnLayout { - visible: !editor.hasNote - Layout.fillWidth: true - Layout.fillHeight: true - spacing: 12 - Item { Layout.fillHeight: true } - Label { - Layout.alignment: Qt.AlignHCenter - text: qsTr("No note selected") - font.pixelSize: 16 - font.weight: Font.DemiBold - color: Theme.secondaryText - } - Button { - Layout.alignment: Qt.AlignHCenter - text: qsTr("New Note") - onClicked: root.newNoteRequested() - } - Item { Layout.fillHeight: true } - } - - // ------------------------------------------------------------ status - Rectangle { - Layout.fillWidth: true - Layout.preferredHeight: 1 - color: Theme.divider - } - RowLayout { - visible: editor.hasNote && !editor.readOnly - Layout.fillWidth: true - Layout.preferredHeight: 30 - Layout.leftMargin: 14 - Layout.rightMargin: 8 - spacing: 8 - - Label { - id: status - Layout.fillWidth: true - elide: Text.ElideRight - font.pixelSize: 12 - color: editor.saveState === NoteEditor.Failed || editor.saveState === NoteEditor.Conflict - ? Theme.error : Theme.secondaryText - text: { - switch (editor.saveState) { - case NoteEditor.Saved: return qsTr("Saved") - case NoteEditor.Edited: return qsTr("Edited") - case NoteEditor.Saving: return qsTr("Saving…") - case NoteEditor.Failed: return qsTr("Couldn't save: %1 Your changes are kept here.").arg(editor.saveError) - case NoteEditor.Conflict: return qsTr("This note was changed elsewhere.") - } - return "" - } - Accessible.role: Accessible.StaticText - Accessible.name: text - } - ToolIcon { - visible: editor.saveState === NoteEditor.Failed - text: qsTr("Retry") - onClicked: editor.retrySave() - } - ToolIcon { - visible: editor.saveState === NoteEditor.Failed - text: qsTr("Export…") - onClicked: exportDialog.open() - } - ToolIcon { - visible: editor.saveState === NoteEditor.Conflict - text: qsTr("Keep this version") - onClicked: editor.keepMyVersion() - } - } - } - - NoteLinkPicker { - id: linkPicker - excludeNoteId: editor.noteId - onPicked: noteId => { - editor.insertNoteLink(noteId) - root.focusEditor() - } - onClosed: root.focusEditor() - } - - FileDialog { - id: imageDialog - title: qsTr("Insert Image") - nameFilters: [qsTr("Images (*.png *.jpg *.jpeg *.gif *.webp *.svg *.bmp)")] - onAccepted: { editor.insertImageFile(selectedFile); root.focusEditor() } - } - FileDialog { - id: attachDialog - title: qsTr("Attach File") - onAccepted: { editor.attachFile(selectedFile); root.focusEditor() } - } - FileDialog { - id: noteExportDialog - property string format: "md" - title: qsTr("Export Note") - fileMode: FileDialog.SaveFile - currentFolder: StandardPaths.writableLocation(StandardPaths.DocumentsLocation) - onAccepted: { - editor.flush() - const result = Library.exportNote(editor.noteId, format, selectedFile) - root.notice(result.ok ? qsTr("Exported to %1").arg(result.path) : result.error) - } - } - FileDialog { - id: exportDialog - title: qsTr("Export Note") - fileMode: FileDialog.SaveFile - defaultSuffix: "md" - nameFilters: [qsTr("Markdown (*.md)")] - onAccepted: editor.exportDraft(selectedFile) - } - - // ------------------------------------------------------------ shortcuts - Shortcut { sequences: [StandardKey.Bold]; enabled: textArea.activeFocus; onActivated: root.toggleMark(NoteEditor.Bold) } - Shortcut { sequences: [StandardKey.Italic]; enabled: textArea.activeFocus; onActivated: root.toggleMark(NoteEditor.Italic) } - Shortcut { sequences: [StandardKey.Underline]; enabled: textArea.activeFocus; onActivated: root.toggleMark(NoteEditor.Underline) } - Shortcut { sequence: "Ctrl+Shift+X"; enabled: textArea.activeFocus; onActivated: root.toggleMark(NoteEditor.Strikethrough) } - Shortcut { sequence: "Ctrl+Shift+Y"; enabled: textArea.activeFocus; onActivated: root.toggleMark(NoteEditor.Highlight) } - Shortcut { sequence: "Ctrl+E"; enabled: textArea.activeFocus; onActivated: root.toggleMark(NoteEditor.Code) } - Shortcut { sequence: "Ctrl+Shift+T"; enabled: textArea.activeFocus; onActivated: editor.setBlockStyle(1) } - Shortcut { sequence: "Ctrl+Shift+H"; enabled: textArea.activeFocus; onActivated: editor.setBlockStyle(2) } - Shortcut { sequence: "Ctrl+Shift+J"; enabled: textArea.activeFocus; onActivated: editor.setBlockStyle(3) } - Shortcut { sequence: "Ctrl+Shift+B"; enabled: textArea.activeFocus; onActivated: editor.setBlockStyle(0) } - Shortcut { sequence: "Ctrl+Shift+L"; enabled: textArea.activeFocus; onActivated: editor.toggleList(NoteEditor.CheckList) } - Shortcut { sequence: "Ctrl+Shift+U"; enabled: textArea.activeFocus; onActivated: editor.toggleCheckAtCursor() } - Shortcut { sequences: ["Ctrl+Shift+8", "Ctrl+*"]; enabled: textArea.activeFocus; onActivated: editor.toggleList(NoteEditor.BulletList) } - Shortcut { sequences: ["Ctrl+Shift+7", "Ctrl+&"]; enabled: textArea.activeFocus; onActivated: editor.toggleList(NoteEditor.OrderedList) } - Shortcut { sequence: "Ctrl+]"; enabled: textArea.activeFocus; onActivated: editor.indent() } - Shortcut { sequence: "Ctrl+["; enabled: textArea.activeFocus; onActivated: editor.outdent() } - Shortcut { sequence: "Ctrl+Alt+T"; enabled: textArea.activeFocus; onActivated: editor.insertTable(2, 2) } - Shortcut { sequence: "Ctrl+Shift+A"; enabled: toolbar.editable; onActivated: attachDialog.open() } - Shortcut { sequence: "Ctrl+L"; enabled: toolbar.editable; onActivated: linkPicker.open() } - Shortcut { sequences: [StandardKey.Find]; enabled: editor.hasNote; onActivated: root.openFind() } - // Opens the image or attachment next to the cursor. - Shortcut { sequences: ["Ctrl+Return", "Ctrl+Enter"]; enabled: textArea.activeFocus; onActivated: editor.activateObjectAt(textArea.cursorPosition) } - Shortcut { sequences: [StandardKey.FindNext]; enabled: findBar.visible; onActivated: editor.findNext() } - Shortcut { sequences: [StandardKey.FindPrevious]; enabled: findBar.visible; onActivated: editor.findPrevious() } -} diff --git a/src/app/qml/FolderNameDialog.qml b/src/app/qml/FolderNameDialog.qml deleted file mode 100644 index 72a5a77..0000000 --- a/src/app/qml/FolderNameDialog.qml +++ /dev/null @@ -1,100 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Layouts -import OmarchyNotes - -// Names a new folder or renames one. Errors (e.g. a duplicate name) show -// inline and keep the dialog open. -Dialog { - id: dialog - - property string folderId // set when renaming - property string parentId // set when creating inside a folder - signal created(string folderId) - - function openForCreate(parent) { - folderId = "" - parentId = parent - nameField.text = "" - error.text = "" - open() - } - function openForRename(id, name) { - folderId = id - parentId = "" - nameField.text = name - error.text = "" - open() - } - function submit() { - const result = folderId ? Library.renameFolder(folderId, nameField.text) - : Library.createFolder(nameField.text, parentId) - if (!result.ok) { - error.text = result.error - nameField.forceActiveFocus() - return - } - if (!folderId) - created(result.id) - close() - } - - title: folderId ? qsTr("Rename Folder") - : parentId ? qsTr("New Folder in “%1”").arg(Library.folderName(parentId)) - : qsTr("New Folder") - modal: true - anchors.centerIn: Overlay.overlay - width: Math.min(380, Overlay.overlay ? Overlay.overlay.width - 32 : 380) - onOpened: { - nameField.forceActiveFocus() - nameField.selectAll() - } - - background: Rectangle { radius: 10; color: Theme.canvas; border.color: Theme.divider } - - ColumnLayout { - anchors.fill: parent - spacing: 8 - TextField { - id: nameField - Layout.fillWidth: true - placeholderText: qsTr("Folder name") - placeholderTextColor: Theme.secondaryText - color: Theme.text - selectionColor: Theme.selection - selectedTextColor: Theme.selectionText - Accessible.name: qsTr("Folder name") - onAccepted: dialog.submit() - onTextEdited: error.text = "" - background: Rectangle { - radius: 6 - color: Theme.raised - border.width: nameField.activeFocus ? 2 : 1 - border.color: error.text ? Theme.error : nameField.activeFocus ? Theme.focus : Theme.divider - } - } - Label { - id: error - Layout.fillWidth: true - visible: text.length > 0 - wrapMode: Text.Wrap - color: Theme.error - font.pixelSize: 12 - Accessible.role: Accessible.AlertMessage - } - } - - footer: DialogButtonBox { - background: null - Button { - text: qsTr("Cancel") - DialogButtonBox.buttonRole: DialogButtonBox.RejectRole - } - Button { - text: dialog.folderId ? qsTr("Rename") : qsTr("Create") - enabled: nameField.text.trim().length > 0 - DialogButtonBox.buttonRole: DialogButtonBox.ActionRole - onClicked: dialog.submit() - } - } -} diff --git a/src/app/qml/Main.qml b/src/app/qml/Main.qml deleted file mode 100644 index 858db80..0000000 --- a/src/app/qml/Main.qml +++ /dev/null @@ -1,527 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Dialogs -import QtQuick.Layouts -import OmarchyNotes - -ApplicationWindow { - id: window - - required property string initialNoteId - // Wide: folders | notes | editor. Medium: notes | editor, folders in a - // drawer. Narrow: one pane at a time. - readonly property bool wide: width >= 1040 - readonly property bool narrow: width < 720 - property bool sidebarCollapsed: false - readonly property bool sidebarInline: wide && !sidebarCollapsed - property bool showingEditor: true - readonly property var editor: editorPane.editor - // Gallery and attachments use the whole centre; opening a note from - // them shows the editor full width with a back button. - readonly property bool wideContent: Library.inAttachments || noteList.gallery - readonly property bool singlePane: narrow || wideContent - - width: 1240 - height: 780 - minimumWidth: 360 - minimumHeight: 400 - // Launched for a Quick Note, only that window shows at first. - visible: !App.startHidden - title: qsTr("Omarchy Notes") - color: Theme.canvas - - palette { - window: Theme.canvas - windowText: Theme.text - base: Theme.canvas - text: Theme.text - button: Theme.raised - buttonText: Theme.text - highlight: Theme.selection - highlightedText: Theme.selectionText - mid: Theme.divider - light: Theme.raised - dark: Theme.divider - placeholderText: Theme.secondaryText - toolTipBase: Theme.raised - toolTipText: Theme.text - } - - // ------------------------------------------------------------ selection - - function openNote(noteId) { - if (!noteId) - return false - if (editor.openNote(noteId)) { - showingEditor = true - return true - } - return false - } - - // Opens the first note of the list, or nothing if the list is empty. - function openFirstNote() { - const first = Library.notes.idAt(0) - if (first) - openNote(first) - else if (editor.flush()) - editor.closeNote() - } - - function showView(key) { - Library.showKey(key) - if (sidebarDrawer.opened) - sidebarDrawer.close() - if (!Library.inAttachments && !noteList.gallery && Library.notes.indexOf(editor.noteId) < 0) - openFirstNote() - if (singlePane) - showingEditor = false - } - - function newNote() { - const noteId = Library.createNote() - if (noteId && openNote(noteId)) - editorPane.focusEditor() - } - - // Runs `action` on a note that is about to leave the list, then selects - // its neighbour, like Notes does. - function removeFromList(noteId, action) { - const row = Library.notes.indexOf(noteId) - const wasOpen = noteId === editor.noteId - if (wasOpen && !editor.flush()) - return false - if (!action(noteId)) - return false - if (wasOpen || !editor.hasNote) { - const next = Library.notes.idAt(Math.min(Math.max(row, 0), Library.notes.count - 1)) - if (next) - openNote(next) - else - editor.closeNote() - } - return true - } - - function trashNote(noteId) { - if (removeFromList(noteId, id => Library.trashNote(id))) - toast.show(qsTr("Moved to Recently Deleted.")) - } - - function deleteForever(noteId) { - const title = Library.notes.titleOf(noteId) || qsTr("This note") - confirm.ask(qsTr("Delete Permanently?"), - qsTr("“%1” will be deleted permanently. This can't be undone.").arg(title), - qsTr("Delete Permanently"), true, - () => removeFromList(noteId, id => Library.deleteNotePermanently(id))) - } - - function recoverNote(noteId) { - if (removeFromList(noteId, id => Library.recoverNote(id))) - toast.show(qsTr("Note recovered.")) - } - - function handleAction(action, noteId) { - switch (action) { - case "trash": trashNote(noteId); break - case "deleteForever": deleteForever(noteId); break - case "recover": recoverNote(noteId); break - case "pin": Library.setPinned(noteId, true); break - case "unpin": Library.setPinned(noteId, false); break - case "move": moveDialog.openFor(noteId); break - case "duplicate": { - if (noteId === editor.noteId) - editor.flush() - const copy = Library.duplicateNote(noteId) - if (copy) - openNote(copy) - break - } - } - } - - function emptyTrash() { - confirm.ask(qsTr("Empty Recently Deleted?"), - qsTr("%n note(s) will be deleted permanently. This can't be undone.", "", Library.trashCount), - qsTr("Delete Permanently"), true, () => { - const showingTrashedNote = editor.readOnly - Library.emptyTrash() - if (showingTrashedNote) - editor.closeNote() - }) - } - - function deleteFolder(id, name, count) { - confirm.ask(qsTr("Delete “%1”?").arg(name), - count > 0 - ? qsTr("The folder and any folders inside it will be removed. Their notes move to Recently Deleted, where you can recover them for 30 days.") - : qsTr("The folder and any folders inside it will be removed."), - qsTr("Delete Folder"), true, () => { - Library.deleteFolder(id) - if (!editor.hasNote || editor.readOnly || Library.notes.indexOf(editor.noteId) < 0) - window.openFirstNote() - }) - } - - Component.onCompleted: { - const remembered = Library.lastNoteId - const first = window.initialNoteId - || (Library.notes.indexOf(remembered) >= 0 ? remembered : Library.notes.idAt(0)) - if (first) - openNote(first) - else if (Library.notes.count === 0 && Library.currentKey !== "trash") - newNote() // an empty library opens straight into a note - if (wideContent) - showingEditor = false // reopen on the gallery or attachments - else - editorPane.focusEditor() - if (App.startWithQuickNote) - quickNote.start("") - } - - // Requests from other launches (desktop actions, the command line). - Connections { - target: App - function onActivateRequested(token) { App.activate(window, token) } - function onNewNoteRequested(token) { - App.activate(window, token) - window.newNote() - } - function onQuickNoteRequested(token) { quickNote.start(token) } - function onOpenNoteRequested(noteId, token) { - App.activate(window, token) - window.openNote(noteId) - } - function onCaptured(noteId) { - if (window.visible) - toast.show(qsTr("Captured a new note.")) - } - } - - QuickNoteWindow { - id: quickNote - objectName: "quickNote" - onOpenInNotes: noteId => { - App.activate(window, "") - window.showView("all") - window.openNote(noteId) - } - } - - onClosing: close => { - if (!editor.flush()) { - close.accepted = false - unsavedDialog.open() - } - } - - Connections { - target: Library - function onErrorOccurred(message) { toast.show(message) } - function onLibraryReplaced() { window.openFirstNote() } - function onGalleryModeChanged() { window.showingEditor = !window.singlePane } - } - - function deleteSmartFolder(id, name) { - confirm.ask(qsTr("Delete \u201c%1\u201d?").arg(name), - qsTr("Only the Smart Folder is removed. The notes it shows stay where they are."), - qsTr("Delete Smart Folder"), true, () => { - Library.deleteSmartFolder(id) - if (Library.currentKey === "all") - window.openFirstNote() - }) - } - - // ------------------------------------------------------------ layout - - RowLayout { - anchors.fill: parent - spacing: 0 - - Sidebar { - id: inlineSidebar - objectName: "sidebar" - visible: window.sidebarInline - Layout.fillHeight: true - Layout.preferredWidth: 220 - onViewChosen: key => window.showView(key) - onNewFolderRequested: parentId => folderDialog.openForCreate(parentId) - onRenameFolderRequested: (id, name) => folderDialog.openForRename(id, name) - onDeleteFolderRequested: (id, name, count) => window.deleteFolder(id, name, count) - onEmptyTrashRequested: window.emptyTrash() - onBackupRequested: backupFolderDialog.open() - onRestoreRequested: restoreFolderDialog.open() - onNewSmartFolderRequested: smartDialog.openForCreate() - onEditSmartFolderRequested: id => smartDialog.openForEdit(id) - onDeleteSmartFolderRequested: (id, name) => window.deleteSmartFolder(id, name) - onImportRequested: importDialog.open() - onImportFolderRequested: importFolderDialog.open() - onExportAllRequested: exportAllDialog.open() - } - Rectangle { - visible: window.sidebarInline - Layout.fillHeight: true - Layout.preferredWidth: 1 - color: Theme.divider - } - NoteList { - id: noteList - objectName: "noteList" - Layout.fillHeight: true - Layout.fillWidth: window.singlePane - Layout.preferredWidth: window.singlePane ? window.width : 300 - visible: !Library.inAttachments && (!window.singlePane || !window.showingEditor) - currentNoteId: window.editor.noteId - showSidebarButton: !window.sidebarInline - onNoteChosen: noteId => window.openNote(noteId) - onNewNoteRequested: window.newNote() - onSidebarToggled: window.wide ? (window.sidebarCollapsed = false) : sidebarDrawer.open() - onActionRequested: (action, noteId) => window.handleAction(action, noteId) - onEmptyTrashRequested: window.emptyTrash() - } - AttachmentsView { - id: attachmentsView - objectName: "attachmentsView" - Layout.fillHeight: true - Layout.fillWidth: true - visible: Library.inAttachments && !window.showingEditor - showSidebarButton: !window.sidebarInline - onNoteChosen: noteId => window.openNote(noteId) - onSidebarToggled: window.wide ? (window.sidebarCollapsed = false) : sidebarDrawer.open() - } - Rectangle { - Layout.fillHeight: true - Layout.preferredWidth: 1 - color: Theme.divider - visible: !window.singlePane - } - EditorPane { - id: editorPane - Layout.fillWidth: true - Layout.fillHeight: true - visible: !window.singlePane || window.showingEditor - narrow: window.singlePane - onBackRequested: window.showingEditor = false - onOpenNoteRequested: noteId => window.openNote(noteId) - onNewNoteRequested: window.newNote() - onDeleteRequested: window.trashNote(window.editor.noteId) - onRecoverRequested: window.recoverNote(window.editor.noteId) - onDeleteForeverRequested: window.deleteForever(window.editor.noteId) - onNotice: message => toast.show(message) - onTagRequested: tag => window.showView("tag:" + tag) - } - } - - Drawer { - id: sidebarDrawer - width: Math.min(280, window.width * 0.8) - height: window.height - edge: Qt.LeftEdge - background: Rectangle { color: Theme.sidebar } - onOpened: drawerSidebar.focusList() - Sidebar { - id: drawerSidebar - anchors.fill: parent - onViewChosen: key => window.showView(key) - onNewFolderRequested: parentId => { sidebarDrawer.close(); folderDialog.openForCreate(parentId) } - onRenameFolderRequested: (id, name) => { sidebarDrawer.close(); folderDialog.openForRename(id, name) } - onDeleteFolderRequested: (id, name, count) => { sidebarDrawer.close(); window.deleteFolder(id, name, count) } - onEmptyTrashRequested: { sidebarDrawer.close(); window.emptyTrash() } - onBackupRequested: { sidebarDrawer.close(); backupFolderDialog.open() } - onRestoreRequested: { sidebarDrawer.close(); restoreFolderDialog.open() } - onNewSmartFolderRequested: { sidebarDrawer.close(); smartDialog.openForCreate() } - onEditSmartFolderRequested: id => { sidebarDrawer.close(); smartDialog.openForEdit(id) } - onDeleteSmartFolderRequested: (id, name) => { sidebarDrawer.close(); window.deleteSmartFolder(id, name) } - onImportRequested: { sidebarDrawer.close(); importDialog.open() } - onImportFolderRequested: { sidebarDrawer.close(); importFolderDialog.open() } - onExportAllRequested: { sidebarDrawer.close(); exportAllDialog.open() } - } - } - - // ------------------------------------------------------------ dialogs - - Toast { - id: toast - objectName: "toast" - z: 10 - anchors.horizontalCenter: parent.horizontalCenter - anchors.bottom: parent.bottom - anchors.bottomMargin: 44 - } - ConfirmDialog { id: confirm; objectName: "confirmDialog" } - FolderNameDialog { - id: folderDialog - objectName: "folderDialog" - onCreated: folderId => window.showView(folderId) - } - SmartFolderDialog { - id: smartDialog - objectName: "smartDialog" - onCreated: key => window.showView(key) - } - FileDialog { - id: importDialog - title: qsTr("Import Notes") - fileMode: FileDialog.OpenFiles - nameFilters: [qsTr("Markdown and text (*.md *.markdown *.txt)"), qsTr("All files (*)")] - onAccepted: { - const result = Library.importFiles(selectedFiles) - if (result.count > 0) { - window.openNote(result.first) - toast.show(result.warnings.length - ? qsTr("Imported %n note(s). %1", "", result.count).arg(result.warnings.join(" ")) - : qsTr("Imported %n note(s).", "", result.count)) - } else { - toast.show(result.error || qsTr("Nothing was imported.")) - } - } - } - FolderDialog { - id: importFolderDialog - title: qsTr("Choose a Folder of Notes to Import") - onAccepted: { - const result = Library.importFolder(selectedFolder) - if (result.count > 0) { - window.openFirstNote() - toast.show(result.warnings.length - ? qsTr("Imported %n note(s). %1", "", result.count).arg(result.warnings.join(" ")) - : qsTr("Imported %n note(s).", "", result.count)) - } else { - toast.show(result.error || qsTr("Nothing was imported.")) - } - } - } - FolderDialog { - id: exportAllDialog - title: qsTr("Choose Where to Export Your Notes") - onAccepted: { - window.editor.flush() - const result = Library.exportAll(selectedFolder) - toast.show(result.ok ? qsTr("Exported to %1").arg(result.path) : result.error) - } - } - MoveNoteDialog { - id: moveDialog - onMoved: (noteId, folderId) => { - if (Library.moveNote(noteId, folderId)) - toast.show(qsTr("Moved to “%1”.").arg(Library.folderName(folderId))) - } - } - - FolderDialog { - id: backupFolderDialog - title: qsTr("Choose Where to Save the Backup") - onAccepted: { - window.editor.flush() - const result = Library.backupTo(selectedFolder, Library.defaultBackupName()) - if (result.ok) - toast.show(qsTr("Backed up %n note(s) (%1) to %2", "", result.notes).arg(result.size).arg(result.path)) - else - toast.show(result.error) - } - } - FolderDialog { - id: restoreFolderDialog - title: qsTr("Choose a Backup to Restore") - onAccepted: { - const info = Library.inspectBackup(selectedFolder) - if (!info.ok) { - toast.show(info.error) - return - } - const folder = selectedFolder - confirm.ask(qsTr("Restore This Backup?"), - qsTr("Your notes will be replaced with the backup from %1 (%n note(s), %2).\n\nYour current notes aren't deleted: they're set aside in a folder next to your library, so you can go back.", "", info.notes) - .arg(info.created).arg(info.size), - qsTr("Restore"), false, () => { - if (!window.editor.flush()) { - toast.show(qsTr("Save or export your current changes before restoring.")) - return - } - window.editor.closeNote() - const result = Library.restoreFrom(folder) - toast.show(result.ok ? qsTr("Restored. Your previous notes are in %1").arg(result.previous) - : result.error) - }) - } - } - - // ------------------------------------------------------------ shortcuts - - Shortcut { sequences: [StandardKey.New]; onActivated: window.newNote() } - Shortcut { sequence: "Ctrl+Shift+N"; onActivated: folderDialog.openForCreate("") } - Shortcut { - sequence: "Ctrl+Shift+F" - onActivated: { - if (Library.inAttachments) - window.showView("all") - if (window.singlePane) - window.showingEditor = false - noteList.focusSearch() - } - } - Shortcut { - sequence: "Ctrl+D" - enabled: window.editor.hasNote && !window.editor.readOnly - onActivated: window.handleAction("duplicate", window.editor.noteId) - } - Shortcut { - sequence: "Ctrl+Shift+S" - onActivated: window.wide ? (window.sidebarCollapsed = !window.sidebarCollapsed) : sidebarDrawer.open() - } - // Developer switch for exercising the save-failure path. - Shortcut { - sequence: "Ctrl+Alt+Shift+F" - onActivated: Library.simulateSaveFailure = !Library.simulateSaveFailure - } - - Dialog { - id: unsavedDialog - anchors.centerIn: parent - modal: true - title: qsTr("Your latest changes aren't saved") - Label { - width: 380 - wrapMode: Text.Wrap - color: Theme.text - text: qsTr("%1\n\nRetry saving, export the note as Markdown, or quit and lose the unsaved changes.") - .arg(window.editor.saveError) - } - footer: DialogButtonBox { - Button { - text: qsTr("Retry") - DialogButtonBox.buttonRole: DialogButtonBox.AcceptRole - onClicked: { - window.editor.retrySave() - if (window.editor.flush()) - Qt.quit() - } - } - Button { - text: qsTr("Export…") - DialogButtonBox.buttonRole: DialogButtonBox.ActionRole - onClicked: quitExportDialog.open() - } - Button { - text: qsTr("Quit Without Saving") - DialogButtonBox.buttonRole: DialogButtonBox.DestructiveRole - onClicked: Qt.exit(0) - } - Button { - text: qsTr("Cancel") - DialogButtonBox.buttonRole: DialogButtonBox.RejectRole - onClicked: unsavedDialog.close() - } - } - } - FileDialog { - id: quitExportDialog - fileMode: FileDialog.SaveFile - defaultSuffix: "md" - nameFilters: [qsTr("Markdown (*.md)")] - onAccepted: { - if (window.editor.exportDraft(selectedFile)) - unsavedDialog.close() - } - } -} diff --git a/src/app/qml/MoveNoteDialog.qml b/src/app/qml/MoveNoteDialog.qml deleted file mode 100644 index d826813..0000000 --- a/src/app/qml/MoveNoteDialog.qml +++ /dev/null @@ -1,79 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Controls.impl -import QtQuick.Layouts -import OmarchyNotes - -// Picks the folder a note moves to. -Dialog { - id: dialog - - property string noteId - signal moved(string noteId, string folderId) - - function openFor(id) { - noteId = id - choices.model = Library.folderChoices() - choices.currentIndex = 0 - open() - } - - title: qsTr("Move “%1” to…").arg(Library.notes.titleOf(noteId)) - modal: true - anchors.centerIn: Overlay.overlay - width: Math.min(360, Overlay.overlay ? Overlay.overlay.width - 32 : 360) - height: Math.min(460, Overlay.overlay ? Overlay.overlay.height - 64 : 460) - background: Rectangle { radius: 10; color: Theme.canvas; border.color: Theme.divider } - onOpened: choices.forceActiveFocus() - - ListView { - id: choices - anchors.fill: parent - clip: true - keyNavigationEnabled: true - Accessible.role: Accessible.List - Accessible.name: qsTr("Folders") - Keys.onReturnPressed: if (currentItem) currentItem.clicked() - - delegate: ItemDelegate { - required property int index - required property var modelData - width: ListView.view.width - height: 34 - leftPadding: 12 + modelData.depth * 16 - focusPolicy: Qt.NoFocus - onClicked: { - dialog.close() - dialog.moved(dialog.noteId, modelData.id) - } - Accessible.name: modelData.name - background: Rectangle { - radius: 6 - color: parent.ListView.isCurrentItem ? Theme.selection - : parent.hovered ? Theme.raised : "transparent" - } - contentItem: RowLayout { - spacing: 8 - IconImage { - source: "qrc:/qt/qml/OmarchyNotes/icons/" + (modelData.id ? "folder" : "note") + ".svg" - sourceSize: Qt.size(16, 16) - color: Theme.secondaryText - } - Label { - Layout.fillWidth: true - text: modelData.name - elide: Text.ElideRight - color: Theme.text - } - } - } - } - - footer: DialogButtonBox { - background: null - Button { - text: qsTr("Cancel") - DialogButtonBox.buttonRole: DialogButtonBox.RejectRole - } - } -} diff --git a/src/app/qml/NoteLinkPicker.qml b/src/app/qml/NoteLinkPicker.qml deleted file mode 100644 index 0deb530..0000000 --- a/src/app/qml/NoteLinkPicker.qml +++ /dev/null @@ -1,72 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Layouts -import OmarchyNotes - -// Chooses a note to link to from the current one. -Popup { - id: picker - - property string excludeNoteId - signal picked(string noteId) - - modal: true - focus: true - width: 360 - height: Math.min(420, list.contentHeight + header.height + 24) - padding: 8 - anchors.centerIn: Overlay.overlay - - background: Rectangle { - radius: 10 - color: Theme.canvas - border.color: Theme.divider - } - - onOpened: list.forceActiveFocus() - - contentItem: ColumnLayout { - spacing: 4 - Label { - id: header - Layout.margins: 8 - text: qsTr("Link to note") - font.weight: Font.DemiBold - color: Theme.text - } - ListView { - id: list - Layout.fillWidth: true - Layout.fillHeight: true - clip: true - model: Library.notes - keyNavigationEnabled: true - currentIndex: 0 - Keys.onReturnPressed: if (currentItem && currentItem.enabled) picker.choose(currentItem.noteId) - Accessible.role: Accessible.List - Accessible.name: qsTr("Notes") - - delegate: ItemDelegate { - required property int index - required property string noteId - required property string title - width: ListView.view.width - enabled: noteId !== picker.excludeNoteId - text: title - palette.text: Theme.text - palette.windowText: Theme.text - background: Rectangle { - radius: 6 - color: parent.ListView.isCurrentItem ? Theme.selection - : parent.hovered ? Theme.raised : "transparent" - } - onClicked: picker.choose(noteId) - } - } - } - - function choose(noteId) { - close() - picked(noteId) - } -} diff --git a/src/app/qml/NoteList.qml b/src/app/qml/NoteList.qml deleted file mode 100644 index ec26bd4..0000000 --- a/src/app/qml/NoteList.qml +++ /dev/null @@ -1,515 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Controls.impl -import QtQuick.Layouts -import OmarchyNotes - -Rectangle { - id: root - - property string currentNoteId - property bool showSidebarButton: false - // Cards instead of rows; the list then takes the editor's space. - readonly property bool gallery: Library.galleryMode && !Library.inTrash - signal noteChosen(string noteId) - signal newNoteRequested() - signal sidebarToggled() - // "trash", "recover", "deleteForever", "pin", "unpin", "move", "duplicate" - signal actionRequested(string action, string noteId) - signal emptyTrashRequested() - - function focusSearch() { - search.forceActiveFocus() - search.selectAll() - } - function focusList() { (gallery ? grid : list).forceActiveFocus() } - - color: Theme.sidebar - - ColumnLayout { - anchors.fill: parent - spacing: 0 - - RowLayout { - Layout.fillWidth: true - Layout.preferredHeight: 52 - Layout.leftMargin: root.showSidebarButton ? 8 : 16 - Layout.rightMargin: 8 - spacing: 6 - - ToolIcon { - visible: root.showSidebarButton - iconName: "sidebar" - text: qsTr("Show folders") - onClicked: root.sidebarToggled() - } - Label { - Layout.fillWidth: true - text: Library.viewTitle - elide: Text.ElideRight - color: Theme.text - font.pixelSize: 17 - font.weight: Font.DemiBold - Accessible.role: Accessible.Heading - } - Label { - text: list.count - color: Theme.secondaryText - Accessible.name: qsTr("%n notes", "", list.count) - } - ToolIcon { - iconName: Library.galleryMode ? "list" : "gallery" - text: Library.galleryMode ? qsTr("View as list") : qsTr("View as gallery") - visible: !Library.inTrash - onClicked: Library.galleryMode = !Library.galleryMode - } - ToolIcon { - id: sortButton - iconName: "more" - text: qsTr("Sort notes") - visible: !Library.inTrash && !Library.searching - onClicked: sortMenu.popup(sortButton, 0, sortButton.height) - Menu { - id: sortMenu - MenuItem { text: qsTr("Sort by Date Edited"); checkable: true; checked: Library.sortOrder === Library.SortEdited; onTriggered: Library.sortOrder = Library.SortEdited } - MenuItem { text: qsTr("Sort by Date Created"); checkable: true; checked: Library.sortOrder === Library.SortCreated; onTriggered: Library.sortOrder = Library.SortCreated } - MenuItem { text: qsTr("Sort by Title"); checkable: true; checked: Library.sortOrder === Library.SortTitle; onTriggered: Library.sortOrder = Library.SortTitle } - } - } - ToolIcon { - iconName: "compose" - text: qsTr("New note") - shortcutHint: "Ctrl+N" - onClicked: root.newNoteRequested() - } - } - - TextField { - id: search - objectName: "searchField" - Layout.fillWidth: true - Layout.leftMargin: 12 - Layout.rightMargin: 12 - Layout.bottomMargin: 8 - leftPadding: 32 - rightPadding: clearSearch.visible ? 30 : 10 - placeholderText: qsTr("Search all notes") - placeholderTextColor: Theme.secondaryText - color: Theme.text - selectionColor: Theme.selection - selectedTextColor: Theme.selectionText - text: Library.searchText - onTextEdited: Library.searchText = text - Accessible.name: qsTr("Search all notes") - background: Rectangle { - radius: 7 - color: Theme.raised - border.width: search.activeFocus ? 2 : 1 - border.color: search.activeFocus ? Theme.focus : Theme.divider - } - IconImage { - anchors.left: parent.left - anchors.leftMargin: 10 - anchors.verticalCenter: parent.verticalCenter - source: "qrc:/qt/qml/OmarchyNotes/icons/search.svg" - sourceSize: Qt.size(15, 15) - color: Theme.secondaryText - } - ToolButton { - id: clearSearch - visible: search.text.length > 0 - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - width: 28 - height: 28 - focusPolicy: Qt.NoFocus - icon.source: "qrc:/qt/qml/OmarchyNotes/icons/close.svg" - icon.width: 12 - icon.height: 12 - icon.color: Theme.secondaryText - background: null - onClicked: Library.searchText = "" - Accessible.name: qsTr("Clear search") - } - Keys.onEscapePressed: Library.searchText = "" - Keys.onDownPressed: list.forceActiveFocus() - // Enter opens the best match. - onAccepted: if (list.count > 0) root.noteChosen(Library.notes.idAt(0)) - } - - // Recently Deleted explains itself and offers to empty. - RowLayout { - visible: Library.inTrash && list.count > 0 - Layout.fillWidth: true - Layout.leftMargin: 16 - Layout.rightMargin: 12 - Layout.bottomMargin: 6 - Label { - Layout.fillWidth: true - text: qsTr("Notes are deleted for good after 30 days.") - wrapMode: Text.Wrap - font.pixelSize: 12 - color: Theme.secondaryText - } - ToolIcon { - text: qsTr("Empty") - onClicked: root.emptyTrashRequested() - } - } - - ListView { - id: list - objectName: "noteListView" - visible: !root.gallery - Layout.fillWidth: true - Layout.fillHeight: true - clip: true - model: Library.notes - keyNavigationEnabled: true - activeFocusOnTab: true - boundsBehavior: Flickable.StopAtBounds - spacing: 2 - bottomMargin: 8 - currentIndex: Library.notes.indexOf(root.currentNoteId) - Accessible.role: Accessible.List - Accessible.name: Library.viewTitle - ScrollBar.vertical: ScrollBar {} - - section.property: "section" - section.delegate: Label { - required property string section - width: ListView.view.width - visible: section.length > 0 - height: visible ? 30 : 0 - leftPadding: 18 - verticalAlignment: Text.AlignBottom - bottomPadding: 4 - text: section - font.pixelSize: 12 - font.weight: Font.DemiBold - color: Theme.secondaryText - Accessible.role: Accessible.Heading - } - - // Moving through the list opens notes, like Notes does. - onCurrentIndexChanged: { - if (activeFocus && currentItem && currentItem.noteId !== root.currentNoteId) - root.noteChosen(currentItem.noteId) - } - Keys.onReturnPressed: if (currentItem) root.noteChosen(currentItem.noteId) - Keys.onDeletePressed: if (currentItem) root.actionRequested(Library.inTrash ? "deleteForever" : "trash", currentItem.noteId) - Keys.onMenuPressed: if (currentItem) currentItem.openMenu() - - delegate: ItemDelegate { - id: row - - required property int index - required property string noteId - required property string title - required property string snippet - required property string date - required property string folderName - required property bool pinned - required property bool hasAttachments - required property bool hasChecklist - readonly property bool selected: noteId === root.currentNoteId - // Where a note lives matters when the list mixes folders. - readonly property bool showFolder: (Library.searching || Library.currentKey === "all") - && folderName.length > 0 - - function openMenu() { contextMenu.popup(row, 24, row.height) } - - width: ListView.view.width - height: showFolder ? 78 : 62 - leftPadding: 16 - rightPadding: 14 - focusPolicy: Qt.NoFocus - onClicked: { - ListView.view.currentIndex = index - root.noteChosen(noteId) - } - Accessible.name: title + ", " + date - Accessible.description: snippet - Accessible.selected: selected - - background: Rectangle { - anchors.fill: parent - anchors.leftMargin: 8 - anchors.rightMargin: 8 - radius: 7 - color: row.selected ? Theme.selection - : row.hovered ? Theme.raised : "transparent" - border.width: row.ListView.isCurrentItem && row.ListView.view.activeFocus ? 2 : 0 - border.color: Theme.focus - } - - contentItem: ColumnLayout { - spacing: 2 - RowLayout { - spacing: 6 - Label { - Layout.fillWidth: true - text: row.title - elide: Text.ElideRight - font.weight: Font.DemiBold - color: row.selected ? Theme.selectionText : Theme.text - } - IconImage { - visible: row.pinned && !Library.inTrash - source: "qrc:/qt/qml/OmarchyNotes/icons/pin.svg" - sourceSize: Qt.size(13, 13) - color: row.selected ? Theme.selectionText : Theme.secondaryText - Accessible.name: qsTr("Pinned") - } - } - RowLayout { - spacing: 8 - Label { - text: row.date - font.pixelSize: 12 - color: row.selected ? Theme.selectionText : Theme.secondaryText - } - Label { - Layout.fillWidth: true - text: row.snippet - textFormat: Text.StyledText - elide: Text.ElideRight - maximumLineCount: 1 - font.pixelSize: 12 - color: row.selected ? Theme.selectionText : Theme.secondaryText - } - IconImage { - visible: row.hasChecklist - source: "qrc:/qt/qml/OmarchyNotes/icons/checklist.svg" - sourceSize: Qt.size(14, 14) - color: row.selected ? Theme.selectionText : Theme.secondaryText - Accessible.name: qsTr("Has a checklist") - } - IconImage { - visible: row.hasAttachments - source: "qrc:/qt/qml/OmarchyNotes/icons/attach.svg" - sourceSize: Qt.size(14, 14) - color: row.selected ? Theme.selectionText : Theme.secondaryText - Accessible.name: qsTr("Has attachments") - } - } - RowLayout { - visible: row.showFolder - spacing: 5 - IconImage { - source: "qrc:/qt/qml/OmarchyNotes/icons/folder.svg" - sourceSize: Qt.size(12, 12) - color: row.selected ? Theme.selectionText : Theme.secondaryText - } - Label { - Layout.fillWidth: true - text: row.folderName - elide: Text.ElideRight - font.pixelSize: 11 - color: row.selected ? Theme.selectionText : Theme.secondaryText - } - } - } - - TapHandler { - acceptedButtons: Qt.RightButton - onTapped: row.openMenu() - } - - NoteMenu { - id: contextMenu - noteId: row.noteId - pinned: row.pinned - onAction: (action, noteId) => root.actionRequested(action, noteId) - } - } - - // Empty states say what's going on and what to do next. - ColumnLayout { - anchors.centerIn: parent - width: parent.width - 48 - visible: list.count === 0 - spacing: 10 - Label { - Layout.fillWidth: true - horizontalAlignment: Text.AlignHCenter - wrapMode: Text.Wrap - font.weight: Font.DemiBold - color: Theme.text - text: Library.searching ? qsTr("No notes match “%1”").arg(Library.searchText.trim()) - : Library.inTrash ? qsTr("Recently Deleted is empty") - : qsTr("No notes here yet") - } - Label { - Layout.fillWidth: true - horizontalAlignment: Text.AlignHCenter - wrapMode: Text.Wrap - font.pixelSize: 12 - color: Theme.secondaryText - text: Library.searching ? qsTr("Try fewer or shorter words.") - : Library.inTrash ? qsTr("Notes you delete stay here for 30 days.") - : qsTr("Press Ctrl+N to start one.") - } - } - - } - GridView { - id: grid - objectName: "noteGrid" - visible: root.gallery - Layout.fillWidth: true - Layout.fillHeight: true - Layout.leftMargin: 10 - clip: true - model: Library.notes - keyNavigationEnabled: true - activeFocusOnTab: true - boundsBehavior: Flickable.StopAtBounds - readonly property int columns: Math.max(1, Math.floor(width / 230)) - cellWidth: Math.floor(width / columns) - cellHeight: 236 - currentIndex: Library.notes.indexOf(root.currentNoteId) - Accessible.role: Accessible.List - Accessible.name: Library.viewTitle - ScrollBar.vertical: ScrollBar {} - Keys.onReturnPressed: if (currentItem) root.noteChosen(currentItem.noteId) - Keys.onDeletePressed: if (currentItem) root.actionRequested("trash", currentItem.noteId) - Keys.onMenuPressed: if (currentItem) currentItem.openMenu() - - delegate: Item { - id: card - - required property int index - required property string noteId - required property string title - required property string snippet - required property string date - required property bool pinned - required property string thumbnail - readonly property bool selected: noteId === root.currentNoteId - - function openMenu() { cardMenu.popup(card, 24, 40) } - - width: GridView.view.cellWidth - height: GridView.view.cellHeight - Accessible.role: Accessible.ListItem - Accessible.name: title + ", " + date - Accessible.selected: selected - - Rectangle { - id: frame - anchors.fill: parent - anchors.margins: 7 - radius: 10 - color: Theme.canvas - border.width: card.selected || (card.GridView.isCurrentItem && card.GridView.view.activeFocus) ? 2 : 1 - border.color: card.selected || card.GridView.isCurrentItem && card.GridView.view.activeFocus - ? Theme.focus : (hover.hovered ? Theme.tableBorder : Theme.divider) - clip: true - - Item { - id: preview - anchors.left: parent.left - anchors.right: parent.right - anchors.top: parent.top - anchors.margins: 1 - height: 134 - Image { - anchors.fill: parent - visible: card.thumbnail.length > 0 - source: card.thumbnail ? "image://blob/" + card.thumbnail : "" - sourceSize: Qt.size(460, 268) - fillMode: Image.PreserveAspectCrop - asynchronous: true - } - // Text notes preview their opening lines. - Column { - anchors.fill: parent - anchors.margins: 12 - visible: card.thumbnail.length === 0 - spacing: 4 - Label { - width: parent.width - text: card.title - wrapMode: Text.Wrap - maximumLineCount: 2 - elide: Text.ElideRight - font.pixelSize: 13 - font.weight: Font.DemiBold - color: Theme.text - } - Label { - width: parent.width - text: card.snippet - textFormat: Text.StyledText - wrapMode: Text.Wrap - maximumLineCount: 4 - elide: Text.ElideRight - font.pixelSize: 12 - color: Theme.secondaryText - } - } - Rectangle { - anchors.bottom: parent.bottom - width: parent.width - height: 1 - color: Theme.divider - } - } - ColumnLayout { - anchors.left: parent.left - anchors.right: parent.right - anchors.top: preview.bottom - anchors.margins: 10 - spacing: 2 - RowLayout { - Label { - Layout.fillWidth: true - text: card.title - elide: Text.ElideRight - font.weight: Font.DemiBold - color: Theme.text - } - IconImage { - visible: card.pinned - source: "qrc:/qt/qml/OmarchyNotes/icons/pin.svg" - sourceSize: Qt.size(13, 13) - color: Theme.secondaryText - } - } - Label { - text: card.date - font.pixelSize: 12 - color: Theme.secondaryText - } - } - } - HoverHandler { id: hover } - TapHandler { - onTapped: { - card.GridView.view.currentIndex = card.index - root.noteChosen(card.noteId) - } - } - TapHandler { - acceptedButtons: Qt.RightButton - onTapped: card.openMenu() - } - NoteMenu { - id: cardMenu - noteId: card.noteId - pinned: card.pinned - onAction: (action, noteId) => root.actionRequested(action, noteId) - } - } - - Label { - anchors.centerIn: parent - visible: grid.count === 0 - text: Library.searching ? qsTr("No notes match \u201c%1\u201d").arg(Library.searchText.trim()) - : qsTr("No notes here yet") - color: Theme.secondaryText - } - } - } -} diff --git a/src/app/qml/NoteMenu.qml b/src/app/qml/NoteMenu.qml deleted file mode 100644 index 9308da6..0000000 --- a/src/app/qml/NoteMenu.qml +++ /dev/null @@ -1,50 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import OmarchyNotes - -// Actions on one note, shared by the list and the gallery. -Menu { - id: menu - - property string noteId - property bool pinned - // "trash", "recover", "deleteForever", "pin", "unpin", "move", "duplicate" - signal action(string action, string noteId) - - MenuItem { - text: menu.pinned ? qsTr("Unpin Note") : qsTr("Pin Note") - visible: !Library.inTrash - height: visible ? implicitHeight : 0 - onTriggered: menu.action(menu.pinned ? "unpin" : "pin", menu.noteId) - } - MenuItem { - text: qsTr("Move to Folder…") - visible: !Library.inTrash - height: visible ? implicitHeight : 0 - onTriggered: menu.action("move", menu.noteId) - } - MenuItem { - text: qsTr("Duplicate") - visible: !Library.inTrash - height: visible ? implicitHeight : 0 - onTriggered: menu.action("duplicate", menu.noteId) - } - MenuItem { - text: qsTr("Delete") - visible: !Library.inTrash - height: visible ? implicitHeight : 0 - onTriggered: menu.action("trash", menu.noteId) - } - MenuItem { - text: qsTr("Recover") - visible: Library.inTrash - height: visible ? implicitHeight : 0 - onTriggered: menu.action("recover", menu.noteId) - } - MenuItem { - text: qsTr("Delete Permanently…") - visible: Library.inTrash - height: visible ? implicitHeight : 0 - onTriggered: menu.action("deleteForever", menu.noteId) - } -} diff --git a/src/app/qml/QuickNoteWindow.qml b/src/app/qml/QuickNoteWindow.qml deleted file mode 100644 index 38a050d..0000000 --- a/src/app/qml/QuickNoteWindow.qml +++ /dev/null @@ -1,116 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Layouts -import OmarchyNotes - -// A small window for jotting something down without the full app. It uses -// the same editor and storage; notes land in Notes. A Quick Note you never -// write in is discarded when the window closes. -Window { - id: quick - - property string noteId - signal openInNotes(string noteId) - - function start(token) { - if (!visible || !noteId) { - noteId = Library.createQuickNote() - pane.editor.openNote(noteId) - } - App.activate(quick, token) - pane.focusEditor() - } - - function finish() { - const id = noteId - if (!pane.editor.flush()) - return false - pane.editor.closeNote() - if (id) - Library.discardIfEmpty(id) - noteId = "" - return true - } - - title: qsTr("Quick Note") - width: 520 - height: 440 - minimumWidth: 360 - minimumHeight: 260 - color: Theme.canvas - - palette { - window: Theme.canvas - windowText: Theme.text - base: Theme.canvas - text: Theme.text - button: Theme.raised - buttonText: Theme.text - highlight: Theme.selection - highlightedText: Theme.selectionText - mid: Theme.divider - light: Theme.raised - dark: Theme.divider - placeholderText: Theme.secondaryText - toolTipBase: Theme.raised - toolTipText: Theme.text - } - - onClosing: close => { - if (!finish()) { - close.accepted = false - pane.notice(qsTr("This note has changes that couldn't be saved. Retry or export them first.")) - } - } - - ColumnLayout { - anchors.fill: parent - spacing: 0 - - EditorPane { - id: pane - objectName: "quickNotePane" - Layout.fillWidth: true - Layout.fillHeight: true - onDeleteRequested: quick.close() - onNotice: message => toast.show(message) - } - - Rectangle { - Layout.fillWidth: true - Layout.preferredHeight: 1 - color: Theme.divider - } - RowLayout { - Layout.fillWidth: true - Layout.margins: 8 - spacing: 8 - Item { Layout.fillWidth: true } - Button { - text: qsTr("Open in Omarchy Notes") - onClicked: { - const id = quick.noteId - if (!pane.editor.flush()) - return - pane.editor.closeNote() - quick.noteId = "" - quick.hide() - quick.openInNotes(id) - } - } - Button { - text: qsTr("Done") - onClicked: quick.close() - } - } - } - - Toast { - id: toast - z: 10 - anchors.horizontalCenter: parent.horizontalCenter - anchors.bottom: parent.bottom - anchors.bottomMargin: 56 - } - Shortcut { sequences: [StandardKey.Close]; onActivated: quick.close() } -} diff --git a/src/app/qml/Sidebar.qml b/src/app/qml/Sidebar.qml deleted file mode 100644 index 8a9e64d..0000000 --- a/src/app/qml/Sidebar.qml +++ /dev/null @@ -1,234 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Controls.impl -import QtQuick.Layouts -import OmarchyNotes - -// Folder list: All Notes, Notes, your folders, Recently Deleted. -Rectangle { - id: root - - signal viewChosen(string key) - signal newFolderRequested(string parentId) - signal renameFolderRequested(string folderId, string name) - signal deleteFolderRequested(string folderId, string name, int count) - signal emptyTrashRequested() - signal backupRequested() - signal restoreRequested() - signal newSmartFolderRequested() - signal editSmartFolderRequested(string smartId) - signal deleteSmartFolderRequested(string smartId, string name) - signal importRequested() - signal importFolderRequested() - signal exportAllRequested() - - function focusList() { list.forceActiveFocus() } - - color: Theme.sidebar - - ColumnLayout { - anchors.fill: parent - spacing: 0 - - Label { - Layout.fillWidth: true - Layout.preferredHeight: 52 - leftPadding: 18 - verticalAlignment: Text.AlignVCenter - text: qsTr("Folders") - color: Theme.secondaryText - font.pixelSize: 12 - font.weight: Font.DemiBold - font.letterSpacing: 0.4 - Accessible.role: Accessible.Heading - } - - ListView { - id: list - Layout.fillWidth: true - Layout.fillHeight: true - clip: true - model: Library.folders - activeFocusOnTab: true - keyNavigationEnabled: true - boundsBehavior: Flickable.StopAtBounds - spacing: 1 - Accessible.role: Accessible.List - Accessible.name: qsTr("Folders") - ScrollBar.vertical: ScrollBar {} - - section.property: "section" - section.delegate: Label { - required property string section - width: ListView.view.width - visible: section.length > 0 - height: visible ? 34 : 0 - leftPadding: 18 - verticalAlignment: Text.AlignBottom - bottomPadding: 5 - text: section - color: Theme.secondaryText - font.pixelSize: 12 - font.weight: Font.DemiBold - font.letterSpacing: 0.4 - Accessible.role: Accessible.Heading - } - - currentIndex: Library.folders.indexOfKey(Library.currentKey) - Connections { - target: Library - function onViewChanged() { list.currentIndex = Library.folders.indexOfKey(Library.currentKey) } - } - // Arrow keys move through folders and show them. - onCurrentIndexChanged: { - if (activeFocus && currentItem && currentItem.key !== Library.currentKey) - root.viewChosen(currentItem.key) - } - Keys.onMenuPressed: if (currentItem) currentItem.openMenu() - - delegate: ItemDelegate { - id: row - - required property int index - required property string key - required property string name - required property string kind - required property int depth - required property int count - required property string folderId - readonly property bool selected: key === Library.currentKey && !Library.searching - - function openMenu() { - if (kind !== "tag" && kind !== "attachments") - contextMenu.popup(row, 24, row.height) - } - - width: ListView.view.width - height: 34 - leftPadding: 18 + depth * 16 - rightPadding: 14 - focusPolicy: Qt.NoFocus - onClicked: root.viewChosen(key) - Accessible.name: name + ", " + qsTr("%n notes", "", count) - Accessible.selected: selected - - background: Rectangle { - anchors.fill: parent - anchors.leftMargin: 8 - anchors.rightMargin: 8 - radius: 6 - color: row.selected ? Theme.selection - : row.hovered ? Theme.raised : "transparent" - border.width: row.ListView.isCurrentItem && row.ListView.view.activeFocus ? 2 : 0 - border.color: Theme.focus - } - - contentItem: RowLayout { - spacing: 9 - IconImage { - source: "qrc:/qt/qml/OmarchyNotes/icons/" - + ({all: "all-notes", notes: "note", folder: "folder", trash: "trash", - attachments: "attach", smart: "smart-folder", tag: "tag"})[row.kind] + ".svg" - sourceSize: Qt.size(16, 16) - color: row.selected ? Theme.selectionText : Theme.secondaryText - } - Label { - Layout.fillWidth: true - text: row.name - elide: Text.ElideRight - color: row.selected ? Theme.selectionText : Theme.text - } - Label { - visible: row.count > 0 - text: row.count - font.pixelSize: 12 - color: row.selected ? Theme.selectionText : Theme.secondaryText - } - } - - TapHandler { - acceptedButtons: Qt.RightButton - onTapped: row.openMenu() - } - - Menu { - id: contextMenu - MenuItem { - text: qsTr("Edit Smart Folder…") - visible: row.kind === "smart" - height: visible ? implicitHeight : 0 - onTriggered: root.editSmartFolderRequested(row.folderId) - } - MenuItem { - text: qsTr("Delete Smart Folder…") - visible: row.kind === "smart" - height: visible ? implicitHeight : 0 - onTriggered: root.deleteSmartFolderRequested(row.folderId, row.name) - } - MenuItem { - text: row.kind === "folder" ? qsTr("New Folder Inside") : qsTr("New Folder") - visible: row.kind === "folder" || row.kind === "notes" || row.kind === "all" - height: visible ? implicitHeight : 0 - onTriggered: root.newFolderRequested(row.kind === "folder" ? row.folderId : "") - } - MenuItem { - text: qsTr("Rename…") - visible: row.kind === "folder" - height: visible ? implicitHeight : 0 - onTriggered: root.renameFolderRequested(row.folderId, row.name) - } - MenuItem { - text: qsTr("Delete Folder…") - visible: row.kind === "folder" - height: visible ? implicitHeight : 0 - onTriggered: root.deleteFolderRequested(row.folderId, row.name, row.count) - } - MenuItem { - text: qsTr("Empty Recently Deleted…") - visible: row.kind === "trash" - height: visible ? implicitHeight : 0 - enabled: row.count > 0 - onTriggered: root.emptyTrashRequested() - } - } - } - } - - Rectangle { - Layout.fillWidth: true - Layout.preferredHeight: 1 - color: Theme.divider - } - RowLayout { - Layout.fillWidth: true - Layout.margins: 6 - spacing: 2 - ToolIcon { - iconName: "folder-new" - text: qsTr("New folder") - shortcutHint: "Ctrl+Shift+N" - onClicked: root.newFolderRequested("") - } - Item { Layout.fillWidth: true } - ToolIcon { - id: libraryButton - iconName: "more" - text: qsTr("Library options") - onClicked: libraryMenu.popup(libraryButton, 0, -libraryMenu.implicitHeight) - Menu { - id: libraryMenu - MenuItem { text: qsTr("New Smart Folder…"); onTriggered: root.newSmartFolderRequested() } - MenuSeparator {} - MenuItem { text: qsTr("Import Markdown or Text…"); onTriggered: root.importRequested() } - MenuItem { text: qsTr("Import a Folder of Notes…"); onTriggered: root.importFolderRequested() } - MenuItem { text: qsTr("Export All Notes as Markdown…"); onTriggered: root.exportAllRequested() } - MenuSeparator {} - MenuItem { text: qsTr("Back Up Library…"); onTriggered: root.backupRequested() } - MenuItem { text: qsTr("Restore from Backup…"); onTriggered: root.restoreRequested() } - MenuSeparator {} - MenuItem { text: qsTr("Show Library Folder"); onTriggered: Library.openLibraryFolder() } - } - } - } - } -} diff --git a/src/app/qml/SmartFolderDialog.qml b/src/app/qml/SmartFolderDialog.qml deleted file mode 100644 index 720527a..0000000 --- a/src/app/qml/SmartFolderDialog.qml +++ /dev/null @@ -1,201 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Layouts -import OmarchyNotes - -// Creates or edits a Smart Folder: a saved set of filters. -Dialog { - id: dialog - - property string smartId // set when editing - property var selectedTags: [] - signal created(string key) - - readonly property var dayChoices: [0, 1, 7, 30, 365] - readonly property var dayLabels: [qsTr("Any time"), qsTr("Today"), qsTr("In the last 7 days"), - qsTr("In the last 30 days"), qsTr("In the last year")] - - function openForCreate() { - smartId = "" - nameField.text = "" - load({}) - open() - } - function openForEdit(id) { - smartId = id - const current = Library.smartFolder(id) - nameField.text = current.name || "" - load(current) - open() - } - function load(c) { - selectedTags = (c.tags || []).slice() - matchAll.checked = !!c.matchAllTags - checklist.checked = !!c.hasChecklist - attachments.checked = !!c.hasAttachments - pinned.checked = !!c.pinnedOnly - edited.currentIndex = Math.max(0, dayChoices.indexOf(c.editedWithinDays || 0)) - created.currentIndex = Math.max(0, dayChoices.indexOf(c.createdWithinDays || 0)) - folders.model = [{id: "", name: qsTr("Any folder"), depth: 0}] - .concat(Library.folderChoices().filter(f => f.id !== "")) - folders.currentIndex = Math.max(0, folders.model.findIndex(f => f.id === (c.folderId || ""))) - error.text = "" - } - function toggleTag(tag) { - const next = selectedTags.slice() - const at = next.indexOf(tag) - if (at >= 0) - next.splice(at, 1) - else - next.push(tag) - selectedTags = next - } - function criteria() { - const c = {} - if (selectedTags.length) c.tags = selectedTags - if (matchAll.checked) c.matchAllTags = true - if (checklist.checked) c.hasChecklist = true - if (attachments.checked) c.hasAttachments = true - if (pinned.checked) c.pinnedOnly = true - if (edited.currentIndex > 0) c.editedWithinDays = dayChoices[edited.currentIndex] - if (created.currentIndex > 0) c.createdWithinDays = dayChoices[created.currentIndex] - if (folders.currentIndex > 0) c.folderId = folders.model[folders.currentIndex].id - return c - } - function submit() { - const result = smartId ? Library.updateSmartFolder(smartId, nameField.text, criteria()) - : Library.createSmartFolder(nameField.text, criteria()) - if (!result.ok) { - error.text = result.error - return - } - if (!smartId) - created(result.id) - close() - } - - title: smartId ? qsTr("Edit Smart Folder") : qsTr("New Smart Folder") - modal: true - anchors.centerIn: Overlay.overlay - width: Math.min(460, Overlay.overlay ? Overlay.overlay.width - 32 : 460) - background: Rectangle { radius: 10; color: Theme.canvas; border.color: Theme.divider } - onOpened: nameField.forceActiveFocus() - - ColumnLayout { - anchors.fill: parent - spacing: 12 - - TextField { - id: nameField - Layout.fillWidth: true - placeholderText: qsTr("Name") - placeholderTextColor: Theme.secondaryText - color: Theme.text - Accessible.name: qsTr("Smart Folder name") - onAccepted: dialog.submit() - background: Rectangle { - radius: 6 - color: Theme.raised - border.width: nameField.activeFocus ? 2 : 1 - border.color: nameField.activeFocus ? Theme.focus : Theme.divider - } - } - - Label { - text: qsTr("Notes with these tags") - font.weight: Font.DemiBold - color: Theme.text - } - Flow { - Layout.fillWidth: true - spacing: 6 - visible: Library.allTags.length > 0 - Repeater { - model: Library.allTags - delegate: Button { - required property string modelData - readonly property bool chosen: dialog.selectedTags.indexOf(modelData) >= 0 - text: "#" + modelData - checkable: true - checked: chosen - onClicked: dialog.toggleTag(modelData) - Accessible.name: qsTr("Tag %1").arg(modelData) - background: Rectangle { - radius: 12 - implicitHeight: 26 - color: parent.chosen ? Theme.accent : Theme.raised - border.color: parent.visualFocus ? Theme.focus : Theme.divider - } - contentItem: Label { - text: parent.text - leftPadding: 4 - rightPadding: 4 - color: parent.chosen ? Theme.accentText : Theme.text - } - } - } - } - Label { - visible: Library.allTags.length === 0 - Layout.fillWidth: true - wrapMode: Text.Wrap - text: qsTr("Tags you add to notes (like #work) show up here.") - color: Theme.secondaryText - font.pixelSize: 12 - } - CheckBox { - id: matchAll - visible: dialog.selectedTags.length > 1 - text: qsTr("Only notes with all of these tags") - } - - Label { - text: qsTr("And notes that…") - font.weight: Font.DemiBold - color: Theme.text - } - CheckBox { id: checklist; text: qsTr("Have a checklist") } - CheckBox { id: attachments; text: qsTr("Have images or attachments") } - CheckBox { id: pinned; text: qsTr("Are pinned") } - - GridLayout { - columns: 2 - columnSpacing: 12 - rowSpacing: 8 - Label { text: qsTr("Edited"); color: Theme.text } - ComboBox { id: edited; Layout.fillWidth: true; model: dialog.dayLabels } - Label { text: qsTr("Created"); color: Theme.text } - ComboBox { id: created; Layout.fillWidth: true; model: dialog.dayLabels } - Label { text: qsTr("In"); color: Theme.text } - ComboBox { - id: folders - Layout.fillWidth: true - textRole: "name" - } - } - - Label { - id: error - Layout.fillWidth: true - visible: text.length > 0 - wrapMode: Text.Wrap - color: Theme.error - font.pixelSize: 12 - Accessible.role: Accessible.AlertMessage - } - } - - footer: DialogButtonBox { - background: null - Button { - text: qsTr("Cancel") - DialogButtonBox.buttonRole: DialogButtonBox.RejectRole - } - Button { - text: dialog.smartId ? qsTr("Save") : qsTr("Create") - enabled: nameField.text.trim().length > 0 - DialogButtonBox.buttonRole: DialogButtonBox.ActionRole - onClicked: dialog.submit() - } - } -} diff --git a/src/app/qml/StartupError.qml b/src/app/qml/StartupError.qml deleted file mode 100644 index 2fae441..0000000 --- a/src/app/qml/StartupError.qml +++ /dev/null @@ -1,74 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import QtQuick.Layouts -import OmarchyNotes - -// Shown instead of the main window when the library can't be opened, so a -// launch from the app launcher never fails silently. -ApplicationWindow { - id: window - - required property string heading - required property string message - required property string location - - width: 520 - height: 300 - minimumWidth: 360 - visible: true - title: qsTr("Omarchy Notes") - color: Theme.canvas - palette { - window: Theme.canvas - windowText: Theme.text - button: Theme.raised - buttonText: Theme.text - } - - ColumnLayout { - anchors.fill: parent - anchors.margins: 28 - spacing: 12 - Label { - Layout.fillWidth: true - text: window.heading - wrapMode: Text.Wrap - font.pixelSize: 18 - font.weight: Font.DemiBold - color: Theme.text - Accessible.role: Accessible.Heading - } - Label { - Layout.fillWidth: true - text: window.message - wrapMode: Text.Wrap - color: Theme.text - textFormat: Text.PlainText - Accessible.role: Accessible.AlertMessage - } - Label { - Layout.fillWidth: true - visible: window.location.length > 0 - text: qsTr("Your notes are in %1. Nothing has been changed or deleted.").arg(window.location) - wrapMode: Text.Wrap - color: Theme.secondaryText - font.pixelSize: 12 - textFormat: Text.PlainText - } - Item { Layout.fillHeight: true } - RowLayout { - Layout.alignment: Qt.AlignRight - spacing: 8 - Button { - visible: window.location.length > 0 - text: qsTr("Open Library Folder") - onClicked: Qt.openUrlExternally("file://" + window.location) - } - Button { - text: qsTr("Quit") - focus: true - onClicked: Qt.quit() - } - } - } -} diff --git a/src/app/qml/Toast.qml b/src/app/qml/Toast.qml deleted file mode 100644 index 70f101e..0000000 --- a/src/app/qml/Toast.qml +++ /dev/null @@ -1,45 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import OmarchyNotes - -// Transient message at the bottom of the window, e.g. content that couldn't -// be pasted. Announced to screen readers as an alert. -Rectangle { - id: toast - - function show(message) { - label.text = message - visible = true - hideTimer.restart() - } - - visible: false - width: Math.min(label.implicitWidth + 32, parent.width - 32) - height: label.implicitHeight + 20 - radius: 8 - color: Theme.raised - border.color: Theme.divider - Accessible.role: Accessible.AlertMessage - Accessible.name: label.text - - Label { - id: label - anchors.fill: parent - anchors.margins: 10 - anchors.leftMargin: 16 - anchors.rightMargin: 16 - color: Theme.text - wrapMode: Text.Wrap - horizontalAlignment: Text.AlignHCenter - } - - Timer { - id: hideTimer - interval: 5000 - onTriggered: toast.visible = false - } - - TapHandler { - onTapped: toast.visible = false - } -} diff --git a/src/app/qml/ToolIcon.qml b/src/app/qml/ToolIcon.qml deleted file mode 100644 index 6b48c06..0000000 --- a/src/app/qml/ToolIcon.qml +++ /dev/null @@ -1,40 +0,0 @@ -import QtQuick -import QtQuick.Controls.Basic -import OmarchyNotes - -// Toolbar button: a monochrome line icon (or short text label) that follows -// the theme, with a tooltip naming the action and its shortcut. -ToolButton { - id: control - - property string iconName - property bool active: false - property string shortcutHint - - implicitWidth: iconName ? 32 : Math.max(32, implicitContentWidth + 14) - implicitHeight: 32 - padding: 7 - focusPolicy: Qt.NoFocus - display: iconName ? AbstractButton.IconOnly : AbstractButton.TextOnly - icon.source: iconName ? "qrc:/qt/qml/OmarchyNotes/icons/" + iconName + ".svg" : "" - icon.width: 18 - icon.height: 18 - icon.color: enabled ? Theme.text : Theme.secondaryText - palette.buttonText: enabled ? Theme.text : Theme.secondaryText - - background: Rectangle { - radius: 6 - color: control.active ? Theme.selection - : control.down ? Theme.divider - : control.hovered ? Theme.raised : "transparent" - border.width: control.visualFocus ? 2 : 0 - border.color: Theme.focus - } - - ToolTip.visible: hovered && text.length > 0 - ToolTip.delay: 600 - ToolTip.text: shortcutHint ? text + " (" + shortcutHint + ")" : text - Accessible.name: text - Accessible.checkable: true - Accessible.checked: active -} diff --git a/src/core/BlobStore.cpp b/src/core/BlobStore.cpp deleted file mode 100644 index 421d5ff..0000000 --- a/src/core/BlobStore.cpp +++ /dev/null @@ -1,175 +0,0 @@ -#include "BlobStore.h" - -#include "RichDocument.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -namespace { - -bool fail(QString *error, const QString &message) -{ - if (error) - *error = message; - return false; -} - -QString errnoString() -{ - switch (errno) { - case ENOSPC: - case EDQUOT: - return u"your disk is full"_s; - case EROFS: - return u"your notes folder is read-only"_s; - default: - return QString::fromLocal8Bit(std::strerror(errno)); - } -} - -} // namespace - -bool syncFileDescriptor(int fd) -{ - int rc; - do { - rc = ::fsync(fd); - } while (rc != 0 && errno == EINTR); - return rc == 0; -} - -bool syncDirectory(const QString &path) -{ - const int fd = ::open(QFile::encodeName(path).constData(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if (fd < 0) - return false; - const bool ok = syncFileDescriptor(fd); - ::close(fd); - return ok; -} - -BlobStore::BlobStore(LibraryPaths paths) : m_paths(std::move(paths)) {} - -bool BlobStore::prepare(QString *error) -{ - QDir dir; - if (!dir.mkpath(m_paths.blobs()) || !dir.mkpath(m_paths.staging())) - return fail(error, u"Could not create the attachment directories in %1."_s.arg(m_paths.root)); - QDir staging(m_paths.staging()); - for (const QString &name : staging.entryList(QDir::Files | QDir::Hidden)) - staging.remove(name); - return true; -} - -std::optional BlobStore::install(QIODevice &source, QString *error) -{ - const QString stagingPath = m_paths.staging() + u'/' + newId() + u".part"_s; - QFile staged(stagingPath); - if (!staged.open(QIODevice::WriteOnly | QIODevice::Truncate)) { - fail(error, u"Could not write attachment: %1"_s.arg(staged.errorString())); - return std::nullopt; - } - - QCryptographicHash sha(QCryptographicHash::Sha256); - qint64 total = 0; - QByteArray chunk; - while (!source.atEnd()) { - chunk = source.read(1 << 20); - if (chunk.isEmpty() && source.atEnd()) - break; - if (chunk.isEmpty()) { - staged.remove(); - fail(error, u"Could not read attachment: %1"_s.arg(source.errorString())); - return std::nullopt; - } - sha.addData(chunk); - if (staged.write(chunk) != chunk.size()) { - const QString why = staged.errorString(); - staged.remove(); - fail(error, u"Could not write attachment: %1"_s.arg(why)); - return std::nullopt; - } - total += chunk.size(); - } - if (!staged.flush() || !syncFileDescriptor(staged.handle())) { - staged.remove(); - fail(error, u"Could not write attachment to disk: %1"_s.arg(errnoString())); - return std::nullopt; - } - staged.close(); - - const QString hash = QString::fromLatin1(sha.result().toHex()); - const QString target = path(hash); - const QString shard = QFileInfo(target).absolutePath(); - if (!QFileInfo::exists(shard)) { - if (!QDir().mkpath(shard) || !syncDirectory(m_paths.blobs())) { - QFile::remove(stagingPath); - fail(error, u"Could not create attachment directory."_s); - return std::nullopt; - } - } - - if (QFileInfo::exists(target)) { - // Same content already stored. - QFile::remove(stagingPath); - } else { - if (std::rename(QFile::encodeName(stagingPath).constData(), - QFile::encodeName(target).constData()) != 0) { - const QString why = errnoString(); - QFile::remove(stagingPath); - fail(error, u"Could not store attachment: %1"_s.arg(why)); - return std::nullopt; - } - if (!syncDirectory(shard)) { - fail(error, u"Could not store attachment durably: %1"_s.arg(errnoString())); - return std::nullopt; - } - } - return Installed{hash, total}; -} - -std::optional BlobStore::installFile(const QString &filePath, QString *error) -{ - QFile file(filePath); - if (!file.open(QIODevice::ReadOnly)) { - fail(error, u"Could not open %1: %2"_s.arg(QFileInfo(filePath).fileName(), file.errorString())); - return std::nullopt; - } - return install(file, error); -} - -std::optional BlobStore::installBytes(const QByteArray &bytes, QString *error) -{ - QBuffer buffer; - buffer.setData(bytes); - buffer.open(QIODevice::ReadOnly); - return install(buffer, error); -} - -QString BlobStore::path(const QString &hash) const -{ - if (!isValidBlobHash(hash)) - return {}; - return m_paths.blobs() + u'/' + hash.left(2) + u'/' + hash; -} - -bool BlobStore::contains(const QString &hash) const -{ - const QString p = path(hash); - return !p.isEmpty() && QFileInfo::exists(p); -} - -} // namespace onotes diff --git a/src/core/BlobStore.h b/src/core/BlobStore.h deleted file mode 100644 index d8b6002..0000000 --- a/src/core/BlobStore.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include "LibraryPaths.h" - -#include - -#include - -class QIODevice; - -namespace onotes { - -// Content-addressed attachment bytes: blobs//. -// Files are written to staging, fsynced, and renamed into place before any -// database row refers to them, so a committed reference always resolves. -class BlobStore -{ -public: - struct Installed { - QString hash; - qint64 size = 0; - }; - - explicit BlobStore(LibraryPaths paths); - - // Creates directories and discards staging files left by an interrupted run. - bool prepare(QString *error); - - std::optional install(QIODevice &source, QString *error); - std::optional installFile(const QString &path, QString *error); - std::optional installBytes(const QByteArray &bytes, QString *error); - - // Empty when `hash` is not a well-formed blob hash. - QString path(const QString &hash) const; - bool contains(const QString &hash) const; - -private: - LibraryPaths m_paths; -}; - -// fsync helpers; return false on failure. -bool syncFileDescriptor(int fd); -bool syncDirectory(const QString &path); - -} // namespace onotes diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt deleted file mode 100644 index 0c62e42..0000000 --- a/src/core/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -add_library(notes_core STATIC - BlobStore.cpp BlobStore.h - Database.cpp Database.h - DocumentConverter.cpp DocumentConverter.h - LibraryBackup.cpp LibraryBackup.h - LibraryPaths.cpp LibraryPaths.h - LibraryService.cpp LibraryService.h - NoteExchange.cpp NoteExchange.h - NoteStore.cpp NoteStore.h - RichDocument.cpp RichDocument.h - SampleLibrary.cpp SampleLibrary.h - ThemePalette.cpp ThemePalette.h -) - -target_include_directories(notes_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -target_link_libraries(notes_core - PUBLIC Qt6::Core Qt6::Gui - PRIVATE PkgConfig::SQLITE3) -target_compile_definitions(notes_core PUBLIC - ONOTES_APP_ID="${ONOTES_APP_ID}" - ONOTES_VERSION="${PROJECT_VERSION}") diff --git a/src/core/Database.cpp b/src/core/Database.cpp deleted file mode 100644 index e0fdf7b..0000000 --- a/src/core/Database.cpp +++ /dev/null @@ -1,225 +0,0 @@ -#include "Database.h" - -#include - -#include - -namespace onotes { - -Statement::Statement(sqlite3 *db, const char *sql) : m_db(db) -{ - if (sqlite3_prepare_v2(db, sql, -1, &m_stmt, nullptr) != SQLITE_OK) { - m_stmt = nullptr; - m_failed = true; - } -} - -Statement::Statement(Statement &&other) noexcept - : m_db(other.m_db), m_stmt(other.m_stmt), m_failed(other.m_failed) -{ - other.m_stmt = nullptr; -} - -Statement &Statement::operator=(Statement &&other) noexcept -{ - if (this != &other) { - sqlite3_finalize(m_stmt); - m_db = other.m_db; - m_stmt = other.m_stmt; - m_failed = other.m_failed; - other.m_stmt = nullptr; - } - return *this; -} - -Statement::~Statement() -{ - sqlite3_finalize(m_stmt); -} - -Statement &Statement::bind(int index, const QString &value) -{ - if (!m_stmt) - return *this; - const QByteArray utf8 = value.toUtf8(); - if (sqlite3_bind_text(m_stmt, index, utf8.constData(), int(utf8.size()), SQLITE_TRANSIENT) != SQLITE_OK) - m_failed = true; - return *this; -} - -Statement &Statement::bind(int index, qint64 value) -{ - if (m_stmt && sqlite3_bind_int64(m_stmt, index, value) != SQLITE_OK) - m_failed = true; - return *this; -} - -Statement &Statement::bindNull(int index) -{ - if (m_stmt && sqlite3_bind_null(m_stmt, index) != SQLITE_OK) - m_failed = true; - return *this; -} - -bool Statement::next() -{ - if (!m_stmt || m_failed) - return false; - const int rc = sqlite3_step(m_stmt); - if (rc == SQLITE_ROW) - return true; - if (rc != SQLITE_DONE) - m_failed = true; - return false; -} - -bool Statement::exec() -{ - while (next()) { - } - return !m_failed; -} - -QString Statement::text(int column) const -{ - const auto *data = reinterpret_cast(sqlite3_column_text(m_stmt, column)); - if (!data) - return {}; - return QString::fromUtf8(data, sqlite3_column_bytes(m_stmt, column)); -} - -qint64 Statement::int64(int column) const -{ - return sqlite3_column_int64(m_stmt, column); -} - -bool Statement::isNull(int column) const -{ - return sqlite3_column_type(m_stmt, column) == SQLITE_NULL; -} - -Database::~Database() -{ - close(); -} - -bool Database::open(const QString &path, QString *error) -{ - return openWithFlags(path, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, error); -} - -bool Database::openReadOnly(const QString &path, QString *error) -{ - return openWithFlags(path, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, error); -} - -bool Database::openWithFlags(const QString &path, int flags, QString *error) -{ - close(); - const int rc = sqlite3_open_v2(QFile::encodeName(path).constData(), &m_db, flags, nullptr); - if (rc != SQLITE_OK) { - if (error) - *error = m_db ? QString::fromUtf8(sqlite3_errmsg(m_db)) : QStringLiteral("out of memory"); - close(); - return false; - } - sqlite3_extended_result_codes(m_db, 1); - sqlite3_busy_timeout(m_db, 5000); - return true; -} - -void Database::close() -{ - if (m_db) { - sqlite3_close_v2(m_db); - m_db = nullptr; - } -} - -bool Database::exec(const char *sql) -{ - return sqlite3_exec(m_db, sql, nullptr, nullptr, nullptr) == SQLITE_OK; -} - -Statement Database::prepare(const char *sql) -{ - return Statement(m_db, sql); -} - -QString Database::lastError() const -{ - return m_db ? QString::fromUtf8(sqlite3_errmsg(m_db)) : QString(); -} - -QString Database::friendlyError() const -{ - if (!m_db) - return QStringLiteral("The notes library isn't open."); - switch (sqlite3_extended_errcode(m_db) & 0xff) { - case SQLITE_FULL: - return QStringLiteral("Your disk is full. Free up some space and try again."); - case SQLITE_READONLY: - return QStringLiteral("Your notes folder is read-only, so changes can't be saved."); - case SQLITE_IOERR: - return QStringLiteral("The disk reported an error while saving."); - case SQLITE_CORRUPT: - case SQLITE_NOTADB: - return QStringLiteral("The notes database is damaged. Restore it from a backup."); - case SQLITE_BUSY: - case SQLITE_LOCKED: - return QStringLiteral("The notes database is busy. Try again in a moment."); - case SQLITE_CANTOPEN: - return QStringLiteral("The notes database can't be opened. Check the folder's permissions."); - default: - return lastError(); - } -} - -int Database::changes() const -{ - return m_db ? sqlite3_changes(m_db) : 0; -} - -int Database::userVersion() -{ - Statement s = prepare("PRAGMA user_version"); - return s.next() ? int(s.int64(0)) : -1; -} - -Transaction::Transaction(Database &db) : m_db(db) -{ - if (sqlite3_get_autocommit(m_db.handle()) == 0) { - static int counter = 0; - m_savepoint = "tx" + QByteArray::number(++counter); - m_active = m_db.exec(("SAVEPOINT " + m_savepoint).constData()); - } else { - m_active = m_db.exec("BEGIN IMMEDIATE"); - } -} - -Transaction::~Transaction() -{ - if (!m_active) - return; - if (m_savepoint.isEmpty()) { - m_db.exec("ROLLBACK"); - } else { - m_db.exec(("ROLLBACK TO " + m_savepoint).constData()); - m_db.exec(("RELEASE " + m_savepoint).constData()); - } -} - -bool Transaction::commit() -{ - if (!m_active) - return false; - m_active = false; - if (!m_savepoint.isEmpty()) - return m_db.exec(("RELEASE " + m_savepoint).constData()); - if (m_db.exec("COMMIT")) - return true; - m_db.exec("ROLLBACK"); - return false; -} - -} // namespace onotes diff --git a/src/core/Database.h b/src/core/Database.h deleted file mode 100644 index 84e4eb4..0000000 --- a/src/core/Database.h +++ /dev/null @@ -1,91 +0,0 @@ -#pragma once - -#include -#include - -struct sqlite3; -struct sqlite3_stmt; - -namespace onotes { - -class Statement -{ -public: - Statement() = default; - Statement(sqlite3 *db, const char *sql); - Statement(Statement &&other) noexcept; - Statement &operator=(Statement &&other) noexcept; - Statement(const Statement &) = delete; - Statement &operator=(const Statement &) = delete; - ~Statement(); - - bool isValid() const { return m_stmt != nullptr; } - - // Strings always bind as TEXT (a null QString binds ''); use bindNull for NULL. - Statement &bind(int index, const QString &value); - Statement &bind(int index, qint64 value); - Statement &bindNull(int index); - - // Returns true while a row is available. - bool next(); - // Runs to completion; true on success. - bool exec(); - bool failed() const { return m_failed; } - - QString text(int column) const; - qint64 int64(int column) const; - bool isNull(int column) const; - -private: - sqlite3 *m_db = nullptr; - sqlite3_stmt *m_stmt = nullptr; - bool m_failed = false; -}; - -class Database -{ -public: - Database() = default; - Database(const Database &) = delete; - Database &operator=(const Database &) = delete; - ~Database(); - - bool open(const QString &path, QString *error); - bool openReadOnly(const QString &path, QString *error); - void close(); - bool isOpen() const { return m_db != nullptr; } - - bool exec(const char *sql); - Statement prepare(const char *sql); - QString lastError() const; - // The last error in words a person can act on (disk full, read-only...). - QString friendlyError() const; - int userVersion(); - // Rows changed by the most recent INSERT, UPDATE or DELETE. - int changes() const; - - sqlite3 *handle() const { return m_db; } - -private: - bool openWithFlags(const QString &path, int flags, QString *error); - - sqlite3 *m_db = nullptr; -}; - -// BEGIN IMMEDIATE ... COMMIT, rolled back unless committed. Inside another -// transaction it becomes a savepoint, so helpers can use it freely. -class Transaction -{ -public: - explicit Transaction(Database &db); - ~Transaction(); - bool isActive() const { return m_active; } - bool commit(); - -private: - Database &m_db; - bool m_active = false; - QByteArray m_savepoint; // non-empty when nested -}; - -} // namespace onotes diff --git a/src/core/DocumentConverter.cpp b/src/core/DocumentConverter.cpp deleted file mode 100644 index 461b471..0000000 --- a/src/core/DocumentConverter.cpp +++ /dev/null @@ -1,648 +0,0 @@ -#include "DocumentConverter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -namespace { - -constexpr char16_t kObjectReplacement = 0xFFFC; -constexpr auto kTableIdProperty = "onotesId"; - -class BlockIdentity : public QTextBlockUserData -{ -public: - explicit BlockIdentity(QString id) : id(std::move(id)) {} - QString id; -}; - -// ---------------------------------------------------------------- writing - -class Writer -{ -public: - Writer(QTextCursor cursor, const DocumentStyle &style) - : m_cursor(std::move(cursor)), m_style(style) - { - } - - void writeBlocks(const QList &blocks) - { - for (const Block &block : blocks) { - if (block.type == Block::Type::Table) - writeTable(block); - else - writeTextBlock(block); - } - } - -private: - // Positions the cursor on an empty block ready to receive content, - // without inheriting list membership from the previous block. - void beginBlock() - { - if (!m_fresh) { - m_cursor.insertBlock(); - if (QTextList *list = m_cursor.currentList()) - list->remove(m_cursor.block()); - } - m_fresh = false; - } - - void writeTextBlock(const Block &block) - { - beginBlock(); - - QTextBlockFormat bf = m_style.bodyBlockFormat(); - if (block.type == Block::Type::Heading) { - bf.setHeadingLevel(block.level); - bf.setTopMargin(block.level == 1 ? 4 : 10); - bf.setBottomMargin(4); - } - if (block.type == Block::Type::ListItem && block.list == ListKind::Check) { - bf.setMarker(block.checked ? QTextBlockFormat::MarkerType::Checked - : QTextBlockFormat::MarkerType::Unchecked); - } - m_cursor.setBlockFormat(bf); - - const QTextCharFormat base = DocumentConverter::charFormatForBlock(block, m_style); - m_cursor.setBlockCharFormat(withCellProperties(m_cursor.blockCharFormat(), base)); - - if (block.type == Block::Type::ListItem) - attachToList(block); - else - m_lists.clear(); - - for (const Span &span : block.spans) - writeSpan(span, base); - - m_cursor.setCharFormat(base); - DocumentConverter::setBlockId(m_cursor.block(), block.id); - } - - void attachToList(const Block &block) - { - // Lists deeper than this item end here, so later siblings at those - // depths restart their numbering. - for (auto it = m_lists.begin(); it != m_lists.end();) { - if (it.key() > block.indent) - it = m_lists.erase(it); - else - ++it; - } - auto existing = m_lists.find(block.indent); - if (existing != m_lists.end() && existing->kind == block.list) { - existing->list->add(m_cursor.block()); - return; - } - QTextList *list = m_cursor.createList(DocumentConverter::listFormat(block.list, block.indent)); - m_lists.insert(block.indent, {block.list, list}); - } - - void writeSpan(const Span &span, const QTextCharFormat &base) - { - switch (span.kind) { - case Span::Kind::Text: { - QTextCharFormat fmt = base; - DocumentConverter::applyMarks(fmt, span.marks, span.href, m_style); - QString text = span.text; - text.replace(u'\n', QChar::LineSeparator); - text.remove(QChar(kObjectReplacement)); - m_cursor.insertText(text, fmt); - break; - } - case Span::Kind::Image: { - QTextImageFormat fmt; - fmt.setName(DocumentConverter::imageResourceName(span.ref)); - if (span.width > 0 && span.height > 0) { - qreal w = span.width; - qreal h = span.height; - if (w > m_style.maxImageWidth) { - h = h * m_style.maxImageWidth / w; - w = m_style.maxImageWidth; - } - fmt.setWidth(w); - fmt.setHeight(h); - } - fmt.setProperty(QTextFormat::ImageAltText, span.alt); - // Keep the logical size from the schema so a narrower display - // does not rewrite the stored dimensions. - fmt.setProperty(TextProperty::ImageLogicalSize, QSize(span.width, span.height)); - m_cursor.insertImage(fmt); - break; - } - case Span::Kind::Attachment: { - QTextImageFormat fmt; - fmt.setName(DocumentConverter::attachmentResourceName(span.ref)); - fmt.setWidth(m_style.attachmentChipSize.width()); - fmt.setHeight(m_style.attachmentChipSize.height()); - fmt.setVerticalAlignment(QTextCharFormat::AlignMiddle); - m_cursor.insertImage(fmt); - break; - } - } - } - - void writeTable(const Block &block) - { - m_lists.clear(); - QTextTable *table = m_cursor.insertTable(block.rows, block.columns, - DocumentConverter::tableFormat(m_style)); - table->setProperty(kTableIdProperty, block.id); - - for (const TableCell &cell : block.cells) { - if (cell.rowSpan > 1 || cell.columnSpan > 1) - table->mergeCells(cell.row, cell.column, cell.rowSpan, cell.columnSpan); - } - for (const TableCell &cell : block.cells) { - const QTextTableCell target = table->cellAt(cell.row, cell.column); - Writer inner(target.firstCursorPosition(), m_style); - inner.writeBlocks(cell.blocks); - } - - // Qt always keeps a block after a table; the next block reuses it. - m_cursor = table->lastCursorPosition(); - m_cursor.movePosition(QTextCursor::NextBlock); - m_fresh = true; - } - - // The first block of a table cell carries the cell's own format (spans, - // padding) in its block char format; replacing it would unmerge cells. - static QTextCharFormat withCellProperties(const QTextCharFormat ¤t, const QTextCharFormat &base) - { - QTextCharFormat out = base; - const auto props = current.properties(); - for (auto it = props.cbegin(); it != props.cend(); ++it) { - if (it.key() >= QTextFormat::TableCellRowSpan && it.key() < QTextFormat::ImageName) - out.setProperty(it.key(), it.value()); - } - return out; - } - - struct ActiveList { - ListKind kind; - QTextList *list; - }; - - QTextCursor m_cursor; - const DocumentStyle &m_style; - bool m_fresh = true; - QHash m_lists; -}; - -// ---------------------------------------------------------------- reading - -class Reader -{ -public: - explicit Reader(ConversionReport *report) : m_report(report) {} - - QList readFrame(QTextFrame::iterator it) - { - struct Item { - QTextBlock block; - QTextFrame *frame = nullptr; - }; - QList items; - for (; !it.atEnd(); ++it) { - if (QTextFrame *frame = it.currentFrame()) - items.append(Item{QTextBlock(), frame}); - else if (it.currentBlock().isValid()) - items.append(Item{it.currentBlock(), nullptr}); - } - - QList blocks; - for (qsizetype i = 0; i < items.size(); ++i) { - const Item &item = items[i]; - if (item.frame) { - if (auto *table = qobject_cast(item.frame)) { - blocks.append(readTable(table)); - } else { - warn(u"Framed content was flattened into paragraphs."_s); - blocks.append(readFrame(item.frame->begin())); - } - continue; - } - if (isStructural(items, i)) - continue; - blocks.append(readBlock(item.block)); - } - return blocks; - } - -private: - // Qt requires a text block before and after every table in a frame. An - // empty paragraph that only exists to satisfy that is not content. - template - static bool isStructural(const Items &items, qsizetype i) - { - const QTextBlock &block = items[i].block; - if (block.length() > 1 || block.textList()) - return false; - const bool prevTable = i > 0 && items[i - 1].frame; - const bool nextTable = i + 1 < items.size() && items[i + 1].frame; - const bool prevBoundary = i == 0 || prevTable; - const bool nextBoundary = i + 1 == items.size() || nextTable; - return prevBoundary && nextBoundary && (prevTable || nextTable); - } - - QString claimId(QString id) - { - if (id.isEmpty() || m_seen.contains(id)) - id = newId(); - m_seen.insert(id); - return id; - } - - Block readBlock(const QTextBlock &textBlock) - { - Block block; - const QTextBlockFormat bf = textBlock.blockFormat(); - - QString id = DocumentConverter::blockId(textBlock); - const QString claimed = claimId(id); - if (claimed != id) - DocumentConverter::setBlockId(textBlock, claimed); - block.id = claimed; - - if (textBlock.textList()) { - const QTextListFormat lf = textBlock.textList()->format(); - block.type = Block::Type::ListItem; - block.list = DocumentConverter::listKindOf(textBlock); - block.indent = std::clamp(lf.indent() - 1, 0, 16); - block.checked = bf.marker() == QTextBlockFormat::MarkerType::Checked; - } else if (bf.headingLevel() > 0) { - block.type = Block::Type::Heading; - block.level = std::min(bf.headingLevel(), 3); - } - // A checkbox marker outside a list is ignored: Qt's Markdown importer - // can leave one on blocks that follow a task list. - - const bool inHeading = block.type == Block::Type::Heading; - for (auto it = textBlock.begin(); !it.atEnd(); ++it) { - const QTextFragment fragment = it.fragment(); - if (!fragment.isValid()) - continue; - const QTextCharFormat cf = fragment.charFormat(); - const QString text = fragment.text(); - if (cf.isImageFormat()) { - readObjects(cf.toImageFormat(), text.count(QChar(kObjectReplacement)), &block); - continue; - } - QString clean = text; - clean.remove(QChar(kObjectReplacement)); - clean.replace(QChar::LineSeparator, u'\n'); - clean.replace(QChar::ParagraphSeparator, u'\n'); - if (clean.isEmpty()) - continue; - - QString href; - if (cf.isAnchor()) { - href = cf.anchorHref(); - if (!DocumentConverter::isAllowedLink(href)) { - if (!href.isEmpty()) - warn(u"A link with an unsupported address was removed."_s); - href.clear(); - } - } - appendText(&block, clean, DocumentConverter::marksOf(cf, inHeading), href); - } - return block; - } - - void readObjects(const QTextImageFormat &fmt, qsizetype count, Block *block) - { - const QString name = fmt.name(); - for (qsizetype n = 0; n < count; ++n) { - if (const QString hash = DocumentConverter::blobHashFromResource(name); !hash.isEmpty()) { - QSize logical = fmt.property(TextProperty::ImageLogicalSize).toSize(); - if (!logical.isValid() || logical.isEmpty()) - logical = QSize(qRound(fmt.width()), qRound(fmt.height())); - block->spans.append(Span::image(hash, logical.width(), logical.height(), - fmt.property(QTextFormat::ImageAltText).toString())); - } else if (const QString id = DocumentConverter::attachmentIdFromResource(name); !id.isEmpty()) { - block->spans.append(Span::attachment(id)); - } else { - warn(u"An image that isn't stored in this library was not kept."_s); - } - } - } - - static void appendText(Block *block, const QString &text, quint32 marks, const QString &href) - { - if (!block->spans.isEmpty()) { - Span &last = block->spans.last(); - if (last.kind == Span::Kind::Text && last.marks == marks && last.href == href) { - last.text += text; - return; - } - } - block->spans.append(Span::plain(text, marks, href)); - } - - Block readTable(QTextTable *table) - { - Block block; - block.type = Block::Type::Table; - const QString id = table->property(kTableIdProperty).toString(); - block.id = claimId(id); - if (block.id != id) - table->setProperty(kTableIdProperty, block.id); - block.rows = table->rows(); - block.columns = table->columns(); - for (int r = 0; r < block.rows; ++r) { - for (int c = 0; c < block.columns; ++c) { - const QTextTableCell cell = table->cellAt(r, c); - if (!cell.isValid() || cell.row() != r || cell.column() != c) - continue; // covered by a merged cell - TableCell out; - out.row = r; - out.column = c; - out.rowSpan = cell.rowSpan(); - out.columnSpan = cell.columnSpan(); - out.blocks = readFrame(cell.begin()); - block.cells.append(out); - } - } - return block; - } - - void warn(const QString &message) - { - if (m_report) - m_report->warn(message); - } - - ConversionReport *m_report; - QSet m_seen; -}; - -} // namespace - -qreal DocumentStyle::headingPixelSize(int level) const -{ - switch (level) { - case 1: return std::round(bodyPixelSize * 1.75); - case 2: return std::round(bodyPixelSize * 1.35); - default: return std::round(bodyPixelSize * 1.15); - } -} - -QTextBlockFormat DocumentStyle::bodyBlockFormat() const -{ - QTextBlockFormat bf; - bf.setLineHeight(std::round(bodyPixelSize * lineSpacing), QTextBlockFormat::LineDistanceHeight); - return bf; -} - -void ConversionReport::warn(const QString &message) -{ - if (!warnings.contains(message)) - warnings.append(message); -} - -void DocumentConverter::load(const RichDocument &source, QTextDocument *doc, const DocumentStyle &style) -{ - doc->setUndoRedoEnabled(false); - doc->clear(); - { - QTextCursor cursor(doc); - cursor.beginEditBlock(); - Writer writer(cursor, style); - writer.writeBlocks(source.blocks); - cursor.endEditBlock(); - } - doc->setUndoRedoEnabled(true); - doc->setModified(false); -} - -void DocumentConverter::insert(const RichDocument &source, QTextCursor &cursor, const DocumentStyle &style) -{ - QTextDocument scratch; - scratch.setDefaultFont(cursor.document()->defaultFont()); - load(source, &scratch, style); - cursor.insertFragment(QTextDocumentFragment(&scratch)); -} - -RichDocument DocumentConverter::read(QTextDocument *doc, ConversionReport *report) -{ - Reader reader(report); - RichDocument out; - out.blocks = reader.readFrame(doc->rootFrame()->begin()); - if (out.blocks.isEmpty()) - out.blocks.append(Block::paragraph()); - return out; -} - -RichDocument DocumentConverter::readSelection(const QTextCursor &cursor, ConversionReport *report) -{ - QTextDocument scratch; - QTextCursor(&scratch).insertFragment(cursor.selection()); - RichDocument out = read(&scratch, report); - // A selection that starts at a block boundary is inserted after the - // scratch document's initial empty block; that block is not content. - const int start = cursor.selectionStart(); - const bool startsAtBlock = cursor.document()->findBlock(start).position() == start; - if (startsAtBlock && out.blocks.size() > 1 && out.blocks.first().isEmptyParagraph()) - out.blocks.removeFirst(); - return out; -} - -RichDocument DocumentConverter::fromHtml(const QString &html, ConversionReport *report) -{ - QTextDocument scratch; - scratch.setHtml(html); - return read(&scratch, report); -} - -RichDocument DocumentConverter::fromPlainText(const QString &text) -{ - RichDocument doc; - QString normalized = text; - normalized.replace(u"\r\n"_s, u"\n"_s); - for (const QString &line : normalized.split(u'\n')) { - Block b = Block::paragraph(); - if (!line.isEmpty()) - b.spans.append(Span::plain(line)); - doc.blocks.append(b); - } - return doc; -} - -QTextCharFormat DocumentConverter::charFormatForBlock(const Block &block, const DocumentStyle &style) -{ - // Plain text color is left to the editor so theme changes need no rebuild. - QTextCharFormat fmt; - if (block.type == Block::Type::Heading) { - if (style.pointSizes) - fmt.setFontPointSize(style.headingPixelSize(block.level) * 0.75); - else - fmt.setProperty(QTextFormat::FontPixelSize, int(style.headingPixelSize(block.level))); - fmt.setFontWeight(QFont::Bold); - } - return fmt; -} - -void DocumentConverter::applyMarks(QTextCharFormat &fmt, quint32 marks, const QString &href, - const DocumentStyle &style) -{ - if (marks & Bold) - fmt.setFontWeight(QFont::Bold); - if (marks & Italic) - fmt.setFontItalic(true); - if (marks & Underline) - fmt.setFontUnderline(true); - if (marks & Strikethrough) - fmt.setFontStrikeOut(true); - if (marks & Highlight) { - fmt.setBackground(style.highlight); - fmt.setProperty(TextProperty::Highlight, true); - } - if (marks & Code) { - fmt.setFontFamilies({style.codeFamily}); - fmt.setFontFixedPitch(true); - fmt.setProperty(TextProperty::Code, true); - } - if (!href.isEmpty()) { - fmt.setAnchor(true); - fmt.setAnchorHref(href); - fmt.setForeground(style.link); - fmt.setFontUnderline(true); - } -} - -quint32 DocumentConverter::marksOf(const QTextCharFormat &cf, bool inHeading) -{ - quint32 marks = 0; - if (!inHeading && cf.fontWeight() >= QFont::DemiBold) - marks |= Bold; - if (cf.fontItalic()) - marks |= Italic; - // Links are drawn underlined; that is presentation, not a mark. - if (cf.fontUnderline() && !cf.isAnchor()) - marks |= Underline; - if (cf.fontStrikeOut()) - marks |= Strikethrough; - if (cf.boolProperty(TextProperty::Highlight)) - marks |= Highlight; - if (cf.boolProperty(TextProperty::Code) || cf.fontFixedPitch()) - marks |= Code; - return marks; -} - -ListKind DocumentConverter::listKindOf(const QTextBlock &block) -{ - const QTextList *list = block.textList(); - if (!list) - return ListKind::None; - if (block.blockFormat().marker() != QTextBlockFormat::MarkerType::NoMarker) - return ListKind::Check; - const QTextListFormat lf = list->format(); - if (lf.hasProperty(TextProperty::ListKind)) - return static_cast(lf.intProperty(TextProperty::ListKind)); - switch (lf.style()) { - case QTextListFormat::ListDecimal: - case QTextListFormat::ListLowerAlpha: - case QTextListFormat::ListUpperAlpha: - case QTextListFormat::ListLowerRoman: - case QTextListFormat::ListUpperRoman: - return ListKind::Ordered; - default: - return ListKind::Bullet; - } -} - -QTextListFormat DocumentConverter::listFormat(ListKind kind, int indent) -{ - static constexpr QTextListFormat::Style bullets[] = { - QTextListFormat::ListDisc, QTextListFormat::ListCircle, QTextListFormat::ListSquare}; - static constexpr QTextListFormat::Style ordered[] = { - QTextListFormat::ListDecimal, QTextListFormat::ListLowerAlpha, QTextListFormat::ListLowerRoman}; - QTextListFormat lf; - lf.setIndent(indent + 1); - lf.setStyle(kind == ListKind::Ordered ? ordered[indent % 3] : bullets[indent % 3]); - lf.setProperty(TextProperty::ListKind, int(kind)); - return lf; -} - -QTextTableFormat DocumentConverter::tableFormat(const DocumentStyle &style) -{ - QTextTableFormat tf; - tf.setBorder(1); - tf.setBorderBrush(style.tableBorder); - tf.setBorderStyle(QTextFrameFormat::BorderStyle_Solid); - tf.setBorderCollapse(true); - tf.setCellPadding(6); - tf.setCellSpacing(0); - tf.setTopMargin(8); - tf.setBottomMargin(8); - tf.setWidth(QTextLength(QTextLength::PercentageLength, 100)); - return tf; -} - -QString DocumentConverter::imageResourceName(const QString &blobHash) -{ - return u"blob:"_s + blobHash; -} - -QString DocumentConverter::attachmentResourceName(const QString &attachmentId) -{ - return u"attachment:"_s + attachmentId; -} - -QString DocumentConverter::blobHashFromResource(const QString &name) -{ - if (!name.startsWith(u"blob:")) - return {}; - const QString hash = name.mid(5); - return isValidBlobHash(hash) ? hash : QString(); -} - -QString DocumentConverter::attachmentIdFromResource(const QString &name) -{ - if (!name.startsWith(u"attachment:")) - return {}; - const QString id = name.mid(11); - return QUuid::fromString(id).isNull() ? QString() : id; -} - -QString DocumentConverter::blockId(const QTextBlock &block) -{ - if (auto *identity = dynamic_cast(block.userData())) - return identity->id; - return {}; -} - -void DocumentConverter::setBlockId(QTextBlock block, const QString &id) -{ - if (id.isEmpty()) - return; - block.setUserData(new BlockIdentity(id)); -} - -bool DocumentConverter::isAllowedLink(const QString &href) -{ - const QUrl url(href); - if (!url.isValid()) - return false; - static const QStringList schemes = {u"http"_s, u"https"_s, u"mailto"_s, u"note"_s}; - return schemes.contains(url.scheme().toLower()); -} - -} // namespace onotes diff --git a/src/core/DocumentConverter.h b/src/core/DocumentConverter.h deleted file mode 100644 index eab5823..0000000 --- a/src/core/DocumentConverter.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once - -#include "RichDocument.h" - -#include -#include -#include -#include - -class QTextBlock; -class QTextCharFormat; -class QTextCursor; -class QTextDocument; -class QTextTable; - -namespace onotes { - -// Presentation parameters applied when a RichDocument is laid into a -// QTextDocument. None of these are persisted; they come from the theme and -// user font settings, and changing them means reloading the document. -struct DocumentStyle { - qreal bodyPixelSize = 15; - // Extra space between lines, as a fraction of the body size. A fixed - // distance (not a proportional height) keeps lines holding images tight. - qreal lineSpacing = 0.35; - QColor link = QColor(0x2f, 0x6f, 0xd0); - QColor highlight = QColor(255, 204, 0, 110); - QColor tableBorder = QColor(0x90, 0x90, 0x90); - QString codeFamily = QStringLiteral("monospace"); - QSize attachmentChipSize = QSize(320, 52); - int maxImageWidth = 640; - // Print output (PDF) sizes type in points; the screen uses pixels. - bool pointSizes = false; - - qreal headingPixelSize(int level) const; - QTextBlockFormat bodyBlockFormat() const; -}; - -// Semantic markers stored on QTextFormats so that reading a document back -// does not have to guess from presentation (colors, sizes). -namespace TextProperty { -enum : int { - Highlight = QTextFormat::UserProperty + 1, - Code, - ListKind, - // Image size as stored in the schema, before display scaling. - ImageLogicalSize, -}; -} - -struct ConversionReport { - QStringList warnings; - void warn(const QString &message); -}; - -class DocumentConverter -{ -public: - // Replaces the contents of `doc` and clears its undo history. - static void load(const RichDocument &source, QTextDocument *doc, const DocumentStyle &style); - - // Inserts `source` at `cursor` as a single fragment (used for paste). - static void insert(const RichDocument &source, QTextCursor &cursor, const DocumentStyle &style); - - // Reads `doc` back into the schema. Blocks without an identity (new or - // pasted) are given one, stored as block user data so it is stable across - // subsequent reads but never duplicated by copy/paste or block splits. - static RichDocument read(QTextDocument *doc, ConversionReport *report = nullptr); - static RichDocument readSelection(const QTextCursor &cursor, ConversionReport *report = nullptr); - static RichDocument fromHtml(const QString &html, ConversionReport *report = nullptr); - static RichDocument fromPlainText(const QString &text); - - // Formats shared with the editing commands. - static QTextCharFormat charFormatForBlock(const Block &block, const DocumentStyle &style); - static void applyMarks(QTextCharFormat &format, quint32 marks, const QString &href, - const DocumentStyle &style); - static quint32 marksOf(const QTextCharFormat &format, bool inHeading); - static ListKind listKindOf(const QTextBlock &block); - static QTextListFormat listFormat(ListKind kind, int indent); - static QTextTableFormat tableFormat(const DocumentStyle &style); - - static QString imageResourceName(const QString &blobHash); - static QString attachmentResourceName(const QString &attachmentId); - // Returns the blob hash / attachment id for a resource name, or empty. - static QString blobHashFromResource(const QString &name); - static QString attachmentIdFromResource(const QString &name); - - static QString blockId(const QTextBlock &block); - static void setBlockId(QTextBlock block, const QString &id); - static bool isAllowedLink(const QString &href); -}; - -} // namespace onotes diff --git a/src/core/LibraryBackup.cpp b/src/core/LibraryBackup.cpp deleted file mode 100644 index a35fb28..0000000 --- a/src/core/LibraryBackup.cpp +++ /dev/null @@ -1,277 +0,0 @@ -#include "LibraryBackup.h" - -#include "BlobStore.h" -#include "Database.h" -#include "NoteStore.h" - -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -namespace { - -constexpr auto kFormat = "omarchy-notes-backup"; -const QStringList kDatabaseFiles = {u"library.sqlite3"_s, u"library.sqlite3-wal"_s, u"library.sqlite3-shm"_s}; - -bool fail(QString *error, const QString &message) -{ - if (error) - *error = message; - return false; -} - -bool copyDurably(const QString &from, const QString &to) -{ - if (!QFile::copy(from, to)) - return false; - QFile copied(to); - return copied.open(QIODevice::ReadWrite) && syncFileDescriptor(copied.handle()); -} - -bool writeDurably(const QString &path, const QByteArray &data) -{ - QFile file(path); - if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) - return false; - return file.write(data) == data.size() && file.flush() && syncFileDescriptor(file.handle()); -} - -bool renamePath(const QString &from, const QString &to) -{ - return std::rename(QFile::encodeName(from).constData(), QFile::encodeName(to).constData()) == 0; -} - -// Copies blobs/xx/ files, fsyncing each file and directory. -bool copyBlobTree(const QString &fromRoot, const QString &toRoot, QString *error) -{ - if (!QDir().mkpath(toRoot)) - return fail(error, u"Couldn't create %1."_s.arg(toRoot)); - QDirIterator it(fromRoot, QDir::Files, QDirIterator::Subdirectories); - QStringList shards; - while (it.hasNext()) { - const QFileInfo file(it.next()); - const QString shard = file.dir().dirName(); - const QString targetDir = toRoot + u'/' + shard; - if (!shards.contains(shard)) { - if (!QDir().mkpath(targetDir)) - return fail(error, u"Couldn't create %1."_s.arg(targetDir)); - shards << shard; - } - if (!copyDurably(file.filePath(), targetDir + u'/' + file.fileName())) - return fail(error, u"Couldn't copy attachment %1."_s.arg(file.fileName())); - } - for (const QString &shard : shards) - syncDirectory(toRoot + u'/' + shard); - syncDirectory(toRoot); - return true; -} - -} // namespace - -QString defaultBackupName() -{ - return u"Omarchy Notes Backup "_s + QDateTime::currentDateTime().toString(u"yyyy-MM-dd HHmm"_s); -} - -std::optional NoteStore::backupTo(const QString &directory, QString *error) -{ - const QString target = QDir::cleanPath(directory); - if (QFileInfo::exists(target)) { - fail(error, u"%1 already exists. Choose a new name for the backup."_s.arg(target)); - return std::nullopt; - } - // Build in a temporary folder and rename at the end, so a half-written - // backup never looks like a real one. - const QString partial = target + u".partial"_s; - QDir(partial).removeRecursively(); - if (!QDir().mkpath(partial)) { - fail(error, u"Couldn't create the backup folder at %1."_s.arg(target)); - return std::nullopt; - } - auto abandon = [&](const QString &message) -> std::optional { - QDir(partial).removeRecursively(); - fail(error, message); - return std::nullopt; - }; - - const QString snapshotPath = partial + u"/library.sqlite3"_s; - QString dbError; - if (!backupDatabase(snapshotPath, &dbError)) - return abandon(u"Couldn't copy the notes database: %1"_s.arg(dbError)); - - BackupManifest manifest; - manifest.path = target; - manifest.appVersion = QStringLiteral(ONOTES_VERSION); - manifest.schemaVersion = SchemaVersion; - manifest.createdAt = QDateTime::currentMSecsSinceEpoch(); - { - Database snapshot; - if (!snapshot.open(snapshotPath, &dbError)) - return abandon(dbError); - // A standalone single file, readable without WAL side files. - snapshot.exec("PRAGMA journal_mode=DELETE"); - Statement notes = snapshot.prepare("SELECT COUNT(*) FROM notes"); - manifest.notes = notes.next() ? int(notes.int64(0)) : 0; - - // Copy exactly the attachments the snapshot records. They're - // content-addressed and never modified, so copying after the - // snapshot is consistent. - Statement blobs = snapshot.prepare("SELECT hash, size FROM blobs"); - QStringList shards; - while (blobs.next()) { - const QString hash = blobs.text(0); - const QString source = m_blobs.path(hash); - if (source.isEmpty() || QFileInfo(source).size() != blobs.int64(1)) - return abandon(u"An attachment is missing or damaged (%1). The backup was not written."_s.arg(hash.left(12))); - const QString shardDir = partial + u"/blobs/"_s + hash.left(2); - if (!shards.contains(hash.left(2))) { - QDir().mkpath(shardDir); - shards << hash.left(2); - } - if (!copyDurably(source, shardDir + u'/' + hash)) - return abandon(u"Couldn't copy an attachment into the backup."_s); - ++manifest.blobs; - manifest.bytes += blobs.int64(1); - } - for (const QString &shard : shards) - syncDirectory(partial + u"/blobs/"_s + shard); - } - QDir().mkpath(partial + u"/blobs"_s); - syncDirectory(partial + u"/blobs"_s); - manifest.bytes += QFileInfo(snapshotPath).size(); - - QJsonObject json; - json[u"format"] = QLatin1StringView(kFormat); - json[u"formatVersion"] = BackupManifest::FormatVersion; - json[u"appVersion"] = manifest.appVersion; - json[u"schemaVersion"] = manifest.schemaVersion; - json[u"createdAt"] = manifest.createdAt; - json[u"notes"] = manifest.notes; - json[u"blobs"] = manifest.blobs; - json[u"bytes"] = manifest.bytes; - if (!writeDurably(partial + u"/manifest.json"_s, QJsonDocument(json).toJson())) - return abandon(u"Couldn't finish writing the backup."_s); - syncDirectory(partial); - if (!renamePath(partial, target)) - return abandon(u"Couldn't finish writing the backup."_s); - syncDirectory(QFileInfo(target).absolutePath()); - return manifest; -} - -std::optional NoteStore::inspectBackup(const QString &directory, QString *error) -{ - const QString dir = QDir::cleanPath(directory); - QFile manifestFile(dir + u"/manifest.json"_s); - if (!manifestFile.open(QIODevice::ReadOnly)) { - fail(error, u"This folder isn't an Omarchy Notes backup (no manifest.json)."_s); - return std::nullopt; - } - const QJsonObject json = QJsonDocument::fromJson(manifestFile.readAll()).object(); - if (json[u"format"].toString() != QLatin1StringView(kFormat)) { - fail(error, u"This folder isn't an Omarchy Notes backup."_s); - return std::nullopt; - } - BackupManifest manifest; - manifest.path = dir; - manifest.appVersion = json[u"appVersion"].toString(); - manifest.schemaVersion = json[u"schemaVersion"].toInt(); - manifest.createdAt = json[u"createdAt"].toInteger(); - manifest.notes = json[u"notes"].toInt(); - manifest.blobs = json[u"blobs"].toInt(); - manifest.bytes = json[u"bytes"].toInteger(); - if (json[u"formatVersion"].toInt() > BackupManifest::FormatVersion || manifest.schemaVersion > SchemaVersion) { - fail(error, u"This backup was made by a newer version of Omarchy Notes (%1). Update the app to restore it."_s - .arg(manifest.appVersion)); - return std::nullopt; - } - - Database db; - QString dbError; - if (!db.openReadOnly(dir + u"/library.sqlite3"_s, &dbError)) { - fail(error, u"The backup's notes database can't be opened: %1"_s.arg(dbError)); - return std::nullopt; - } - Statement check = db.prepare("PRAGMA quick_check"); - if (!check.next() || check.text(0) != u"ok") { - fail(error, u"The backup's notes database is damaged."_s); - return std::nullopt; - } - Statement blobs = db.prepare("SELECT hash, size FROM blobs"); - const BlobStore store(LibraryPaths::at(dir)); - while (blobs.next()) { - const QString path = store.path(blobs.text(0)); - if (path.isEmpty() || QFileInfo(path).size() != blobs.int64(1)) { - fail(error, u"The backup is incomplete: some attachments are missing."_s); - return std::nullopt; - } - } - return manifest; -} - -bool replaceLibraryFiles(const LibraryPaths &paths, const QString &backupDir, QString *safetyDir, - QString *error) -{ - const QString root = paths.root; - const QString safety = root + u".before-restore-"_s - + QDateTime::currentDateTime().toString(u"yyyyMMdd-HHmmss"_s); - if (!QDir().mkpath(safety)) - return fail(error, u"Couldn't set your current notes aside at %1."_s.arg(safety)); - - // Set the current library aside. Renames within one filesystem are - // atomic and cheap, and nothing is deleted. - for (const QString &name : kDatabaseFiles) { - const QString from = root + u'/' + name; - if (QFileInfo::exists(from) && !renamePath(from, safety + u'/' + name)) - return fail(error, u"Couldn't set your current notes aside."_s); - } - if (QFileInfo::exists(paths.blobs()) && !renamePath(paths.blobs(), safety + u"/blobs"_s)) { - rollbackLibraryFiles(paths, safety, nullptr); - return fail(error, u"Couldn't set your current attachments aside."_s); - } - syncDirectory(root); - syncDirectory(safety); - - QString copyError; - if (!copyDurably(backupDir + u"/library.sqlite3"_s, paths.database()) - || !copyBlobTree(backupDir + u"/blobs"_s, paths.blobs(), ©Error)) { - rollbackLibraryFiles(paths, safety, nullptr); - return fail(error, copyError.isEmpty() ? u"Couldn't copy the backup into place."_s : copyError); - } - syncDirectory(root); - if (safetyDir) - *safetyDir = safety; - return true; -} - -bool rollbackLibraryFiles(const LibraryPaths &paths, const QString &safetyDir, QString *error) -{ - for (const QString &name : kDatabaseFiles) - QFile::remove(paths.root + u'/' + name); - QDir(paths.blobs()).removeRecursively(); - bool ok = true; - for (const QString &name : kDatabaseFiles) { - const QString from = safetyDir + u'/' + name; - if (QFileInfo::exists(from)) - ok = renamePath(from, paths.root + u'/' + name) && ok; - } - if (QFileInfo::exists(safetyDir + u"/blobs"_s)) - ok = renamePath(safetyDir + u"/blobs"_s, paths.blobs()) && ok; - syncDirectory(paths.root); - if (ok) - QDir().rmdir(safetyDir); - else - fail(error, u"Your original notes are still safe in %1."_s.arg(safetyDir)); - return ok; -} - -} // namespace onotes diff --git a/src/core/LibraryBackup.h b/src/core/LibraryBackup.h deleted file mode 100644 index fed49a0..0000000 --- a/src/core/LibraryBackup.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include "LibraryPaths.h" - -#include - -namespace onotes { - -// A backup is a folder: -// manifest.json written last; its presence marks the backup complete -// library.sqlite3 consistent snapshot (single file, rollback journal) -// blobs/xx/ every attachment the snapshot refers to -// -// NoteStore::backupTo writes one and NoteStore::inspectBackup validates one. -// The functions below swap files while the library is closed; LibraryService -// orchestrates closing and reopening around them. - -// A folder name like "Omarchy Notes Backup 2026-09-23 1530". -QString defaultBackupName(); - -// Moves the current library files aside into `*safetyDir` (a sibling of the -// library folder) and copies the backup in. On failure the original files are -// put back. -bool replaceLibraryFiles(const LibraryPaths &paths, const QString &backupDir, QString *safetyDir, - QString *error); - -// Undoes replaceLibraryFiles: removes the restored files and moves the -// originals back from `safetyDir`. -bool rollbackLibraryFiles(const LibraryPaths &paths, const QString &safetyDir, QString *error); - -} // namespace onotes diff --git a/src/core/LibraryPaths.cpp b/src/core/LibraryPaths.cpp deleted file mode 100644 index 1754351..0000000 --- a/src/core/LibraryPaths.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "LibraryPaths.h" - -#include -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -namespace { -constexpr auto kDirName = "omarchy-notes"; -} - -QString LibraryPaths::database() const -{ - return root + u"/library.sqlite3"_s; -} - -QString LibraryPaths::blobs() const -{ - return root + u"/blobs"_s; -} - -QString LibraryPaths::staging() const -{ - return root + u"/staging"_s; -} - -LibraryPaths LibraryPaths::standard() -{ - const QString override = qEnvironmentVariable("OMARCHY_NOTES_DATA_DIR"); - if (!override.isEmpty()) - return at(override); - const QString base = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); - return at(base + u'/' + QLatin1StringView(kDirName)); -} - -LibraryPaths LibraryPaths::at(const QString &root) -{ - return LibraryPaths{QDir::cleanPath(QDir(root).absolutePath())}; -} - -QString cacheDirectory() -{ - return QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + u'/' - + QLatin1StringView(kDirName); -} - -} // namespace onotes diff --git a/src/core/LibraryPaths.h b/src/core/LibraryPaths.h deleted file mode 100644 index 8bd74bb..0000000 --- a/src/core/LibraryPaths.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -namespace onotes { - -// Where a library lives on disk. User data goes under XDG_DATA_HOME so that -// uninstalling the package never touches notes. -struct LibraryPaths { - QString root; - - QString database() const; - QString blobs() const; - QString staging() const; - - // $OMARCHY_NOTES_DATA_DIR, else $XDG_DATA_HOME/omarchy-notes. - static LibraryPaths standard(); - static LibraryPaths at(const QString &root); -}; - -// Cache for disposable files (e.g. copies handed to external viewers). -QString cacheDirectory(); - -} // namespace onotes diff --git a/src/core/LibraryService.cpp b/src/core/LibraryService.cpp deleted file mode 100644 index 33b82a2..0000000 --- a/src/core/LibraryService.cpp +++ /dev/null @@ -1,316 +0,0 @@ -#include "LibraryService.h" - -#include "LibraryBackup.h" - -#include -#include -#include -#include -#include -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -LibraryService::LibraryService(LibraryPaths paths, QObject *parent) - : QObject(parent), m_paths(paths), m_pathResolver(paths) -{ - qRegisterMetaType(); - qRegisterMetaType>(); - m_thread.setObjectName(u"persistence"_s); -} - -LibraryService::~LibraryService() -{ - if (m_context) { - waitForIdle(); - blocking([this] { - m_store->close(); - return true; - }); - m_context->deleteLater(); - m_thread.quit(); - m_thread.wait(); - } -} - -template -auto LibraryService::blocking(Fn &&fn) -> decltype(fn()) -{ - decltype(fn()) result{}; - QMetaObject::invokeMethod(m_context, [&] { result = fn(); }, Qt::BlockingQueuedConnection); - return result; -} - -bool LibraryService::start(QString *error) -{ - m_store = std::make_unique(m_paths); - m_context = new QObject; - m_context->moveToThread(&m_thread); - m_thread.start(); - - QString openError; - const bool ok = blocking([&] { return m_store->open(&openError); }); - if (!ok) { - if (error) - *error = openError; - return false; - } - // Housekeeping (purging old deleted notes, removing unused attachment - // data) reads every note, so it waits until the app has settled and runs - // at most once a day. It never delays opening the window. - const QString marker = m_paths.root + u"/.last-cleanup"_s; - const QFileInfo last(marker); - if (!last.exists() || last.lastModified().secsTo(QDateTime::currentDateTime()) > 24 * 60 * 60) { - QMetaObject::invokeMethod(m_context, [this, marker] { - QTimer::singleShot(HousekeepingDelayMs, m_context, [this, marker] { - const int purged = m_store->purgeExpiredTrash(); - m_store->collectGarbage(); - QFile touch(marker); - if (touch.open(QIODevice::WriteOnly | QIODevice::Truncate)) - touch.write(QByteArray::number(QDateTime::currentSecsSinceEpoch())); - if (purged > 0) - QMetaObject::invokeMethod(this, &LibraryService::notesChanged, Qt::QueuedConnection); - }); - }, Qt::QueuedConnection); - } - return true; -} - -QList LibraryService::listNotes(const NoteQuery &query) -{ - return blocking([&] { return m_store->listNotes(query); }); -} - -quint64 LibraryService::search(const QString &text) -{ - const quint64 ticket = m_nextTicket++; - QMetaObject::invokeMethod(m_context, [this, ticket, text] { - const QList results = m_store->search(text); - QMetaObject::invokeMethod(this, [this, ticket, results] { - emit searchFinished(ticket, results); - }, Qt::QueuedConnection); - }, Qt::QueuedConnection); - return ticket; -} - -bool LibraryService::moveNote(const QString ¬eId, const QString &folderId, QString *error) -{ - return blocking([&] { return m_store->moveNote(noteId, folderId, error); }); -} - -std::optional LibraryService::duplicateNote(const QString ¬eId, QString *error) -{ - return blocking([&] { return m_store->duplicateNote(noteId, error); }); -} - -bool LibraryService::trashNote(const QString ¬eId, QString *error) -{ - return blocking([&] { return m_store->trashNote(noteId, error); }); -} - -bool LibraryService::recoverNote(const QString ¬eId, QString *error) -{ - return blocking([&] { return m_store->recoverNote(noteId, error); }); -} - -bool LibraryService::deleteNotePermanently(const QString ¬eId, QString *error) -{ - return blocking([&] { return m_store->deleteNotePermanently(noteId, error); }); -} - -int LibraryService::emptyTrash(QString *error) -{ - return blocking([&] { return m_store->emptyTrash(error); }); -} - -int LibraryService::trashCount() -{ - return blocking([this] { return m_store->trashCount(); }); -} - -int LibraryService::noteCount() -{ - return blocking([this] { return m_store->noteCount(); }); -} - -QList LibraryService::listTags() -{ - return blocking([this] { return m_store->listTags(); }); -} - -QList LibraryService::listSmartFolders() -{ - return blocking([this] { return m_store->listSmartFolders(); }); -} - -std::optional LibraryService::createSmartFolder(const QString &name, const SmartCriteria &criteria, - QString *error) -{ - return blocking([&] { return m_store->createSmartFolder(name, criteria, error); }); -} - -bool LibraryService::updateSmartFolder(const QString &id, const QString &name, const SmartCriteria &criteria, - QString *error) -{ - return blocking([&] { return m_store->updateSmartFolder(id, name, criteria, error); }); -} - -bool LibraryService::deleteSmartFolder(const QString &id, QString *error) -{ - return blocking([&] { return m_store->deleteSmartFolder(id, error); }); -} - -QList LibraryService::listAttachmentItems() -{ - return blocking([this] { return m_store->listAttachmentItems(); }); -} - -QList LibraryService::listFolders() -{ - return blocking([this] { return m_store->listFolders(); }); -} - -std::optional LibraryService::createFolder(const QString &name, const QString &parentId, - QString *error) -{ - return blocking([&] { return m_store->createFolder(name, parentId, error); }); -} - -bool LibraryService::renameFolder(const QString &id, const QString &name, QString *error) -{ - return blocking([&] { return m_store->renameFolder(id, name, error); }); -} - -bool LibraryService::deleteFolder(const QString &id, QString *error) -{ - return blocking([&] { return m_store->deleteFolder(id, error); }); -} - -std::optional LibraryService::backupTo(const QString &directory, QString *error) -{ - return blocking([&] { return m_store->backupTo(directory, error); }); -} - -std::optional LibraryService::inspectBackup(const QString &directory, QString *error) -{ - return blocking([&] { return NoteStore::inspectBackup(directory, error); }); -} - -bool LibraryService::restoreFrom(const QString &directory, QString *safetyDir, QString *error) -{ - return blocking([&] { - if (!NoteStore::inspectBackup(directory, error)) - return false; - m_store->close(); - QString safety; - if (!replaceLibraryFiles(m_paths, directory, &safety, error)) { - m_store->open(nullptr); - return false; - } - auto restored = std::make_unique(m_paths); - QString openError; - QStringList problems; - const bool opened = restored->open(&openError); - if (opened) - problems = restored->verify(); - if (!opened || !problems.isEmpty()) { - restored.reset(); - rollbackLibraryFiles(m_paths, safety, nullptr); - m_store->open(nullptr); - if (error) - *error = u"The backup couldn't be opened, so your notes were left as they were. %1"_s - .arg(opened ? problems.value(0) : openError); - return false; - } - m_store = std::move(restored); - if (safetyDir) - *safetyDir = safety; - return true; - }); -} - -std::optional LibraryService::loadNote(const QString &id, QString *error) -{ - return blocking([&] { return m_store->loadNote(id, error); }); -} - -std::optional LibraryService::createNote(const RichDocument &body, QString *error, - const QString &folderId) -{ - auto result = blocking([&] { return m_store->createNote(body, error, folderId); }); - if (result) - emit notesChanged(); - return result; -} - -bool LibraryService::setPinned(const QString &id, bool pinned) -{ - const bool ok = blocking([&] { return m_store->setPinned(id, pinned); }); - if (ok) - emit notesChanged(); - return ok; -} - -std::optional LibraryService::addAttachment(const QString ¬eId, const QString &filePath, - QString *error) -{ - return blocking([&] { return m_store->addAttachment(noteId, filePath, error); }); -} - -std::optional LibraryService::attachment(const QString &id) -{ - return blocking([&] { return m_store->attachment(id); }); -} - -std::optional LibraryService::addImage(const QByteArray &bytes, QString *error) -{ - return blocking([&] { return m_store->addImage(bytes, error); }); -} - -std::optional LibraryService::addImageFile(const QString &filePath, QString *error) -{ - return blocking([&] { return m_store->addImageFile(filePath, error); }); -} - -QStringList LibraryService::verify() -{ - return blocking([this] { return m_store->verify(); }); -} - -QString LibraryService::blobPath(const QString &hash) const -{ - return m_pathResolver.path(hash); -} - -quint64 LibraryService::saveNote(const SaveRequest &request) -{ - const quint64 ticket = m_nextTicket++; - QMetaObject::invokeMethod(m_context, [this, ticket, request] { - SaveResult result; - if (m_simulateFailure) - result.error = u"Simulated storage failure."_s; - else - result = m_store->saveNote(request); - QMetaObject::invokeMethod(this, [this, ticket, id = request.noteId, result] { - emit saveFinished(ticket, id, result); - }, Qt::QueuedConnection); - }, Qt::QueuedConnection); - return ticket; -} - -void LibraryService::waitForIdle() -{ - // The persistence thread processes calls in order, so a blocking no-op - // returns only after every earlier save. - blocking([] { return true; }); -} - -void LibraryService::deliverPendingResults() -{ - waitForIdle(); - QCoreApplication::sendPostedEvents(this, QEvent::MetaCall); -} - -} // namespace onotes diff --git a/src/core/LibraryService.h b/src/core/LibraryService.h deleted file mode 100644 index 0e5f9d8..0000000 --- a/src/core/LibraryService.h +++ /dev/null @@ -1,112 +0,0 @@ -#pragma once - -#include "NoteStore.h" - -#include -#include - -#include -#include - -namespace onotes { - -// The single owner of a library. Every database and file operation runs on a -// dedicated persistence thread; the UI thread never touches SQLite. -// -// Saves are asynchronous and acknowledged through saveFinished(). The -// remaining calls block on the persistence thread and are meant for small, -// user-initiated operations. -class LibraryService : public QObject -{ - Q_OBJECT - -public: - // How long after startup the daily housekeeping runs. - static constexpr int HousekeepingDelayMs = 30000; - - explicit LibraryService(LibraryPaths paths, QObject *parent = nullptr); - ~LibraryService() override; - - bool start(QString *error); - const LibraryPaths &paths() const { return m_paths; } - - QList listNotes(const NoteQuery &query = {}); - std::optional loadNote(const QString &id, QString *error = nullptr); - std::optional createNote(const RichDocument &body, QString *error = nullptr, - const QString &folderId = {}); - bool setPinned(const QString &id, bool pinned); - - // Runs a search on the persistence thread; results arrive through - // searchFinished with the returned ticket. - quint64 search(const QString &text); - - bool moveNote(const QString ¬eId, const QString &folderId, QString *error = nullptr); - std::optional duplicateNote(const QString ¬eId, QString *error = nullptr); - bool trashNote(const QString ¬eId, QString *error = nullptr); - bool recoverNote(const QString ¬eId, QString *error = nullptr); - bool deleteNotePermanently(const QString ¬eId, QString *error = nullptr); - int emptyTrash(QString *error = nullptr); - int trashCount(); - int noteCount(); - - QList listTags(); - QList listSmartFolders(); - std::optional createSmartFolder(const QString &name, const SmartCriteria &criteria, - QString *error = nullptr); - bool updateSmartFolder(const QString &id, const QString &name, const SmartCriteria &criteria, - QString *error = nullptr); - bool deleteSmartFolder(const QString &id, QString *error = nullptr); - QList listAttachmentItems(); - - QList listFolders(); - std::optional createFolder(const QString &name, const QString &parentId = {}, - QString *error = nullptr); - bool renameFolder(const QString &id, const QString &name, QString *error = nullptr); - bool deleteFolder(const QString &id, QString *error = nullptr); - - std::optional backupTo(const QString &directory, QString *error = nullptr); - std::optional inspectBackup(const QString &directory, QString *error = nullptr); - // Replaces the library with a backup. The previous library is moved to - // `*safetyDir`; on any failure it is put back and false is returned. - bool restoreFrom(const QString &directory, QString *safetyDir, QString *error = nullptr); - std::optional addAttachment(const QString ¬eId, const QString &filePath, - QString *error = nullptr); - std::optional attachment(const QString &id); - std::optional addImage(const QByteArray &bytes, QString *error = nullptr); - std::optional addImageFile(const QString &filePath, QString *error = nullptr); - QStringList verify(); - - // Path computation only; safe from any thread. - QString blobPath(const QString &hash) const; - - // Queues a save; the result arrives through saveFinished with the ticket. - quint64 saveNote(const SaveRequest &request); - // Blocks until every queued save has been committed or has failed. - // Their saveFinished signals are still delivered through the event loop; - // call deliverPendingResults() to receive them immediately. - void waitForIdle(); - void deliverPendingResults(); - - // Makes subsequent saves fail, for exercising failure handling. - void setSimulatedSaveFailure(bool fail) { m_simulateFailure = fail; } - bool simulatedSaveFailure() const { return m_simulateFailure; } - -signals: - void saveFinished(quint64 ticket, const QString ¬eId, const onotes::SaveResult &result); - void searchFinished(quint64 ticket, const QList &results); - void notesChanged(); - -private: - template - auto blocking(Fn &&fn) -> decltype(fn()); - - LibraryPaths m_paths; - BlobStore m_pathResolver; - QThread m_thread; - QObject *m_context = nullptr; // lives on m_thread - std::unique_ptr m_store; // used only on m_thread - std::atomic m_nextTicket{1}; - std::atomic m_simulateFailure{false}; -}; - -} // namespace onotes diff --git a/src/core/NoteExchange.cpp b/src/core/NoteExchange.cpp deleted file mode 100644 index 07c9cc5..0000000 --- a/src/core/NoteExchange.cpp +++ /dev/null @@ -1,490 +0,0 @@ -#include "NoteExchange.h" - -#include "DocumentConverter.h" -#include "LibraryService.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -namespace { - -bool fail(QString *error, const QString &message) -{ - if (error) - *error = message; - return false; -} - -bool writeText(const QString &path, const QString &text, QString *error) -{ - QSaveFile file(path); - if (!file.open(QIODevice::WriteOnly)) { - return fail(error, u"Couldn't write %1: %2"_s.arg(QFileInfo(path).fileName(), file.errorString())); - } - file.write(text.toUtf8()); - if (!file.commit()) - return fail(error, u"Couldn't write %1: %2"_s.arg(QFileInfo(path).fileName(), file.errorString())); - return true; -} - -// Markdown front matter (Obsidian, Jekyll...) isn't note content. -QString stripFrontMatter(const QString &text) -{ - if (!text.startsWith(u"---\n"_s) && !text.startsWith(u"---\r\n"_s)) - return text; - static const QRegularExpression end(u"\\r?\\n---\\r?\\n"_s); - const QRegularExpressionMatch m = end.match(text, 3); - return m.hasMatch() ? text.mid(m.capturedEnd()) : text; -} - -// Swaps images that point at files on disk for images stored in the library. -void storeLocalImages(QTextDocument &doc, const QString &baseDir, LibraryService &library, const QString &fileName, - QStringList *warnings) -{ - struct Found { - int position; - QTextImageFormat format; - }; - QList images; - for (QTextBlock block = doc.begin(); block.isValid(); block = block.next()) { - for (auto it = block.begin(); !it.atEnd(); ++it) { - const QTextFragment fragment = it.fragment(); - if (fragment.charFormat().isImageFormat()) - images.append({fragment.position(), fragment.charFormat().toImageFormat()}); - } - } - bool warnedWeb = false; - QList unusable; - for (Found &image : images) { - const QUrl url(image.format.name()); - const QString path = url.isLocalFile() ? url.toLocalFile() - : url.scheme().isEmpty() ? QDir(baseDir).absoluteFilePath(QUrl::fromPercentEncoding(image.format.name().toUtf8())) - : QString(); - if (path.isEmpty()) { - if (!warnedWeb) - warnings->append(u"%1: images from the web weren't imported."_s.arg(fileName)); - warnedWeb = true; - unusable << image.position; - continue; - } - QImageReader reader(path); - const QSize size = reader.size(); - QString error; - const auto hash = size.isValid() ? library.addImageFile(path, &error) : std::nullopt; - if (!hash) { - warnings->append(u"%1: couldn't import the image %2."_s.arg(fileName, QFileInfo(path).fileName())); - unusable << image.position; - continue; - } - QTextImageFormat stored = image.format; - stored.setName(DocumentConverter::imageResourceName(*hash)); - stored.setWidth(size.width()); - stored.setHeight(size.height()); - stored.setProperty(TextProperty::ImageLogicalSize, size); - QTextCursor cursor(&doc); - cursor.setPosition(image.position); - cursor.setPosition(image.position + 1, QTextCursor::KeepAnchor); - cursor.setCharFormat(stored); - } - // Already reported above; remove them so they aren't reported again. - for (auto it = unusable.crbegin(); it != unusable.crend(); ++it) { - QTextCursor cursor(&doc); - cursor.setPosition(*it); - cursor.setPosition(*it + 1, QTextCursor::KeepAnchor); - cursor.removeSelectedText(); - } -} - -// What an exported note needs from the library, resolved up front. -struct ExportContext { - LibraryService &library; - QString filesDirName; // " files", relative to the note file - QString filesDir; // absolute - QStringList used; // file names already written into filesDir - std::function linkForNote; // empty: drop note links - - QString uniqueName(const QString &wanted) - { - const QFileInfo info(wanted); - QString name = wanted; - for (int n = 2; used.contains(name, Qt::CaseInsensitive); ++n) - name = info.suffix().isEmpty() ? u"%1 %2"_s.arg(info.completeBaseName()).arg(n) - : u"%1 %2.%3"_s.arg(info.completeBaseName()).arg(n).arg(info.suffix()); - used << name; - return name; - } - - // Copies a blob into the files folder; returns its relative path. - QString copyBlob(const QString &hash, const QString &wantedName) - { - QDir().mkpath(filesDir); - const QString name = uniqueName(wantedName); - QFile::copy(library.blobPath(hash), filesDir + u'/' + name); - return filesDirName + u'/' + name; - } -}; - -QString encodePath(const QString &relative) -{ - QStringList parts; - for (const QString &part : relative.split(u'/')) - parts << QString::fromUtf8(QUrl::toPercentEncoding(part)); - return parts.join(u'/'); -} - -// Rewrites a note for export: attachments become links to copied files, -// note links point at exported files (or become plain text). -RichDocument prepareForExport(const RichDocument &source, ExportContext &ctx, bool copyImages, - QHash *imagePaths) -{ - RichDocument doc = source; - int imageNumber = 0; - std::function &)> walk = [&](QList &blocks) { - for (Block &b : blocks) { - for (Span &span : b.spans) { - if (span.kind == Span::Kind::Attachment) { - const auto info = ctx.library.attachment(span.ref); - const QString name = info ? info->fileName : u"attachment"_s; - const QString path = info ? ctx.copyBlob(info->blobHash, name) : QString(); - span = Span::plain(u"\U0001F4CE "_s + name, 0, path.isEmpty() ? QString() : encodePath(path)); - } else if (span.kind == Span::Kind::Image && copyImages && !imagePaths->contains(span.ref)) { - const QString suffix = QMimeDatabase().mimeTypeForFile(ctx.library.blobPath(span.ref)).preferredSuffix(); - const QString name = u"image-%1.%2"_s.arg(++imageNumber).arg(suffix.isEmpty() ? u"png"_s : suffix); - imagePaths->insert(span.ref, encodePath(ctx.copyBlob(span.ref, name))); - } else if (span.kind == Span::Kind::Text) { - if (span.href.startsWith(u"note://")) - span.href = ctx.linkForNote ? ctx.linkForNote(span.href.mid(7)) : QString(); - // Markdown has no underline; Qt would write it as - // emphasis, which reads back as italic. - if (copyImages) - span.marks &= ~quint32(Underline); - } - } - for (TableCell &cell : b.cells) - walk(cell.blocks); - } - }; - walk(doc.blocks); - return doc; -} - -QString toMarkdown(const RichDocument &doc, const QHash &imagePaths) -{ - QTextDocument text; - DocumentStyle style; - DocumentConverter::load(doc, &text, style); - QString markdown = text.toMarkdown(QTextDocument::MarkdownDialectGitHub); - for (auto it = imagePaths.cbegin(); it != imagePaths.cend(); ++it) - markdown.replace(DocumentConverter::imageResourceName(it.key()), it.value()); - return markdown; -} - -QString uniqueFile(const QString &dir, const QString &base, const QString &suffix, QStringList *taken) -{ - QString name = base + suffix; - for (int n = 2; taken->contains(name, Qt::CaseInsensitive) || QFileInfo::exists(dir + u'/' + name); ++n) - name = u"%1 %2%3"_s.arg(base).arg(n).arg(suffix); - taken->append(name); - return name; -} - -} // namespace - -QString fileNameForTitle(const QString &title) -{ - QString name = title; - static const QRegularExpression reserved(u"[/\\\\:*?\"<>|\\x00-\\x1f]"_s); - name.replace(reserved, u" "_s); - name = name.simplified(); - while (name.startsWith(u'.')) - name.remove(0, 1); - if (name.size() > 120) - name = name.left(120).trimmed(); - return name.isEmpty() ? u"Untitled note"_s : name; -} - -ImportReport importFiles(LibraryService &library, const QStringList &paths, const QString &folderId) -{ - ImportReport report; - for (const QString &path : paths) { - const QFileInfo info(path); - QFile file(path); - if (!file.open(QIODevice::ReadOnly)) { - report.warnings << u"%1: %2"_s.arg(info.fileName(), file.errorString()); - continue; - } - const QString text = QString::fromUtf8(file.readAll()); - const QString suffix = info.suffix().toLower(); - - RichDocument body; - if (suffix == u"md" || suffix == u"markdown" || suffix == u"mdown") { - QTextDocument doc; - doc.setMarkdown(stripFrontMatter(text), QTextDocument::MarkdownDialectGitHub); - storeLocalImages(doc, info.absolutePath(), library, info.fileName(), &report.warnings); - ConversionReport conversion; - body = DocumentConverter::read(&doc, &conversion); - for (const QString &warning : conversion.warnings) - report.warnings << u"%1: %2"_s.arg(info.fileName(), warning); - } else { - body = DocumentConverter::fromPlainText(text); - } - // A file without a first line gets its name as the title. - if (body.title().isEmpty() || body.blocks.value(0).plainText().trimmed().isEmpty()) - body.blocks.prepend(Block::heading(1, {Span::plain(info.completeBaseName())})); - - QString error; - const auto note = library.createNote(body, &error, folderId); - if (note) - report.createdIds << note->id; - else - report.warnings << u"%1: %2"_s.arg(info.fileName(), error); - } - return report; -} - -namespace { - -const QStringList kImportable = {u"*.md"_s, u"*.markdown"_s, u"*.mdown"_s, u"*.txt"_s}; - -bool hasImportableFiles(const QDir &dir) -{ - QDirIterator it(dir.path(), kImportable, QDir::Files, QDirIterator::Subdirectories); - return it.hasNext(); -} - -// A folder name that doesn't clash with a sibling. -std::optional createUniqueFolder(LibraryService &library, const QString &name, const QString &parentId, - QString *error) -{ - for (int n = 1; n < 100; ++n) { - const QString candidate = n == 1 ? name : u"%1 %2"_s.arg(name).arg(n); - QString attempt; - if (auto folder = library.createFolder(candidate, parentId, &attempt)) - return folder; - if (!attempt.contains(u"already"_s)) { - if (error) - *error = attempt; - return std::nullopt; - } - } - if (error) - *error = u"Too many folders with that name."_s; - return std::nullopt; -} - -void importTree(LibraryService &library, const QDir &dir, const QString &folderId, ImportReport *report) -{ - QStringList files; - for (const QFileInfo &file : dir.entryInfoList(kImportable, QDir::Files, QDir::Name)) - files << file.absoluteFilePath(); - const ImportReport here = importFiles(library, files, folderId); - report->createdIds << here.createdIds; - report->warnings << here.warnings; - - for (const QFileInfo &sub : dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name)) { - const QDir child(sub.absoluteFilePath()); - if (sub.fileName().startsWith(u'.') || !hasImportableFiles(child)) - continue; - QString error; - const auto folder = createUniqueFolder(library, sub.fileName(), folderId, &error); - if (!folder) { - report->warnings << u"%1: %2"_s.arg(sub.fileName(), error); - continue; - } - importTree(library, child, folder->id, report); - } -} - -} // namespace - -ImportReport importFolder(LibraryService &library, const QString &directory, const QString &parentFolderId, - QString *createdFolderId) -{ - ImportReport report; - const QDir dir(directory); - if (!dir.exists() || !hasImportableFiles(dir)) { - report.warnings << u"%1 has no Markdown or text files to import."_s.arg(dir.dirName()); - return report; - } - QString error; - const auto folder = createUniqueFolder(library, dir.dirName(), parentFolderId, &error); - if (!folder) { - report.warnings << error; - return report; - } - if (createdFolderId) - *createdFolderId = folder->id; - importTree(library, dir, folder->id, &report); - return report; -} - -bool exportNote(LibraryService &library, const QString ¬eId, ExportFormat format, const QString &file, - QString *error) -{ - QString loadError; - const auto note = library.loadNote(noteId, &loadError); - if (!note) - return fail(error, loadError); - - const QFileInfo target(file); - ExportContext ctx{library, target.completeBaseName() + u" files"_s, - target.absolutePath() + u'/' + target.completeBaseName() + u" files"_s, {}, {}}; - - switch (format) { - case ExportFormat::Markdown: { - QHash images; - const RichDocument doc = prepareForExport(note->body, ctx, true, &images); - return writeText(file, toMarkdown(doc, images), error); - } - case ExportFormat::Html: { - QHash unused; - const RichDocument doc = prepareForExport(note->body, ctx, false, &unused); - QTextDocument text; - DocumentConverter::load(doc, &text, DocumentStyle{}); - text.setMetaInformation(QTextDocument::DocumentTitle, note->body.title()); - QString html = text.toHtml(); - // Embed images so the page is one self-contained file. - for (const QString &hash : doc.referencedBlobs()) { - QFile blob(library.blobPath(hash)); - if (!blob.open(QIODevice::ReadOnly)) - continue; - const QString mime = QMimeDatabase().mimeTypeForFile(blob.fileName()).name(); - html.replace(DocumentConverter::imageResourceName(hash), - u"data:%1;base64,%2"_s.arg(mime, QString::fromLatin1(blob.readAll().toBase64()))); - } - return writeText(file, html, error); - } - case ExportFormat::Pdf: { - // Attachments can't live inside a PDF; they're listed by name. - RichDocument doc = note->body; - std::function &)> strip = [&](QList &blocks) { - for (Block &b : blocks) { - for (Span &span : b.spans) { - if (span.kind == Span::Kind::Attachment) { - const auto info = library.attachment(span.ref); - span = Span::plain(u"\U0001F4CE "_s + (info ? info->fileName : u"attachment"_s)); - } else if (span.kind == Span::Kind::Text && span.href.startsWith(u"note://")) { - span.href.clear(); - } - } - for (TableCell &cell : b.cells) - strip(cell.blocks); - } - }; - strip(doc.blocks); - - DocumentStyle style; - style.pointSizes = true; - style.bodyPixelSize = 11 / 0.75; // 11 pt body text - style.maxImageWidth = 460; // points, within A4/Letter margins - QTextDocument text; - QFont font = QGuiApplication::font(); - font.setPointSizeF(11); - text.setDefaultFont(font); - DocumentConverter::load(doc, &text, style); - for (const QString &hash : doc.referencedBlobs()) { - QImage image(library.blobPath(hash)); - if (!image.isNull()) - text.addResource(QTextDocument::ImageResource, QUrl(DocumentConverter::imageResourceName(hash)), image); - } - - QPdfWriter writer(file); - writer.setTitle(note->body.title()); - writer.setCreator(u"Omarchy Notes"_s); - const bool metric = QLocale().measurementSystem() == QLocale::MetricSystem; - writer.setPageLayout(QPageLayout(QPageSize(metric ? QPageSize::A4 : QPageSize::Letter), - QPageLayout::Portrait, QMarginsF(18, 18, 18, 18), QPageLayout::Millimeter)); - text.print(&writer); - if (!QFileInfo::exists(file) || QFileInfo(file).size() == 0) - return fail(error, u"Couldn't write the PDF."_s); - return true; - } - } - return false; -} - -std::optional exportLibraryAsMarkdown(LibraryService &library, const QString &directory, - QString *error) -{ - const QString root = QDir(directory).filePath( - u"Omarchy Notes Export "_s + QDateTime::currentDateTime().toString(u"yyyy-MM-dd HHmm"_s)); - if (QFileInfo::exists(root) || !QDir().mkpath(root)) { - fail(error, u"Couldn't create %1."_s.arg(root)); - return std::nullopt; - } - - // Folder paths, parents before children. - QHash folderDirs; // folder id -> relative dir ("" is the root) - const QList folders = library.listFolders(); - QHash takenNames; - std::function dirFor = [&](const QString &id) -> QString { - if (id.isEmpty()) - return {}; - if (folderDirs.contains(id)) - return folderDirs.value(id); - for (const FolderInfo &f : folders) { - if (f.id == id) { - const QString parent = dirFor(f.parentId); - const QString name = uniqueFile(root + u'/' + parent, fileNameForTitle(f.name), {}, - &takenNames[parent]); - const QString dir = parent.isEmpty() ? name : parent + u'/' + name; - QDir().mkpath(root + u'/' + dir); - folderDirs.insert(id, dir); - return dir; - } - } - return {}; - }; - - // Decide every note's file first so links can point at them. - const QList notes = library.listNotes(NoteQuery::all(NoteSort::Title)); - QHash noteFiles; // note id -> relative path of its .md - for (const NoteSummary &n : notes) { - const QString dir = dirFor(n.folderId); - const QString name = uniqueFile(root + u'/' + dir, fileNameForTitle(n.title), u".md"_s, &takenNames[dir]); - noteFiles.insert(n.id, dir.isEmpty() ? name : dir + u'/' + name); - } - - for (const NoteSummary &n : notes) { - const auto note = library.loadNote(n.id); - if (!note) - continue; - const QString relative = noteFiles.value(n.id); - const QFileInfo info(root + u'/' + relative); - ExportContext ctx{library, info.completeBaseName() + u" files"_s, - info.absolutePath() + u'/' + info.completeBaseName() + u" files"_s, {}, {}}; - const QDir from(info.absolutePath()); - ctx.linkForNote = [&](const QString &id) { - return noteFiles.contains(id) ? encodePath(from.relativeFilePath(root + u'/' + noteFiles.value(id))) - : QString(); - }; - QHash images; - const RichDocument doc = prepareForExport(note->body, ctx, true, &images); - if (!writeText(info.absoluteFilePath(), toMarkdown(doc, images), error)) - return std::nullopt; - } - return root; -} - -} // namespace onotes diff --git a/src/core/NoteExchange.h b/src/core/NoteExchange.h deleted file mode 100644 index a17632d..0000000 --- a/src/core/NoteExchange.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include -#include - -#include - -namespace onotes { - -class LibraryService; - -// Moving notes in and out of the library as ordinary files. These run on the -// UI thread (they use QTextDocument) and reach storage through the service. - -struct ImportReport { - QStringList createdIds; - QStringList warnings; // one line per problem, naming the file -}; - -// Imports Markdown (.md, .markdown) and plain-text files as notes in -// `folderId` ("" is Notes). Images a Markdown file references on disk are -// stored with the note; anything that can't be kept is listed in warnings. -ImportReport importFiles(LibraryService &library, const QStringList &paths, const QString &folderId); - -// Imports a folder tree: the folder becomes a folder inside `parentFolderId` -// ("" is the top level), each subfolder with notes becomes a subfolder, and -// every Markdown/text file becomes a note. Asset-only folders (images next to -// the notes, as exporters write them) are not turned into folders; their -// images come in through the notes that use them. -ImportReport importFolder(LibraryService &library, const QString &directory, const QString &parentFolderId, - QString *createdFolderId = nullptr); - -enum class ExportFormat { Markdown, Html, Pdf }; - -// Writes one note to `file`. Markdown and HTML put attachments (and, for -// Markdown, images) in a " files" folder next to it; HTML embeds its -// images so the page is a single file. -bool exportNote(LibraryService &library, const QString ¬eId, ExportFormat format, const QString &file, - QString *error = nullptr); - -// Writes every note (not deleted ones) as Markdown into a new folder inside -// `directory`, mirroring the folder tree. Links between notes become -// relative links. Returns the created folder. -std::optional exportLibraryAsMarkdown(LibraryService &library, const QString &directory, - QString *error = nullptr); - -// A file name for a note title: path separators and reserved characters -// removed, trimmed, and never empty. -QString fileNameForTitle(const QString &title); - -} // namespace onotes diff --git a/src/core/NoteStore.cpp b/src/core/NoteStore.cpp deleted file mode 100644 index 09fe153..0000000 --- a/src/core/NoteStore.cpp +++ /dev/null @@ -1,1230 +0,0 @@ -#include "NoteStore.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -namespace { - -constexpr const char *kSchemaV1 = R"sql( -CREATE TABLE folders ( - id TEXT PRIMARY KEY NOT NULL, - parent_id TEXT REFERENCES folders(id) ON DELETE RESTRICT, - name TEXT NOT NULL, - sort_key INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL, - deleted_at INTEGER -); - -CREATE TABLE notes ( - id TEXT PRIMARY KEY NOT NULL, - folder_id TEXT REFERENCES folders(id) ON DELETE RESTRICT, - title TEXT NOT NULL DEFAULT '', - snippet TEXT NOT NULL DEFAULT '', - plain_text TEXT NOT NULL DEFAULT '', - body TEXT NOT NULL, - body_schema INTEGER NOT NULL, - has_attachments INTEGER NOT NULL DEFAULT 0, - has_checklist INTEGER NOT NULL DEFAULT 0, - pinned INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL, - deleted_at INTEGER, - revision INTEGER NOT NULL DEFAULT 1 -); -CREATE INDEX notes_by_folder ON notes(folder_id, deleted_at, pinned DESC, updated_at DESC); - -CREATE TABLE note_revisions ( - note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE, - revision INTEGER NOT NULL, - body TEXT NOT NULL, - body_schema INTEGER NOT NULL, - created_at INTEGER NOT NULL, - PRIMARY KEY (note_id, revision) -) WITHOUT ROWID; - -CREATE TABLE blobs ( - hash TEXT PRIMARY KEY NOT NULL, - size INTEGER NOT NULL, - created_at INTEGER NOT NULL -) WITHOUT ROWID; - -CREATE TABLE attachments ( - id TEXT PRIMARY KEY NOT NULL, - note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE, - blob_hash TEXT NOT NULL REFERENCES blobs(hash), - file_name TEXT NOT NULL, - mime_type TEXT NOT NULL, - size INTEGER NOT NULL, - created_at INTEGER NOT NULL -); -CREATE INDEX attachments_by_note ON attachments(note_id); - -CREATE TABLE note_blob_refs ( - note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE, - blob_hash TEXT NOT NULL REFERENCES blobs(hash), - PRIMARY KEY (note_id, blob_hash) -) WITHOUT ROWID; -CREATE INDEX note_blob_refs_by_blob ON note_blob_refs(blob_hash); - -CREATE VIRTUAL TABLE notes_fts USING fts5( - title, plain_text, - content='notes', content_rowid='rowid', - tokenize='unicode61 remove_diacritics 2' -); -CREATE TRIGGER notes_fts_insert AFTER INSERT ON notes BEGIN - INSERT INTO notes_fts(rowid, title, plain_text) VALUES (new.rowid, new.title, new.plain_text); -END; -CREATE TRIGGER notes_fts_delete AFTER DELETE ON notes BEGIN - INSERT INTO notes_fts(notes_fts, rowid, title, plain_text) VALUES ('delete', old.rowid, old.title, old.plain_text); -END; -CREATE TRIGGER notes_fts_update AFTER UPDATE OF title, plain_text ON notes BEGIN - INSERT INTO notes_fts(notes_fts, rowid, title, plain_text) VALUES ('delete', old.rowid, old.title, old.plain_text); - INSERT INTO notes_fts(rowid, title, plain_text) VALUES (new.rowid, new.title, new.plain_text); -END; -)sql"; - -// v2: tags, Smart Folders, attachment references and note thumbnails. -constexpr const char *kSchemaV2 = R"sql( -ALTER TABLE notes ADD COLUMN thumbnail TEXT; - -CREATE TABLE note_tags ( - note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE, - tag TEXT NOT NULL, - PRIMARY KEY (note_id, tag) -) WITHOUT ROWID; -CREATE INDEX note_tags_by_tag ON note_tags(tag); - -CREATE TABLE note_attachment_refs ( - note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE, - attachment_id TEXT NOT NULL, - PRIMARY KEY (note_id, attachment_id) -) WITHOUT ROWID; -CREATE INDEX note_attachment_refs_by_attachment ON note_attachment_refs(attachment_id); - -CREATE TABLE smart_folders ( - id TEXT PRIMARY KEY NOT NULL, - name TEXT NOT NULL, - criteria TEXT NOT NULL, - sort_key INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL -); -)sql"; - -qint64 now() -{ - return QDateTime::currentMSecsSinceEpoch(); -} - -bool setError(QString *error, const QString &message) -{ - if (error) - *error = message; - return false; -} - -bool hasChecklist(const QList &blocks) -{ - for (const Block &b : blocks) { - if (b.type == Block::Type::ListItem && b.list == ListKind::Check) - return true; - for (const TableCell &c : b.cells) { - if (hasChecklist(c.blocks)) - return true; - } - } - return false; -} - -} // namespace - -NoteStore::NoteStore(LibraryPaths paths) : m_paths(paths), m_blobs(std::move(paths)) {} - -bool NoteStore::open(QString *error) -{ - if (!QDir().mkpath(m_paths.root)) - return setError(error, u"Could not create the library folder %1."_s.arg(m_paths.root)); - // Say what's wrong plainly rather than failing somewhere inside SQLite. - const QFileInfo folder(m_paths.root); - const QFileInfo database(m_paths.database()); - if (!folder.isWritable() || (database.exists() && !database.isWritable())) { - return setError(error, u"Omarchy Notes can't write to its library at %1. Check that the folder " - "and its files belong to you and aren't read-only."_s.arg(m_paths.root)); - } - if (!m_blobs.prepare(error)) - return false; - if (!m_db.open(m_paths.database(), error)) - return false; - - // WAL keeps readers unblocked; synchronous=FULL makes every acknowledged - // commit durable across power loss, which "Saved" promises. - { - Statement wal = m_db.prepare("PRAGMA journal_mode=WAL"); - if (!wal.next() || wal.text(0).compare(u"wal"_s, Qt::CaseInsensitive) != 0) - return setError(error, u"The library database does not support write-ahead logging."_s); - } - if (!m_db.exec("PRAGMA synchronous=FULL") || !m_db.exec("PRAGMA foreign_keys=ON")) - return setError(error, m_db.friendlyError()); - - return migrate(error); -} - -void NoteStore::close() -{ - m_db.close(); -} - -bool NoteStore::migrate(QString *error) -{ - const int version = m_db.userVersion(); - if (version > SchemaVersion) { - return setError(error, u"This library was created by a newer version of the app " - "(schema %1). Update the app to open it."_s.arg(version)); - } - if (version == SchemaVersion) - return true; - - Transaction tx(m_db); - if (!tx.isActive()) - return setError(error, m_db.lastError()); - if (version < 1) { - if (!m_db.exec(kSchemaV1)) - return setError(error, u"Could not create the library: %1"_s.arg(m_db.lastError())); - } - if (version < 2) { - if (!m_db.exec(kSchemaV2)) - return setError(error, u"Could not upgrade the library: %1"_s.arg(m_db.lastError())); - // Fill in tags, references and thumbnails for existing notes. - QList> notes; - Statement all = m_db.prepare("SELECT id, body FROM notes"); - while (all.next()) - notes.append({all.text(0), all.text(1)}); - for (const auto &[id, json] : notes) { - const auto body = RichDocument::fromJsonBytes(json.toUtf8()); - if (body && !writeDerived(id, *body)) - return setError(error, u"Could not upgrade the library: %1"_s.arg(m_db.lastError())); - } - } - // Future migrations go here, each guarded by `version < N`. - const QByteArray setVersion = "PRAGMA user_version=" + QByteArray::number(SchemaVersion); - if (!m_db.exec(setVersion.constData()) || !tx.commit()) - return setError(error, u"Could not upgrade the library: %1"_s.arg(m_db.lastError())); - return true; -} - -namespace { - -constexpr const char *kSummaryColumns = - "n.id, n.folder_id, n.title, n.snippet, n.created_at, n.updated_at, n.deleted_at, " - "n.pinned, n.has_attachments, n.has_checklist, n.thumbnail"; - -NoteSummary readSummary(const Statement &s) -{ - NoteSummary n; - n.id = s.text(0); - n.folderId = s.text(1); - n.title = s.text(2); - n.snippet = s.text(3); - n.createdAt = s.int64(4); - n.updatedAt = s.int64(5); - n.deletedAt = s.isNull(6) ? 0 : s.int64(6); - n.pinned = s.int64(7) != 0; - n.hasAttachments = s.int64(8) != 0; - n.hasChecklist = s.int64(9) != 0; - n.thumbnail = s.text(10); - return n; -} - -// A WHERE clause with its positional parameters. -struct Filter { - QStringList conditions; - QVariantList params; - - void add(const QString &condition, const QVariantList &values = {}) - { - conditions << condition; - params << values; - } - QByteArray sql() const { return conditions.join(u" AND "_s).toUtf8(); } - void bindTo(Statement &s) const - { - for (int i = 0; i < params.size(); ++i) { - if (params[i].typeId() == QMetaType::QString) - s.bind(i + 1, params[i].toString()); - else - s.bind(i + 1, params[i].toLongLong()); - } - } -}; - -Filter filterFor(const NoteQuery &query, qint64 timestamp) -{ - Filter f; - switch (query.scope) { - case NoteQuery::Scope::All: - f.add(u"n.deleted_at IS NULL"_s); - break; - case NoteQuery::Scope::Folder: - f.add(u"n.deleted_at IS NULL"_s); - if (query.folderId.isEmpty()) - f.add(u"n.folder_id IS NULL"_s); - else - f.add(u"n.folder_id = ?"_s, {query.folderId}); - break; - case NoteQuery::Scope::Trash: - f.add(u"n.deleted_at IS NOT NULL"_s); - break; - case NoteQuery::Scope::Tag: - f.add(u"n.deleted_at IS NULL"_s); - f.add(u"n.id IN (SELECT note_id FROM note_tags WHERE tag = ?)"_s, {query.tag.toLower()}); - break; - case NoteQuery::Scope::Smart: { - const SmartCriteria &c = query.criteria; - f.add(u"n.deleted_at IS NULL"_s); - if (!c.tags.isEmpty()) { - QStringList marks; - QVariantList tags; - for (const QString &tag : c.tags) { - marks << u"?"_s; - tags << tag.toLower(); - } - if (c.matchAllTags) { - tags << qint64(c.tags.size()); - f.add(u"(SELECT COUNT(DISTINCT t.tag) FROM note_tags t WHERE t.note_id = n.id AND t.tag IN (%1)) = ?"_s - .arg(marks.join(u',')), tags); - } else { - f.add(u"n.id IN (SELECT note_id FROM note_tags WHERE tag IN (%1))"_s.arg(marks.join(u',')), tags); - } - } - if (c.hasChecklist) - f.add(u"n.has_checklist = 1"_s); - if (c.hasAttachments) - f.add(u"n.has_attachments = 1"_s); - if (c.pinnedOnly) - f.add(u"n.pinned = 1"_s); - constexpr qint64 day = 24 * 60 * 60 * 1000; - if (c.editedWithinDays > 0) - f.add(u"n.updated_at >= ?"_s, {timestamp - c.editedWithinDays * day}); - if (c.createdWithinDays > 0) - f.add(u"n.created_at >= ?"_s, {timestamp - c.createdWithinDays * day}); - if (!c.folderId.isEmpty()) - f.add(u"n.folder_id = ?"_s, {c.folderId}); - break; - } - } - return f; -} - -// Turns what someone typed into an FTS5 query: every word must match, each -// as a prefix, with FTS syntax characters treated as plain text. -QString ftsQuery(const QString &text) -{ - QStringList terms; - for (QString word : text.split(QRegularExpression(u"\\s+"_s), Qt::SkipEmptyParts)) { - word.remove(u'"'); - const bool hasWordChar = std::any_of(word.cbegin(), word.cend(), - [](QChar c) { return c.isLetterOrNumber(); }); - if (hasWordChar) - terms << u'"' + word + u"\"*"_s; - } - return terms.join(u' '); -} - -} // namespace - -QList NoteStore::listNotes(const NoteQuery &query) -{ - const Filter filter = filterFor(query, now()); - QByteArray sql = "SELECT "; - sql += kSummaryColumns; - sql += " FROM notes n WHERE " + filter.sql(); - if (query.scope == NoteQuery::Scope::Trash) { - sql += " ORDER BY n.deleted_at DESC"; - } else { - sql += " ORDER BY n.pinned DESC, "; - switch (query.sort) { - case NoteSort::Edited: sql += "n.updated_at DESC"; break; - case NoteSort::Created: sql += "n.created_at DESC"; break; - case NoteSort::Title: sql += "n.title = '', n.title COLLATE NOCASE, n.updated_at DESC"; break; - } - } - Statement s = m_db.prepare(sql.constData()); - filter.bindTo(s); - QList out; - while (s.next()) - out.append(readSummary(s)); - return out; -} - -int NoteStore::countMatching(const NoteQuery &query) -{ - const Filter filter = filterFor(query, now()); - Statement s = m_db.prepare(("SELECT COUNT(*) FROM notes n WHERE " + filter.sql()).constData()); - filter.bindTo(s); - return s.next() ? int(s.int64(0)) : 0; -} - -QList NoteStore::search(const QString &text, int limit) -{ - const QString match = ftsQuery(text); - if (match.isEmpty()) - return {}; - QByteArray sql = "SELECT "; - sql += QByteArray(kSummaryColumns).replace("n.snippet", "snippet(notes_fts, -1, char(2), char(3), '…', 12)"); - sql += " FROM notes_fts JOIN notes n ON n.rowid = notes_fts.rowid " - "WHERE notes_fts MATCH ?1 AND n.deleted_at IS NULL " - "ORDER BY bm25(notes_fts, 4.0, 1.0) LIMIT ?2"; - Statement s = m_db.prepare(sql.constData()); - s.bind(1, match).bind(2, qint64(limit)); - QList out; - while (s.next()) - out.append(readSummary(s)); - return out; -} - -std::optional NoteStore::loadNote(const QString &id, QString *error) -{ - Statement s = m_db.prepare( - "SELECT folder_id, body, created_at, updated_at, revision, pinned, deleted_at " - "FROM notes WHERE id = ?1"); - s.bind(1, id); - if (!s.next()) { - setError(error, s.failed() ? m_db.lastError() : u"The note no longer exists."_s); - return std::nullopt; - } - QString parseError; - auto body = RichDocument::fromJsonBytes(s.text(1).toUtf8(), &parseError); - if (!body) { - setError(error, u"The note could not be read: %1"_s.arg(parseError)); - return std::nullopt; - } - NoteRecord r; - r.id = id; - r.folderId = s.text(0); - r.body = std::move(*body); - r.createdAt = s.int64(2); - r.updatedAt = s.int64(3); - r.revision = s.int64(4); - r.pinned = s.int64(5) != 0; - r.deletedAt = s.isNull(6) ? 0 : s.int64(6); - return r; -} - -std::optional NoteStore::createNote(const RichDocument &body, QString *error, - const QString &folderId) -{ - if (!folderId.isEmpty() && !folderExists(folderId)) { - setError(error, u"That folder no longer exists."_s); - return std::nullopt; - } - NoteRecord r; - r.id = newId(); - r.folderId = folderId; - r.body = body; - r.body.assignMissingIds(); - r.createdAt = r.updatedAt = now(); - r.revision = 1; - - const bool media = !r.body.referencedAttachments().isEmpty() || !r.body.referencedBlobs().isEmpty(); - Statement s = m_db.prepare( - "INSERT INTO notes (id, folder_id, title, snippet, plain_text, body, body_schema, " - "has_attachments, has_checklist, created_at, updated_at, revision) " - "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10, 1)"); - s.bind(1, r.id); - if (folderId.isEmpty()) - s.bindNull(2); - else - s.bind(2, folderId); - s.bind(3, r.body.title()) - .bind(4, r.body.snippet()) - .bind(5, r.body.plainText()) - .bind(6, QString::fromUtf8(r.body.toJsonBytes())) - .bind(7, qint64(RichDocument::SchemaVersion)) - .bind(8, qint64(media)) - .bind(9, qint64(hasChecklist(r.body.blocks))) - .bind(10, r.createdAt); - Transaction tx(m_db); - if (!tx.isActive() || !s.exec() || !writeDerived(r.id, r.body) || !tx.commit()) { - setError(error, m_db.lastError()); - return std::nullopt; - } - return r; -} - -SaveResult NoteStore::saveNote(const SaveRequest &request) -{ - SaveResult result; - Transaction tx(m_db); - if (!tx.isActive()) { - result.error = m_db.friendlyError(); - return result; - } - - Statement current = m_db.prepare("SELECT revision FROM notes WHERE id = ?1"); - current.bind(1, request.noteId); - if (!current.next()) { - result.error = current.failed() ? m_db.lastError() : u"The note no longer exists."_s; - return result; - } - const qint64 storedRevision = current.int64(0); - if (storedRevision != request.baseRevision) { - result.status = SaveResult::Status::Conflict; - result.revision = storedRevision; - result.error = u"The note was changed elsewhere."_s; - return result; - } - - const RichDocument &body = request.body; - const QString json = QString::fromUtf8(body.toJsonBytes()); - const qint64 timestamp = now(); - const qint64 revision = storedRevision + 1; - const QStringList attachments = body.referencedAttachments(); - - Statement update = m_db.prepare( - "UPDATE notes SET title = ?2, snippet = ?3, plain_text = ?4, body = ?5, body_schema = ?6, " - "has_attachments = ?7, has_checklist = ?8, updated_at = ?9, revision = ?10 WHERE id = ?1"); - update.bind(1, request.noteId) - .bind(2, body.title()) - .bind(3, body.snippet()) - .bind(4, body.plainText()) - .bind(5, json) - .bind(6, qint64(RichDocument::SchemaVersion)) - .bind(7, qint64(!attachments.isEmpty() || !body.referencedBlobs().isEmpty())) - .bind(8, qint64(hasChecklist(body.blocks))) - .bind(9, timestamp) - .bind(10, revision); - if (!update.exec()) { - result.error = m_db.friendlyError(); - return result; - } - - if (!writeDerived(request.noteId, body)) { - result.error = m_db.friendlyError(); - return result; - } - - Statement lastSnapshot = m_db.prepare( - "SELECT MAX(created_at) FROM note_revisions WHERE note_id = ?1"); - lastSnapshot.bind(1, request.noteId); - const bool needSnapshot = !lastSnapshot.next() || lastSnapshot.isNull(0) - || timestamp - lastSnapshot.int64(0) >= RevisionIntervalMs; - if (needSnapshot) { - Statement snap = m_db.prepare( - "INSERT INTO note_revisions (note_id, revision, body, body_schema, created_at) " - "VALUES (?1, ?2, ?3, ?4, ?5)"); - snap.bind(1, request.noteId) - .bind(2, revision) - .bind(3, json) - .bind(4, qint64(RichDocument::SchemaVersion)) - .bind(5, timestamp); - if (!snap.exec()) { - result.error = m_db.friendlyError(); - return result; - } - } - - if (!tx.commit()) { - result.error = m_db.friendlyError(); - return result; - } - result.status = SaveResult::Status::Saved; - result.revision = revision; - result.updatedAt = timestamp; - return result; -} - -bool NoteStore::setPinned(const QString &id, bool pinned) -{ - Statement s = m_db.prepare("UPDATE notes SET pinned = ?2 WHERE id = ?1"); - s.bind(1, id).bind(2, qint64(pinned)); - return s.exec(); -} - -int NoteStore::revisionCount(const QString ¬eId) -{ - Statement s = m_db.prepare("SELECT COUNT(*) FROM note_revisions WHERE note_id = ?1"); - s.bind(1, noteId); - return s.next() ? int(s.int64(0)) : 0; -} - -// ---------------------------------------------------------------- derived data - -bool NoteStore::writeDerived(const QString ¬eId, const RichDocument &body) -{ - auto run = [&](const char *sql, const QVariantList &values) { - Statement s = m_db.prepare(sql); - for (int i = 0; i < values.size(); ++i) - s.bind(i + 1, values[i].toString()); - return s.exec(); - }; - // References to data this library doesn't have (e.g. pasted from - // elsewhere) are skipped rather than failing the save. - if (!run("DELETE FROM note_blob_refs WHERE note_id = ?1", {noteId})) - return false; - for (const QString &hash : body.referencedBlobs()) { - if (!run("INSERT OR IGNORE INTO note_blob_refs (note_id, blob_hash) " - "SELECT ?1, hash FROM blobs WHERE hash = ?2", {noteId, hash})) - return false; - } - if (!run("DELETE FROM note_attachment_refs WHERE note_id = ?1", {noteId})) - return false; - for (const QString &id : body.referencedAttachments()) { - if (!run("INSERT OR IGNORE INTO note_attachment_refs (note_id, attachment_id) " - "SELECT ?1, id FROM attachments WHERE id = ?2", {noteId, id})) - return false; - } - if (!run("DELETE FROM note_tags WHERE note_id = ?1", {noteId})) - return false; - for (const QString &tag : body.tags()) { - if (!run("INSERT OR IGNORE INTO note_tags (note_id, tag) VALUES (?1, ?2)", {noteId, tag})) - return false; - } - return run("UPDATE notes SET thumbnail = (SELECT hash FROM blobs WHERE hash = ?2) WHERE id = ?1", - {noteId, body.firstImage()}); -} - -QList NoteStore::listTags() -{ - Statement s = m_db.prepare( - "SELECT t.tag, COUNT(*) FROM note_tags t JOIN notes n ON n.id = t.note_id " - "WHERE n.deleted_at IS NULL GROUP BY t.tag ORDER BY t.tag"); - QList out; - while (s.next()) - out.append({s.text(0), int(s.int64(1))}); - return out; -} - -QList NoteStore::listSmartFolders() -{ - QList out; - { - Statement s = m_db.prepare("SELECT id, name, criteria FROM smart_folders ORDER BY name COLLATE NOCASE"); - while (s.next()) { - SmartFolder f; - f.id = s.text(0); - f.name = s.text(1); - f.criteria = SmartCriteria::fromJson(QJsonDocument::fromJson(s.text(2).toUtf8()).object()); - out.append(f); - } - } - for (SmartFolder &f : out) - f.noteCount = countMatching(NoteQuery::smart(f.criteria)); - return out; -} - -namespace { - -bool checkSmartFolder(Database &db, const QString &name, const SmartCriteria &criteria, const QString &selfId, - QString *error) -{ - if (name.isEmpty()) - return setError(error, u"Give the Smart Folder a name."_s); - if (name.size() > 200) - return setError(error, u"That name is too long."_s); - if (criteria.isEmpty()) - return setError(error, u"Choose at least one filter."_s); - Statement s = db.prepare("SELECT 1 FROM smart_folders WHERE name = ?1 COLLATE NOCASE AND id != ?2"); - s.bind(1, name).bind(2, selfId); - if (s.next()) - return setError(error, u"There's already a Smart Folder called “%1”."_s.arg(name)); - return true; -} - -} // namespace - -std::optional NoteStore::createSmartFolder(const QString &rawName, const SmartCriteria &criteria, - QString *error) -{ - const QString name = rawName.simplified(); - if (!checkSmartFolder(m_db, name, criteria, {}, error)) - return std::nullopt; - SmartFolder folder{newId(), name, criteria, 0}; - Statement s = m_db.prepare( - "INSERT INTO smart_folders (id, name, criteria, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?4)"); - s.bind(1, folder.id) - .bind(2, name) - .bind(3, QString::fromUtf8(QJsonDocument(criteria.toJson()).toJson(QJsonDocument::Compact))) - .bind(4, now()); - if (!s.exec()) { - setError(error, m_db.lastError()); - return std::nullopt; - } - folder.noteCount = countMatching(NoteQuery::smart(criteria)); - return folder; -} - -bool NoteStore::updateSmartFolder(const QString &id, const QString &rawName, const SmartCriteria &criteria, - QString *error) -{ - const QString name = rawName.simplified(); - if (!checkSmartFolder(m_db, name, criteria, id, error)) - return false; - Statement s = m_db.prepare("UPDATE smart_folders SET name = ?2, criteria = ?3, updated_at = ?4 WHERE id = ?1"); - s.bind(1, id) - .bind(2, name) - .bind(3, QString::fromUtf8(QJsonDocument(criteria.toJson()).toJson(QJsonDocument::Compact))) - .bind(4, now()); - if (!s.exec()) - return setError(error, m_db.lastError()); - return m_db.changes() == 1 || setError(error, u"That Smart Folder no longer exists."_s); -} - -bool NoteStore::deleteSmartFolder(const QString &id, QString *error) -{ - Statement s = m_db.prepare("DELETE FROM smart_folders WHERE id = ?1"); - s.bind(1, id); - return s.exec() || setError(error, m_db.lastError()); -} - -QList NoteStore::listAttachmentItems() -{ - Statement s = m_db.prepare( - "SELECT 1, r.blob_hash, NULL, NULL, NULL, b.size, n.id, n.title, n.updated_at " - " FROM note_blob_refs r JOIN notes n ON n.id = r.note_id JOIN blobs b ON b.hash = r.blob_hash " - " WHERE n.deleted_at IS NULL " - "UNION ALL " - "SELECT 0, a.blob_hash, a.id, a.file_name, a.mime_type, a.size, n.id, n.title, n.updated_at " - " FROM note_attachment_refs r JOIN attachments a ON a.id = r.attachment_id " - " JOIN notes n ON n.id = r.note_id WHERE n.deleted_at IS NULL " - "ORDER BY 9 DESC, 4"); - QList out; - while (s.next()) { - AttachmentItem item; - item.isImage = s.int64(0) != 0; - item.blobHash = s.text(1); - item.attachmentId = s.text(2); - item.fileName = s.text(3); - item.mimeType = s.text(4); - item.size = s.int64(5); - item.noteId = s.text(6); - item.noteTitle = s.text(7); - item.noteUpdatedAt = s.int64(8); - out.append(item); - } - return out; -} - -bool SmartCriteria::isEmpty() const -{ - return tags.isEmpty() && !hasChecklist && !hasAttachments && !pinnedOnly && editedWithinDays <= 0 - && createdWithinDays <= 0 && folderId.isEmpty(); -} - -QJsonObject SmartCriteria::toJson() const -{ - QJsonObject o; - if (!tags.isEmpty()) - o[u"tags"] = QJsonArray::fromStringList(tags); - if (matchAllTags) - o[u"matchAllTags"] = true; - if (hasChecklist) - o[u"hasChecklist"] = true; - if (hasAttachments) - o[u"hasAttachments"] = true; - if (pinnedOnly) - o[u"pinnedOnly"] = true; - if (editedWithinDays > 0) - o[u"editedWithinDays"] = editedWithinDays; - if (createdWithinDays > 0) - o[u"createdWithinDays"] = createdWithinDays; - if (!folderId.isEmpty()) - o[u"folderId"] = folderId; - return o; -} - -SmartCriteria SmartCriteria::fromJson(const QJsonObject &o) -{ - SmartCriteria c; - for (const QJsonValue &v : o[u"tags"].toArray()) - c.tags << v.toString().toLower(); - c.matchAllTags = o[u"matchAllTags"].toBool(); - c.hasChecklist = o[u"hasChecklist"].toBool(); - c.hasAttachments = o[u"hasAttachments"].toBool(); - c.pinnedOnly = o[u"pinnedOnly"].toBool(); - c.editedWithinDays = o[u"editedWithinDays"].toInt(); - c.createdWithinDays = o[u"createdWithinDays"].toInt(); - c.folderId = o[u"folderId"].toString(); - return c; -} - -// ---------------------------------------------------------------- notes - -bool NoteStore::moveNote(const QString ¬eId, const QString &folderId, QString *error) -{ - if (!folderId.isEmpty() && !folderExists(folderId)) - return setError(error, u"That folder no longer exists."_s); - Statement s = m_db.prepare("UPDATE notes SET folder_id = ?2 WHERE id = ?1 AND deleted_at IS NULL"); - s.bind(1, noteId); - if (folderId.isEmpty()) - s.bindNull(2); - else - s.bind(2, folderId); - if (!s.exec()) - return setError(error, m_db.lastError()); - return m_db.changes() == 1 || setError(error, u"The note no longer exists."_s); -} - -std::optional NoteStore::duplicateNote(const QString ¬eId, QString *error) -{ - auto source = loadNote(noteId, error); - if (!source) - return std::nullopt; - - Transaction tx(m_db); - if (!tx.isActive()) { - setError(error, m_db.lastError()); - return std::nullopt; - } - // Attachments belong to one note, so the copy gets its own records - // pointing at the same stored bytes. - QHash renamed; - for (const QString &id : source->body.referencedAttachments()) { - if (attachment(id)) - renamed.insert(id, newId()); - } - - RichDocument body = source->body; - std::function &)> rewrite = [&](QList &blocks) { - for (Block &b : blocks) { - for (Span &span : b.spans) { - if (span.kind == Span::Kind::Attachment && renamed.contains(span.ref)) - span.ref = renamed.value(span.ref); - } - for (TableCell &c : b.cells) - rewrite(c.blocks); - } - }; - rewrite(body.blocks); - - auto copy = createNote(body, error, source->folderId); - if (!copy) - return std::nullopt; - for (auto it = renamed.cbegin(); it != renamed.cend(); ++it) { - Statement s = m_db.prepare( - "INSERT INTO attachments (id, note_id, blob_hash, file_name, mime_type, size, created_at) " - "SELECT ?1, ?2, blob_hash, file_name, mime_type, size, ?3 FROM attachments WHERE id = ?4"); - s.bind(1, it.value()).bind(2, copy->id).bind(3, now()).bind(4, it.key()); - if (!s.exec()) { - setError(error, m_db.lastError()); - return std::nullopt; - } - } - // Attachment references were written before these records existed. - if (!writeDerived(copy->id, copy->body) || !tx.commit()) { - setError(error, m_db.lastError()); - return std::nullopt; - } - return copy; -} - -bool NoteStore::trashNote(const QString ¬eId, QString *error) -{ - Statement s = m_db.prepare("UPDATE notes SET deleted_at = ?2 WHERE id = ?1 AND deleted_at IS NULL"); - s.bind(1, noteId).bind(2, now()); - if (!s.exec()) - return setError(error, m_db.lastError()); - return m_db.changes() == 1 || setError(error, u"The note is already in Recently Deleted."_s); -} - -bool NoteStore::recoverNote(const QString ¬eId, QString *error) -{ - Statement s = m_db.prepare("UPDATE notes SET deleted_at = NULL WHERE id = ?1 AND deleted_at IS NOT NULL"); - s.bind(1, noteId); - if (!s.exec()) - return setError(error, m_db.lastError()); - return m_db.changes() == 1 || setError(error, u"The note isn't in Recently Deleted."_s); -} - -bool NoteStore::deleteNotePermanently(const QString ¬eId, QString *error) -{ - Statement s = m_db.prepare("DELETE FROM notes WHERE id = ?1 AND deleted_at IS NOT NULL"); - s.bind(1, noteId); - if (!s.exec()) - return setError(error, m_db.lastError()); - return m_db.changes() == 1 || setError(error, u"Only notes in Recently Deleted can be deleted permanently."_s); -} - -int NoteStore::emptyTrash(QString *error) -{ - Statement s = m_db.prepare("DELETE FROM notes WHERE deleted_at IS NOT NULL"); - if (!s.exec()) { - setError(error, m_db.lastError()); - return -1; - } - return m_db.changes(); -} - -int NoteStore::purgeExpiredTrash(qint64 at) -{ - Statement s = m_db.prepare("DELETE FROM notes WHERE deleted_at IS NOT NULL AND deleted_at < ?1"); - s.bind(1, (at ? at : now()) - TrashRetentionMs); - return s.exec() ? m_db.changes() : -1; -} - -int NoteStore::trashCount() -{ - Statement s = m_db.prepare("SELECT COUNT(*) FROM notes WHERE deleted_at IS NOT NULL"); - return s.next() ? int(s.int64(0)) : 0; -} - -int NoteStore::noteCount() -{ - Statement s = m_db.prepare("SELECT COUNT(*) FROM notes WHERE deleted_at IS NULL"); - return s.next() ? int(s.int64(0)) : 0; -} - -// ---------------------------------------------------------------- folders - -bool NoteStore::folderExists(const QString &id) -{ - Statement s = m_db.prepare("SELECT 1 FROM folders WHERE id = ?1"); - s.bind(1, id); - return s.next(); -} - -QStringList NoteStore::folderAndDescendants(const QString &id) -{ - Statement s = m_db.prepare( - "WITH RECURSIVE sub(id) AS (" - " SELECT id FROM folders WHERE id = ?1" - " UNION ALL SELECT f.id FROM folders f JOIN sub ON f.parent_id = sub.id" - ") SELECT id FROM sub"); - s.bind(1, id); - QStringList ids; - while (s.next()) - ids << s.text(0); - return ids; -} - -QList NoteStore::listFolders() -{ - Statement s = m_db.prepare( - "SELECT f.id, f.parent_id, f.name, " - " (SELECT COUNT(*) FROM notes n WHERE n.folder_id = f.id AND n.deleted_at IS NULL) " - "FROM folders f ORDER BY f.name COLLATE NOCASE, f.created_at"); - QList out; - while (s.next()) - out.append({s.text(0), s.text(1), s.text(2), int(s.int64(3))}); - return out; -} - -namespace { - -// Validates a folder name and checks it is unique among its siblings. -bool checkFolderName(Database &db, const QString &name, const QString &parentId, const QString &selfId, - QString *error) -{ - if (name.isEmpty()) - return setError(error, u"Give the folder a name."_s); - if (name.size() > 200) - return setError(error, u"That name is too long."_s); - Statement s = db.prepare( - "SELECT 1 FROM folders WHERE name = ?1 COLLATE NOCASE AND id != ?3 AND " - "((?2 IS NULL AND parent_id IS NULL) OR parent_id = ?2)"); - s.bind(1, name); - if (parentId.isEmpty()) - s.bindNull(2); - else - s.bind(2, parentId); - s.bind(3, selfId); - if (s.next()) - return setError(error, u"There's already a folder called “%1” here."_s.arg(name)); - return true; -} - -} // namespace - -std::optional NoteStore::createFolder(const QString &rawName, const QString &parentId, - QString *error) -{ - const QString name = rawName.simplified(); - if (!parentId.isEmpty() && !folderExists(parentId)) { - setError(error, u"That folder no longer exists."_s); - return std::nullopt; - } - if (!checkFolderName(m_db, name, parentId, {}, error)) - return std::nullopt; - FolderInfo folder{newId(), parentId, name, 0}; - Statement s = m_db.prepare( - "INSERT INTO folders (id, parent_id, name, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?4)"); - s.bind(1, folder.id); - if (parentId.isEmpty()) - s.bindNull(2); - else - s.bind(2, parentId); - s.bind(3, name).bind(4, now()); - if (!s.exec()) { - setError(error, m_db.lastError()); - return std::nullopt; - } - return folder; -} - -bool NoteStore::renameFolder(const QString &id, const QString &rawName, QString *error) -{ - const QString name = rawName.simplified(); - Statement parent = m_db.prepare("SELECT parent_id FROM folders WHERE id = ?1"); - parent.bind(1, id); - if (!parent.next()) - return setError(error, u"That folder no longer exists."_s); - if (!checkFolderName(m_db, name, parent.text(0), id, error)) - return false; - Statement s = m_db.prepare("UPDATE folders SET name = ?2, updated_at = ?3 WHERE id = ?1"); - s.bind(1, id).bind(2, name).bind(3, now()); - return s.exec() || setError(error, m_db.lastError()); -} - -bool NoteStore::deleteFolder(const QString &id, QString *error) -{ - const QStringList ids = folderAndDescendants(id); - if (ids.isEmpty()) - return setError(error, u"That folder no longer exists."_s); - Transaction tx(m_db); - if (!tx.isActive()) - return setError(error, m_db.lastError()); - const qint64 timestamp = now(); - for (const QString &folder : ids) { - // Deleted notes can't return to a folder that's gone; they recover - // into Notes instead. - Statement notes = m_db.prepare( - "UPDATE notes SET deleted_at = COALESCE(deleted_at, ?2), folder_id = NULL WHERE folder_id = ?1"); - notes.bind(1, folder).bind(2, timestamp); - if (!notes.exec()) - return setError(error, m_db.lastError()); - } - // Children first, so no folder is removed while another points at it. - for (auto it = ids.crbegin(); it != ids.crend(); ++it) { - Statement del = m_db.prepare("DELETE FROM folders WHERE id = ?1"); - del.bind(1, *it); - if (!del.exec()) - return setError(error, m_db.lastError()); - } - return tx.commit() || setError(error, m_db.lastError()); -} - -// ---------------------------------------------------------------- garbage - -GarbageReport NoteStore::collectGarbage(qint64 at) -{ - GarbageReport report; - const qint64 cutoff = (at ? at : now()) - GarbageGraceMs; - - // Everything any note or saved revision still refers to. - QSet blobs; - QSet attachments; - Statement bodies = m_db.prepare("SELECT body FROM notes UNION ALL SELECT body FROM note_revisions"); - while (bodies.next()) { - const auto doc = RichDocument::fromJsonBytes(bodies.text(0).toUtf8()); - if (!doc) - continue; - for (const QString &hash : doc->referencedBlobs()) - blobs.insert(hash); - for (const QString &id : doc->referencedAttachments()) - attachments.insert(id); - } - - QStringList removedHashes; - { - Transaction tx(m_db); - if (!tx.isActive()) - return report; - Statement rows = m_db.prepare("SELECT id FROM attachments WHERE created_at < ?1"); - rows.bind(1, cutoff); - QStringList staleAttachments; - while (rows.next()) { - if (!attachments.contains(rows.text(0))) - staleAttachments << rows.text(0); - } - for (const QString &id : staleAttachments) { - Statement del = m_db.prepare("DELETE FROM attachments WHERE id = ?1"); - del.bind(1, id); - if (!del.exec()) - return report; - } - - Statement candidates = m_db.prepare( - "SELECT hash, size FROM blobs WHERE created_at < ?1 " - "AND hash NOT IN (SELECT blob_hash FROM attachments) " - "AND hash NOT IN (SELECT blob_hash FROM note_blob_refs)"); - candidates.bind(1, cutoff); - QList> stale; - while (candidates.next()) { - if (!blobs.contains(candidates.text(0))) - stale.append({candidates.text(0), candidates.int64(1)}); - } - for (const auto &[hash, size] : stale) { - Statement del = m_db.prepare("DELETE FROM blobs WHERE hash = ?1"); - del.bind(1, hash); - if (!del.exec()) - return report; - removedHashes << hash; - report.bytesFreed += size; - } - if (!tx.commit()) - return GarbageReport{}; - report.attachmentsRemoved = int(staleAttachments.size()); - } - // Files go only after the database no longer refers to them. - for (const QString &hash : removedHashes) - QFile::remove(m_blobs.path(hash)); - report.blobsRemoved = int(removedHashes.size()); - - // Files left by an install that was interrupted before it was recorded. - QSet known; - Statement all = m_db.prepare("SELECT hash FROM blobs"); - while (all.next()) - known.insert(all.text(0)); - const QDateTime cutoffTime = QDateTime::fromMSecsSinceEpoch(cutoff); - QDirIterator it(m_paths.blobs(), QDir::Files, QDirIterator::Subdirectories); - while (it.hasNext()) { - const QFileInfo file(it.next()); - if (!known.contains(file.fileName()) && file.lastModified() < cutoffTime) { - report.bytesFreed += file.size(); - QFile::remove(file.filePath()); - ++report.blobsRemoved; - } - } - return report; -} - -bool NoteStore::registerBlob(const BlobStore::Installed &blob) -{ - Statement s = m_db.prepare( - "INSERT OR IGNORE INTO blobs (hash, size, created_at) VALUES (?1, ?2, ?3)"); - s.bind(1, blob.hash).bind(2, blob.size).bind(3, now()); - return s.exec(); -} - -std::optional NoteStore::addAttachment(const QString ¬eId, const QString &filePath, - QString *error) -{ - const auto installed = m_blobs.installFile(filePath, error); - if (!installed) - return std::nullopt; - - AttachmentInfo info; - info.id = newId(); - info.noteId = noteId; - info.blobHash = installed->hash; - info.fileName = QFileInfo(filePath).fileName(); - info.mimeType = QMimeDatabase().mimeTypeForFile(filePath).name(); - info.size = installed->size; - - Transaction tx(m_db); - Statement s = m_db.prepare( - "INSERT INTO attachments (id, note_id, blob_hash, file_name, mime_type, size, created_at) " - "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"); - s.bind(1, info.id) - .bind(2, info.noteId) - .bind(3, info.blobHash) - .bind(4, info.fileName) - .bind(5, info.mimeType) - .bind(6, info.size) - .bind(7, now()); - if (!tx.isActive() || !registerBlob(*installed) || !s.exec() || !tx.commit()) { - setError(error, u"Could not record the attachment: %1"_s.arg(m_db.lastError())); - return std::nullopt; - } - return info; -} - -std::optional NoteStore::attachment(const QString &id) -{ - Statement s = m_db.prepare( - "SELECT note_id, blob_hash, file_name, mime_type, size FROM attachments WHERE id = ?1"); - s.bind(1, id); - if (!s.next()) - return std::nullopt; - AttachmentInfo info; - info.id = id; - info.noteId = s.text(0); - info.blobHash = s.text(1); - info.fileName = s.text(2); - info.mimeType = s.text(3); - info.size = s.int64(4); - return info; -} - -std::optional NoteStore::addImage(const QByteArray &bytes, QString *error) -{ - const auto installed = m_blobs.installBytes(bytes, error); - if (!installed) - return std::nullopt; - if (!registerBlob(*installed)) { - setError(error, m_db.lastError()); - return std::nullopt; - } - return installed->hash; -} - -std::optional NoteStore::addImageFile(const QString &filePath, QString *error) -{ - const auto installed = m_blobs.installFile(filePath, error); - if (!installed) - return std::nullopt; - if (!registerBlob(*installed)) { - setError(error, m_db.lastError()); - return std::nullopt; - } - return installed->hash; -} - -QStringList NoteStore::verify() -{ - QStringList problems; - Statement integrity = m_db.prepare("PRAGMA integrity_check"); - while (integrity.next()) { - const QString row = integrity.text(0); - if (row != u"ok") - problems.append(u"integrity: "_s + row); - } - Statement fk = m_db.prepare("PRAGMA foreign_key_check"); - while (fk.next()) - problems.append(u"foreign key: %1 row %2"_s.arg(fk.text(0)).arg(fk.int64(1))); - Statement blobs = m_db.prepare("SELECT hash FROM blobs"); - while (blobs.next()) { - if (!m_blobs.contains(blobs.text(0))) - problems.append(u"missing blob "_s + blobs.text(0)); - } - Statement notes = m_db.prepare("SELECT id, body FROM notes"); - while (notes.next()) { - QString err; - if (!RichDocument::fromJsonBytes(notes.text(1).toUtf8(), &err)) - problems.append(u"note %1: %2"_s.arg(notes.text(0), err)); - } - return problems; -} - -bool NoteStore::backupDatabase(const QString &destination, QString *error) -{ - Database target; - if (!target.open(destination, error)) - return false; - sqlite3_backup *backup = sqlite3_backup_init(target.handle(), "main", m_db.handle(), "main"); - if (!backup) - return setError(error, target.lastError()); - const int rc = sqlite3_backup_step(backup, -1); - sqlite3_backup_finish(backup); - if (rc != SQLITE_DONE) - return setError(error, target.lastError()); - return true; -} - -} // namespace onotes diff --git a/src/core/NoteStore.h b/src/core/NoteStore.h deleted file mode 100644 index 81e933e..0000000 --- a/src/core/NoteStore.h +++ /dev/null @@ -1,268 +0,0 @@ -#pragma once - -#include "BlobStore.h" -#include "Database.h" -#include "LibraryPaths.h" -#include "RichDocument.h" - -#include -#include -#include -#include - -#include - -namespace onotes { - -struct NoteSummary { - QString id; - QString folderId; // empty: the top-level "Notes" folder - QString title; - QString snippet; // for search results: the best match, marked with \x02..\x03 - QString thumbnail; // blob hash of the first image, if any - qint64 createdAt = 0; // ms since epoch - qint64 updatedAt = 0; - qint64 deletedAt = 0; // non-zero while in Recently Deleted - bool pinned = false; - bool hasAttachments = false; - bool hasChecklist = false; -}; - -struct NoteRecord { - QString id; - QString folderId; - RichDocument body; - qint64 createdAt = 0; - qint64 updatedAt = 0; - qint64 deletedAt = 0; - qint64 revision = 0; - bool pinned = false; -}; - -struct FolderInfo { - QString id; - QString parentId; // empty: top level - QString name; - int noteCount = 0; // notes directly inside, excluding deleted ones -}; - -enum class NoteSort { Edited, Created, Title }; - -struct TagInfo { - QString name; // lowercased, without '#' - int noteCount = 0; -}; - -// What a Smart Folder matches. Every set criterion must hold. -struct SmartCriteria { - QStringList tags; - bool matchAllTags = false; // otherwise any of the tags - bool hasChecklist = false; - bool hasAttachments = false; - bool pinnedOnly = false; - int editedWithinDays = 0; // 0: any time - int createdWithinDays = 0; - QString folderId; // empty: any folder - - bool isEmpty() const; - QJsonObject toJson() const; - static SmartCriteria fromJson(const QJsonObject &json); - bool operator==(const SmartCriteria &) const = default; -}; - -struct SmartFolder { - QString id; - QString name; - SmartCriteria criteria; - int noteCount = 0; -}; - -// Which notes a list shows. -struct NoteQuery { - enum class Scope { - All, // every note not in Recently Deleted - Folder, // one folder; an empty folderId is the top-level "Notes" - Trash, // Recently Deleted - Tag, // notes with `tag` - Smart, // notes matching `criteria` - }; - Scope scope = Scope::All; - QString folderId; - NoteSort sort = NoteSort::Edited; - QString tag; - SmartCriteria criteria; - - static NoteQuery all(NoteSort sort = NoteSort::Edited) { return {Scope::All, {}, sort, {}, {}}; } - static NoteQuery folder(const QString &id, NoteSort sort = NoteSort::Edited) { return {Scope::Folder, id, sort, {}, {}}; } - static NoteQuery trash() { return {Scope::Trash, {}, NoteSort::Edited, {}, {}}; } - static NoteQuery tagged(const QString &tag, NoteSort sort = NoteSort::Edited) { return {Scope::Tag, {}, sort, tag, {}}; } - static NoteQuery smart(const SmartCriteria &criteria, NoteSort sort = NoteSort::Edited) { return {Scope::Smart, {}, sort, {}, criteria}; } -}; - -// An image or file inside a note, for the attachment browser. -struct AttachmentItem { - bool isImage = false; - QString blobHash; - QString attachmentId; // files only - QString fileName; // files only - QString mimeType; // files only - qint64 size = 0; - QString noteId; - QString noteTitle; - qint64 noteUpdatedAt = 0; -}; - -struct GarbageReport { - int blobsRemoved = 0; - int attachmentsRemoved = 0; - qint64 bytesFreed = 0; -}; - -// Describes a backup folder (see NoteStore::backupTo). -struct BackupManifest { - static constexpr int FormatVersion = 1; - QString path; - QString appVersion; - int schemaVersion = 0; - qint64 createdAt = 0; - int notes = 0; - int blobs = 0; - qint64 bytes = 0; -}; - -struct AttachmentInfo { - QString id; - QString noteId; - QString blobHash; - QString fileName; - QString mimeType; - qint64 size = 0; -}; - -struct SaveRequest { - QString noteId; - qint64 baseRevision = 0; // must match the stored revision - RichDocument body; -}; - -struct SaveResult { - enum class Status { Saved, Conflict, Failed }; - Status status = Status::Failed; - qint64 revision = 0; - qint64 updatedAt = 0; - QString error; -}; - -// Owns the SQLite library and blob directory. Not thread-safe: one instance -// is owned by the persistence thread (see LibraryService). -class NoteStore -{ -public: - static constexpr int SchemaVersion = 2; - // Keep at most one history snapshot per note per interval. - static constexpr qint64 RevisionIntervalMs = 10 * 60 * 1000; - - explicit NoteStore(LibraryPaths paths); - - bool open(QString *error); - void close(); - - // Deleted notes stay in Recently Deleted this long before being purged. - static constexpr qint64 TrashRetentionMs = qint64(30) * 24 * 60 * 60 * 1000; - // Unreferenced attachment data younger than this is kept: an image may - // have been inserted into a note whose save is still pending. - static constexpr qint64 GarbageGraceMs = qint64(24) * 60 * 60 * 1000; - - QList listNotes(const NoteQuery &query = {}); - // Full-text search over notes not in Recently Deleted, best matches first. - // Every word must match; words match as prefixes ("bench" finds "benchmark"). - QList search(const QString &text, int limit = 200); - std::optional loadNote(const QString &id, QString *error = nullptr); - std::optional createNote(const RichDocument &body, QString *error = nullptr, - const QString &folderId = {}); - SaveResult saveNote(const SaveRequest &request); - bool setPinned(const QString &id, bool pinned); - int revisionCount(const QString ¬eId); - - // Notes - bool moveNote(const QString ¬eId, const QString &folderId, QString *error = nullptr); - std::optional duplicateNote(const QString ¬eId, QString *error = nullptr); - bool trashNote(const QString ¬eId, QString *error = nullptr); - // Brings a note back from Recently Deleted, into its folder if that still exists. - bool recoverNote(const QString ¬eId, QString *error = nullptr); - // Only notes already in Recently Deleted can be deleted permanently. - bool deleteNotePermanently(const QString ¬eId, QString *error = nullptr); - int emptyTrash(QString *error = nullptr); - int purgeExpiredTrash(qint64 now = 0); - int trashCount(); - int noteCount(); - - // Tags come from #tags in note text and are kept up to date on save. - QList listTags(); - - // Smart Folders - QList listSmartFolders(); - std::optional createSmartFolder(const QString &name, const SmartCriteria &criteria, - QString *error = nullptr); - bool updateSmartFolder(const QString &id, const QString &name, const SmartCriteria &criteria, - QString *error = nullptr); - bool deleteSmartFolder(const QString &id, QString *error = nullptr); - - // Every image and file in notes that aren't deleted, newest notes first. - QList listAttachmentItems(); - - // Folders - QList listFolders(); - std::optional createFolder(const QString &name, const QString &parentId = {}, - QString *error = nullptr); - bool renameFolder(const QString &id, const QString &name, QString *error = nullptr); - // Moves the folder's notes (and its subfolders' notes) to Recently Deleted, - // then removes the folders. - bool deleteFolder(const QString &id, QString *error = nullptr); - - // Removes attachment data no note or revision refers to any more. - GarbageReport collectGarbage(qint64 now = 0); - - // Writes a complete, self-describing backup folder at `directory` - // (which must not exist yet). - std::optional backupTo(const QString &directory, QString *error = nullptr); - // Checks that a backup folder is complete and readable by this version. - static std::optional inspectBackup(const QString &directory, QString *error = nullptr); - - std::optional addAttachment(const QString ¬eId, const QString &filePath, - QString *error = nullptr); - std::optional attachment(const QString &id); - // Stores image bytes and returns the blob hash. - std::optional addImage(const QByteArray &bytes, QString *error = nullptr); - std::optional addImageFile(const QString &filePath, QString *error = nullptr); - - QString blobPath(const QString &hash) const { return m_blobs.path(hash); } - // The open connection, for maintenance tasks and failure-injection tests. - Database &database() { return m_db; } - const LibraryPaths &paths() const { return m_paths; } - - // PRAGMA integrity_check plus attachment reference checks. - QStringList verify(); - // Consistent online snapshot of the database (attachments are copied separately). - bool backupDatabase(const QString &destination, QString *error); - -private: - bool migrate(QString *error); - bool folderExists(const QString &id); - // Rewrites what's derived from a note's body: image and attachment - // references, tags and the thumbnail. - bool writeDerived(const QString ¬eId, const RichDocument &body); - int countMatching(const NoteQuery &query); - QStringList folderAndDescendants(const QString &id); - bool registerBlob(const BlobStore::Installed &blob); - - LibraryPaths m_paths; - BlobStore m_blobs; - Database m_db; -}; - -} // namespace onotes - -Q_DECLARE_METATYPE(onotes::SaveResult) -Q_DECLARE_METATYPE(onotes::NoteSummary) -Q_DECLARE_METATYPE(QList) diff --git a/src/core/RichDocument.cpp b/src/core/RichDocument.cpp deleted file mode 100644 index ed89773..0000000 --- a/src/core/RichDocument.cpp +++ /dev/null @@ -1,547 +0,0 @@ -#include "RichDocument.h" - -#include -#include -#include -#include -#include - -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -namespace { - -struct MarkName { - Mark mark; - const char *name; -}; - -constexpr MarkName kMarkNames[] = { - {Bold, "bold"}, - {Italic, "italic"}, - {Underline, "underline"}, - {Strikethrough, "strikethrough"}, - {Highlight, "highlight"}, - {Code, "code"}, -}; - -const char *listKindName(ListKind kind) -{ - switch (kind) { - case ListKind::Bullet: return "bullet"; - case ListKind::Ordered: return "ordered"; - case ListKind::Check: return "check"; - case ListKind::None: break; - } - return "bullet"; -} - -std::optional listKindFromName(const QString &name) -{ - if (name == u"bullet") return ListKind::Bullet; - if (name == u"ordered") return ListKind::Ordered; - if (name == u"check") return ListKind::Check; - return std::nullopt; -} - -QJsonObject spanToJson(const Span &span) -{ - QJsonObject o; - switch (span.kind) { - case Span::Kind::Text: { - o[u"text"] = span.text; - if (span.marks) { - QJsonArray marks; - for (const auto &m : kMarkNames) { - if (span.marks & m.mark) - marks.append(QLatin1StringView(m.name)); - } - o[u"marks"] = marks; - } - if (!span.href.isEmpty()) - o[u"href"] = span.href; - break; - } - case Span::Kind::Image: - o[u"image"] = span.ref; - if (span.width > 0) o[u"width"] = span.width; - if (span.height > 0) o[u"height"] = span.height; - if (!span.alt.isEmpty()) o[u"alt"] = span.alt; - break; - case Span::Kind::Attachment: - o[u"attachment"] = span.ref; - break; - } - return o; -} - -QJsonArray blocksToJson(const QList &blocks); - -QJsonObject blockToJson(const Block &block) -{ - QJsonObject o; - o[u"id"] = block.id; - auto spans = [&] { - QJsonArray a; - for (const Span &s : block.spans) - a.append(spanToJson(s)); - return a; - }; - switch (block.type) { - case Block::Type::Paragraph: - o[u"type"] = u"paragraph"_s; - o[u"spans"] = spans(); - break; - case Block::Type::Heading: - o[u"type"] = u"heading"_s; - o[u"level"] = block.level; - o[u"spans"] = spans(); - break; - case Block::Type::ListItem: - o[u"type"] = u"list"_s; - o[u"list"] = QLatin1StringView(listKindName(block.list)); - o[u"indent"] = block.indent; - if (block.list == ListKind::Check) - o[u"checked"] = block.checked; - o[u"spans"] = spans(); - break; - case Block::Type::Table: { - o[u"type"] = u"table"_s; - o[u"rows"] = block.rows; - o[u"columns"] = block.columns; - QJsonArray cells; - for (const TableCell &c : block.cells) { - QJsonObject co; - co[u"row"] = c.row; - co[u"col"] = c.column; - if (c.rowSpan != 1) co[u"rowSpan"] = c.rowSpan; - if (c.columnSpan != 1) co[u"colSpan"] = c.columnSpan; - co[u"blocks"] = blocksToJson(c.blocks); - cells.append(co); - } - o[u"cells"] = cells; - break; - } - } - return o; -} - -QJsonArray blocksToJson(const QList &blocks) -{ - QJsonArray a; - for (const Block &b : blocks) - a.append(blockToJson(b)); - return a; -} - -bool fail(QString *error, const QString &message) -{ - if (error) - *error = message; - return false; -} - -bool spanFromJson(const QJsonObject &o, Span *out, QString *error) -{ - Span s; - if (o.contains(u"text")) { - s.kind = Span::Kind::Text; - s.text = o[u"text"].toString(); - for (const QJsonValue &v : o[u"marks"].toArray()) { - const QString name = v.toString(); - bool known = false; - for (const auto &m : kMarkNames) { - if (name == QLatin1StringView(m.name)) { - s.marks |= m.mark; - known = true; - } - } - if (!known) - return fail(error, u"unknown mark '%1'"_s.arg(name)); - } - s.href = o[u"href"].toString(); - } else if (o.contains(u"image")) { - s.kind = Span::Kind::Image; - s.ref = o[u"image"].toString(); - if (!isValidBlobHash(s.ref)) - return fail(error, u"invalid image reference"_s); - s.width = o[u"width"].toInt(); - s.height = o[u"height"].toInt(); - s.alt = o[u"alt"].toString(); - } else if (o.contains(u"attachment")) { - s.kind = Span::Kind::Attachment; - s.ref = o[u"attachment"].toString(); - if (QUuid::fromString(s.ref).isNull()) - return fail(error, u"invalid attachment reference"_s); - } else { - return fail(error, u"span has no content"_s); - } - *out = s; - return true; -} - -bool blocksFromJson(const QJsonArray &array, QList *out, QString *error, int depth); - -bool blockFromJson(const QJsonObject &o, Block *out, QString *error, int depth) -{ - Block b; - b.id = o[u"id"].toString(); - const QString type = o[u"type"].toString(); - - auto readSpans = [&]() -> bool { - for (const QJsonValue &v : o[u"spans"].toArray()) { - Span s; - if (!spanFromJson(v.toObject(), &s, error)) - return false; - b.spans.append(s); - } - return true; - }; - - if (type == u"paragraph") { - b.type = Block::Type::Paragraph; - if (!readSpans()) return false; - } else if (type == u"heading") { - b.type = Block::Type::Heading; - b.level = o[u"level"].toInt(); - if (b.level < 1 || b.level > 3) - return fail(error, u"heading level out of range"_s); - if (!readSpans()) return false; - } else if (type == u"list") { - b.type = Block::Type::ListItem; - const auto kind = listKindFromName(o[u"list"].toString()); - if (!kind) - return fail(error, u"unknown list kind"_s); - b.list = *kind; - b.indent = o[u"indent"].toInt(); - if (b.indent < 0 || b.indent > 16) - return fail(error, u"list indent out of range"_s); - b.checked = b.list == ListKind::Check && o[u"checked"].toBool(); - if (!readSpans()) return false; - } else if (type == u"table") { - b.type = Block::Type::Table; - if (depth > 4) - return fail(error, u"tables nested too deeply"_s); - b.rows = o[u"rows"].toInt(); - b.columns = o[u"columns"].toInt(); - if (b.rows < 1 || b.columns < 1 || b.rows > 1000 || b.columns > 64) - return fail(error, u"table dimensions out of range"_s); - for (const QJsonValue &v : o[u"cells"].toArray()) { - const QJsonObject co = v.toObject(); - TableCell c; - c.row = co[u"row"].toInt(); - c.column = co[u"col"].toInt(); - c.rowSpan = co[u"rowSpan"].toInt(1); - c.columnSpan = co[u"colSpan"].toInt(1); - if (c.row < 0 || c.column < 0 || c.rowSpan < 1 || c.columnSpan < 1 - || c.row + c.rowSpan > b.rows || c.column + c.columnSpan > b.columns) - return fail(error, u"table cell out of range"_s); - if (!blocksFromJson(co[u"blocks"].toArray(), &c.blocks, error, depth + 1)) - return false; - // A cell always holds at least one paragraph, as in the editor. - if (c.blocks.isEmpty()) - c.blocks.append(Block::paragraph()); - b.cells.append(c); - } - } else { - return fail(error, u"unknown block type '%1'"_s.arg(type)); - } - *out = b; - return true; -} - -bool blocksFromJson(const QJsonArray &array, QList *out, QString *error, int depth) -{ - for (const QJsonValue &v : array) { - Block b; - if (!blockFromJson(v.toObject(), &b, error, depth)) - return false; - out->append(b); - } - return true; -} - -void appendText(const QList &blocks, QString *out) -{ - for (const Block &b : blocks) { - if (b.type == Block::Type::Table) { - for (const TableCell &c : b.cells) { - appendText(c.blocks, out); - } - continue; - } - const QString text = b.plainText(); - if (text.isEmpty()) - continue; - if (!out->isEmpty()) - out->append(u'\n'); - out->append(text); - } -} - -template -void forEachSpan(const QList &blocks, Fn fn) -{ - for (const Block &b : blocks) { - for (const Span &s : b.spans) - fn(s); - for (const TableCell &c : b.cells) - forEachSpan(c.blocks, fn); - } -} - -void assignIds(QList &blocks, QSet &seen) -{ - for (Block &b : blocks) { - if (b.id.isEmpty() || seen.contains(b.id)) - b.id = newId(); - seen.insert(b.id); - for (TableCell &c : b.cells) - assignIds(c.blocks, seen); - } -} - -} // namespace - -Span Span::plain(const QString &text, quint32 marks, const QString &href) -{ - Span s; - s.text = text; - s.marks = marks; - s.href = href; - return s; -} - -Span Span::image(const QString &blobHash, int width, int height, const QString &alt) -{ - Span s; - s.kind = Kind::Image; - s.ref = blobHash; - s.width = width; - s.height = height; - s.alt = alt; - return s; -} - -Span Span::attachment(const QString &attachmentId) -{ - Span s; - s.kind = Kind::Attachment; - s.ref = attachmentId; - return s; -} - -bool TableCell::operator==(const TableCell &o) const -{ - return row == o.row && column == o.column && rowSpan == o.rowSpan - && columnSpan == o.columnSpan && blocks == o.blocks; -} - -bool Block::operator==(const Block &o) const -{ - return type == o.type && id == o.id && level == o.level && list == o.list - && indent == o.indent && checked == o.checked && spans == o.spans - && rows == o.rows && columns == o.columns && cells == o.cells; -} - -Block Block::paragraph(const QList &spans) -{ - Block b; - b.spans = spans; - return b; -} - -Block Block::heading(int level, const QList &spans) -{ - Block b; - b.type = Type::Heading; - b.level = level; - b.spans = spans; - return b; -} - -Block Block::listItem(ListKind kind, int indent, const QList &spans, bool checked) -{ - Block b; - b.type = Type::ListItem; - b.list = kind; - b.indent = indent; - b.spans = spans; - b.checked = kind == ListKind::Check && checked; - return b; -} - -QString Block::plainText() const -{ - QString text; - for (const Span &s : spans) { - if (s.kind == Span::Kind::Text) - text += s.text; - } - return text; -} - -bool Block::isEmptyParagraph() const -{ - return type == Type::Paragraph && spans.isEmpty(); -} - -QString RichDocument::title() const -{ - QString text; - appendText(blocks, &text); - for (const QString &line : text.split(u'\n')) { - const QString trimmed = line.trimmed(); - if (!trimmed.isEmpty()) - return trimmed.left(200); - } - return {}; -} - -QString RichDocument::snippet(int maxLength) const -{ - QString text; - appendText(blocks, &text); - QStringList lines = text.split(u'\n', Qt::SkipEmptyParts); - // Drop the title line. - while (!lines.isEmpty() && lines.first().trimmed().isEmpty()) - lines.removeFirst(); - if (!lines.isEmpty()) - lines.removeFirst(); - QString joined = lines.join(u' ').simplified(); - if (joined.size() > maxLength) - joined = joined.left(maxLength - 1) + u'…'; - return joined; -} - -QString RichDocument::plainText() const -{ - QString text; - appendText(blocks, &text); - return text; -} - -QStringList RichDocument::referencedBlobs() const -{ - QStringList out; - forEachSpan(blocks, [&](const Span &s) { - if (s.kind == Span::Kind::Image && !out.contains(s.ref)) - out.append(s.ref); - }); - return out; -} - -QStringList RichDocument::referencedAttachments() const -{ - QStringList out; - forEachSpan(blocks, [&](const Span &s) { - if (s.kind == Span::Kind::Attachment && !out.contains(s.ref)) - out.append(s.ref); - }); - return out; -} - -QStringList RichDocument::tags() const -{ - QStringList out; - forEachSpan(blocks, [&](const Span &s) { - if (s.kind != Span::Kind::Text || (s.marks & Code) || !s.href.isEmpty()) - return; - for (const TagMatch &m : findTags(s.text)) { - if (!out.contains(m.tag)) - out.append(m.tag); - } - }); - return out; -} - -QString RichDocument::firstImage() const -{ - QString first; - forEachSpan(blocks, [&](const Span &s) { - if (first.isEmpty() && s.kind == Span::Kind::Image) - first = s.ref; - }); - return first; -} - -void RichDocument::assignMissingIds() -{ - QSet seen; - assignIds(blocks, seen); -} - -QJsonObject RichDocument::toJson() const -{ - QJsonObject o; - o[u"schema"] = SchemaVersion; - o[u"blocks"] = blocksToJson(blocks); - return o; -} - -QByteArray RichDocument::toJsonBytes() const -{ - return QJsonDocument(toJson()).toJson(QJsonDocument::Compact); -} - -std::optional RichDocument::fromJson(const QJsonObject &json, QString *error) -{ - const int schema = json[u"schema"].toInt(); - if (schema != SchemaVersion) { - fail(error, u"unsupported document schema %1"_s.arg(schema)); - return std::nullopt; - } - RichDocument doc; - if (!blocksFromJson(json[u"blocks"].toArray(), &doc.blocks, error, 0)) - return std::nullopt; - if (doc.blocks.isEmpty()) - doc.blocks.append(Block::paragraph()); - return doc; -} - -std::optional RichDocument::fromJsonBytes(const QByteArray &bytes, QString *error) -{ - QJsonParseError parseError; - const QJsonDocument json = QJsonDocument::fromJson(bytes, &parseError); - if (!json.isObject()) { - fail(error, parseError.errorString()); - return std::nullopt; - } - return fromJson(json.object(), error); -} - -QString newId() -{ - return QUuid::createUuid().toString(QUuid::WithoutBraces); -} - -QList findTags(const QString &text) -{ - static const QRegularExpression re( - u"(?:^|(?<=[\\s(\\[{\"'\u201c\u2018]))#([\\p{L}\\p{N}_][\\p{L}\\p{N}_/\\-]*)"_s); - QList out; - auto it = re.globalMatch(text); - while (it.hasNext()) { - const QRegularExpressionMatch m = it.next(); - QString tag = m.captured(1); - // Trailing separators aren't part of the tag ("#todo-" -> "todo"). - while (tag.endsWith(u'-') || tag.endsWith(u'/')) - tag.chop(1); - const bool hasLetter = std::any_of(tag.cbegin(), tag.cend(), [](QChar c) { return c.isLetter(); }); - if (!hasLetter || tag.size() > 64) - continue; - out.append({m.capturedStart(0), tag.size() + 1, tag.toLower()}); - } - return out; -} - -bool isValidBlobHash(const QString &hash) -{ - static const QRegularExpression re(u"^[0-9a-f]{64}$"_s); - return re.match(hash).hasMatch(); -} - -} // namespace onotes diff --git a/src/core/RichDocument.h b/src/core/RichDocument.h deleted file mode 100644 index eb2e401..0000000 --- a/src/core/RichDocument.h +++ /dev/null @@ -1,142 +0,0 @@ -#pragma once - -#include -#include -#include - -#include - -namespace onotes { - -// The persisted note format. This is the contract between the editor and -// storage: everything the editor can express must round-trip through it, and -// anything it cannot express is reported rather than silently dropped. -// -// Serialized as JSON: -// { "schema": 1, "blocks": [ Block, ... ] } -// Block: -// { "id": "...", "type": "paragraph", "spans": [ Span, ... ] } -// { "id": "...", "type": "heading", "level": 1..3, "spans": [...] } -// { "id": "...", "type": "list", "list": "bullet|ordered|check", -// "indent": 0.., "checked": bool, "spans": [...] } -// { "id": "...", "type": "table", "rows": n, "columns": n, -// "cells": [ { "row", "col", "rowSpan", "colSpan", "blocks": [...] } ] } -// Span (exactly one of text / image / attachment): -// { "text": "...", "marks": ["bold", ...], "href": "..." } -// { "image": "", "width": px, "height": px, "alt": "..." } -// { "attachment": "" } - -enum Mark : quint32 { - Bold = 1u << 0, - Italic = 1u << 1, - Underline = 1u << 2, - Strikethrough = 1u << 3, - Highlight = 1u << 4, - Code = 1u << 5, -}; -constexpr quint32 AllMarks = Bold | Italic | Underline | Strikethrough | Highlight | Code; - -struct Span { - enum class Kind { Text, Image, Attachment }; - - Kind kind = Kind::Text; - QString text; // Text; soft line breaks are '\n' - quint32 marks = 0; // Text - QString href; // Text - QString ref; // Image: blob hash; Attachment: attachment id - int width = 0; // Image, logical pixels (0 = natural size) - int height = 0; - QString alt; - - static Span plain(const QString &text, quint32 marks = 0, const QString &href = {}); - static Span image(const QString &blobHash, int width, int height, const QString &alt = {}); - static Span attachment(const QString &attachmentId); - - bool operator==(const Span &) const = default; -}; - -struct Block; - -struct TableCell { - int row = 0; - int column = 0; - int rowSpan = 1; - int columnSpan = 1; - QList blocks; - - bool operator==(const TableCell &) const; -}; - -enum class ListKind { None, Bullet, Ordered, Check }; - -struct Block { - enum class Type { Paragraph, Heading, ListItem, Table }; - - Type type = Type::Paragraph; - QString id; - int level = 0; // Heading: 1..3 - ListKind list = ListKind::None; - int indent = 0; // ListItem: 0-based nesting depth - bool checked = false; - QList spans; // Paragraph, Heading, ListItem - int rows = 0; // Table - int columns = 0; - QList cells; - - static Block paragraph(const QList &spans = {}); - static Block heading(int level, const QList &spans); - static Block listItem(ListKind kind, int indent, const QList &spans, bool checked = false); - - QString plainText() const; - bool isEmptyParagraph() const; - bool operator==(const Block &) const; -}; - -struct RichDocument { - static constexpr int SchemaVersion = 1; - - QList blocks; - - // The first non-empty line, like Apple Notes. - QString title() const; - // Text after the title, for list excerpts. - QString snippet(int maxLength = 160) const; - // All searchable text. - QString plainText() const; - - QStringList referencedBlobs() const; - QStringList referencedAttachments() const; - // #tags written in the text (not in code or links), lowercased, unique, - // in order of first appearance. - QStringList tags() const; - // First image in the note, for thumbnails; empty if none. - QString firstImage() const; - - // Gives every block and table a unique, stable id, keeping existing ones. - void assignMissingIds(); - - QJsonObject toJson() const; - QByteArray toJsonBytes() const; - static std::optional fromJson(const QJsonObject &json, QString *error = nullptr); - static std::optional fromJsonBytes(const QByteArray &bytes, QString *error = nullptr); - - bool operator==(const RichDocument &) const = default; -}; - -QString newId(); -bool isValidBlobHash(const QString &hash); - -// A #tag inside a run of text: `start`/`length` cover the whole "#tag". -struct TagMatch { - qsizetype start = 0; - qsizetype length = 0; - QString tag; // lowercased, without '#' -}; -// Tags start after whitespace or opening punctuation, begin with a letter, -// number or underscore, contain at least one letter, and may continue with -// letters, numbers, '_', '-' or '/'. "#1" and "url#anchor" are not tags. -QList findTags(const QString &text); - -} // namespace onotes - -Q_DECLARE_METATYPE(onotes::RichDocument) diff --git a/src/core/SampleLibrary.cpp b/src/core/SampleLibrary.cpp deleted file mode 100644 index 5380ecc..0000000 --- a/src/core/SampleLibrary.cpp +++ /dev/null @@ -1,216 +0,0 @@ -#include "SampleLibrary.h" - -#include "LibraryService.h" - -#include -#include -#include -#include -#include - -using namespace Qt::StringLiterals; - -namespace onotes::SampleLibrary { - -namespace { - -Span t(const QString &text, quint32 marks = 0) -{ - return Span::plain(text, marks); -} - -Block p(const QList &spans) -{ - return Block::paragraph(spans); -} - -Block li(ListKind kind, int indent, const QList &spans, bool checked = false) -{ - return Block::listItem(kind, indent, spans, checked); -} - -TableCell cell(int row, int column, const QList &spans) -{ - TableCell c; - c.row = row; - c.column = column; - c.blocks = {Block::paragraph(spans)}; - return c; -} - -} // namespace - -RichDocument mixedContentNote(const QString &imageHash, const QString &attachmentId, - const QString &linkedNoteId) -{ - RichDocument doc; - auto &b = doc.blocks; - b << Block::heading(1, {t(u"Q3 planning — product sync"_s)}); - b << p({t(u"Met with Dana, Luis and Priya on 22 September. "_s), - t(u"Decisions"_s, Bold), - t(u" are below; open questions are at the end. #planning #q3"_s)}); - - b << Block::heading(2, {t(u"Decisions"_s)}); - b << li(ListKind::Bullet, 0, {t(u"Ship the offline importer in the October release"_s)}); - b << li(ListKind::Bullet, 1, {t(u"Markdown and plain text first; ENEX later"_s)}); - b << li(ListKind::Bullet, 1, {t(u"Report anything we can't convert instead of dropping it"_s, Italic)}); - b << li(ListKind::Bullet, 0, {t(u"Collapse the folder sidebar on narrow tiles"_s)}); - - b << Block::heading(2, {t(u"Action items"_s)}); - b << li(ListKind::Check, 0, {t(u"Draft the migration guide"_s)}, true); - b << li(ListKind::Check, 0, {t(u"Benchmark search on the 10,000-note library"_s)}); - b << li(ListKind::Check, 1, {t(u"Use the reference ThinkPad, not a dev box"_s)}, true); - b << li(ListKind::Check, 1, {t(u"Record p95 without typing debounce"_s)}); - b << li(ListKind::Check, 0, {t(u"Review the "_s), - Span::plain(u"vendor research"_s, 0, u"note://"_s + linkedNoteId), - t(u" before Friday"_s)}); - - b << Block::heading(2, {t(u"Owners"_s)}); - Block table; - table.type = Block::Type::Table; - table.rows = 4; - table.columns = 3; - table.cells = { - cell(0, 0, {t(u"Owner"_s, Bold)}), cell(0, 1, {t(u"Task"_s, Bold)}), cell(0, 2, {t(u"Due"_s, Bold)}), - cell(1, 0, {t(u"Dana"_s)}), cell(1, 1, {t(u"Importer error report"_s)}), cell(1, 2, {t(u"3 Oct"_s)}), - cell(2, 0, {t(u"Luis"_s)}), cell(2, 1, {t(u"Search benchmark"_s)}), cell(2, 2, {t(u"8 Oct"_s)}), - cell(3, 0, {t(u"Priya"_s)}), cell(3, 1, {t(u"Narrow-tile layout 🚀"_s)}), cell(3, 2, {t(u"10 Oct"_s)}), - }; - b << table; - - b << Block::heading(2, {t(u"Attachments"_s)}); - b << p({t(u"Search latency from last sprint:"_s)}); - b << p({Span::image(imageHash, 800, 360, u"Bar chart of search latency by week"_s)}); - b << p({t(u"Roadmap draft: "_s), Span::attachment(attachmentId)}); - - b << Block::heading(2, {t(u"Next week"_s)}); - b << li(ListKind::Ordered, 0, {t(u"Walk through the importer demo"_s)}); - b << li(ListKind::Ordered, 0, {t(u"Agree the release checklist"_s)}); - b << li(ListKind::Ordered, 1, {t(u"Accessibility pass"_s)}); - b << li(ListKind::Ordered, 1, {t(u"Recovery drills"_s)}); - b << li(ListKind::Ordered, 0, {t(u"Retro"_s)}); - - b << Block::heading(3, {t(u"Open questions"_s)}); - b << p({t(u"Do we need "_s), t(u"locked notes"_s, Highlight), t(u" in v1? "_s), - t(u"Probably not"_s, Strikethrough), t(u" — revisit after the beta."_s)}); - b << p({t(u"Try it: "_s), t(u"omarchy-notes --new \"Groceries\""_s, Code)}); - b << p({t(u"Background reading: "_s), - Span::plain(u"SQLite FTS5"_s, 0, u"https://sqlite.org/fts5.html"_s), - t(u" and the Qt rich text docs."_s, Underline)}); - b << p({t(u"Localized greeting for the demo:\nمرحبا بالعالم — שלום עולם — 你好"_s)}); - doc.assignMissingIds(); - return doc; -} - -RichDocument vendorResearchNote() -{ - RichDocument doc; - doc.blocks << Block::heading(1, {t(u"Vendor research"_s)}); - doc.blocks << p({t(u"Shortlist for the sync server, compared on self-hosting, " - "encryption at rest and export."_s)}); - doc.blocks << li(ListKind::Bullet, 0, {t(u"Option A — "_s), t(u"self-hosted"_s, Bold), - t(u", Postgres, MIT"_s)}); - doc.blocks << li(ListKind::Bullet, 0, {t(u"Option B — managed, per-seat pricing"_s)}); - doc.blocks << li(ListKind::Bullet, 0, {t(u"Option C — "_s), - Span::plain(u"CRDT docs"_s, 0, u"https://crdt.tech"_s)}); - doc.assignMissingIds(); - return doc; -} - -RichDocument shoppingNote() -{ - RichDocument doc; - doc.blocks << Block::heading(1, {t(u"Groceries"_s)}); - doc.blocks << li(ListKind::Check, 0, {t(u"Oat milk"_s)}, true); - doc.blocks << li(ListKind::Check, 0, {t(u"Coffee beans"_s)}); - doc.blocks << li(ListKind::Check, 0, {t(u"Lemons (6)"_s)}); - doc.blocks << li(ListKind::Check, 0, {t(u"Basil"_s)}, true); - doc.assignMissingIds(); - return doc; -} - -QByteArray chartPng() -{ - QImage image(800, 360, QImage::Format_ARGB32_Premultiplied); - image.fill(QColor(0xf6, 0xf6, 0xf4)); - QPainter painter(&image); - painter.setRenderHint(QPainter::Antialiasing); - const int values[] = {182, 164, 151, 139, 128, 121, 117, 112}; - const int baseline = 320; - painter.setPen(QPen(QColor(0xc8, 0xc8, 0xc4), 1)); - for (int y = baseline; y > 40; y -= 50) - painter.drawLine(40, y, 780, y); - for (int i = 0; i < 8; ++i) { - const int h = values[i] * 250 / 200; - painter.fillRect(QRectF(60 + i * 90, baseline - h, 56, h), QColor(0x5a, 0x7d, 0xb0)); - } - painter.setPen(QColor(0x40, 0x40, 0x40)); - QFont font = painter.font(); - font.setPixelSize(18); - painter.setFont(font); - painter.drawText(QRect(40, 8, 740, 28), Qt::AlignLeft, u"Search p95 (ms), weeks 31–38"_s); - painter.end(); - - QByteArray bytes; - QBuffer buffer(&bytes); - buffer.open(QIODevice::WriteOnly); - image.save(&buffer, "PNG"); - return bytes; -} - -bool writeSamplePdf(const QString &path) -{ - QPdfWriter writer(path); - writer.setTitle(u"Q3 roadmap draft"_s); - writer.setPageSize(QPageSize(QPageSize::A4)); - QPainter painter; - if (!painter.begin(&writer)) - return false; - QFont font = painter.font(); - font.setPointSize(20); - painter.setFont(font); - painter.drawText(QRect(0, 0, writer.width(), 800), Qt::AlignLeft, u"Q3 roadmap — draft"_s); - font.setPointSize(11); - painter.setFont(font); - painter.drawText(QRect(0, 1000, writer.width(), 4000), Qt::AlignLeft | Qt::TextWordWrap, - u"1. Offline importer\n2. Search benchmark\n3. Narrow-tile layout\n" - "4. Release checklist"_s); - return painter.end(); -} - -QString seed(LibraryService &library, QString *error) -{ - auto vendor = library.createNote(vendorResearchNote(), error); - if (!vendor || !library.createNote(shoppingNote(), error)) - return {}; - - const auto imageHash = library.addImage(chartPng(), error); - if (!imageHash) - return {}; - - // The attachment belongs to a note, so create the note first. - auto mixed = library.createNote(RichDocument{{Block::paragraph()}}, error); - if (!mixed) - return {}; - - QTemporaryDir scratch; - const QString pdfPath = scratch.filePath(u"Q3 roadmap draft.pdf"_s); - if (!writeSamplePdf(pdfPath)) { - if (error) - *error = u"Could not create the sample PDF."_s; - return {}; - } - const auto attachment = library.addAttachment(mixed->id, pdfPath, error); - if (!attachment) - return {}; - - SaveRequest save; - save.noteId = mixed->id; - save.baseRevision = mixed->revision; - save.body = mixedContentNote(*imageHash, attachment->id, vendor->id); - library.saveNote(save); - library.waitForIdle(); - return mixed->id; -} - -} // namespace onotes::SampleLibrary diff --git a/src/core/SampleLibrary.h b/src/core/SampleLibrary.h deleted file mode 100644 index 503ef52..0000000 --- a/src/core/SampleLibrary.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include "RichDocument.h" - -#include -#include - -namespace onotes { - -class LibraryService; - -// Realistic content used to seed an empty library and as the round-trip -// fixture: headings, marks, nested and checked lists, a table, an image, a -// file attachment, a note link, emoji and right-to-left text. -namespace SampleLibrary { - -RichDocument mixedContentNote(const QString &imageHash, const QString &attachmentId, - const QString &linkedNoteId); -RichDocument vendorResearchNote(); -RichDocument shoppingNote(); - -// A small PNG chart and a one-page PDF, generated so the fixture has real -// media without shipping binary files. -QByteArray chartPng(); -bool writeSamplePdf(const QString &path); - -// Adds the sample notes to `library`. Returns the id of the mixed-content note. -QString seed(LibraryService &library, QString *error = nullptr); - -} // namespace SampleLibrary -} // namespace onotes diff --git a/src/core/ThemePalette.cpp b/src/core/ThemePalette.cpp deleted file mode 100644 index c76debc..0000000 --- a/src/core/ThemePalette.cpp +++ /dev/null @@ -1,325 +0,0 @@ -#include "ThemePalette.h" - -#include -#include -#include -#include - -#include - -using namespace Qt::StringLiterals; - -namespace onotes { - -namespace { - -constexpr double kTextContrast = 4.5; -constexpr double kUiContrast = 3.0; - -QColor parseColor(const QString &value) -{ - QString v = value.trimmed(); - if (v.startsWith(u"0x"_s, Qt::CaseInsensitive)) - v = u'#' + v.mid(2); - QColor c = QColor::fromString(v); - return c.isValid() ? c : QColor(); -} - -QString readFile(const QString &path, QString *error) -{ - QFile file(path); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - if (error) - *error = file.errorString(); - return {}; - } - return QString::fromUtf8(file.readAll()); -} - -// Moves `color` toward `target` until it reaches `ratio` against `background`. -QColor ensureContrast(QColor color, const QColor &background, const QColor &target, double ratio, - const QString &role, QStringList *log) -{ - if (contrastRatio(color, background) >= ratio) - return color; - for (int step = 1; step <= 20; ++step) { - const QColor candidate = mix(color, target, step / 20.0); - if (contrastRatio(candidate, background) >= ratio) { - log->append(u"%1 adjusted for contrast"_s.arg(role)); - return candidate; - } - } - log->append(u"%1 replaced for contrast"_s.arg(role)); - return target; -} - -QColor bestTextOn(const QColor &background, const QColor &a, const QColor &b) -{ - return contrastRatio(a, background) >= contrastRatio(b, background) ? a : b; -} - -bool nearlyEqual(const QColor &a, const QColor &b) -{ - return std::abs(a.redF() - b.redF()) + std::abs(a.greenF() - b.greenF()) - + std::abs(a.blueF() - b.blueF()) < 0.12; -} - -struct Inputs { - QColor background, foreground, accent, selection, muted; - QColor darkBackground, dimForeground, red, yellow, blue; - std::optional dark; -}; - -ThemePalette derive(const Inputs &in, const QString &name, const QString &source) -{ - ThemePalette p; - p.name = name; - p.source = source; - p.dark = in.dark.value_or(relativeLuminance(in.background) < 0.4); - - const QColor bg = in.background; - const QColor extreme = bestTextOn(bg, Qt::white, Qt::black); - const QColor fg = ensureContrast(in.foreground, bg, extreme, kTextContrast, u"text"_s, &p.adjustments); - const QColor away = p.dark ? Qt::black : Qt::white; - - p.canvas = bg; - p.text = fg; - p.sidebar = in.darkBackground.isValid() ? in.darkBackground - : mix(bg, p.dark ? Qt::black : QColor(0x60, 0x60, 0x60), 0.06); - // On low-contrast themes a tinted sidebar can push text below the - // threshold; keep the sidebar on the canvas color then. - if (contrastRatio(fg, p.sidebar) < kTextContrast) - p.sidebar = bg; - p.raised = mix(bg, fg, p.dark ? 0.08 : 0.06); - p.divider = mix(bg, fg, p.dark ? 0.16 : 0.14); - p.tableBorder = mix(bg, fg, 0.30); - - const QColor dim = in.dimForeground.isValid() ? in.dimForeground : mix(fg, bg, 0.40); - // Secondary text sits on both the canvas and the sidebar. - p.secondaryText = ensureContrast(dim, p.sidebar, fg, kTextContrast, u"secondary text"_s, &p.adjustments); - p.secondaryText = ensureContrast(p.secondaryText, bg, fg, kTextContrast, u"secondary text"_s, &p.adjustments); - - p.selection = in.selection.isValid() ? in.selection : mix(bg, fg, 0.25); - p.selectionText = bestTextOn(p.selection, fg, bg); - if (contrastRatio(p.selectionText, p.selection) < kTextContrast) { - p.selection = ensureContrast(p.selection, p.selectionText, away, kTextContrast, - u"selection"_s, &p.adjustments); - } - - // Some themes set accent == foreground; fall back to a hue so selected - // and focused states stay distinguishable from text. - QColor accent = in.accent.isValid() ? in.accent : in.blue; - if (!accent.isValid() || nearlyEqual(accent, fg)) - accent = in.blue.isValid() ? in.blue : mix(fg, QColor(0x3b, 0x82, 0xf6), 0.6); - p.accent = ensureContrast(accent, bg, fg, kUiContrast, u"accent"_s, &p.adjustments); - p.accentText = bestTextOn(p.accent, bg, fg); - p.focus = p.accent; - - const QColor link = in.blue.isValid() ? in.blue : p.accent; - p.link = ensureContrast(link, bg, fg, kTextContrast, u"link"_s, &p.adjustments); - const QColor red = in.red.isValid() ? in.red : QColor(0xd0, 0x3a, 0x3a); - p.error = ensureContrast(red, bg, fg, kTextContrast, u"error"_s, &p.adjustments); - - QColor yellow = in.yellow.isValid() ? in.yellow : QColor(0xf2, 0xc9, 0x4c); - for (double alpha = p.dark ? 0.40 : 0.55; alpha >= 0.10; alpha -= 0.05) { - yellow.setAlphaF(alpha); - if (contrastRatio(fg, composite(yellow, bg)) >= kTextContrast) - break; - } - p.highlight = yellow; - return p; -} - -QString themeNameFor(const QString &dir) -{ - const QFileInfo info(dir); - const QString nameFile = info.absolutePath() + u"/theme.name"_s; - QFile file(nameFile); - if (file.open(QIODevice::ReadOnly)) - return QString::fromUtf8(file.readAll()).trimmed(); - if (info.isSymLink()) - return QFileInfo(info.symLinkTarget()).fileName(); - return info.fileName(); -} - -} // namespace - -double relativeLuminance(const QColor &color) -{ - auto channel = [](double c) { - return c <= 0.03928 ? c / 12.92 : std::pow((c + 0.055) / 1.055, 2.4); - }; - return 0.2126 * channel(color.redF()) + 0.7152 * channel(color.greenF()) - + 0.0722 * channel(color.blueF()); -} - -double contrastRatio(const QColor &a, const QColor &b) -{ - const double la = relativeLuminance(a); - const double lb = relativeLuminance(b); - return (std::max(la, lb) + 0.05) / (std::min(la, lb) + 0.05); -} - -QColor mix(const QColor &a, const QColor &b, double t) -{ - return QColor::fromRgbF(float(a.redF() * (1 - t) + b.redF() * t), - float(a.greenF() * (1 - t) + b.greenF() * t), - float(a.blueF() * (1 - t) + b.blueF() * t)); -} - -QColor composite(const QColor &over, const QColor &under) -{ - return mix(under, QColor::fromRgbF(over.redF(), over.greenF(), over.blueF()), over.alphaF()); -} - -QHash parseSimpleToml(const QString &text) -{ - QHash out; - QString section; - for (QString line : text.split(u'\n')) { - line = line.trimmed(); - if (line.isEmpty() || line.startsWith(u'#')) - continue; - if (line.startsWith(u'[')) { - const qsizetype end = line.indexOf(u']'); - if (end > 0) - section = line.mid(1, end - 1).trimmed().remove(u'"'); - continue; - } - const qsizetype eq = line.indexOf(u'='); - if (eq <= 0) - continue; - const QString key = line.left(eq).trimmed().remove(u'"'); - QString value = line.mid(eq + 1).trimmed(); - if (value.startsWith(u'"') || value.startsWith(u'\'')) { - const QChar quote = value.front(); - const qsizetype close = value.indexOf(quote, 1); - value = close > 0 ? value.mid(1, close - 1) : value.mid(1); - } else { - const qsizetype comment = value.indexOf(u'#'); - if (comment >= 0) - value = value.left(comment).trimmed(); - } - out.insert(section.isEmpty() ? key : section + u'.' + key, value); - } - return out; -} - -ThemePalette ThemePalette::builtIn(bool dark) -{ - Inputs in; - in.dark = dark; - if (dark) { - in.background = QColor(0x1a, 0x1b, 0x26); - in.foreground = QColor(0xc0, 0xca, 0xf5); - in.accent = QColor(0x7a, 0xa2, 0xf7); - in.selection = QColor(0x33, 0x46, 0x7c); - in.dimForeground = QColor(0x9a, 0xa5, 0xce); - in.blue = QColor(0x7a, 0xa2, 0xf7); - in.red = QColor(0xf7, 0x76, 0x8e); - in.yellow = QColor(0xe0, 0xaf, 0x68); - } else { - in.background = QColor(0xfb, 0xfb, 0xfa); - in.foreground = QColor(0x1f, 0x1f, 0x1f); - in.accent = QColor(0x2f, 0x6f, 0xd0); - in.selection = QColor(0xc9, 0xdc, 0xf7); - in.dimForeground = QColor(0x5f, 0x5f, 0x5f); - in.blue = QColor(0x2f, 0x6f, 0xd0); - in.red = QColor(0xc0, 0x2b, 0x2b); - in.yellow = QColor(0xf2, 0xc9, 0x4c); - } - return derive(in, dark ? u"Built-in dark"_s : u"Built-in light"_s, u"built-in"_s); -} - -std::optional ThemePalette::fromColorsToml(const QString &path, QString *error) -{ - const QString text = readFile(path, error); - if (text.isNull()) - return std::nullopt; - const auto keys = parseSimpleToml(text); - auto color = [&](const char *key) { return parseColor(keys.value(QLatin1StringView(key))); }; - - Inputs in; - in.background = color("background"); - in.foreground = color("foreground"); - if (!in.background.isValid() || !in.foreground.isValid()) { - if (error) - *error = u"colors.toml has no valid background/foreground"_s; - return std::nullopt; - } - in.accent = color("accent"); - in.selection = color("selection"); - in.darkBackground = color("dark_background"); - in.dimForeground = color("dark_foreground"); - in.red = color("red"); - in.yellow = color("yellow"); - in.blue = color("blue"); - const QString mode = keys.value(u"mode"_s).toLower(); - if (mode == u"dark") - in.dark = true; - else if (mode == u"light") - in.dark = false; - return derive(in, themeNameFor(QFileInfo(path).absolutePath()), path); -} - -std::optional ThemePalette::fromAlacrittyToml(const QString &path, QString *error) -{ - const QString text = readFile(path, error); - if (text.isNull()) - return std::nullopt; - const auto keys = parseSimpleToml(text); - auto color = [&](const char *key) { return parseColor(keys.value(QLatin1StringView(key))); }; - - Inputs in; - in.background = color("colors.primary.background"); - in.foreground = color("colors.primary.foreground"); - if (!in.background.isValid() || !in.foreground.isValid()) { - if (error) - *error = u"alacritty.toml has no primary colors"_s; - return std::nullopt; - } - in.selection = color("colors.selection.background"); - in.dimForeground = color("colors.primary.dim_foreground"); - in.red = color("colors.normal.red"); - in.yellow = color("colors.normal.yellow"); - in.blue = color("colors.normal.blue"); - in.accent = in.blue; - return derive(in, themeNameFor(QFileInfo(path).absolutePath()), path); -} - -QStringList ThemePalette::candidateDirectories() -{ - QStringList dirs; - const QString override = qEnvironmentVariable("OMARCHY_NOTES_THEME_DIR"); - if (!override.isEmpty()) - dirs << override; - QString state = qEnvironmentVariable("XDG_STATE_HOME"); - if (state.isEmpty()) - state = QDir::homePath() + u"/.local/state"_s; - dirs << state + u"/omarchy/current/theme"_s; - dirs << QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) - + u"/omarchy/current/theme"_s; - return dirs; -} - -ThemePalette ThemePalette::loadFromDirectory(const QString &dir) -{ - if (auto p = fromColorsToml(dir + u"/colors.toml"_s)) - return *p; - if (auto p = fromAlacrittyToml(dir + u"/alacritty.toml"_s)) - return *p; - return builtIn(true); -} - -ThemePalette ThemePalette::loadActive() -{ - for (const QString &dir : candidateDirectories()) { - if (auto p = fromColorsToml(dir + u"/colors.toml"_s)) - return *p; - if (auto p = fromAlacrittyToml(dir + u"/alacritty.toml"_s)) - return *p; - } - return builtIn(true); -} - -} // namespace onotes diff --git a/src/core/ThemePalette.h b/src/core/ThemePalette.h deleted file mode 100644 index 2ade005..0000000 --- a/src/core/ThemePalette.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include - -namespace onotes { - -// Semantic colors for the app, derived from the active Omarchy theme and -// corrected for contrast. The UI only ever uses these roles, never raw -// palette entries, so themes without a given key still render sensibly. -struct ThemePalette { - QString name; - QString source; // file the palette came from, or "built-in" - bool dark = true; - - QColor canvas; // window and editor background - QColor sidebar; // list / sidebar background - QColor raised; // hover, pressed and popup surfaces - QColor divider; - QColor text; - QColor secondaryText; // timestamps, excerpts - QColor selection; - QColor selectionText; - QColor accent; // selected rows, primary actions - QColor accentText; // text on accent - QColor focus; // focus rings - QColor link; - QColor error; - QColor highlight; // text highlight mark (translucent) - QColor tableBorder; - - // Contrast corrections that were applied, for diagnostics. - QStringList adjustments; - - static ThemePalette builtIn(bool dark = true); - - // Omarchy 3.x+/4.x colors.toml (flat keys: background, foreground, accent...). - static std::optional fromColorsToml(const QString &path, QString *error = nullptr); - // Older themes that only ship alacritty.toml. - static std::optional fromAlacrittyToml(const QString &path, QString *error = nullptr); - - // Loads from the first usable theme directory, else the built-in palette. - static ThemePalette loadActive(); - static ThemePalette loadFromDirectory(const QString &dir); - - // Theme directories to try, most specific first: - // $OMARCHY_NOTES_THEME_DIR, $XDG_STATE_HOME/omarchy/current/theme (4.x), - // $XDG_CONFIG_HOME/omarchy/current/theme (3.x). - static QStringList candidateDirectories(); - - bool operator==(const ThemePalette &) const = default; -}; - -double relativeLuminance(const QColor &color); -double contrastRatio(const QColor &a, const QColor &b); -QColor mix(const QColor &a, const QColor &b, double t); -// Composites a translucent color over an opaque one. -QColor composite(const QColor &over, const QColor &under); - -// Minimal TOML reader for theme files: [sections], key = "string" | bare. -// Keys are returned as "section.key" (or "key" at top level). -QHash parseSimpleToml(const QString &text); - -} // namespace onotes diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt deleted file mode 100644 index bdce259..0000000 --- a/tests/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -function(onotes_test name) - add_executable(${name} ${name}.cpp ${ARGN}) - target_link_libraries(${name} PRIVATE notes_core Qt6::Test Qt6::Gui) - add_test(NAME ${name} COMMAND ${name}) - set_tests_properties(${name} PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") -endfunction() - -onotes_test(tst_document) -onotes_test(tst_theme) -onotes_test(tst_store) -onotes_test(tst_exchange) - -# Child process for the kill -9 durability test. -add_executable(crash_helper crash_helper.cpp) -target_link_libraries(crash_helper PRIVATE notes_core) -target_compile_definitions(tst_store PRIVATE CRASH_HELPER_PATH="$") -add_dependencies(tst_store crash_helper) - -if(TARGET notes_app_lib AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tst_editor.cpp) - onotes_test(tst_editor) - target_link_libraries(tst_editor PRIVATE notes_app_lib notes_app_libplugin Qt6::Quick Qt6::Qml Qt6::QuickControls2) - target_compile_definitions(tst_editor PRIVATE SCREENSHOT_DIR="${CMAKE_BINARY_DIR}/screenshots") - set_tests_properties(tst_editor PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QUICK_BACKEND=software") -endif() - -onotes_test(tst_launch) -target_link_libraries(tst_launch PRIVATE notes_app_lib Qt6::Network) -target_compile_definitions(tst_launch PRIVATE APP_PATH="$") -add_dependencies(tst_launch ${ONOTES_BINARY_NAME}) - -# Release performance benchmark; run by hand: ./tests/bench_library [notes] [attachment-mb] -add_executable(bench_library bench_library.cpp) -target_link_libraries(bench_library PRIVATE notes_core Qt6::Gui) -add_dependencies(bench_library ${ONOTES_BINARY_NAME}) diff --git a/tests/bench_library.cpp b/tests/bench_library.cpp deleted file mode 100644 index 6be2b1f..0000000 --- a/tests/bench_library.cpp +++ /dev/null @@ -1,170 +0,0 @@ -// Performance benchmark for the release gates (not part of ctest): -// bench_library [notes=10000] [attachment-mb=0] -// Builds a realistic library, then measures storage, search and app startup -// against the targets in the plan. Prints a Markdown table. - -#include "LibraryService.h" -#include "SampleLibrary.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -using namespace onotes; -using namespace Qt::StringLiterals; - -namespace { - -const QStringList kWords = { - u"meeting"_s, u"roadmap"_s, u"benchmark"_s, u"budget"_s, u"customer"_s, u"release"_s, u"design"_s, - u"search"_s, u"notes"_s, u"travel"_s, u"groceries"_s, u"invoice"_s, u"planning"_s, u"research"_s, - u"interview"_s, u"recipe"_s, u"workout"_s, u"project"_s, u"feedback"_s, u"quarterly"_s, u"launch"_s, - u"migration"_s, u"sqlite"_s, u"wayland"_s, u"hyprland"_s, u"omarchy"_s, u"lisbon"_s, u"kyoto"_s, -}; - -QString sentence(QRandomGenerator &rng, int words) -{ - QStringList out; - for (int i = 0; i < words; ++i) - out << kWords[rng.bounded(int(kWords.size()))]; - out[0][0] = out[0][0].toUpper(); - return out.join(u' ') + u'.'; -} - -RichDocument note(QRandomGenerator &rng, int index) -{ - RichDocument doc; - doc.blocks << Block::heading(1, {Span::plain(sentence(rng, 3).chopped(1) + u' ' + QString::number(index))}); - const int paragraphs = 3 + rng.bounded(12); - for (int p = 0; p < paragraphs; ++p) - doc.blocks << Block::paragraph({Span::plain(sentence(rng, 12 + rng.bounded(30)))}); - if (index % 5 == 0) { - for (int i = 0; i < 4; ++i) - doc.blocks << Block::listItem(ListKind::Check, 0, {Span::plain(sentence(rng, 5))}, i % 2); - } - if (index % 7 == 0) - doc.blocks << Block::paragraph({Span::plain(u"#"_s + kWords[rng.bounded(int(kWords.size()))])}); - doc.assignMissingIds(); - return doc; -} - -qint64 percentile(QList values, double p) -{ - std::sort(values.begin(), values.end()); - return values.isEmpty() ? 0 : values[std::min(values.size() - 1, qsizetype(p * values.size()))]; -} - -qint64 firstFrameMs(const QString &app, const QString &library) -{ - QProcess process; - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - env.insert(u"ONOTES_EXIT_AFTER_FIRST_FRAME"_s, u"1"_s); - process.setProcessEnvironment(env); - QElapsedTimer timer; - timer.start(); - process.start(app, {u"--data-dir"_s, library}); - if (!process.waitForFinished(60000)) - return -1; - return process.readAllStandardOutput().contains("first-frame") ? timer.elapsed() : -1; -} - -} // namespace - -int main(int argc, char **argv) -{ - QGuiApplication app(argc, argv); - const int noteCount = argc > 1 ? QString::fromLocal8Bit(argv[1]).toInt() : 10000; - const int attachmentMb = argc > 2 ? QString::fromLocal8Bit(argv[2]).toInt() : 0; - QTemporaryDir dir; - const QString libraryPath = dir.filePath(u"library"_s); - QRandomGenerator rng(20260923); - - QElapsedTimer timer; - { - LibraryService library(LibraryPaths::at(libraryPath)); - library.start(nullptr); - timer.start(); - for (int i = 0; i < noteCount; ++i) - library.createNote(note(rng, i)); - std::fprintf(stderr, "created %d notes in %lld ms\n", noteCount, static_cast(timer.elapsed())); - // Attachments, if requested: 1 MB images spread across notes. - const auto notes = library.listNotes(); - QByteArray blob(1024 * 1024, '\0'); - for (int i = 0; i < attachmentMb; ++i) { - for (int b = 0; b < blob.size(); b += 4096) - blob[b] = char(rng.bounded(256)); - const auto hash = library.addImage(blob); - if (!hash) - break; - SaveRequest save; - const auto record = library.loadNote(notes[i % notes.size()].id); - save.noteId = record->id; - save.baseRevision = record->revision; - save.body = record->body; - save.body.blocks << Block::paragraph({Span::image(*hash, 64, 64)}); - library.saveNote(save); - } - library.waitForIdle(); - } - - qint64 openMs = 0, listMs = 0, sidebarMs = 0, listed = 0; - QList searches; - { - LibraryService library(LibraryPaths::at(libraryPath)); - timer.restart(); - library.start(nullptr); - openMs = timer.restart(); - listed = library.listNotes().size(); - listMs = timer.restart(); - library.listTags(); - library.listFolders(); - library.listSmartFolders(); - library.listAttachmentItems(); - sidebarMs = timer.restart(); - - for (int i = 0; i < 200; ++i) { - QStringList terms; - for (int t = 0; t < 1 + rng.bounded(3); ++t) - terms << kWords[rng.bounded(int(kWords.size()))].left(3 + rng.bounded(4)); - QElapsedTimer one; - one.start(); - QEventLoop loop; - quint64 ticket = 0; - QObject::connect(&library, &LibraryService::searchFinished, &loop, [&](quint64 t) { - if (t == ticket) - loop.quit(); - }); - ticket = library.search(terms.join(u' ')); - loop.exec(); - searches << one.elapsed(); - } - } - - // Launches of the real app on this library, to its first rendered frame. - const QString binary = QCoreApplication::applicationDirPath() + u"/../src/app/omarchy-notes"_s; - const qint64 first = firstFrameMs(binary, libraryPath); - QList warm; - for (int i = 0; i < 5; ++i) - warm << firstFrameMs(binary, libraryPath); - - std::printf("| Measure | Target | Result |\n|---|---|---|\n"); - std::printf("| Notes in library | 10,000 | %lld |\n", static_cast(listed)); - std::printf("| Attachment data | 1 GB | %d MB |\n", attachmentMb); - std::printf("| First launch to first frame | < 1.5 s | %lld ms |\n", static_cast(first)); - std::printf("| Warm launch to first frame (median of 5) | < 500 ms | %lld ms |\n", - static_cast(percentile(warm, 0.5))); - std::printf("| Open library | | %lld ms |\n", static_cast(openMs)); - std::printf("| List all notes | | %lld ms |\n", static_cast(listMs)); - std::printf("| Sidebar data (folders, tags, Smart Folders, attachments) | | %lld ms |\n", - static_cast(sidebarMs)); - std::printf("| Search p50 (200 queries) | | %lld ms |\n", static_cast(percentile(searches, 0.5))); - std::printf("| Search p95 (200 queries) | < 150 ms | %lld ms |\n", static_cast(percentile(searches, 0.95))); - return 0; -} diff --git a/tests/check-arch-package.sh b/tests/check-arch-package.sh deleted file mode 100755 index 4cf82ae..0000000 --- a/tests/check-arch-package.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -package_dir="$(realpath "${1:?usage: check-arch-package.sh PACKAGE_DIRECTORY}")" -shopt -s nullglob -packages=("$package_dir"/omarchy-notes-[0-9]*-*.pkg.tar.zst) -[[ ${#packages[@]} == 1 ]] || { echo 'Expected one application package' >&2; exit 1; } -package="${packages[0]}" -work_dir="$(mktemp -d)" -trap 'rm -rf "$work_dir"' EXIT - -# namcap can report errors with exit status zero; inspect its diagnostics as well. -namcap "$package_dir/PKGBUILD" "$package" | tee "$work_dir/namcap.log" -if grep -q ' E: ' "$work_dir/namcap.log"; then - echo 'namcap reported packaging errors' >&2 - exit 1 -fi -bsdtar -xf "$package" -C "$work_dir" -for path in usr/bin/omarchy-notes \ - usr/share/licenses/omarchy-notes/LICENSE \ - usr/share/applications/org.omarchy.Notes.desktop \ - usr/share/icons/hicolor/scalable/apps/org.omarchy.Notes.svg \ - usr/share/metainfo/org.omarchy.Notes.metainfo.xml \ - usr/share/man/man1/omarchy-notes.1.gz \ - usr/share/doc/omarchy-notes/README.md; do - [[ -s "$work_dir/$path" ]] || { echo "Missing package file: $path" >&2; exit 1; } -done -if readelf -d "$work_dir/usr/bin/omarchy-notes" | grep -Eq '\((RPATH|RUNPATH)\)'; then - echo 'Unexpected runtime library path in omarchy-notes' >&2 - exit 1 -fi -grep -q '^Exec=/usr/bin/omarchy-notes$' "$work_dir/usr/share/applications/org.omarchy.Notes.desktop" -echo 'Arch package validation: ok' diff --git a/tests/crash_helper.cpp b/tests/crash_helper.cpp deleted file mode 100644 index 5590ba6..0000000 --- a/tests/crash_helper.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// Saves a note in a tight loop and prints "ACK " only after each -// commit returns. The parent test kills this process with SIGKILL at random -// points and checks that every acknowledged save survived. - -#include "NoteStore.h" - -#include -#include - -#include - -using namespace onotes; -using namespace Qt::StringLiterals; - -int main(int argc, char **argv) -{ - QCoreApplication app(argc, argv); - if (argc < 3) - return 2; - NoteStore store(LibraryPaths::at(QString::fromLocal8Bit(argv[1]))); - QString error; - if (!store.open(&error)) { - std::fprintf(stderr, "open failed: %s\n", qPrintable(error)); - return 1; - } - const QString noteId = QString::fromLocal8Bit(argv[2]); - auto note = store.loadNote(noteId, &error); - if (!note) { - std::fprintf(stderr, "load failed: %s\n", qPrintable(error)); - return 1; - } - qint64 revision = note->revision; - const QString filler = u"Lorem ipsum dolor sit amet, consectetur adipiscing elit. "_s.repeated(40); - - for (qint64 counter = 1;; ++counter) { - SaveRequest request; - request.noteId = noteId; - request.baseRevision = revision; - request.body.blocks = { - Block::heading(1, {Span::plain(u"Counter"_s)}), - Block::paragraph({Span::plain(QString::number(counter))}), - Block::paragraph({Span::plain(filler)}), - }; - request.body.assignMissingIds(); - const SaveResult result = store.saveNote(request); - if (result.status != SaveResult::Status::Saved) { - std::fprintf(stderr, "save failed: %s\n", qPrintable(result.error)); - return 1; - } - revision = result.revision; - std::printf("ACK %lld\n", static_cast(counter)); - std::fflush(stdout); - } -} diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 9164e2f..5f5770b 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -1,48 +1,29 @@ -# Rebuild fixtures +# Regression fixtures -`preview/library.json` contains deterministic, disposable sample content for the -GPUI visual foundation. It is **not** a persisted rich-document schema. Quote -blocks here do not authorize changing an existing library's format. +`preview/library.json` contains deterministic, disposable GPUI sample content, +not a persisted rich-document schema. -`qt-v1/` contains a real schema-2 SQLite library produced by the current Qt -application's `--samples` path, its two content-addressed blobs, and a JSON export -of the three schema-1 note bodies. The JSON export includes headings, marks, -nested lists, checklists, a table, image, attachment, note link and multilingual -text. `manifest.json` records checksums and is a test manifest, not an app backup. +`qt-v1/` is a frozen schema-2 SQLite library captured from the retired Qt app, +with two content-addressed blobs and JSON exports of its schema-1 note bodies. +The documents cover headings, marks, nested lists, checklists, tables, images, +attachments, note links and multilingual text. `manifest.json` records checksums; +it is a test manifest, not an app backup. `qt-merged-table.json` captures legacy +merged-cell behavior; its provenance is recorded in `qt-merged-table.md`. -Regenerate to a **new** directory after building the Qt app: +Keep these captures fixed. Rust compatibility tests use scratch copies to verify +that existing libraries and rich documents remain readable and preserve data. +The Qt implementation and fixture-generation tools have been retired; running +the regression tests does not require Qt. -```sh -python tools/capture-qt-fixture.py build-baseline/src/app/omarchy-notes /tmp/new-qt-fixture -``` - -The tool launches only the supplied Qt binary with a newly allocated temporary -library and offscreen rendering. It takes a consistent SQLite backup, validates -blob hashes and terminates its own child. It refuses an existing destination. -Generated IDs, timestamps and PDF metadata will differ between captures. Keep the -checked-in capture fixed for compatibility tests; use scratch copies for writes. - -Additional fixtures still needed before M2 exits: schema-1 database upgrade, -merged-cell/edge-case tables, a legacy backup, missing/corrupt blobs and a newer -unsupported schema. See the rebuild baseline checklist. - -## Rust writing checks - -`notes-core` parses and round-trips every captured document. `notes-editor` edits -a table cell without changing adjacent structure or asset references. -`notes-storage` saves fixture copies, checks conflicts/version guards and tests -a transactional schema-1 upgrade. The durability integration test kills its own -writer after 20 commit acknowledgments, then verifies every note on reopen. +## Rust checks -The cross-version probe additionally compiles the current Qt document reader and -uses `QLockFile`, with scratch libraries only: +`notes-core` parses and round-trips captured documents. `notes-editor` verifies +edits preserve neighboring structure and assets. `notes-storage` covers legacy +schema upgrades, conflicts, version guards, backup/restore and durable writes. ```sh -cargo build --release -p omarchy-notes-preview --locked -cargo build -p notes-storage --example compatibility-edit --locked -python tests/test-rust-compatibility.py target/release/omarchy-notes-preview target/debug/examples/compatibility-edit +cargo test --workspace --locked ``` -Requires Qt6Core/sqlite3 development headers, pkg-config, g++ and Python. The -Rust app itself does not link Qt. GPUI screenshots and writing workflows are -covered by `notes-ui`'s `writing-check` example; use copies of fixtures for edits. +GPUI native workflows use the `notes-ui` examples and the Python native harnesses +in `tests/`. Always use copies of fixtures for edits. diff --git a/tests/qt-backup-probe.cpp b/tests/qt-backup-probe.cpp deleted file mode 100644 index 9a0f9c2..0000000 --- a/tests/qt-backup-probe.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// Test-only oracle using the supported Qt edition's actual backup implementation. -#include "NoteStore.h" -#include -#include -#include - -int main(int argc, char **argv) { - QCoreApplication app(argc, argv); - if (argc < 3) return 2; - const std::string mode(argv[1]); - const QString root = QString::fromLocal8Bit(argv[2]); - onotes::NoteStore store(onotes::LibraryPaths::at(root)); - QString error; - if (mode == "inspect") { - const auto backup = store.inspectBackup(root, &error); - if (!backup) { std::cerr << error.toStdString() << '\n'; return 3; } - std::cout << "Qt inspected schema " << backup->schemaVersion << ": " << backup->notes << " notes, " << backup->blobs << " blobs.\n"; - return 0; - } - QLockFile lock(root + "/.lock"); - if (!lock.tryLock(0)) return 4; - if (!store.open(&error)) { std::cerr << error.toStdString() << '\n'; return 5; } - if (!store.verify().isEmpty()) { std::cerr << store.verify().join("; ").toStdString() << '\n'; return 6; } - if (mode == "backup" && argc == 4) { - if (!store.backupTo(QString::fromLocal8Bit(argv[3]), &error)) { - std::cerr << error.toStdString() << '\n'; return 7; - } - std::cout << "Qt created a format-1 backup.\n"; - } else if (mode == "verify") { - std::cout << "Qt opened and verified the restored library.\n"; - } else { return 2; } - return 0; -} diff --git a/tests/qt-organization-probe.cpp b/tests/qt-organization-probe.cpp deleted file mode 100644 index 0fb6727..0000000 --- a/tests/qt-organization-probe.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// Test oracle against the supported Qt edition's actual folder/note APIs. -#include "NoteStore.h" -#include -#include -#include -#include -#include -#include - -int main(int argc, char **argv) { - QCoreApplication app(argc, argv); - if (argc != 2) return 2; - const QString root = QString::fromLocal8Bit(argv[1]); - auto require = [](bool condition, const QString &message) { - if (!condition) { std::cerr << message.toStdString() << '\n'; std::exit(3); } - }; - QFile input(root + "/expected.json"); - require(input.open(QIODevice::ReadOnly), "Missing expected state"); - const auto expected = QJsonDocument::fromJson(input.readAll()).object(); - QLockFile lock(root + "/.lock"); - require(lock.tryLock(0), "Library locked"); - onotes::NoteStore store(onotes::LibraryPaths::at(root)); - QString error; - require(store.open(&error), error); - require(store.verify().isEmpty(), "Library integrity failure"); - const auto folders = store.listFolders(); - require(folders.size() == expected["folders"].toArray().size(), "Folder count changed"); - for (const auto value : expected["folders"].toArray()) { - const auto f = value.toObject(); - const auto found = std::find_if(folders.begin(), folders.end(), [&](const auto &v) { return v.id == f["id"].toString(); }); - require(found != folders.end(), "Missing stable folder identity"); - require(found->name == f["name"].toString() && found->parentId == f["parent"].toString(), "Folder path changed"); - } - const auto original = expected["note"].toObject(); - const auto noteId = original["id"].toString(); - const auto note = store.loadNote(noteId, &error); - require(note.has_value(), error); - require(note->folderId == original["folder"].toString(), "Filing lost to content save"); - require(note->body.toJson() == original["body"].toObject(), "Rich content changed"); - require(note->revision == original["revision"].toInteger(), "Revision changed"); - require(store.listNotes(onotes::NoteQuery::folder(note->folderId)).size() == 1, "Folder note isolation failed"); - const auto work = expected["work"].toString(); - require(!store.createFolder("clients", work, &error), "Duplicate sibling accepted"); - require(store.renameFolder(expected["subject"].toString(), "Renamed by Qt", &error), error); - const auto destination = store.createFolder("Research", work, &error); - require(destination.has_value(), error); - const auto child = store.createFolder("Clients", destination->id, &error); - require(child.has_value(), error); - require(store.moveNote(noteId, destination->id, &error), error); - const auto moved = store.loadNote(noteId, &error); - require(moved && moved->body.toJson() == note->body.toJson() && moved->revision == note->revision - && moved->updatedAt == note->updatedAt, "Qt move changed note content"); - require(store.verify().isEmpty(), "Final library integrity failure"); - QFile output(root + "/qt-result.json"); - require(output.open(QIODevice::WriteOnly), "Could not write Qt result"); - require(output.write(QJsonDocument(QJsonObject{{"destination", destination->id}, {"child", child->id}}).toJson()) > 0, "Result write failed"); - std::cout << "PASS: Qt reads Rust folders and documents, rejects duplicate siblings, and writes compatible moves and nested folders.\n"; -} diff --git a/tests/qt-table-probe.cpp b/tests/qt-table-probe.cpp deleted file mode 100644 index 2034d3c..0000000 --- a/tests/qt-table-probe.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Test oracle only: actual QTextTable merge and app-converter round trips. -#include "DocumentConverter.h" -#include -#include -#include -#include -#include -#include -#include -using namespace onotes; -using namespace Qt::StringLiterals; -int main(int argc, char **argv) { - QGuiApplication app(argc, argv); - if (argc != 3) return 2; - if (std::string(argv[1]) == "create") { - QTextDocument text; - QTextCursor cursor(&text); - cursor.insertText(u"A table with room to grow"_s); - cursor.insertBlock(); - QTextTable *table = cursor.insertTable(3, 3, DocumentConverter::tableFormat(DocumentStyle{})); - const QStringList values{u"Merged ideas"_s, u"é and 👩‍👩‍👧‍👦"_s, u"Status"_s, u"Keep every paragraph"_s, u"中文"_s, u"Ready"_s, u"Owner"_s, u"Next step"_s, u"Friday"_s}; - for (int row=0; row<3; ++row) for (int col=0; col<3; ++col) { - QTextCursor cell = table->cellAt(row,col).firstCursorPosition(); - QTextCharFormat format; - if (row == 0) format.setFontWeight(QFont::Bold); - if (col == 1) format.setFontItalic(true); - cell.insertText(values[row*3+col],format); - } - table->mergeCells(0,0,2,2); - QFile file(QString::fromLocal8Bit(argv[2])); - if (!file.open(QIODevice::WriteOnly | QIODevice::NewOnly)) return 3; - file.write(QJsonDocument(DocumentConverter::read(&text).toJson()).toJson(QJsonDocument::Indented)); - return 0; - } - QFile file(QString::fromLocal8Bit(argv[2])); - if (!file.open(QIODevice::ReadOnly)) return 4; - QString error; - auto original=RichDocument::fromJsonBytes(file.readAll(), &error); - if (!original) { std::cerr< -#include -#include -#include -#include -#include - -int main(int argc, char **argv) { - QCoreApplication app(argc, argv); - if (argc != 3) return 2; - const QString root = QString::fromLocal8Bit(argv[2]); - QLockFile lock(root + "/.lock"); - if (!lock.tryLock(0)) return 3; - if (std::string(argv[1]) == "hold") { - std::cout << "LOCKED" << std::endl; - std::string line; std::getline(std::cin, line); - return 0; - } - sqlite3 *db = nullptr; - if (sqlite3_open_v2((root + "/library.sqlite3").toUtf8().constData(), &db, SQLITE_OPEN_READONLY, nullptr) != SQLITE_OK) return 4; - sqlite3_stmt *query = nullptr; - sqlite3_prepare_v2(db, "SELECT body,title,snippet,plain_text,body_schema FROM notes", -1, &query, nullptr); - int count = 0; - while (sqlite3_step(query) == SQLITE_ROW) { - auto text = [&](int index) { return QString::fromUtf8(reinterpret_cast(sqlite3_column_text(query,index))); }; - QString error; - const auto document = onotes::RichDocument::fromJsonBytes(text(0).toUtf8(), &error); - if (!document || document->title() != text(1) || document->snippet() != text(2) - || document->plainText() != text(3) || sqlite3_column_int(query,4) != 1) { - std::cerr << "Qt could not validate a Rust-written note: " << error.toStdString() << std::endl; - return 5; - } - ++count; - } - sqlite3_finalize(query); sqlite3_close(db); - std::cout << "Qt verified " << count << " notes and their derived text." << std::endl; - return 0; -} diff --git a/tests/test-installer-package.sh b/tests/test-installer-package.sh deleted file mode 100755 index 6821570..0000000 --- a/tests/test-installer-package.sh +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env bash -# Real pacman installation, restricted to CI's disposable Arch container. -set -euo pipefail -[[ ${CI:-} == true && -f /.dockerenv && $EUID != 0 ]] || { - echo 'Run this test as the build user in the disposable CI container.' >&2 - exit 1 -} -if pacman -Q omarchy-notes >/dev/null 2>&1; then - echo 'Expected a fresh container without Omarchy Notes installed.' >&2 - exit 1 -fi -project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -package_dir="$(realpath "${1:?usage: test-installer-package.sh PACKAGE_DIRECTORY}")" -shopt -s nullglob -packages=("$package_dir"/omarchy-notes-[0-9]*-*.pkg.tar.zst) -[[ ${#packages[@]} == 1 ]] -identity=$(pacman -Qp "${packages[0]}") -version=${identity#omarchy-notes }; version=${version%-*} -test_workspace=$(mktemp -d) -trap 'rm -rf "$test_workspace"' EXIT -mkdir -p "$test_workspace/bin" "$test_workspace/assets" "$test_workspace/data" "$test_workspace/config" -cp "${packages[0]}" "$test_workspace/assets/" -(cd "$test_workspace/assets" && sha256sum ./*.pkg.tar.zst >SHA256SUMS) - -# Only transport is replaced; identity checks, pacman, and the app are real. -cat >"$test_workspace/bin/curl" <<'CURL' -#!/usr/bin/env bash -set -euo pipefail -output=''; url=''; latest=0 -while (( $# )); do - case "$1" in - --output) output=$2; shift ;; - --write-out) latest=1; shift ;; - https://github.com/last-refuge/omarchy-notes/releases/*|https://api.github.com/repos/last-refuge/omarchy-notes/releases*) url=$1 ;; - esac - shift -done -if [[ $url == https://api.github.com/* ]]; then - printf '[{"tag_name":"%s","published_at":"2026-10-13T00:00:00Z","draft":false,"prerelease":false}]' "$NOTES_INSTALLER_TEST_TAG" >"$output" -elif (( latest )); then - printf 'https://github.com/last-refuge/omarchy-notes/releases/tag/%s' "$NOTES_INSTALLER_TEST_TAG" -else - [[ $url == "https://github.com/last-refuge/omarchy-notes/releases/download/$NOTES_INSTALLER_TEST_TAG/"* ]] - cp -- "$NOTES_INSTALLER_TEST_ASSETS/${url##*/}" "$output" -fi -CURL -chmod +x "$test_workspace/bin/curl" -export NOTES_INSTALLER_TEST_ASSETS="$test_workspace/assets" -export NOTES_INSTALLER_TEST_TAG="v$version" -export XDG_DATA_HOME="$test_workspace/data" XDG_CONFIG_HOME="$test_workspace/config" -export PATH="$test_workspace/bin:$PATH" -printf 'keep my notes\n' >"$XDG_DATA_HOME/sentinel" -bash "$project_dir/install.sh" --dry-run -if pacman -Q omarchy-notes >/dev/null 2>&1; then - echo 'Dry run unexpectedly installed the package.' >&2 - exit 1 -fi -bash "$project_dir/install.sh" --yes --no-quick-note -[[ $(pacman -Q omarchy-notes) == "$identity" ]] -[[ $(env -u QT_QPA_PLATFORMTHEME QT_QPA_PLATFORM=offscreen /usr/bin/omarchy-notes --version) == "omarchy-notes $version" ]] -test -s /usr/share/applications/org.omarchy.Notes.desktop -bash "$project_dir/install.sh" --yes --no-quick-note >"$test_workspace/repeat.log" -cat "$test_workspace/repeat.log" -rg -q 'already installed' "$test_workspace/repeat.log" -[[ $(cat "$XDG_DATA_HOME/sentinel") == 'keep my notes' ]] -echo 'real installer package contract: ok' diff --git a/tests/test-package-install.sh b/tests/test-package-install.sh deleted file mode 100755 index 3aea85c..0000000 --- a/tests/test-package-install.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -work_dir="$(mktemp -d)" -trap 'rm -rf "$work_dir"' EXIT -version="$(sed -n '/^project(omarchy-notes/,/)/s/^ *VERSION \([0-9.]*\).*/\1/p' "$project_dir/CMakeLists.txt")" -[[ -n "$version" ]] - -cmake -S "$project_dir" -B "$work_dir/build" -G Ninja \ - -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib -DBUILD_TESTING=OFF -cmake --build "$work_dir/build" -DESTDIR="$work_dir/root" cmake --install "$work_dir/build" - -required=( - usr/bin/omarchy-notes - usr/share/applications/org.omarchy.Notes.desktop - usr/share/icons/hicolor/scalable/apps/org.omarchy.Notes.svg - usr/share/metainfo/org.omarchy.Notes.metainfo.xml - usr/share/man/man1/omarchy-notes.1 - usr/share/doc/omarchy-notes/README.md - usr/share/doc/omarchy-notes/CHANGELOG.md - usr/share/doc/omarchy-notes/SECURITY.md - usr/share/licenses/omarchy-notes/LICENSE -) -for path in "${required[@]}"; do - [[ -f "$work_dir/root/$path" ]] || { echo "missing installed file: $path" >&2; exit 1; } -done - -[[ "$(env -u QT_QPA_PLATFORMTHEME QT_QPA_PLATFORM=offscreen \ - "$work_dir/root/usr/bin/omarchy-notes" --version)" == "omarchy-notes $version" ]] -cmp "$project_dir/LICENSE" "$work_dir/root/usr/share/licenses/omarchy-notes/LICENSE" -if readelf -d "$work_dir/root/usr/bin/omarchy-notes" | grep -Eq '\((RPATH|RUNPATH)\)'; then - echo 'unexpected runtime library path' >&2 - exit 1 -fi - -if command -v desktop-file-validate >/dev/null; then - desktop-file-validate "$work_dir/root/usr/share/applications/org.omarchy.Notes.desktop" -fi -if command -v appstreamcli >/dev/null; then - appstreamcli validate --no-net "$work_dir/root/usr/share/metainfo/org.omarchy.Notes.metainfo.xml" -fi - -echo "package install contract: ok" diff --git a/tests/test-release-metadata.sh b/tests/test-release-metadata.sh deleted file mode 100755 index 7ab0a06..0000000 --- a/tests/test-release-metadata.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "$project_dir" -version="$(sed -n '/^project(omarchy-notes/,/)/s/^ *VERSION \([0-9.]*\).*/\1/p' CMakeLists.txt)" -[[ -n "$version" ]] - -grep -q "^pkgver=$version$" packaging/arch/PKGBUILD.in -grep -q "release version=\"$version\"" packaging/metainfo/org.omarchy.Notes.metainfo.xml -grep -q "omarchy-notes $version" packaging/man/omarchy-notes.1 -grep -q "## \[$version\]" CHANGELOG.md -grep -q 'set(ONOTES_APP_ID "org.omarchy.Notes"' CMakeLists.txt -grep -q 'https://lastrefuge.ai/projects/omarchy-notes' packaging/metainfo/org.omarchy.Notes.metainfo.xml -grep -q 'GitHub Security Advisories' SECURITY.md -appstreamcli validate --no-net packaging/metainfo/org.omarchy.Notes.metainfo.xml >/dev/null -if [[ ${GITHUB_REF_NAME:-} == v* && "${GITHUB_REF_TYPE:-}" == "tag" ]]; then - [[ "$GITHUB_REF_NAME" == "v$version" ]] -fi - -echo "release metadata $version: ok" diff --git a/tests/test-rust-backups.py b/tests/test-rust-backups.py index a3699c9..d444d8a 100644 --- a/tests/test-rust-backups.py +++ b/tests/test-rust-backups.py @@ -1,11 +1,10 @@ #!/usr/bin/env python3 -"""Real Qt ↔ Rust backup/restore and headless CLI checks, using scratch libraries.""" +"""Rust backup/restore regressions using a frozen legacy library and scratch copies.""" import argparse import hashlib import json import os from pathlib import Path -import shlex import shutil import sqlite3 import subprocess @@ -13,7 +12,7 @@ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("binary", type=Path) -parser.add_argument("--quote-driver", type=Path, help="Also verify schema-3 upgrade, old-Qt refusal and rollback") +parser.add_argument("--quote-driver", type=Path, help="Also verify schema-3 upgrade and rollback") args = parser.parse_args() binary = args.binary.resolve() repo = Path(__file__).resolve().parents[1] @@ -44,15 +43,6 @@ def dump(root): with tempfile.TemporaryDirectory(prefix="notes-backup-compatibility-") as temporary: root = Path(temporary) - probe = root / "qt-backup-probe" - flags = shlex.split(subprocess.check_output(["pkg-config", "--cflags", "--libs", "Qt6Core", "sqlite3"], text=True)) - sources = [repo / "tests/qt-backup-probe.cpp"] + [repo / "src/core" / (name + ".cpp") - for name in ["NoteStore", "LibraryBackup", "LibraryPaths", "Database", "BlobStore", "RichDocument"]] - result = subprocess.run(["g++", "-std=c++20", "-fPIC", '-DONOTES_VERSION="backup-test"', - f"-I{repo / 'src/core'}", *map(str, sources), "-o", str(probe), *flags], capture_output=True, text=True) - if result.returncode: - raise RuntimeError(result.stdout + result.stderr) - library = root / "library" shutil.copytree(repo / "tests/fixtures/qt-v1", library) with sqlite3.connect(library / "library.sqlite3") as db: @@ -63,9 +53,14 @@ def dump(root): UPDATE notes SET pinned=1,deleted_at=17,folder_id='child' WHERE title='Groceries'; """) - qt_backup = root / "Qt backup" - run(probe, "backup", library, qt_backup) - assert "databaseSha256" not in json.loads((qt_backup / "manifest.json").read_text()) + qt_backup = root / "Legacy format backup" + run(binary, "--data-dir", library, "--backup", qt_backup) + # Exercise the legacy format-1 manifest, which omitted Rust's optional + # integrity fields. The fixture manifest itself is not an app backup. + manifest = json.loads((qt_backup / "manifest.json").read_text()) + manifest.pop("databaseSha256", None) + manifest.pop("committedRevisions", None) + (qt_backup / "manifest.json").write_text(json.dumps(manifest)) original_backup = hashes(qt_backup) original_content = dump(qt_backup) original_library = dump(library) @@ -74,18 +69,18 @@ def dump(root): run(binary, "--restore", qt_backup, "--data-dir", restored) assert hashes(qt_backup) == original_backup assert dump(restored) == original_content - run(probe, "verify", restored) + assert hashes(restored / "blobs") == hashes(library / "blobs") run(binary, "--data-dir", restored, "--capture", "A note added after restore #backup") rust_backup = root / "Rust backup ? # ü" run(binary, "--data-dir", restored, "--backup", rust_backup) assert "databaseSha256" in json.loads((rust_backup / "manifest.json").read_text()) rust_hashes = hashes(rust_backup) - run(probe, "inspect", rust_backup) + run(binary, "--inspect-backup", rust_backup) assert hashes(rust_backup) == rust_hashes - roundtrip = root / "Qt reopen" + roundtrip = root / "Rust roundtrip" run(binary, "--restore", rust_backup, "--data-dir", roundtrip) assert dump(roundtrip) == dump(rust_backup) - run(probe, "verify", roundtrip) + assert hashes(roundtrip / "blobs") == hashes(rust_backup / "blobs") assert hashes(rust_backup) == rust_hashes assert dump(library) == original_library @@ -101,8 +96,8 @@ def dump(root): assert not (root / "bad").exists() and not (root / "missing").exists() assert before == hashes(rust_backup) and dump(library) == original_library - # A real Qt format-1 manifest with a schema-1 snapshot is still restored as - # schema 1; opening a separate restored copy performs the normal migration. + # A legacy format-1 manifest with a schema-1 snapshot is restored without + # migration; opening the restored copy performs the normal Rust migration. old = root / "Schema 1" shutil.copytree(qt_backup, old) with sqlite3.connect(old / "library.sqlite3") as db: @@ -118,7 +113,11 @@ def dump(root): old_restore = root / "Schema 1 restored" run(binary, "--restore", old, "--data-dir", old_restore) assert hashes(old) == old_before and dump(old_restore) == dump(old) - run(probe, "verify", old_restore) + with sqlite3.connect(old_restore / "library.sqlite3") as db: + assert db.execute("PRAGMA user_version").fetchone()[0] == 1 + run(binary, "--data-dir", old_restore, "--capture", "After schema-1 migration") + with sqlite3.connect(old_restore / "library.sqlite3") as db: + assert db.execute("PRAGMA user_version").fetchone()[0] == 2 assert hashes(old) == old_before if args.quote_driver: @@ -128,22 +127,15 @@ def dump(root): safety = root / "before quotes" run(args.quote_driver.resolve(), upgraded, safety) assert dump(safety) == before_upgrade - run(probe, "inspect", safety) + run(binary, "--inspect-backup", safety) with sqlite3.connect(upgraded / "library.sqlite3") as db: assert db.execute("PRAGMA user_version").fetchone()[0] == 3 assert db.execute("SELECT count(*) FROM schema_migrations WHERE version=3").fetchone()[0] == 1 quoted = db.execute("SELECT body,body_schema FROM notes WHERE title='A quotation worth keeping.'").fetchone() assert quoted[1] == 2 and json.loads(quoted[0])["blocks"][0]["type"] == "quote" - rejected_copy = root / "Qt must refuse" - shutil.copytree(upgraded, rejected_copy) - before_refusal = dump(rejected_copy) - rejection = run(probe, "verify", rejected_copy, ok=False) - assert "newer version" in rejection.stderr and "schema 3" in rejection.stderr - assert dump(rejected_copy) == before_refusal new_backup = root / "quoted backup" run(binary, "--data-dir", upgraded, "--backup", new_backup) - rejection = run(probe, "inspect", new_backup, ok=False) - assert "newer version" in rejection.stderr + run(binary, "--inspect-backup", new_backup) preserved = hashes(new_backup) modern_restore = root / "quoted restore" run(binary, "--restore", new_backup, "--data-dir", modern_restore) @@ -151,7 +143,7 @@ def dump(root): rollback = root / "quote rollback" run(binary, "--restore", safety, "--data-dir", rollback) assert dump(rollback) == before_upgrade - run(probe, "verify", rollback) - print("PASS: actual Qt refuses schema-3 libraries/backups; schema-2 rollback reopens in Qt; later Rust quote edits survive a separate backup/restore.") + run(binary, "--data-dir", rollback, "--capture", "After rollback") + print("PASS: Rust schema-3 quote backup/restore and schema-2 rollback.") -print("PASS: actual Qt → Rust backup/restore → Qt inspection/open, full table/history/trash/blob preservation, schema-1 restore, immutable backups and headless CLI failure paths.") +print("PASS: Rust legacy-format backup/restore, full table/history/trash/blob preservation, schema-1 migration, immutable backups and headless CLI failure paths.") diff --git a/tests/test-rust-compatibility.py b/tests/test-rust-compatibility.py index fef9dfd..2533103 100644 --- a/tests/test-rust-compatibility.py +++ b/tests/test-rust-compatibility.py @@ -1,10 +1,12 @@ #!/usr/bin/env python3 -"""Cross-version checks using scratch libraries and the real Qt document/lock APIs.""" +"""Rust edit and lock regressions against a frozen legacy library (scratch copies only).""" import argparse import hashlib +import json +import os from pathlib import Path -import shlex import shutil +import sqlite3 import subprocess import tempfile @@ -14,28 +16,51 @@ args = parser.parse_args() binary, driver = args.binary.resolve(), args.storage_driver.resolve() repo = Path(__file__).resolve().parents[1] +env = dict(os.environ, DISPLAY="", WAYLAND_DISPLAY="", DBUS_SESSION_BUS_ADDRESS="") + + +def snapshot(library): + with sqlite3.connect(library / "library.sqlite3") as db: + return {id: (json.loads(body), revision) for id, body, revision in + db.execute("SELECT id,body,revision FROM notes")} + + with tempfile.TemporaryDirectory(prefix="omarchy-rust-compatibility-") as temporary: - root = Path(temporary) - probe = root / "qt-probe" - flags = shlex.split(subprocess.check_output(["pkg-config", "--cflags", "--libs", "Qt6Core", "sqlite3"], text=True)) - compilation = subprocess.run(["g++", "-std=c++20", "-fPIC", f"-I{repo / 'src/core'}", str(repo / "tests/rust-compatibility-probe.cpp"), str(repo / "src/core/RichDocument.cpp"), "-o", str(probe), *flags], capture_output=True, text=True) - if compilation.returncode: - raise RuntimeError(compilation.stdout + compilation.stderr) - library = root / "library" + library = Path(temporary) / "library" shutil.copytree(repo / "tests/fixtures/qt-v1", library) - before = {p.relative_to(library): hashlib.sha256(p.read_bytes()).hexdigest() for p in (library / "blobs").rglob("*") if p.is_file()} - subprocess.run([str(binary), "--data-dir", str(library), "--capture", "A Rust note\nRich words #compatibility"], check=True) - subprocess.run([str(driver), str(library)], check=True) - subprocess.run([str(probe), "verify", str(library)], check=True) - assert all(hashlib.sha256((library / p).read_bytes()).hexdigest() == digest for p, digest in before.items()) - for owner, contender in [([str(probe), "hold", str(library)], [str(binary), "--data-dir", str(library), "--capture", "Must not be written"]), - ([str(driver), str(library), "hold"], [str(probe), "verify", str(library)])]: - child = subprocess.Popen(owner, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) - try: - assert child.stdout.readline().strip() == "LOCKED" - result = subprocess.run(contender, capture_output=True, text=True, timeout=10) - assert result.returncode != 0, "Both editions acquired the same library" - finally: - child.communicate("close\n", timeout=5) - assert child.returncode == 0 - print("Passed Qt → Rust edit → Qt validation, unchanged blob hashes, and mutual library exclusion.") + original = snapshot(library) + before = {p.relative_to(library): hashlib.sha256(p.read_bytes()).hexdigest() + for p in (library / "blobs").rglob("*") if p.is_file()} + subprocess.run([str(binary), "--data-dir", str(library), "--capture", + "A Rust note\nRich words #compatibility"], env=env, check=True, timeout=30) + captured = snapshot(library) + assert len(captured) == len(original) + 1 + assert all(captured[id] == note for id, note in original.items()) + subprocess.run([str(driver), str(library)], env=env, check=True, timeout=30) + edited = snapshot(library) + assert len(edited) == len(captured) + 2 # Imported media and its duplicate. + for id, (body, revision) in captured.items(): + expected = json.loads(json.dumps(body)) + expected["blocks"][0]["spans"].append({"text": " · Rust", "marks": ["italic"]}) + assert edited[id] == (expected, revision + 1), id + assert all(hashlib.sha256((library / p).read_bytes()).hexdigest() == digest + for p, digest in before.items()) + + # The Rust storage owner must exclude both another storage owner and the CLI. + child = subprocess.Popen([str(driver), str(library), "hold"], env=env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + try: + assert child.stdout.readline().strip() == "LOCKED" + locked = snapshot(library) + for contender in ([str(binary), "--data-dir", str(library), "--capture", "Must not be written"], + [str(driver), str(library)]): + result = subprocess.run(contender, env=env, capture_output=True, text=True, timeout=10) + assert result.returncode != 0, "Two Rust owners acquired the same library" + assert snapshot(library) == locked + finally: + child.communicate("close\n", timeout=5) + assert child.returncode == 0 + subprocess.run([str(binary), "--data-dir", str(library), "--capture", "After lock release"], + env=env, check=True, timeout=30) + assert len(snapshot(library)) == len(edited) + 1 + print("PASS: Rust edits preserve frozen legacy documents and blob hashes; library exclusion and lock release.") diff --git a/tests/test-rust-installer-package.sh b/tests/test-rust-installer-package.sh index f9960e8..b3e94af 100755 --- a/tests/test-rust-installer-package.sh +++ b/tests/test-rust-installer-package.sh @@ -39,9 +39,9 @@ export XDG_DATA_HOME="$test_workspace/data" XDG_CONFIG_HOME="$test_workspace/con export PATH="$test_workspace/bin:$PATH" unset DISPLAY WAYLAND_DISPLAY printf 'Qt library retained\n' > "$XDG_DATA_HOME/omarchy-notes/sentinel" -bash "$project_dir/install.sh" --edition rust --version "$NOTES_INSTALLER_TEST_TAG" --dry-run +bash "$project_dir/install.sh" --version "$NOTES_INSTALLER_TEST_TAG" --dry-run ! pacman -Q omarchy-notes-rust >/dev/null 2>&1 -bash "$project_dir/install.sh" --edition rust --version "$NOTES_INSTALLER_TEST_TAG" --yes --no-quick-note +bash "$project_dir/install.sh" --version "$NOTES_INSTALLER_TEST_TAG" --yes --no-quick-note [[ $(pacman -Q omarchy-notes-rust) == "$identity" ]] [[ $(/usr/bin/omarchy-notes-rust --version) == "omarchy-notes-rust $version" ]] [[ $(/usr/bin/omarchy-notes-preview --version) == "omarchy-notes-rust $version" ]] @@ -50,7 +50,7 @@ request=01234567-89ab-4cde-8fab-0123456789ab /usr/bin/omarchy-notes-rust --capture-status "$request" test -s "$XDG_DATA_HOME/omarchy-notes-gpui/library.sqlite3" before=$(sha256sum "$XDG_DATA_HOME/omarchy-notes-gpui/library.sqlite3") -bash "$project_dir/install.sh" --edition rust --version "$NOTES_INSTALLER_TEST_TAG" --yes --no-quick-note > "$test_workspace/repeat.log" +bash "$project_dir/install.sh" --version "$NOTES_INSTALLER_TEST_TAG" --yes --no-quick-note > "$test_workspace/repeat.log" rg -q 'already installed' "$test_workspace/repeat.log" [[ $(cat "$XDG_DATA_HOME/omarchy-notes/sentinel") == 'Qt library retained' ]] sudo -n pacman -R --noconfirm omarchy-notes-rust diff --git a/tests/test-rust-organization.py b/tests/test-rust-organization.py index 70a2672..65de20c 100644 --- a/tests/test-rust-organization.py +++ b/tests/test-rust-organization.py @@ -1,35 +1,45 @@ #!/usr/bin/env python3 -"""Round-trip folder operations through Rust and the supported Qt NoteStore.""" +"""Rust folder-operation persistence checks in a scratch library.""" import argparse +import json import os from pathlib import Path -import shlex +import sqlite3 import subprocess import tempfile parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("driver", type=Path) args = parser.parse_args() -repo = Path(__file__).resolve().parents[1] env = dict(os.environ, DISPLAY="", WAYLAND_DISPLAY="", DBUS_SESSION_BUS_ADDRESS="") - -def run(arguments): - result = subprocess.run(list(map(str, arguments)), env=env, capture_output=True, text=True, timeout=60) - if result.returncode: - raise RuntimeError(result.stdout + result.stderr) - print(result.stdout, end="") - - -with tempfile.TemporaryDirectory(prefix="notes-folder-compatibility-") as tmp: - root = Path(tmp) - probe = root / "qt-organization-probe" - flags = shlex.split(subprocess.check_output(["pkg-config", "--cflags", "--libs", "Qt6Core", "sqlite3"], text=True)) - sources = [repo / "tests/qt-organization-probe.cpp"] + [repo / "src/core" / (name + ".cpp") - for name in ["NoteStore", "LibraryBackup", "LibraryPaths", "Database", "BlobStore", "RichDocument"]] - run(["g++", "-std=c++20", "-fPIC", '-DONOTES_VERSION="folder-test"', f"-I{repo / 'src/core'}", - *sources, "-o", probe, *flags]) - library = root / "library" - run([args.driver.resolve(), "seed", library]) - run([probe, library]) - run([args.driver.resolve(), "verify", library]) +with tempfile.TemporaryDirectory(prefix="notes-folder-regression-") as tmp: + library = Path(tmp) / "library" + # seed performs Rust create/rename/move operations and asserts that a stale + # content save cannot undo filing. Its verify mode requires Qt mutations, + # so validate the persisted Rust result directly instead. + subprocess.run([str(args.driver.resolve()), "seed", str(library)], env=env, + check=True, timeout=60) + expected = json.loads((library / "expected.json").read_text()) + with sqlite3.connect(library / "library.sqlite3") as db: + assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok" + assert db.execute("PRAGMA user_version").fetchone()[0] == 2 + folders = {id: {"id": id, "name": name, "parent": parent} + for id, name, parent in db.execute("SELECT id,name,parent_id FROM folders")} + assert folders == {f["id"]: f for f in expected["folders"]} + assert len(folders) == 5 + subject = folders[expected["subject"]] + assert subject["name"] == "Projects" + assert folders[subject["parent"]]["name"] == "Personal" + assert folders[expected["work"]]["name"] == "Work" + clients = [f for f in folders.values() if f["name"] == "Clients"] + assert len(clients) == 2 and len({f["parent"] for f in clients}) == 2 + note = expected["note"] + body, revision, updated, folder = db.execute( + "SELECT body,revision,updated_at,folder_id FROM notes WHERE id=?", (note["id"],) + ).fetchone() + assert json.loads(body) == note["body"] + assert revision == note["revision"] and updated == note["updated_at"] + assert folder == expected["subject"] + assert db.execute("SELECT count(*) FROM notes").fetchone()[0] == 2 + print("PASS: Rust folder identities, nesting, rename/move and stale-save protection persist in SQLite.") diff --git a/tests/test-rust-tables.py b/tests/test-rust-tables.py index 78b8d08..c722310 100644 --- a/tests/test-rust-tables.py +++ b/tests/test-rust-tables.py @@ -1,30 +1,32 @@ #!/usr/bin/env python3 -"""Round-trip Rust table edits through SQLite and the actual Qt editable document. -Only scratch directories are used. Requires Qt6Core/Qt6Gui, Python and g++. -""" +"""Rust edits of frozen table fixtures, undo/redo and exact SQLite reopen checks.""" import argparse +import json import os from pathlib import Path -import shlex +import sqlite3 import subprocess import tempfile -parser=argparse.ArgumentParser(description=__doc__) -parser.add_argument("driver",type=Path) -args=parser.parse_args() -repo=Path(__file__).resolve().parents[1] -with tempfile.TemporaryDirectory(prefix="notes-table-compatibility-") as tmp: - root=Path(tmp) - probe=root/"qt-table-probe" - flags=shlex.split(subprocess.check_output(["pkg-config","--cflags","--libs","Qt6Core","Qt6Gui"],text=True)) - compilation=subprocess.run(["g++","-std=c++20","-fPIC",f"-I{repo/'src/core'}",str(repo/"tests/qt-table-probe.cpp"),str(repo/"src/core/RichDocument.cpp"),str(repo/"src/core/DocumentConverter.cpp"),"-o",str(probe),*flags],capture_output=True,text=True) - if compilation.returncode: raise RuntimeError(compilation.stdout+compilation.stderr) - output=root/"roundtrips" - subprocess.run([str(args.driver.resolve()),str(output)],check=True) - runtime=root/"runtime";runtime.mkdir(mode=0o700) - env=dict(os.environ,QT_QPA_PLATFORM="offscreen",QT_QPA_PLATFORMTHEME="",XDG_RUNTIME_DIR=str(runtime)) - files=[repo/"tests/fixtures/qt-merged-table.json",*sorted((output/"documents").glob("*.json"))] - for file in files: - result=subprocess.run([str(probe),"verify",str(file)],env=env,capture_output=True,text=True) - if result.returncode: raise RuntimeError(result.stdout+result.stderr) - print(f"PASS: {len(files)} documents retain exact known schema content, cell spans, formatting and identities through Qt load/read; Rust edits also survive SQLite reopen.") +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("driver", type=Path) +args = parser.parse_args() +env = dict(os.environ, DISPLAY="", WAYLAND_DISPLAY="", DBUS_SESSION_BUS_ADDRESS="") + +with tempfile.TemporaryDirectory(prefix="notes-table-regression-") as tmp: + output = Path(tmp) / "roundtrips" + # The Rust driver loads the frozen merged-table fixture, exercises allowed + # structural edits and undo/redo, then checks every body after Store reopen. + subprocess.run([str(args.driver.resolve()), str(output)], env=env, check=True, timeout=60) + files = sorted((output / "documents").glob("*.json")) + assert files and (output / "documents/created-in-rust.json") in files + for action in ("RowBefore", "RowAfter", "ColumnBefore", "ColumnAfter", + "DeleteRow", "DeleteColumn", "SplitCell"): + assert any(p.stem.endswith("-" + action) for p in files), action + expected = sorted(json.dumps(json.loads(p.read_text()), sort_keys=True) for p in files) + with sqlite3.connect(output / "library/library.sqlite3") as db: + assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok" + saved = sorted(json.dumps(json.loads(body), sort_keys=True) + for (body,) in db.execute("SELECT body FROM notes")) + assert saved == expected, "Persisted documents differ from Rust edit output" + print(f"PASS: {len(files)} Rust table documents survive structural edits, undo/redo and exact SQLite reopen.") diff --git a/tests/test_installer.py b/tests/test_installer.py index 3c24d7a..f28e652 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -24,7 +24,7 @@ import unittest INSTALLER = Path(sys.argv.pop(1)).resolve() -PACKAGE = "omarchy-notes-1.0.0-1-x86_64.pkg.tar.zst" +PACKAGE = "omarchy-notes-rust-1.0.0-1-x86_64.pkg.tar.zst" REPO = "https://github.com/last-refuge/omarchy-notes" RELEASES_API = "https://api.github.com/repos/last-refuge/omarchy-notes/releases?per_page=100" @@ -32,7 +32,7 @@ import json, os, pathlib, subprocess, sys, time root = pathlib.Path(os.environ["MOCK_ROOT"]) cfg = json.loads((root / "config.json").read_text()) -package = cfg.get("package", "omarchy-notes") +package = cfg.get("package", "omarchy-notes-rust") version = cfg.get("version", "1.0.0") name = pathlib.Path(sys.argv[0]).name args = sys.argv[1:] @@ -54,7 +54,7 @@ def fail(message, code=1): if cfg.get("fail_asset") == asset or (url.startswith("https://api.github.com/") and cfg.get("fail_asset") == "latest"): fail("curl: simulated HTTP 404 / network failure", 22) if url.startswith("https://api.github.com/"): - tag = cfg.get("latest_url", "https://github.com/last-refuge/omarchy-notes/releases/tag/v1.0.0").rsplit("/",1)[-1] + tag = cfg.get("latest_url", "https://github.com/last-refuge/omarchy-notes/releases/tag/rust-v1.0.0").rsplit("/",1)[-1] data = json.dumps(cfg.get("releases", [{"tag_name":tag,"published_at":"2026-10-13T00:00:00Z","draft":False,"prerelease":False}])).encode() pathlib.Path(args[args.index("--output") + 1]).write_bytes(data) else: @@ -95,16 +95,10 @@ def fail(message, code=1): destination = pathlib.Path(os.environ["PKGDEST"]) (destination / f"{package}-{version}-1-x86_64.pkg.tar.zst").write_bytes(b"built package") (destination / f"{package}-debug-{version}-1-x86_64.pkg.tar.zst").write_bytes(b"debug") -elif name in ("omarchy-notes", "omarchy-notes-rust"): +elif name == "omarchy-notes-rust": if args == ["--version"]: - if name == "omarchy-notes" and os.environ.get("QT_QPA_PLATFORM") != "offscreen": fail("not off-screen") - if cfg.get("fail_verify"): fail("simulated Qt failure") + if cfg.get("fail_verify"): fail("simulated application failure") print(cfg.get("app_version", name + " " + version)) - elif args == ["--setup-hyprland"]: - if cfg.get("quick_conflict"): - print("Super + Alt + N is already bound, so nothing was changed.") - sys.exit(1) - print("Added Quick Note; backups saved.") else: fail("unexpected app arguments") elif name == "omarchy": fail("installer must not run omarchy commands") @@ -124,7 +118,6 @@ def setUp(self): shim.chmod(0o755) for name in ("curl", "sudo", "pacman", "uname", "makepkg", "omarchy"): (self.root / "bin" / name).symlink_to(shim) - (self.root / "system/bin/omarchy-notes").symlink_to(shim) (self.root / "system/bin/omarchy-notes-rust").symlink_to(shim) alias = self.root / "system/bin/omarchy-notes-preview" alias.write_text('#!/bin/sh\nexec "' + str(self.root / "system/bin/omarchy-notes-rust") + '" "$@"\n') @@ -134,9 +127,9 @@ def setUp(self): (self.root / "config/hypr/hyprland.lua").write_text("-- sentinel rule\n") (self.root / "data/omarchy-notes/library.sqlite3").write_bytes(b"untouched notes") (self.root / "assets" / PACKAGE).write_bytes(b"release package") - (self.root / "assets" / PACKAGE.replace("omarchy-notes-", "omarchy-notes-debug-")).write_bytes(b"debug") - self.archive("omarchy-notes-1.0.0-aur.tar.gz", {"aur/PKGBUILD": "pkgname=omarchy-notes\n", "aur/.SRCINFO": "pkgname = omarchy-notes\n"}) - self.archive("omarchy-notes-1.0.0.tar.gz", {"omarchy-notes-1.0.0/CMakeLists.txt": "source"}) + (self.root / "assets" / PACKAGE.replace("omarchy-notes-rust-", "omarchy-notes-rust-debug-")).write_bytes(b"debug") + self.archive("omarchy-notes-rust-1.0.0-aur.tar.gz", {"aur/PKGBUILD": "pkgname=omarchy-notes-rust\n", "aur/.SRCINFO": "pkgname = omarchy-notes-rust\n"}) + self.archive("omarchy-notes-rust-1.0.0.tar.gz", {"omarchy-notes-rust-1.0.0/Cargo.toml": "source"}) self.manifest() self.env = dict(os.environ, MOCK_ROOT=str(self.root), HOME=str(self.root / "home"), XDG_CONFIG_HOME=str(self.root / "config"), XDG_DATA_HOME=str(self.root / "data"), @@ -192,25 +185,25 @@ def test_fresh_install_and_preservation(self): self.assert_success(result) self.assertIn("Application verified", result.stdout) self.assertIn("pacman transaction visible", result.stdout) - self.assertIn(str(self.root / "data/omarchy-notes"), result.stdout) + self.assertIn(str(self.root / "data/omarchy-notes-gpui"), result.stdout) self.assertEqual(len(self.mutations()), 1) self.assertIn("--noconfirm", self.mutations()[0]) - self.assertEqual(self.calls("omarchy-notes"), [["--version"]]) + self.assertEqual(self.calls("omarchy-notes-rust"), [["--version"], ["--version"]]) self.assertEqual((self.root / "data/omarchy-notes/library.sqlite3").read_bytes(), b"untouched notes") self.assertEqual((self.root / "config/hypr/bindings.lua").read_text(), "-- sentinel binding\n") self.assertEqual(list((self.root / "tmp").iterdir()), []) self.assertNotIn("\x1b", result.stdout) urls = [args[-1] for args in self.calls("curl")] self.assertEqual(urls.count(RELEASES_API), 1) - self.assertTrue(all("/download/v1.0.0/" in url for url in urls[1:])) + self.assertTrue(all("/download/rust-v1.0.0/" in url for url in urls[1:])) self.assertFalse(any("debug" in url for url in urls)) def test_upgrade_and_already_installed(self): - (self.root / "installed").write_text("0.9.0-1") - self.assert_success(self.run_installer("--yes", "--version", "v1.0.0")) + (self.root / "installed-rust").write_text("0.9.0-1") + self.assert_success(self.run_installer("--yes", "--version", "rust-v1.0.0")) self.assertEqual(len(self.mutations()), 1) (self.root / "calls.jsonl").unlink() - result = self.run_installer("--yes", "--version=v1.0.0") + result = self.run_installer("--yes", "--version=rust-v1.0.0") self.assert_success(result) self.assertIn("already installed", result.stdout) self.assertEqual(self.mutations(), []) @@ -221,7 +214,7 @@ def test_dry_run(self): self.assert_success(self.run_installer(*args)) self.assertEqual(self.mutations(), []) self.assertEqual(self.calls("sudo"), []) - self.assertEqual(self.calls("omarchy-notes"), []) + self.assertEqual(self.calls("omarchy-notes-rust"), []) self.assertEqual(self.calls("makepkg"), []) self.assertEqual(list((self.root / "tmp").iterdir()), []) @@ -229,7 +222,7 @@ def test_arguments_and_unattended_input(self): for args, message in (((), "No interactive terminal"), (("--version",), "requires a release tag"), (("--version=", "--yes"), "requires a release tag"), - (("--version", "../bad", "--yes"), "stable release tag"), + (("--version", "../bad", "--yes"), "stable Rust release tag"), (("--quick-note", "--no-quick-note"), "Choose either"), (("--wat",), "Unknown option")): self.assert_failure(self.run_installer(*args), message) @@ -240,7 +233,7 @@ def test_architecture_and_os(self): self.config["arch"] = "riscv64" self.assert_failure(self.run_installer("--yes"), "Unsupported architecture") self.config["arch"] = "aarch64" - self.assert_failure(self.run_installer("--yes"), "No aarch64 application package") + self.assert_failure(self.run_installer("--yes"), "x86_64 only") self.config["os"] = "Darwin" self.assert_failure(self.run_installer("--yes"), "supports Linux") self.assertEqual(self.mutations(), []) @@ -253,7 +246,7 @@ def test_missing_release_and_network(self): self.assertEqual(self.calls("makepkg"), []) def test_unsupported_release_redirect(self): - self.config["latest_url"] = REPO + "/releases/tag/v1.1.0-beta" + self.config["latest_url"] = REPO + "/releases/tag/rust-v1.1.0-beta" self.assert_failure(self.run_installer("--yes"), "No supported published release") self.assertEqual(self.mutations(), []) @@ -292,43 +285,47 @@ def test_denied_privilege_and_transaction(self): self.assertEqual(self.calls("sudo")[0][0], "-n") self.config = {"deny_pacman": True} self.assert_failure(self.run_installer("--yes"), "pacman could not install") - self.assertFalse((self.root / "installed").exists()) + self.assertFalse((self.root / "installed-rust").exists()) def test_post_install_verification_failure(self): self.config["fail_verify"] = True self.assert_failure(self.run_installer("--yes"), "application verification failed") - self.assertTrue((self.root / "installed").exists()) - self.assertEqual(self.calls("omarchy-notes"), [["--version"]]) + self.assertTrue((self.root / "installed-rust").exists()) + self.assertEqual(self.calls("omarchy-notes-rust"), [["--version"]]) + + def test_missing_preview_alias_is_refused(self): + (self.root / "system/bin/omarchy-notes-preview").unlink() + self.assert_failure(self.run_installer("--yes"), "compatibility launcher is missing") - def test_quick_note_explicit_opt_in_and_conflict(self): - self.config["quick_conflict"] = True + def test_wrong_executable_version_is_refused(self): + self.config["app_version"] = "omarchy-notes 1.0.0" + self.assert_failure(self.run_installer("--yes"), "unexpected version") + + def test_quick_note_explicit_opt_in_is_manual(self): result = self.run_installer("--yes", "--quick-note") self.assert_success(result) - self.assertIn("Quick Note setup needs attention", result.stdout) - self.assertIn("already bound", result.stdout) - self.assertEqual(self.calls("omarchy-notes"), [["--version"], ["--setup-hyprland"]]) - logs = list((self.root / "tmp").glob("*.log")) - self.assertEqual(len(logs), 1) - self.assertIn("already bound", logs[0].read_text()) + self.assertIn("No bindings were changed", result.stdout) + self.assertEqual(self.calls("omarchy-notes-rust"), [["--version"], ["--version"]]) + self.assertEqual((self.root / "config/hypr/bindings.lua").read_text(), "-- sentinel binding\n") def test_quick_note_skipped_and_incompatible(self): self.assert_success(self.run_installer("--yes", "--no-quick-note")) (self.root / "config/hypr/bindings.lua").unlink() result = self.run_installer("--yes", "--quick-note") self.assert_success(result) - self.assertIn("requires compatible", result.stdout) - self.assertFalse(any("--setup-hyprland" in args for args in self.calls("omarchy-notes"))) + self.assertIn("No bindings were changed", result.stdout) + self.assertFalse(any("--setup-hyprland" in args for args in self.calls("omarchy-notes-rust"))) def test_shadow_copy_and_data_override(self): # Different real path, rather than a symlink to the package-owned shim. - (self.root / "bin/omarchy-notes").write_text("#!/bin/sh\nexit 99\n") - (self.root / "bin/omarchy-notes").chmod(0o755) - self.env["OMARCHY_NOTES_DATA_DIR"] = str(self.root / "custom-library") + (self.root / "bin/omarchy-notes-rust").write_text("#!/bin/sh\nexit 99\n") + (self.root / "bin/omarchy-notes-rust").chmod(0o755) + self.env["XDG_DATA_HOME"] = str(self.root / "custom-library") result = self.run_installer("--yes") self.assert_success(result) self.assertIn("takes precedence on PATH", result.stdout) self.assertIn(str(self.root / "custom-library"), result.stdout) - self.assertTrue((self.root / "bin/omarchy-notes").exists()) + self.assertTrue((self.root / "bin/omarchy-notes-rust").exists()) def test_source_build(self): result = self.run_installer("--yes", "--source") @@ -351,10 +348,10 @@ def rust_release(self): {"tag_name":"rust-v8.0.0", "published_at":"2026-10-15T00:00:00Z", "draft":True}, ] - def test_rust_edition_coexists_and_latest_selection_is_edition_filtered(self): + def test_legacy_data_preserved_and_latest_selection_is_rust_only(self): self.rust_release() (self.root / "installed").write_text("1.0.0-1") - result = self.run_installer("--yes", "--edition", "rust", "--quick-note") + result = self.run_installer("--yes", "--quick-note") self.assert_success(result) self.assertIn("rust-v0.1.0 selected", result.stdout) self.assertIn(str(self.root / "data/omarchy-notes-gpui"), result.stdout) @@ -365,33 +362,28 @@ def test_rust_edition_coexists_and_latest_selection_is_edition_filtered(self): self.assertEqual((self.root / "data/omarchy-notes/library.sqlite3").read_bytes(), b"untouched notes") self.assertEqual((self.root / "config/hypr/bindings.lua").read_text(), "-- sentinel binding\n") self.assertTrue(all("/download/rust-v0.1.0/" in url[-1] for url in self.calls("curl")[1:])) - # The Qt default still selects its own release despite a newer Rust one. - self.config.pop("package"); self.config.pop("version") - result = self.run_installer("--yes", "--no-quick-note") - self.assert_success(result) - self.assertIn("Release v1.0.0 selected", result.stdout) - def test_cross_edition_tags_packages_and_architectures_are_refused(self): + def test_legacy_tags_options_packages_and_architectures_are_refused(self): self.rust_release() - self.assert_failure(self.run_installer("--yes", "--edition=rust", "--version=v1.0.0"), "stable release tag for rust") - self.assert_failure(self.run_installer("--yes", "--version=rust-v0.1.0"), "stable release tag for qt") - self.assert_failure(self.run_installer("--yes", "--edition=other"), "must be qt or rust") + self.assert_failure(self.run_installer("--yes", "--version=v1.0.0"), "stable Rust release tag") + for edition in ("qt", "rust", "other"): + self.assert_failure(self.run_installer("--yes", f"--edition={edition}"), "Unknown option") self.config["identity"] = "omarchy-notes 0.1.0-1" - self.assert_failure(self.run_installer("--yes", "--edition=rust"), "Unexpected package identity") + self.assert_failure(self.run_installer("--yes"), "Unexpected package identity") self.config["arch"] = "aarch64" - self.assert_failure(self.run_installer("--yes", "--edition=rust"), "x86_64 only") + self.assert_failure(self.run_installer("--yes"), "x86_64 only") self.assertEqual(self.mutations(), []) - def test_rust_source_route_selects_separate_recipe_and_dependencies(self): + def test_source_route_selects_rust_recipe_and_dependencies(self): self.rust_release() - self.assert_success(self.run_installer("--yes", "--source", "--edition=rust")) + self.assert_success(self.run_installer("--yes", "--source")) deps = next(args for args in self.mutations() if args[0] == "-S") self.assertIn("rustup", deps) self.assertNotIn("qt6-base", deps) self.assertEqual(self.calls("omarchy-notes-rust"), [["--version"], ["--version"]]) def test_source_failures(self): - self.config["corrupt_asset"] = "omarchy-notes-1.0.0-aur.tar.gz" + self.config["corrupt_asset"] = "omarchy-notes-rust-1.0.0-aur.tar.gz" self.assert_failure(self.run_installer("--yes", "--source"), "Checksum failed") self.assertEqual(self.mutations(), []) self.config = {"fail_build": True} @@ -399,7 +391,7 @@ def test_source_failures(self): self.assertEqual([args[0] for args in self.mutations()], ["-S"]) def test_unexpected_recipe_path(self): - self.archive("omarchy-notes-1.0.0-aur.tar.gz", {"../escaped": "bad"}) + self.archive("omarchy-notes-rust-1.0.0-aur.tar.gz", {"../escaped": "bad"}) self.manifest() self.assert_failure(self.run_installer("--yes", "--source"), "Unexpected path") self.assertEqual(self.mutations(), []) @@ -461,11 +453,11 @@ def run_pty(self, args, replies=(), interrupt=False, columns=100): return os.waitstatus_to_exitcode(status), output.decode(errors="replace") def test_interactive_prompts_and_narrow_terminal(self): - code, output = self.run_pty([], (("[Y/n]", "y"), ("[y/N]", "n"))) + code, output = self.run_pty([], (("[Y/n]", "y"),)) self.assertEqual(code, 0, output) self.assertIn("\x1b[38;2;126;156;216m", output) self.assertIn("\x1b[?25h", output) - self.assertFalse(any("--setup-hyprland" in args for args in self.calls("omarchy-notes"))) + self.assertFalse(any("--setup-hyprland" in args for args in self.calls("omarchy-notes-rust"))) self.assertNotIn("--noconfirm", self.mutations()[0]) self.assertNotEqual(self.calls("sudo")[0][0], "-n") code, output = self.run_pty(["--yes"], columns=40) diff --git a/tests/test_rust_release.py b/tests/test_rust_release.py index 63d794a..8a7f3a5 100644 --- a/tests/test_rust_release.py +++ b/tests/test_rust_release.py @@ -19,6 +19,26 @@ class RustReleaseTests(unittest.TestCase): + def test_distribution_routes_are_rust_only(self): + installer = (ROOT / "install.sh").read_text() + self.assertNotIn("--edition", installer) + self.assertNotIn("QT_QPA_PLATFORM", installer) + self.assertNotIn("qt6-", installer) + release = (ROOT / ".github/workflows/release.yml").read_text() + self.assertIn('tags: ["rust-v*"]', release) + for workflow in (ROOT / ".github/workflows").glob("*.yml"): + self.assertNotIn("qt6-", workflow.read_text()) + self.assertNotIn("--edition", workflow.read_text()) + for legacy in ("arch/PKGBUILD.in", "desktop/org.omarchy.Notes.desktop.in", + "icons/org.omarchy.Notes.svg", "man/omarchy-notes.1", + "metainfo/org.omarchy.Notes.metainfo.xml"): + self.assertFalse((ROOT / "packaging" / legacy).exists()) + result = subprocess.run(["python3", str(ROOT / "packaging/prepare-release.py"), + "--edition", "qt", "--ref", "HEAD", "--output", "/unused"], + capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("unrecognized arguments", result.stderr) + def test_metadata_names_and_current_preview_version_align(self): version = tomllib.loads((ROOT / "Cargo.toml").read_text())["workspace"]["package"]["version"] component = ET.parse(ROOT / "packaging/metainfo/org.omarchy.Notes.Rust.metainfo.xml").getroot() @@ -121,9 +141,7 @@ def test_candidate_preparation_is_exact_repeatable_and_rejects_cross_edition_tag repo.mkdir() (repo / "packaging/arch").mkdir(parents=True) (repo / "Cargo.toml").write_text('[workspace.package]\nversion="0.1.0"\n') - (repo / "CMakeLists.txt").write_text("project(omarchy-notes VERSION 1.0.0)\n") - for name in ("PKGBUILD.in", "PKGBUILD-rust.in"): - (repo / "packaging/arch" / name).write_bytes((ROOT / "packaging/arch" / name).read_bytes()) + (repo / "packaging/arch/PKGBUILD-rust.in").write_bytes((ROOT / "packaging/arch/PKGBUILD-rust.in").read_bytes()) (repo / "tracked").write_text("committed source\n") subprocess.run(["git", "init", "-q", str(repo)], check=True) subprocess.run(["git", "-C", str(repo), "add", "."], check=True) @@ -141,14 +159,14 @@ def test_candidate_preparation_is_exact_repeatable_and_rejects_cross_edition_tag os.environ["PATH"] = str(bin_dir) + ":" + old_path try: with self.assertRaisesRegex(ValueError, "require --candidate"): - prepare_release.prepare(repo, "HEAD", root / "refused", "rust") - with self.assertRaisesRegex(ValueError, "edition"): - prepare_release.prepare(repo, "v1.0.0", root / "wrong-rust", "rust", True) - with self.assertRaisesRegex(ValueError, "edition"): - prepare_release.prepare(repo, "rust-v0.1.0", root / "wrong-qt") + prepare_release.prepare(repo, "HEAD", root / "refused") + with self.assertRaisesRegex(ValueError, "source version"): + prepare_release.prepare(repo, "v1.0.0", root / "wrong-tag", candidate=True) + with self.assertRaisesRegex(ValueError, "require --candidate"): + prepare_release.prepare(repo, "rust-v0.1.0", root / "unreleased") first, second = root / "first", root / "second" - prepare_release.prepare(repo, revision, first, "rust", True) - prepare_release.prepare(repo, revision, second, "rust", True) + prepare_release.prepare(repo, revision, first, candidate=True) + prepare_release.prepare(repo, revision, second, candidate=True) self.assertEqual((first / "SOURCE_REVISION").read_text().strip(), revision) self.assertEqual((first / "RELEASE_KIND").read_text().strip(), "candidate") self.assertEqual((first / "SHA256SUMS").read_bytes(), (second / "SHA256SUMS").read_bytes()) @@ -162,6 +180,21 @@ def test_candidate_preparation_is_exact_repeatable_and_rejects_cross_edition_tag for line in (first / "SHA256SUMS").read_text().splitlines(): digest, name = line.split() self.assertEqual(hashlib.sha256((first / name).read_bytes()).hexdigest(), digest) + with self.assertRaisesRegex(ValueError, "already exists"): + prepare_release.prepare(repo, revision, first, candidate=True) + (repo / "Cargo.toml").write_text('[workspace.package]\nversion="1.0.0"\n') + subprocess.run(["git", "-C", str(repo), "add", "Cargo.toml"], check=True) + subprocess.run(["git", "-C", str(repo), "-c", "user.name=Release test", "-c", "user.email=release-test@example.invalid", "commit", "-qm", "stable"], check=True) + subprocess.run(["git", "-C", str(repo), "tag", "rust-v1.0.0"], check=True) + stable = root / "stable" + prepare_release.prepare(repo, "rust-v1.0.0", stable) + self.assertEqual((stable / "RELEASE_KIND").read_text(), "stable\n") + self.assertNotIn("early access", (stable / "aur/PKGBUILD").read_text()) + with self.assertRaisesRegex(ValueError, "exact rust-vVERSION tag"): + prepare_release.prepare(repo, "HEAD", root / "untagged-stable") + subprocess.run(["git", "-C", str(repo), "tag", "rust-v2.0.0"], check=True) + with self.assertRaisesRegex(ValueError, "source version"): + prepare_release.prepare(repo, "rust-v2.0.0", root / "mismatched", candidate=True) finally: os.environ["PATH"] = old_path diff --git a/tests/tst_document.cpp b/tests/tst_document.cpp deleted file mode 100644 index 14e472b..0000000 --- a/tests/tst_document.cpp +++ /dev/null @@ -1,332 +0,0 @@ -#include "DocumentConverter.h" -#include "RichDocument.h" -#include "SampleLibrary.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace onotes; -using namespace Qt::StringLiterals; - -namespace { - -const QString kHash = u"a3f1c2d4e5b60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90"_s; -const QString kAttachment = u"8d1c3f0e-6b8a-4f7e-9d2c-1a2b3c4d5e6f"_s; -const QString kLinked = u"2f7d4c1e-0a9b-4c8d-8e7f-6a5b4c3d2e1f"_s; - -RichDocument fixture() -{ - return SampleLibrary::mixedContentNote(kHash, kAttachment, kLinked); -} - -RichDocument viaEditor(const RichDocument &in, QTextDocument *doc) -{ - DocumentConverter::load(in, doc, DocumentStyle{}); - return DocumentConverter::read(doc); -} - -QString describe(const RichDocument &doc) -{ - return QString::fromUtf8(QJsonDocument(doc.toJson()).toJson(QJsonDocument::Indented)); -} - -#define COMPARE_DOCS(actual, expected) \ - do { \ - const RichDocument a_ = (actual); \ - const RichDocument e_ = (expected); \ - if (!(a_ == e_)) { \ - qWarning().noquote() << "actual:\n" << describe(a_) << "\nexpected:\n" << describe(e_); \ - QFAIL("documents differ"); \ - } \ - } while (false) - -Block table(int rows, int columns, QList cells = {}) -{ - Block b; - b.type = Block::Type::Table; - b.rows = rows; - b.columns = columns; - if (cells.isEmpty()) { - for (int r = 0; r < rows; ++r) - for (int c = 0; c < columns; ++c) - cells.append({r, c, 1, 1, {Block::paragraph({Span::plain(u"r%1c%2"_s.arg(r).arg(c))})}}); - } - b.cells = cells; - return b; -} - -RichDocument withIds(RichDocument doc) -{ - doc.assignMissingIds(); - return doc; -} - -} // namespace - -class TestDocument : public QObject -{ - Q_OBJECT - -private slots: - void jsonRoundTrip() - { - const RichDocument doc = fixture(); - const auto parsed = RichDocument::fromJsonBytes(doc.toJsonBytes()); - QVERIFY(parsed); - COMPARE_DOCS(*parsed, doc); - } - - void editorRoundTrip() - { - QTextDocument doc; - const RichDocument source = fixture(); - COMPARE_DOCS(viaEditor(source, &doc), source); - } - - void editorRoundTripIsStable() - { - QTextDocument doc; - const RichDocument first = viaEditor(fixture(), &doc); - QTextDocument again; - COMPARE_DOCS(viaEditor(first, &again), first); - // Reading the same document twice must not mint new ids. - COMPARE_DOCS(DocumentConverter::read(&doc), first); - } - - void derivedFields() - { - const RichDocument doc = fixture(); - QCOMPARE(doc.title(), u"Q3 planning — product sync"_s); - QVERIFY(doc.snippet().startsWith(u"Met with Dana"_s)); - QCOMPARE(doc.referencedBlobs(), QStringList{kHash}); - QCOMPARE(doc.referencedAttachments(), QStringList{kAttachment}); - QVERIFY(doc.plainText().contains(u"Search benchmark"_s)); // table text is searchable - } - - void tableLayouts_data() - { - QTest::addColumn("doc"); - const Block para = Block::paragraph({Span::plain(u"text"_s)}); - QTest::newRow("table only") << withIds({{table(2, 2)}}); - QTest::newRow("two tables") << withIds({{table(1, 2), table(2, 1)}}); - QTest::newRow("sandwich") << withIds({{para, table(2, 3), para}}); - QTest::newRow("empty cells") << withIds({{table(2, 2, {{0, 0, 1, 1, {Block::paragraph()}}, {0, 1, 1, 1, {Block::paragraph()}}, - {1, 0, 1, 1, {Block::paragraph()}}, {1, 1, 1, 1, {Block::paragraph()}}})}}); - - Block merged = table(3, 3, { - {0, 0, 1, 3, {Block::paragraph({Span::plain(u"Header"_s, Bold)})}}, - {1, 0, 2, 1, {Block::paragraph({Span::plain(u"tall"_s)})}}, - {1, 1, 1, 1, {Block::listItem(ListKind::Check, 0, {Span::plain(u"in a cell"_s)}, true), - Block::listItem(ListKind::Check, 0, {Span::plain(u"second"_s)})}}, - {1, 2, 1, 1, {Block::paragraph()}}, - {2, 1, 1, 1, {Block::paragraph({Span::plain(u"a"_s)}), Block::paragraph({Span::plain(u"b"_s)})}}, - {2, 2, 1, 1, {Block::paragraph()}}, - }); - QTest::newRow("merged cells and lists") << withIds({{para, merged}}); - } - - void tableLayouts() - { - QFETCH(RichDocument, doc); - QTextDocument text; - COMPARE_DOCS(viaEditor(doc, &text), doc); - } - - void listNumberingRestartsAfterShallowerItem() - { - const RichDocument doc = withIds({{ - Block::listItem(ListKind::Ordered, 0, {Span::plain(u"one"_s)}), - Block::listItem(ListKind::Ordered, 1, {Span::plain(u"a"_s)}), - Block::listItem(ListKind::Ordered, 0, {Span::plain(u"two"_s)}), - Block::listItem(ListKind::Ordered, 1, {Span::plain(u"a again"_s)}), - }}); - QTextDocument text; - viaEditor(doc, &text); - const QTextBlock second = text.findBlockByNumber(1); - const QTextBlock fourth = text.findBlockByNumber(3); - QVERIFY(second.textList() && fourth.textList()); - QCOMPARE(fourth.textList()->itemNumber(fourth), 0); - QCOMPARE(text.findBlockByNumber(2).textList()->itemNumber(text.findBlockByNumber(2)), 1); - } - - void splitBlockKeepsUniqueIds() - { - QTextDocument text; - const RichDocument before = viaEditor(fixture(), &text); - QTextCursor cursor(&text); - cursor.setPosition(text.findBlockByNumber(1).position() + 5); - cursor.insertBlock(); // Enter in the middle of the first paragraph - const RichDocument after = DocumentConverter::read(&text); - - QSet ids; - std::function &)> collect = [&](const QList &blocks) { - for (const Block &b : blocks) { - QVERIFY2(!ids.contains(b.id), qPrintable(b.id)); - ids.insert(b.id); - for (const TableCell &c : b.cells) - collect(c.blocks); - } - }; - collect(after.blocks); - QCOMPARE(after.blocks[1].id, before.blocks[1].id); // first half keeps identity - QVERIFY(after.blocks[2].id != before.blocks[1].id); - } - - void pasteGetsFreshIds() - { - QTextDocument text; - const RichDocument original = viaEditor(fixture(), &text); - QTextCursor select(&text); - select.setPosition(text.findBlockByNumber(3).position()); - select.setPosition(text.findBlockByNumber(6).position(), QTextCursor::KeepAnchor); - const QTextDocumentFragment copied = select.selection(); - QTextCursor end(&text); - end.movePosition(QTextCursor::End); - end.insertBlock(); - end.insertFragment(copied); - const RichDocument after = DocumentConverter::read(&text); - QVERIFY(after.blocks.size() > original.blocks.size()); - QSet ids; - for (const Block &b : after.blocks) { - QVERIFY(!ids.contains(b.id)); - ids.insert(b.id); - } - } - - void selectionExport() - { - QTextDocument text; - viaEditor(fixture(), &text); - QTextCursor cursor(&text); - cursor.setPosition(text.findBlockByNumber(8).position()); // checklist - cursor.setPosition(text.findBlockByNumber(10).position() + 3, QTextCursor::KeepAnchor); - const RichDocument part = DocumentConverter::readSelection(cursor); - if (part.blocks.size() != 3) - qWarning().noquote() << describe(part); - QCOMPARE(part.blocks.size(), 3); - QCOMPARE(part.blocks[0].list, ListKind::Check); - QVERIFY(part.blocks[0].checked); - QCOMPARE(part.blocks[2].indent, 1); - QCOMPARE(part.blocks[2].plainText(), u"Use"_s); - } - - void htmlPasteIsNormalized() - { - ConversionReport report; - const RichDocument doc = DocumentConverter::fromHtml( - u"

Title

" - "

bold big " - "link bad" - "

" - "
  • one
    • nested
" - "
  1. first
"_s, &report); - - QCOMPARE(doc.blocks[0].type, Block::Type::Heading); - QCOMPARE(doc.blocks[0].plainText(), u"Title"_s); - const Block ¶ = doc.blocks[1]; - QCOMPARE(para.spans[0].marks, quint32(Bold)); - QCOMPARE(para.spans[0].text, u"bold"_s); - bool sawLink = false; - for (const Span &s : para.spans) { - if (s.href == u"https://example.com") - sawLink = true; - QVERIFY(!s.href.startsWith(u"javascript")); - } - QVERIFY(sawLink); - QCOMPARE(doc.blocks[2].list, ListKind::Bullet); - QCOMPARE(doc.blocks[3].indent, 1); - QCOMPARE(doc.blocks[4].list, ListKind::Ordered); - QCOMPARE(report.warnings.size(), 2); // unsupported link, web image - } - - void findsTags_data() - { - QTest::addColumn("text"); - QTest::addColumn("tags"); - QTest::newRow("simple") << u"Plan the #launch and #Q3-review today"_s << QStringList{u"launch"_s, u"q3-review"_s}; - QTest::newRow("start and punctuation") << u"#todo: call (#Dana) “#quoted”"_s - << QStringList{u"todo"_s, u"dana"_s, u"quoted"_s}; - QTest::newRow("not tags") << u"issue #12, url.com/#anchor, a#b, ##, # space"_s << QStringList{}; - QTest::newRow("nested and unicode") << u"#work/clients #café #2026-plan"_s - << QStringList{u"work/clients"_s, u"café"_s, u"2026-plan"_s}; - QTest::newRow("trailing separators") << u"#draft- and #ideas/"_s << QStringList{u"draft"_s, u"ideas"_s}; - } - - void findsTags() - { - QFETCH(QString, text); - QFETCH(QStringList, tags); - QStringList found; - for (const TagMatch &m : findTags(text)) { - found << m.tag; - QCOMPARE(text.mid(m.start, m.length).toLower(), u'#' + m.tag); - } - QCOMPARE(found, tags); - } - - void documentTagsSkipCodeAndLinks() - { - RichDocument doc; - doc.blocks << Block::paragraph({Span::plain(u"Ship #v2 "_s), Span::plain(u"#notatag"_s, Code), - Span::plain(u" see "_s), Span::plain(u"#alsonot"_s, 0, u"https://x.com/#alsonot"_s)}); - doc.blocks << Block::listItem(ListKind::Check, 0, {Span::plain(u"#V2 again, #errands"_s)}); - QCOMPARE(doc.tags(), (QStringList{u"v2"_s, u"errands"_s})); - } - - void rejectsInvalidDocuments_data() - { - QTest::addColumn("json"); - QTest::newRow("future schema") << QByteArray(R"({"schema":2,"blocks":[]})"); - QTest::newRow("unknown block") << QByteArray(R"({"schema":1,"blocks":[{"type":"video"}]})"); - QTest::newRow("path traversal") << QByteArray( - R"({"schema":1,"blocks":[{"type":"paragraph","spans":[{"image":"../../etc/passwd"}]}]})"); - QTest::newRow("bad attachment") << QByteArray( - R"({"schema":1,"blocks":[{"type":"paragraph","spans":[{"attachment":"x"}]}]})"); - QTest::newRow("unknown mark") << QByteArray( - R"({"schema":1,"blocks":[{"type":"paragraph","spans":[{"text":"a","marks":["blink"]}]}]})"); - QTest::newRow("cell outside table") << QByteArray( - R"({"schema":1,"blocks":[{"type":"table","rows":1,"columns":1,"cells":[{"row":1,"col":0,"blocks":[]}]}]})"); - } - - void rejectsInvalidDocuments() - { - QFETCH(QByteArray, json); - QString error; - QVERIFY(!RichDocument::fromJsonBytes(json, &error)); - QVERIFY(!error.isEmpty()); - } - - void largeDocumentTiming() - { - RichDocument doc; - for (int i = 0; i < 5000; ++i) { - doc.blocks << Block::paragraph({Span::plain(u"Paragraph %1 with "_s.arg(i)), - Span::plain(u"some bold"_s, Bold), - Span::plain(u" and plain text to make it realistic."_s)}); - if (i % 50 == 0) - doc.blocks << Block::listItem(ListKind::Check, 0, {Span::plain(u"task"_s)}); - } - doc.assignMissingIds(); - QTextDocument text; - QElapsedTimer timer; - timer.start(); - DocumentConverter::load(doc, &text, DocumentStyle{}); - const qint64 loadMs = timer.restart(); - const RichDocument back = DocumentConverter::read(&text); - const qint64 readMs = timer.restart(); - const QByteArray json = back.toJsonBytes(); - const qint64 jsonMs = timer.elapsed(); - qInfo("5100 blocks: load %lld ms, read %lld ms, serialize %lld ms (%lld KB)", - loadMs, readMs, jsonMs, qint64(json.size() / 1024)); - COMPARE_DOCS(back, doc); - } -}; - -QTEST_MAIN(TestDocument) -#include "tst_document.moc" diff --git a/tests/tst_editor.cpp b/tests/tst_editor.cpp deleted file mode 100644 index 253d961..0000000 --- a/tests/tst_editor.cpp +++ /dev/null @@ -1,929 +0,0 @@ -// Editor feasibility gate: drives the real QML editor offscreen and checks -// behaviour end to end against storage. Screenshots land in SCREENSHOT_DIR -// for visual review of rendering (tables, checkboxes, images, themes). - -#include "AppController.h" -#include "AppLibrary.h" -#include "BlobImageProvider.h" -#include "DocumentConverter.h" -#include "EditorController.h" -#include "LibraryService.h" -#include "SampleLibrary.h" -#include "ThemeController.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -Q_IMPORT_QML_PLUGIN(OmarchyNotesPlugin) - -using namespace onotes; -using namespace Qt::StringLiterals; - -namespace { - -const QByteArray kDarkTheme = R"(mode = "dark" -accent = "#dcd7ba" -selection = "#363646" -background = "#1f1f28" -dark_background = "#17171e" -foreground = "#dcd7ba" -dark_foreground = "#727169" -red = "#c34043" -yellow = "#c0a36e" -blue = "#7e9cd8" -)"; - -const QByteArray kLightTheme = R"(mode = "light" -accent = "#286983" -selection = "#dfdad9" -background = "#faf4ed" -dark_background = "#f2e9e1" -foreground = "#575279" -dark_foreground = "#797593" -red = "#b4637a" -yellow = "#ea9d34" -blue = "#286983" -)"; - -void writeFile(const QString &path, const QByteArray &data) -{ - QFile f(path); - QVERIFY(f.open(QIODevice::WriteOnly | QIODevice::Truncate)); - f.write(data); -} - -RichDocument paragraphs(const QStringList &lines) -{ - RichDocument doc; - for (const QString &line : lines) - doc.blocks << Block::paragraph({Span::plain(line)}); - doc.assignMissingIds(); - return doc; -} - -} // namespace - -class TestEditor : public QObject -{ - Q_OBJECT - - QTemporaryDir m_dataDir; - QTemporaryDir m_themeDir; - std::unique_ptr m_service; - std::unique_ptr m_theme; - std::unique_ptr m_library; - std::unique_ptr m_app; - std::unique_ptr m_engine; - QString m_mixedId; - QQuickWindow *m_window = nullptr; - QQuickItem *m_text = nullptr; - QQuickItem *m_pane = nullptr; - EditorController *m_editor = nullptr; - - QTextDocument *doc() const { return m_editor->textDocument(); } - RichDocument current() const { return DocumentConverter::read(doc()); } - - RichDocument persisted() - { - m_service->waitForIdle(); - return m_service->loadNote(m_editor->noteId())->body; - } - - QString open(const RichDocument &body) - { - const auto note = m_service->createNote(body); - m_library->refresh(); - m_editor->openNote(note->id); - m_text->forceActiveFocus(); - return note->id; - } - - void type(const QString &text) - { - for (const QChar c : text) - QTest::keyClick(m_window, c.toLatin1()); - } - - void setCursor(int position) - { - m_text->setProperty("cursorPosition", position); - } - - void select(int start, int end) - { - QMetaObject::invokeMethod(m_text, "select", Q_ARG(int, start), Q_ARG(int, end)); - } - - int endOfBlock(int blockNumber) const - { - const QTextBlock b = doc()->findBlockByNumber(blockNumber); - return b.position() + b.length() - 1; - } - - QRectF positionToRectangle(int position) - { - QRectF r; - QMetaObject::invokeMethod(m_text, "positionToRectangle", Q_RETURN_ARG(QRectF, r), Q_ARG(int, position)); - return r; - } - - void resetView() - { - m_library->setSearchText({}); - m_library->showKey(u"all"_s); - } - - void call(const char *function, const QVariant &arg = {}) - { - if (arg.isValid()) - QMetaObject::invokeMethod(m_window, function, Q_ARG(QVariant, arg)); - else - QMetaObject::invokeMethod(m_window, function); - } - - QQuickItem *item(const char *name) const - { - return m_window->findChild(QString::fromLatin1(name)); - } - - void screenshot(const QString &name) - { - QDir().mkpath(QStringLiteral(SCREENSHOT_DIR)); - QTest::qWait(50); - const QImage image = m_window->grabWindow(); - QVERIFY(!image.isNull()); - image.save(QStringLiteral(SCREENSHOT_DIR) + u'/' + name + u".png"_s); - } - -private slots: - void initTestCase() - { - writeFile(m_themeDir.filePath(u"colors.toml"_s), kDarkTheme); - qputenv("OMARCHY_NOTES_THEME_DIR", m_themeDir.path().toLocal8Bit()); - QQuickStyle::setStyle(u"Basic"_s); - - m_service = std::make_unique(LibraryPaths::at(m_dataDir.path())); - QString error; - QVERIFY2(m_service->start(&error), qPrintable(error)); - m_mixedId = SampleLibrary::seed(*m_service, &error); - QVERIFY2(!m_mixedId.isEmpty(), qPrintable(error)); - - m_theme = std::make_unique(nullptr); - ThemeController::setInstance(m_theme.get()); - m_library = std::make_unique(m_service.get(), m_dataDir.filePath(u"settings.ini"_s)); - AppLibrary::setInstance(m_library.get()); - m_app = std::make_unique(nullptr); - AppController::setInstance(m_app.get()); - - m_engine = std::make_unique(); - m_engine->addImageProvider(u"blob"_s, new BlobImageProvider(m_service.get())); - m_engine->setInitialProperties({{u"initialNoteId"_s, m_mixedId}}); - m_engine->loadFromModule("OmarchyNotes", "Main"); - QVERIFY(!m_engine->rootObjects().isEmpty()); - m_window = qobject_cast(m_engine->rootObjects().first()); - QVERIFY(m_window); - m_window->resize(1200, 1300); - QVERIFY(QTest::qWaitForWindowExposed(m_window)); - // The Quick Note window has its own editor; use the main window's. - m_pane = m_window->findChild(u"editorPane"_s); - QVERIFY(m_pane); - m_text = m_pane->findChild(u"noteText"_s); - m_editor = m_pane->findChild(u"noteEditor"_s); - QVERIFY(m_text && m_pane && m_editor); - QCOMPARE(m_editor->noteId(), m_mixedId); - } - - void cleanupTestCase() - { - m_engine.reset(); - m_library.reset(); - m_theme.reset(); - m_service.reset(); - } - - void rendersMixedNote() - { - QCOMPARE(m_theme->source(), m_themeDir.filePath(u"colors.toml"_s)); - const RichDocument body = current(); - QCOMPARE(body.title(), u"Q3 planning — product sync"_s); - const QString image = DocumentConverter::imageResourceName(body.referencedBlobs().value(0)); - const QString chip = DocumentConverter::attachmentResourceName(body.referencedAttachments().value(0)); - QVERIFY(!doc()->resource(QTextDocument::ImageResource, QUrl(image)).isNull()); - QVERIFY(!doc()->resource(QTextDocument::ImageResource, QUrl(chip)).isNull()); - // Loading must not mark the note edited. - QCOMPARE(m_editor->saveState(), EditorController::Saved); - screenshot(u"mixed-note-dark-end"_s); - setCursor(0); - screenshot(u"mixed-note-dark"_s); - } - - void typingAutosaves() - { - open(paragraphs({u"Hello"_s})); - setCursor(5); - type(u" world"_s); - QCOMPARE(current().plainText(), u"Hello world"_s); - QVERIFY(m_editor->saveState() != EditorController::Saved); - QTRY_COMPARE_WITH_TIMEOUT(m_editor->saveState(), EditorController::Saved, 3000); - QCOMPARE(persisted().plainText(), u"Hello world"_s); - } - - void continuousTypingIsSavedWithinCap() - { - const QString id = open(paragraphs({u"Log"_s})); - setCursor(3); - const qint64 startRevision = m_service->loadNote(id)->revision; - QElapsedTimer timer; - timer.start(); - qint64 firstSaveMs = -1; - while (timer.elapsed() < 4500) { - QTest::keyClick(m_window, Qt::Key_A); - QTest::qWait(120); - if (firstSaveMs < 0 && m_service->loadNote(id)->revision > startRevision) - firstSaveMs = timer.elapsed(); - } - qInfo("first save while typing continuously: %lld ms (cap %d ms)", firstSaveMs, - EditorController::MaxUnsavedMs); - QVERIFY(firstSaveMs > 0); - QVERIFY(firstSaveMs <= EditorController::MaxUnsavedMs + 500); - } - - void typingFormatAtInsertionPoint() - { - open(paragraphs({u"Plain "_s})); - setCursor(6); - QMetaObject::invokeMethod(m_pane, "toggleMark", Q_ARG(QVariant, int(EditorController::Bold))); - QVERIFY(m_editor->bold()); // toolbar reflects the pending format - type(u"bold"_s); - const RichDocument body = current(); - const QList spans = body.blocks.first().spans; - QCOMPARE(spans.size(), 2); - QCOMPARE(spans.last().text, u"bold"_s); - QCOMPARE(spans.last().marks, quint32(Bold)); - // One undo removes the typed text together with its formatting. - QTest::keyClick(m_window, Qt::Key_Z, Qt::ControlModifier); - QCOMPARE(current().plainText(), u"Plain "_s); - } - - void formattingSelectionAndUndo() - { - open(paragraphs({u"alpha beta"_s})); - select(6, 10); - QVERIFY(m_editor->toggleMark(EditorController::Bold)); - QCOMPARE(current().blocks.first().spans.last().marks, quint32(Bold)); - QTest::keyClick(m_window, Qt::Key_Z, Qt::ControlModifier); - QCOMPARE(current().blocks.first().spans.size(), 1); - QTest::keyClick(m_window, Qt::Key_Z, Qt::ControlModifier | Qt::ShiftModifier); - QCOMPARE(current().blocks.first().spans.last().marks, quint32(Bold)); - - setCursor(10); - type(u" gamma"_s); - QTest::keyClick(m_window, Qt::Key_Z, Qt::ControlModifier); - QVERIFY(!current().plainText().contains(u"gamma"_s)); - } - - void headingThenReturnGivesBody() - { - open(paragraphs({u"Meeting"_s})); - setCursor(0); - m_editor->setBlockStyle(1); - QCOMPARE(current().blocks.first().type, Block::Type::Heading); - setCursor(7); - QTest::keyClick(m_window, Qt::Key_Return); - type(u"notes"_s); - const RichDocument body = current(); - QCOMPARE(body.blocks.size(), 2); - QCOMPARE(body.blocks[1].type, Block::Type::Paragraph); - QCOMPARE(body.blocks[1].plainText(), u"notes"_s); - } - - void checklistKeyboardFlow() - { - RichDocument start; - start.blocks << Block::listItem(ListKind::Check, 0, {Span::plain(u"Buy milk"_s)}, true); - start.assignMissingIds(); - open(start); - setCursor(endOfBlock(0)); - - QTest::keyClick(m_window, Qt::Key_Return); - type(u"Eggs"_s); - RichDocument body = current(); - QCOMPARE(body.blocks.size(), 2); - QCOMPARE(body.blocks[1].list, ListKind::Check); - QVERIFY(!body.blocks[1].checked); // new items start unchecked - - QTest::keyClick(m_window, Qt::Key_Tab); - QCOMPARE(current().blocks[1].indent, 1); - QTest::keyClick(m_window, Qt::Key_Backtab); - QCOMPARE(current().blocks[1].indent, 0); - - // Return on an empty item leaves the list. - QTest::keyClick(m_window, Qt::Key_Return); - QTest::keyClick(m_window, Qt::Key_Return); - type(u"After"_s); - body = current(); - QCOMPARE(body.blocks.last().type, Block::Type::Paragraph); - QCOMPARE(body.blocks.last().plainText(), u"After"_s); - } - - void checkboxClickToggles() - { - RichDocument start; - start.blocks << Block::heading(1, {Span::plain(u"Groceries"_s)}); - start.blocks << Block::listItem(ListKind::Check, 0, {Span::plain(u"Coffee"_s)}); - start.assignMissingIds(); - open(start); - QTest::qWait(50); - screenshot(u"checklist"_s); - const int itemStart = doc()->findBlockByNumber(1).position(); - const QRectF r = positionToRectangle(itemStart); - // The round checkbox drawn over the text engine's glyph. - const QPointF marker = m_text->mapToScene(QPointF(r.x() - 11, r.center().y())); - QTest::mouseClick(m_window, Qt::LeftButton, Qt::NoModifier, marker.toPoint()); - QTRY_VERIFY(current().blocks[1].checked); - QTest::qWait(400); // keep the next click from being a double-click - QTest::mouseClick(m_window, Qt::LeftButton, Qt::NoModifier, marker.toPoint()); - QTRY_VERIFY(!current().blocks[1].checked); - // Keyboard path. - setCursor(itemStart + 2); - QTest::keyClick(m_window, Qt::Key_U, Qt::ControlModifier | Qt::ShiftModifier); - QVERIFY(current().blocks[1].checked); - QTest::keyClick(m_window, Qt::Key_Z, Qt::ControlModifier); - QVERIFY(!current().blocks[1].checked); - // Clicking the text itself must not toggle. - const bool before = current().blocks[1].checked; - QTest::qWait(400); - const QPointF onText = m_text->mapToScene(QPointF(r.x() + 20, r.center().y())); - QTest::mouseClick(m_window, Qt::LeftButton, Qt::NoModifier, onText.toPoint()); - QCOMPARE(current().blocks[1].checked, before); - } - - void clipboardRoundTripKeepsStructure() - { - const auto mixed = m_service->loadNote(m_mixedId); - open(mixed->body); - // Select from "Action items" through the table. - int from = -1; - int to = -1; - for (QTextBlock b = doc()->begin(); b.isValid(); b = b.next()) { - if (b.text() == u"Action items") - from = b.position(); - if (b.text() == u"10 Oct") - to = b.position() + b.length(); - } - QVERIFY(from >= 0 && to > from); - select(from, to + 1); - m_editor->copy(); - QVERIFY(QGuiApplication::clipboard()->mimeData()->hasFormat(u"application/x-omarchy-notes-fragment+json"_s)); - setCursor(doc()->characterCount() - 1); - QTest::keyClick(m_window, Qt::Key_Return); - QTest::keyClick(m_window, Qt::Key_V, Qt::ControlModifier); - - const RichDocument body = current(); - int tables = 0; - int checks = 0; - QSet ids; - for (const Block &b : body.blocks) { - tables += b.type == Block::Type::Table; - checks += b.list == ListKind::Check; - QVERIFY2(!ids.contains(b.id), "duplicate block id after paste"); - ids.insert(b.id); - } - QCOMPARE(tables, 2); - QCOMPARE(checks, 10); - QVERIFY(m_editor->flush()); - QCOMPARE(persisted(), current()); - } - - void htmlPasteIsNormalized() - { - open(paragraphs({u""_s})); - auto *mime = new QMimeData; - mime->setHtml(u"

From the web

" - "
  • first
  • second
" - "

see this

"_s); - QGuiApplication::clipboard()->setMimeData(mime); - QSignalSpy notices(m_editor, &EditorController::notice); - QTest::keyClick(m_window, Qt::Key_V, Qt::ControlModifier); - const RichDocument body = current(); - QCOMPARE(body.blocks[0].type, Block::Type::Heading); - QCOMPARE(body.blocks[1].list, ListKind::Bullet); - QCOMPARE(body.blocks[2].spans.first().marks, quint32(Bold)); - QCOMPARE(body.blocks[3].spans.last().href, u"https://example.com"_s); - QCOMPARE(notices.size(), 1); // the web image was reported, not silently dropped - } - - void inputMethodComposition() - { - open(paragraphs({u"Tokyo: "_s})); - setCursor(7); - QInputMethodEvent preedit(u"とうきょう"_s, {}); - QCoreApplication::sendEvent(m_text, &preedit); - QCOMPARE(current().plainText(), u"Tokyo: "_s); // preedit is not content - QInputMethodEvent commit; - commit.setCommitString(u"東京"_s); - QCoreApplication::sendEvent(m_text, &commit); - QCOMPARE(current().plainText(), u"Tokyo: 東京"_s); - QVERIFY(m_editor->flush()); - QCOMPARE(persisted().plainText(), u"Tokyo: 東京"_s); - } - - void failedSaveKeepsDraftAndRecovers() - { - open(paragraphs({u"Draft"_s})); - setCursor(5); - m_library->setSimulateSaveFailure(true); - type(u" v2"_s); - QTRY_COMPARE_WITH_TIMEOUT(m_editor->saveState(), EditorController::Failed, 3000); - QVERIFY(!m_editor->saveError().isEmpty()); - QCOMPARE(current().plainText(), u"Draft v2"_s); // draft kept in the editor - QVERIFY(!m_editor->flush()); - screenshot(u"save-failed"_s); - - m_library->setSimulateSaveFailure(false); - m_editor->retrySave(); - QTRY_COMPARE_WITH_TIMEOUT(m_editor->saveState(), EditorController::Saved, 3000); - QCOMPARE(persisted().plainText(), u"Draft v2"_s); - } - - void followsThemeSwitch() - { - m_editor->openNote(m_mixedId); - const RichDocument before = current(); - QSignalSpy changed(m_theme.get(), &ThemeController::changed); - writeFile(m_themeDir.filePath(u"colors.toml"_s), kLightTheme); - QTRY_VERIFY_WITH_TIMEOUT(changed.size() > 0, 3000); - QVERIFY(!m_theme->dark()); - QCOMPARE(current(), before); // content untouched by the restyle - QCOMPARE(m_editor->saveState(), EditorController::Saved); - QCOMPARE(m_text->property("color").value(), m_theme->text()); - screenshot(u"mixed-note-light"_s); - } - - void accessibleEditor() - { - QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(m_text); - QVERIFY(iface); - QCOMPARE(iface->role(), QAccessible::EditableText); - QVERIFY(iface->textInterface()); - const QString text = iface->textInterface()->text(0, iface->textInterface()->characterCount()); - QVERIFY(text.contains(u"Q3 planning"_s)); - // Report what assistive tech sees for embedded objects. - qInfo("accessible text has %lld object placeholder(s)", qint64(text.count(QChar(0xFFFC)))); - } - - void narrowTile() - { - m_window->resize(520, 900); - QTest::qWait(100); - QQuickItem *list = m_window->findChild(u"noteList"_s); - QVERIFY(list); - QVERIFY(!list->isVisible()); - QVERIFY(m_pane->isVisible()); - screenshot(u"narrow-tile"_s); - m_window->resize(1200, 1300); - } - - void foldersAndNewNotes() - { - resetView(); - const QVariantMap made = m_library->createFolder(u"Work"_s, {}); - QVERIFY2(made.value(u"ok"_s).toBool(), qPrintable(made.value(u"error"_s).toString())); - const QString folder = made.value(u"id"_s).toString(); - QVERIFY(!m_library->createFolder(u"work"_s, {}).value(u"ok"_s).toBool()); - - call("showView", folder); - QCOMPARE(m_library->currentKey(), folder); - QCOMPARE(m_library->viewTitle(), u"Work"_s); - QCOMPARE(m_library->notes()->count(), 0); - QVERIFY(!m_editor->hasNote()); // an empty folder opens nothing - screenshot(u"empty-folder"_s); - - call("newNote"); - QVERIFY(m_editor->hasNote()); - QCOMPARE(m_service->loadNote(m_editor->noteId())->folderId, folder); - type(u"Standup"_s); - QVERIFY(m_editor->flush()); - QCOMPARE(m_library->notes()->titleOf(m_editor->noteId()), u"Standup"_s); - - QVERIFY(m_library->moveNote(m_editor->noteId(), {})); - QCOMPARE(m_library->notes()->count(), 0); - QCOMPARE(m_service->loadNote(m_editor->noteId())->folderId, QString()); - } - - void deleteAndRecoverFromTheList() - { - resetView(); - const QString older = open(paragraphs({u"Alpha note"_s})); - const QString newer = open(paragraphs({u"Beta note"_s})); - QCOMPARE(m_library->notes()->idAt(0), newer); - - item("noteListView")->forceActiveFocus(); - QTest::keyClick(m_window, Qt::Key_Delete); - QVERIFY(m_service->loadNote(newer)->deletedAt > 0); - QCOMPARE(m_editor->noteId(), older); // the neighbour opens - QCOMPARE(m_library->notes()->indexOf(newer), -1); - - call("showView", u"trash"_s); - QVERIFY(m_library->inTrash()); - call("openNote", newer); - QVERIFY(m_editor->readOnly()); - QVERIFY(m_text->property("readOnly").toBool()); - setCursor(4); - type(u"xyz"_s); - QCOMPARE(current().plainText(), u"Beta note"_s); // read-only - screenshot(u"recently-deleted"_s); - - call("recoverNote", newer); - QCOMPARE(m_service->loadNote(newer)->deletedAt, 0); - QCOMPARE(m_library->notes()->indexOf(newer), -1); // left the trash list - } - - void deletePermanentlyAsksFirst() - { - resetView(); - const QString doomed = open(paragraphs({u"Scratch"_s})); - QVERIFY(m_library->trashNote(doomed)); - call("showView", u"trash"_s); - call("deleteForever", doomed); - QQuickItem *dialog = item("confirmDialog"); - Q_UNUSED(dialog); - QObject *confirm = m_window->findChild(u"confirmDialog"_s); - QTRY_VERIFY(confirm->property("opened").toBool()); - QVERIFY(m_service->loadNote(doomed)); // nothing happens until confirmed - QTest::keyClick(m_window, Qt::Key_Return); - QTRY_VERIFY(!m_service->loadNote(doomed)); - } - - void searchFromTheSearchField() - { - resetView(); - const QString target = open(paragraphs({u"Quarterly benchmark review"_s, u"Numbers look good."_s})); - QVERIFY(m_editor->flush()); - item("searchField")->forceActiveFocus(); - type(u"quarterl bench"_s); - QVERIFY(m_library->searching()); - QCOMPARE(m_library->viewTitle(), u"Search"_s); - // Results arrive asynchronously, with the matching words in bold. - auto snippetOfTarget = [&] { - const int row = m_library->notes()->indexOf(target); - return row < 0 ? QString() : m_library->notes()->index(row).data(NotesModel::SnippetRole).toString(); - }; - QTRY_VERIFY(snippetOfTarget().contains(u""_s)); - screenshot(u"search"_s); - - QTest::keyClick(m_window, Qt::Key_Return); // opens the best match - QCOMPARE(m_editor->noteId(), m_library->notes()->idAt(0)); - item("searchField")->forceActiveFocus(); - QTest::keyClick(m_window, Qt::Key_Escape); - QVERIFY(!m_library->searching()); - QCOMPARE(m_library->viewTitle(), u"All Notes"_s); - } - - void pinningPutsANoteFirst() - { - resetView(); - open(paragraphs({u"Recent"_s})); - const QString oldest = m_library->notes()->idAt(m_library->notes()->count() - 1); - m_editor->openNote(oldest); - m_editor->setPinned(true); - QVERIFY(m_editor->pinned()); - QCOMPARE(m_library->notes()->idAt(0), oldest); - QVERIFY(m_library->notes()->hasPinned()); - screenshot(u"pinned"_s); - m_editor->setPinned(false); - QVERIFY(!m_library->notes()->hasPinned()); - } - - void deletingAFolderMovesItsNotesToTheTrash() - { - resetView(); - const QString folder = m_library->createFolder(u"Temporary"_s, {}).value(u"id"_s).toString(); - call("showView", folder); - call("newNote"); - const QString inside = m_editor->noteId(); - type(u"Inside"_s); - QVERIFY(m_editor->flush()); - QVERIFY(m_library->deleteFolder(folder)); - QCOMPARE(m_library->currentKey(), u"all"_s); // the view moved off the gone folder - QVERIFY(m_service->loadNote(inside)->deletedAt > 0); - QVERIFY(m_editor->noteId() != inside || m_editor->readOnly()); - } - - void tagsAreHighlightedAndListed() - { - resetView(); - open(paragraphs({u"Planning"_s})); - setCursor(8); - type(u" #roadmap"_s); - QVERIFY(m_editor->flush()); - QTRY_VERIFY(m_library->folders()->indexOfKey(u"tag:roadmap"_s) >= 0); // after typing pauses - QTRY_VERIFY(!doc()->findBlockByNumber(0).layout()->formats().isEmpty()); // coloured - - // Reopening a tagged note must not count the colouring as an edit. - const QString id = m_editor->noteId(); - open(paragraphs({u"Elsewhere"_s})); - m_editor->openNote(id); - QTest::qWait(50); - QCOMPARE(m_editor->saveState(), EditorController::Saved); - - call("showView", u"tag:roadmap"_s); - QCOMPARE(m_library->viewTitle(), u"#roadmap"_s); - QCOMPARE(m_library->notes()->count(), 1); - call("newNote"); // a note started from a tag carries it - QVERIFY(m_editor->flush()); - QVERIFY(m_service->loadNote(m_editor->noteId())->body.tags().contains(u"roadmap"_s)); - screenshot(u"tags"_s); - } - - void findInNote() - { - resetView(); - open(paragraphs({u"alpha beta ALPHA gamma alpha"_s})); - setCursor(0); - m_editor->setFindText(u"alpha"_s); - QCOMPARE(m_editor->findCount(), 3); - QCOMPARE(m_editor->findIndex(), 1); - QCOMPARE(m_text->property("selectedText").toString(), u"alpha"_s); - m_editor->findNext(); - QCOMPARE(m_editor->findIndex(), 2); - QCOMPARE(m_text->property("selectionStart").toInt(), 11); - m_editor->findPrevious(); - m_editor->findPrevious(); - QCOMPARE(m_editor->findIndex(), 3); // wraps around - QCOMPARE(m_editor->saveState(), EditorController::Saved); // finding isn't editing - - setCursor(doc()->characterCount() - 1); - type(u" alpha"_s); - QTRY_COMPARE(m_editor->findCount(), 4); // follows edits - m_editor->setFindText({}); - QCOMPARE(m_editor->findCount(), 0); - QVERIFY(m_editor->flush()); - } - - void smartFolderShowsMatchingNotes() - { - resetView(); - RichDocument trip; - trip.blocks = {Block::heading(1, {Span::plain(u"Trip"_s)}), - Block::listItem(ListKind::Check, 0, {Span::plain(u"Passport #travel"_s)})}; - trip.assignMissingIds(); - const QString tripId = open(trip); - open(paragraphs({u"Hotel ideas #travel"_s})); - QVariantMap criteria{{u"tags"_s, QStringList{u"travel"_s}}, {u"hasChecklist"_s, true}}; - const QVariantMap made = m_library->createSmartFolder(u"Travel checklists"_s, criteria); - QVERIFY2(made.value(u"ok"_s).toBool(), qPrintable(made.value(u"error"_s).toString())); - call("showView", made.value(u"id"_s)); - QCOMPARE(m_library->viewTitle(), u"Travel checklists"_s); - QCOMPARE(m_library->notes()->count(), 1); - QCOMPARE(m_library->notes()->idAt(0), tripId); - QVERIFY(!m_library->createSmartFolder(u"Empty"_s, {}).value(u"ok"_s).toBool()); - screenshot(u"smart-folder"_s); - } - - void galleryView() - { - resetView(); - m_library->setGalleryMode(true); - QQuickItem *grid = item("noteGrid"); - QTRY_VERIFY(grid->isVisible()); - QVERIFY(!m_pane->isVisible()); // the gallery takes the editor's space - QTest::qWait(300); // let thumbnails decode - screenshot(u"gallery"_s); - - call("openNote", m_mixedId); - QVERIFY(m_pane->isVisible()); - QVERIFY(!grid->isVisible()); - m_library->setGalleryMode(false); - QVERIFY(m_pane->isVisible()); - QVERIFY(item("noteListView")->isVisible()); - } - - void attachmentBrowser() - { - resetView(); - call("showView", u"attachments"_s); - QVERIFY(m_library->inAttachments()); - QTRY_VERIFY(item("attachmentsView")->isVisible()); - QVERIFY(m_library->attachments()->count() >= 2); - m_library->attachments()->setFilter(AttachmentsModel::Files); - const int files = m_library->attachments()->count(); - m_library->attachments()->setFilter(AttachmentsModel::Images); - QVERIFY(files >= 1 && m_library->attachments()->count() >= 1); - m_library->attachments()->setFilter(AttachmentsModel::All); - QTest::qWait(300); - screenshot(u"attachments"_s); - - const QString noteId = m_library->attachments()->index(0).data(AttachmentsModel::NoteIdRole).toString(); - call("openNote", noteId); - QCOMPARE(m_editor->noteId(), noteId); - QVERIFY(m_pane->isVisible()); - resetView(); - } - - void importAndExportFromTheApp() - { - resetView(); - QTemporaryDir files; - QFile md(files.filePath(u"From Obsidian.md"_s)); - QVERIFY(md.open(QIODevice::WriteOnly)); - md.write("# From Obsidian\n\n- [ ] Try the importer #imported\n"); - md.close(); - const QVariantMap imported = m_library->importFiles({QUrl::fromLocalFile(md.fileName())}); - QCOMPARE(imported.value(u"count"_s).toInt(), 1); - const QString id = imported.value(u"first"_s).toString(); - QVERIFY(m_library->notes()->indexOf(id) >= 0); - QCOMPARE(m_library->exportFileName(id, u"pdf"_s), u"From Obsidian.pdf"_s); - const QVariantMap exported = m_library->exportNote(id, u"md"_s, QUrl::fromLocalFile(files.filePath(u"out.md"_s))); - QVERIFY2(exported.value(u"ok"_s).toBool(), qPrintable(exported.value(u"error"_s).toString())); - QFile out(files.filePath(u"out.md"_s)); - QVERIFY(out.open(QIODevice::ReadOnly)); - QVERIFY(out.readAll().contains("- [ ] Try the importer #imported")); - } - - void quickNote() - { - resetView(); - QQuickWindow *quick = m_window->findChild(u"quickNote"_s); - QVERIFY(quick); - const int before = m_service->noteCount(); - // QML must talk to the same controller the process uses. - QCOMPARE(m_engine->singletonInstance("OmarchyNotes", "App"), m_app.get()); - QCOMPARE(m_engine->singletonInstance("OmarchyNotes", "Theme"), m_theme.get()); - m_app->handle({{u"action"_s, u"quick-note"_s}}); - QTRY_VERIFY(quick->isVisible()); - QVERIFY(QTest::qWaitForWindowExposed(quick)); - auto *pane = quick->findChild(u"quickNotePane"_s); - auto *quickEditor = pane->findChild(u"noteEditor"_s); - QVERIFY(quickEditor->hasNote()); - QCOMPARE(m_service->noteCount(), before + 1); - QDir().mkpath(QStringLiteral(SCREENSHOT_DIR)); - quick->grabWindow().save(QStringLiteral(SCREENSHOT_DIR) + u"/quick-note.png"_s); - - // Closing an untouched Quick Note leaves nothing behind. - quick->close(); - QTRY_VERIFY(!quick->isVisible()); - QCOMPARE(m_service->noteCount(), before); - - // One that was written in is kept, in Notes. - m_app->handle({{u"action"_s, u"quick-note"_s}}); - QTRY_VERIFY(quick->isVisible()); - auto *quickText = pane->findChild(u"noteText"_s); - quickText->forceActiveFocus(); - QTest::keyClick(quick, 'h'); - QTest::keyClick(quick, 'i'); - const QString id = quickEditor->noteId(); - quick->close(); - QTRY_VERIFY(!quick->isVisible()); - QCOMPARE(m_service->loadNote(id)->body.plainText(), u"hi"_s); - QCOMPARE(m_service->loadNote(id)->folderId, QString()); - } - - void captureFromAnotherLaunch() - { - resetView(); - const int before = m_service->noteCount(); - m_app->handle({{u"action"_s, u"capture"_s}, {u"text"_s, u"Call the plumber\nTuesday"_s}}); - QCOMPARE(m_service->noteCount(), before + 1); - QCOMPARE(m_library->notes()->titleOf(m_library->notes()->idAt(0)), u"Call the plumber"_s); - } - - void checklistAndObjectsAreAccessible() - { - resetView(); - m_editor->openNote(m_mixedId); - QTRY_VERIFY(m_editor->overlays().size() >= 7); - int checks = 0, images = 0, files = 0; - for (const QVariant &v : m_editor->overlays()) { - const QVariantMap o = v.toMap(); - checks += o.value(u"kind"_s).toString() == u"check"; - images += o.value(u"kind"_s).toString() == u"image"; - files += o.value(u"kind"_s).toString() == u"attachment"; - } - QCOMPARE(checks, 5); - QCOMPARE(images, 1); - QCOMPARE(files, 1); - - // Screen readers see named checkboxes, images and attachments. - QStringList names; - std::function walk = [&](QAccessibleInterface *iface) { - if (!iface) - return; - if (iface->role() == QAccessible::CheckBox || iface->role() == QAccessible::Graphic - || iface->role() == QAccessible::Button) - names << iface->text(QAccessible::Name); - for (int i = 0; i < iface->childCount(); ++i) - walk(iface->child(i)); - }; - walk(QAccessible::queryAccessibleInterface(m_text)); - QVERIFY2(names.contains(u"Draft the migration guide"_s), qPrintable(names.join(u", "_s))); - QVERIFY(names.contains(u"Attachment: Q3 roadmap draft.pdf"_s)); - QVERIFY(names.contains(u"Image: Bar chart of search latency by week"_s)); - - // The overlay reflects edits made any other way. - const int firstCheck = m_editor->overlays().first().toMap().value(u"position"_s).toInt(); - const bool before = m_editor->overlays().first().toMap().value(u"checked"_s).toBool(); - m_editor->toggleCheckAt(firstCheck); - QTRY_COMPARE(m_editor->overlays().first().toMap().value(u"checked"_s).toBool(), !before); - m_editor->toggleCheckAt(firstCheck); - QVERIFY(m_editor->flush()); - m_text->setProperty("cursorPosition", firstCheck); - screenshot(u"checklist-round"_s); - } - - void largeNoteResponsiveness() - { - RichDocument big; - for (int i = 0; i < 3000; ++i) { - big.blocks << Block::paragraph({Span::plain(u"Paragraph %1 of a long research note with "_s.arg(i)), - Span::plain(u"some emphasis"_s, Italic), - Span::plain(u" and enough text to wrap across the column."_s)}); - if (i % 150 == 0) { - Block t; - t.type = Block::Type::Table; - t.rows = 3; - t.columns = 3; - for (int r = 0; r < 3; ++r) - for (int c = 0; c < 3; ++c) - t.cells << TableCell{r, c, 1, 1, {Block::paragraph({Span::plain(u"cell"_s)})}}; - big.blocks << t; - } - } - big.assignMissingIds(); - const auto note = m_service->createNote(big); - m_library->refresh(); - - QElapsedTimer timer; - timer.start(); - m_editor->openNote(note->id); - QTest::qWait(0); - const qint64 openMs = timer.elapsed(); - - setCursor(doc()->findBlockByNumber(1500).position()); - qint64 worstKeyMs = 0; - for (int i = 0; i < 20; ++i) { - timer.restart(); - QTest::keyClick(m_window, Qt::Key_X); - QCoreApplication::processEvents(); - worstKeyMs = std::max(worstKeyMs, timer.elapsed()); - } - timer.restart(); - const RichDocument body = DocumentConverter::read(doc()); - const qint64 readMs = timer.elapsed(); - qInfo("large note (%lld blocks): open %lld ms, worst keystroke %lld ms, snapshot for save %lld ms", - qint64(body.blocks.size()), openMs, worstKeyMs, readMs); - QVERIFY(m_editor->flush()); - } - // Last: replaces the whole library. - void backupAndRestoreReopenTheLibrary() - { - resetView(); - QTemporaryDir backups; - const QString kept = open(paragraphs({u"Before the backup"_s})); - QVERIFY(m_editor->flush()); - const int notesBefore = m_service->noteCount(); - const QVariantMap backup = m_library->backupTo(QUrl::fromLocalFile(backups.path()), u"nightly"_s); - QVERIFY2(backup.value(u"ok"_s).toBool(), qPrintable(backup.value(u"error"_s).toString())); - - const QString later = open(paragraphs({u"After the backup"_s})); - QVERIFY(m_editor->flush()); - const QUrl source = QUrl::fromLocalFile(backups.filePath(u"nightly"_s)); - QVERIFY(m_library->inspectBackup(source).value(u"ok"_s).toBool()); - - m_editor->closeNote(); - const QVariantMap restored = m_library->restoreFrom(source); - QVERIFY2(restored.value(u"ok"_s).toBool(), qPrintable(restored.value(u"error"_s).toString())); - QCOMPARE(m_service->noteCount(), notesBefore); - QVERIFY(!m_service->loadNote(later)); - QTRY_VERIFY(m_editor->hasNote()); // the window reopened a note - - // The restored library is fully usable. - m_editor->openNote(kept); - m_text->forceActiveFocus(); - setCursor(doc()->characterCount() - 1); - type(u"!"_s); - QVERIFY(m_editor->flush()); - QCOMPARE(persisted().plainText(), u"Before the backup!"_s); - QDir(restored.value(u"previous"_s).toString()).removeRecursively(); - } -}; - -QTEST_MAIN(TestEditor) -#include "tst_editor.moc" diff --git a/tests/tst_exchange.cpp b/tests/tst_exchange.cpp deleted file mode 100644 index 8911916..0000000 --- a/tests/tst_exchange.cpp +++ /dev/null @@ -1,235 +0,0 @@ -#include "LibraryService.h" -#include "NoteExchange.h" -#include "SampleLibrary.h" - -#include -#include -#include -#include -#include -#include -#include - -using namespace onotes; -using namespace Qt::StringLiterals; - -namespace { - -void write(const QString &path, const QByteArray &data) -{ - QFile f(path); - QVERIFY(f.open(QIODevice::WriteOnly)); - f.write(data); -} - -QString read(const QString &path) -{ - QFile f(path); - return f.open(QIODevice::ReadOnly) ? QString::fromUtf8(f.readAll()) : QString(); -} - -int countBlocks(const QList &blocks, Block::Type type) -{ - int n = 0; - for (const Block &b : blocks) { - n += b.type == type; - for (const TableCell &c : b.cells) - n += countBlocks(c.blocks, type); - } - return n; -} - -} // namespace - -class TestExchange : public QObject -{ - Q_OBJECT - - QTemporaryDir m_dir; - std::unique_ptr m_library; - QString m_mixed; - -private slots: - void initTestCase() - { - m_library = std::make_unique(LibraryPaths::at(m_dir.filePath(u"library"_s))); - QString error; - QVERIFY2(m_library->start(&error), qPrintable(error)); - m_mixed = SampleLibrary::seed(*m_library, &error); - QVERIFY(!m_mixed.isEmpty()); - } - - void importsMarkdown() - { - const QString dir = m_dir.filePath(u"import"_s); - QDir().mkpath(dir + u"/img"_s); - write(dir + u"/img/chart one.png"_s, SampleLibrary::chartPng()); - write(dir + u"/Trip plan.md"_s, R"(--- -tags: [travel] -created: 2026-01-01 ---- -# Lisbon trip - -Pack light, see the **tiles**. #travel - -- [x] Book flights -- [ ] Book hotel - - [ ] Near Alfama - -| Day | Plan | -|-----|------| -| Fri | Belém | - -![chart](img/chart%20one.png) -![remote](https://example.com/photo.jpg) -)"); - const ImportReport report = importFiles(*m_library, {dir + u"/Trip plan.md"_s}, {}); - QCOMPARE(report.createdIds.size(), 1); - QCOMPARE(report.warnings.size(), 1); // the web image, named - QVERIFY(report.warnings[0].contains(u"Trip plan.md"_s)); - - const RichDocument body = m_library->loadNote(report.createdIds[0])->body; - QCOMPARE(body.title(), u"Lisbon trip"_s); // front matter stripped - QCOMPARE(body.blocks[0].type, Block::Type::Heading); - QVERIFY(body.tags().contains(u"travel"_s)); - int checks = 0, checked = 0, nested = 0; - for (const Block &b : body.blocks) { - if (b.list == ListKind::Check) { - ++checks; - checked += b.checked; - nested += b.indent == 1; - } - } - QCOMPARE(checks, 3); - QCOMPARE(checked, 1); - QCOMPARE(nested, 1); - QCOMPARE(countBlocks(body.blocks, Block::Type::Table), 1); - QCOMPARE(body.referencedBlobs().size(), 1); // stored in the library - QVERIFY(QFile::exists(m_library->blobPath(body.referencedBlobs()[0]))); - QVERIFY(m_library->verify().isEmpty()); - } - - void importsPlainTextAndNamesUntitledFiles() - { - const QString path = m_dir.filePath(u"Shopping list.txt"_s); - write(path, "\n\nmilk\neggs\n"); - const ImportReport report = importFiles(*m_library, {path, m_dir.filePath(u"missing.md"_s)}, {}); - QCOMPARE(report.createdIds.size(), 1); - QCOMPARE(report.warnings.size(), 1); - QCOMPARE(m_library->loadNote(report.createdIds[0])->body.title(), u"Shopping list"_s); - } - - void exportsMarkdownWithFiles() - { - const QString out = m_dir.filePath(u"export/Q3 planning.md"_s); - QDir().mkpath(m_dir.filePath(u"export"_s)); - QString error; - QVERIFY2(exportNote(*m_library, m_mixed, ExportFormat::Markdown, out, &error), qPrintable(error)); - const QString md = read(out); - QVERIFY(md.contains(u"# Q3 planning"_s)); - QVERIFY(md.contains(u"- [x] Draft the migration guide"_s)); - QVERIFY(md.contains(u"|Owner|"_s)); - QVERIFY(md.contains(u"~~Probably not~~"_s)); - QVERIFY(!md.contains(u"_ and the Qt rich"_s)); // underline isn't turned into italics - QVERIFY(md.contains(u"](Q3%20planning%20files/image-1.png)"_s)); - QVERIFY(md.contains(u"(Q3%20planning%20files/Q3%20roadmap%20draft.pdf)"_s)); - QVERIFY(!md.contains(u"blob:"_s) && !md.contains(u"note://"_s)); - QVERIFY(QFile::exists(m_dir.filePath(u"export/Q3 planning files/image-1.png"_s))); - QVERIFY(QFile::exists(m_dir.filePath(u"export/Q3 planning files/Q3 roadmap draft.pdf"_s))); - - // And it comes back in with its structure. - const ImportReport again = importFiles(*m_library, {out}, {}); - QCOMPARE(again.createdIds.size(), 1); - const RichDocument body = m_library->loadNote(again.createdIds[0])->body; - QCOMPARE(countBlocks(body.blocks, Block::Type::Table), 1); - QCOMPARE(body.referencedBlobs().size(), 1); - } - - void exportsHtmlAsOneFile() - { - const QString out = m_dir.filePath(u"note.html"_s); - QString error; - QVERIFY2(exportNote(*m_library, m_mixed, ExportFormat::Html, out, &error), qPrintable(error)); - const QString html = read(out); - QVERIFY(html.contains(u"Q3 planning"_s)); - QVERIFY(html.contains(u"data:image/png;base64,"_s)); - QVERIFY(html.contains(u"<table"_s)); - QVERIFY(QFile::exists(m_dir.filePath(u"note files/Q3 roadmap draft.pdf"_s))); - } - - void exportsPdf() - { - const QString out = m_dir.filePath(u"note.pdf"_s); - QString error; - QVERIFY2(exportNote(*m_library, m_mixed, ExportFormat::Pdf, out, &error), qPrintable(error)); - QFile pdf(out); - QVERIFY(pdf.open(QIODevice::ReadOnly)); - QVERIFY(pdf.read(5) == "%PDF-"); - QVERIFY(pdf.size() > 5000); - if (qEnvironmentVariableIsSet("ONOTES_KEEP_EXPORTS")) - QFile::copy(out, qEnvironmentVariable("ONOTES_KEEP_EXPORTS") + u"/note.pdf"_s); - } - - void exportsTheWholeLibrary() - { - const auto folder = m_library->createFolder(u"Work/Clients"_s); // name with a slash - QVERIFY(folder); - RichDocument linking; - linking.blocks = {Block::paragraph({Span::plain(u"See "_s), - Span::plain(u"the plan"_s, 0, u"note://"_s + m_mixed)})}; - linking.assignMissingIds(); - QVERIFY(m_library->createNote(linking, nullptr, folder->id)); - - QString error; - const auto root = exportLibraryAsMarkdown(*m_library, m_dir.path(), &error); - QVERIFY2(root, qPrintable(error)); - QVERIFY(QFile::exists(*root + u"/Q3 planning — product sync.md"_s)); - QVERIFY(QFile::exists(*root + u"/Vendor research.md"_s)); - const QString linked = read(*root + u"/Work Clients/See the plan.md"_s); - // (The title is taken twice after the re-import test, so either file is right.) - static const QRegularExpression link(u"\\(\\.\\./Q3%20planning%20%E2%80%94%20product%20sync(%202)?\\.md\\)"_s); - QVERIFY2(link.match(linked).hasMatch(), qPrintable(linked)); - } - - void importsAFolderTree() - { - const QString root = m_dir.filePath(u"Apple Notes Export"_s); - QDir().mkpath(root + u"/Work/Clients"_s); - QDir().mkpath(root + u"/Work/_resources"_s); - QDir().mkpath(root + u"/Empty"_s); - write(root + u"/Groceries.md"_s, "# Groceries\n\n- [ ] Milk\n"); - write(root + u"/Work/Standup.md"_s, "# Standup\n\n![](_resources/chart.png)\n"); - write(root + u"/Work/_resources/chart.png"_s, SampleLibrary::chartPng()); - write(root + u"/Work/Clients/Acme.txt"_s, "Acme\nRenewal in March\n"); - - const ImportReport report = importFolder(*m_library, root, {}); - QCOMPARE(report.createdIds.size(), 3); - QVERIFY2(report.warnings.isEmpty(), qPrintable(report.warnings.join(u'\n'))); - QStringList names; - for (const FolderInfo &f : m_library->listFolders()) - names << f.name; - QVERIFY(names.contains(u"Apple Notes Export"_s)); - QVERIFY(names.contains(u"Work"_s)); - QVERIFY(names.contains(u"Clients"_s)); - QVERIFY(!names.contains(u"_resources"_s)); // assets only - QVERIFY(!names.contains(u"Empty"_s)); - - // Importing again makes a second, separate folder. - const ImportReport again = importFolder(*m_library, root, {}); - QCOMPARE(again.createdIds.size(), 3); - names.clear(); - for (const FolderInfo &f : m_library->listFolders()) - names << f.name; - QVERIFY(names.contains(u"Apple Notes Export 2"_s)); - } - - void fileNames() - { - QCOMPARE(fileNameForTitle(u"a/b: c?"_s), u"a b c"_s); - QCOMPARE(fileNameForTitle(u"..hidden"_s), u"hidden"_s); - QCOMPARE(fileNameForTitle(u" "_s), u"Untitled note"_s); - } -}; - -QTEST_MAIN(TestExchange) -#include "tst_exchange.moc" diff --git a/tests/tst_launch.cpp b/tests/tst_launch.cpp deleted file mode 100644 index b3666ac..0000000 --- a/tests/tst_launch.cpp +++ /dev/null @@ -1,206 +0,0 @@ -// Runs the real binary: headless capture, single-instance hand-off, and -// capture delivered to a running instance. - -#include "InstanceChannel.h" -#include "LibraryService.h" - -#include <QDir> -#include <QFile> -#include <QLocalSocket> - -#include <unistd.h> - -#include <QProcess> -#include <QTemporaryDir> -#include <QTest> - -using namespace onotes; -using namespace Qt::StringLiterals; - -class TestLaunch : public QObject -{ - Q_OBJECT - - QTemporaryDir m_dir; - - QProcessEnvironment env() const - { - QProcessEnvironment e = QProcessEnvironment::systemEnvironment(); - e.insert(u"QT_QPA_PLATFORM"_s, u"offscreen"_s); - e.insert(u"QT_QUICK_BACKEND"_s, u"software"_s); - e.insert(u"XDG_CONFIG_HOME"_s, m_dir.filePath(u"config"_s)); - e.insert(u"XDG_RUNTIME_DIR"_s, m_dir.path()); - e.remove(u"HYPRLAND_INSTANCE_SIGNATURE"_s); - // Desktop theme plugins (e.g. GTK) need a real display. - e.remove(u"QT_QPA_PLATFORMTHEME"_s); - return e; - } - - int run(const QStringList &args, QByteArray *out = nullptr, const QByteArray &input = {}) - { - QProcess p; - p.setProcessEnvironment(env()); - p.start(QStringLiteral(APP_PATH), QStringList{u"--data-dir"_s, m_dir.filePath(u"library"_s)} + args); - if (!input.isEmpty()) { - p.write(input); - p.closeWriteChannel(); - } - if (!p.waitForFinished(15000)) { - p.kill(); - p.waitForFinished(); - return -1; - } - if (out) - *out = p.readAllStandardOutput(); - return p.exitCode(); - } - - QStringList titles() - { - LibraryService library(LibraryPaths::at(m_dir.filePath(u"library"_s))); - QStringList out; - if (library.start(nullptr)) { - for (const NoteSummary &n : library.listNotes()) - out << n.title; - } - return out; - } - -private slots: - void initTestCase() - { - // The app and this test must agree on where the socket lives. - qputenv("XDG_RUNTIME_DIR", m_dir.path().toLocal8Bit()); - } - - void captureWithoutARunningApp() - { - QByteArray out; - QCOMPARE(run({u"--capture"_s, u"Buy stamps"_s}, &out), 0); - QVERIFY(out.contains("Saved")); - QCOMPARE(run({u"--capture"_s, u"-"_s}, nullptr, "From a pipe\nsecond line\n"), 0); - QCOMPARE(run({u"--capture"_s, u" "_s}), 1); - const QStringList t = titles(); - QVERIFY(t.contains(u"Buy stamps"_s)); - QVERIFY(t.contains(u"From a pipe"_s)); - } - - void firstFrameAndStartupTime() - { - QProcess p; - QProcessEnvironment e = env(); - e.insert(u"ONOTES_EXIT_AFTER_FIRST_FRAME"_s, u"1"_s); - p.setProcessEnvironment(e); - p.start(QStringLiteral(APP_PATH), {u"--data-dir"_s, m_dir.filePath(u"startup"_s)}); - QVERIFY(p.waitForFinished(20000)); - const QByteArray out = p.readAllStandardOutput(); - QVERIFY2(out.contains("first-frame") && out.contains("Omarchy Notes"), out.constData()); - qInfo("%s", out.trimmed().constData()); - } - - void unusableLibraryShowsAnErrorWindow() - { - if (::geteuid() == 0) - QSKIP("root can write to read-only folders"); - const QString library = m_dir.filePath(u"locked"_s); - QDir().mkpath(library); - QFile::setPermissions(library, QFileDevice::ReadOwner | QFileDevice::ExeOwner); - QProcess p; - QProcessEnvironment e = env(); - e.insert(u"ONOTES_EXIT_AFTER_FIRST_FRAME"_s, u"1"_s); - p.setProcessEnvironment(e); - p.start(QStringLiteral(APP_PATH), {u"--data-dir"_s, library}); - const bool finished = p.waitForFinished(20000); - QFile::setPermissions(library, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner); - QVERIFY(finished); - QCOMPARE(p.exitCode(), 1); - QVERIFY(p.readAllStandardOutput().contains("first-frame")); // a window was shown - QVERIFY(p.readAllStandardError().contains("can't open your notes")); - } - - void hyprlandSetupIsSafe() - { - const QString config = m_dir.filePath(u"hyprconfig"_s); - const QString omarchy = m_dir.filePath(u"omarchy"_s); - QDir().mkpath(config + u"/hypr"_s); - QDir().mkpath(omarchy + u"/default/hypr/bindings"_s); - auto writeFile = [](const QString &path, const QByteArray &data) { - QFile f(path); - QVERIFY(f.open(QIODevice::WriteOnly)); - f.write(data); - }; - writeFile(config + u"/hypr/bindings.lua"_s, R"(o.bind("SUPER + B", "Browser", { launch = "chromium" }))" "\n"); - writeFile(config + u"/hypr/hyprland.lua"_s, R"(require("bindings"))" "\n"); - writeFile(omarchy + u"/default/hypr/bindings/utilities.lua"_s, - R"(o.bind("SUPER + SPACE", "Omarchy menu", "omarchy-menu toggle"))" "\n"); - - auto setup = [&](QByteArray *out) { - QProcess p; - QProcessEnvironment e = env(); - e.insert(u"XDG_CONFIG_HOME"_s, config); - e.insert(u"OMARCHY_PATH"_s, omarchy); - p.setProcessEnvironment(e); - p.start(QStringLiteral(APP_PATH), {u"--setup-hyprland"_s}); - p.waitForFinished(15000); - *out = p.readAllStandardOutput(); - return p.exitCode(); - }; - auto read = [](const QString &path) { - QFile f(path); - return f.open(QIODevice::ReadOnly) ? f.readAll() : QByteArray(); - }; - QByteArray out; - QCOMPARE(setup(&out), 0); - QVERIFY(read(config + u"/hypr/bindings.lua"_s).contains(R"(o.bind("SUPER + ALT + N", "Quick Note")")); - QVERIFY(read(config + u"/hypr/hyprland.lua"_s).contains(R"(title = "^Quick Note$")")); - - // Running it again changes nothing. - const QByteArray before = read(config + u"/hypr/bindings.lua"_s); - QCOMPARE(setup(&out), 0); - QCOMPARE(read(config + u"/hypr/bindings.lua"_s), before); - QVERIFY(out.contains("already set up")); - - // A key that's taken (here by Omarchy's defaults) is never overwritten. - writeFile(config + u"/hypr/bindings.lua"_s, "-- fresh\n"); - writeFile(omarchy + u"/default/hypr/bindings/utilities.lua"_s, - R"(o.bind("SUPER + ALT + N", "Something else", "thing"))" "\n"); - QCOMPARE(setup(&out), 1); - QVERIFY(out.contains("already bound")); - QCOMPARE(read(config + u"/hypr/bindings.lua"_s), QByteArray("-- fresh\n")); - } - - void secondLaunchHandsOffToTheFirst() - { - QProcess app; - app.setProcessEnvironment(env()); - app.start(QStringLiteral(APP_PATH), {u"--data-dir"_s, m_dir.filePath(u"library"_s)}); - QVERIFY(app.waitForStarted()); - // Wait until it's listening, so the next launch can't race it for - // the library lock. - const QString socket = InstanceChannel::socketPath(LibraryPaths::at(m_dir.filePath(u"library"_s))); - QTRY_VERIFY_WITH_TIMEOUT([&] { - QLocalSocket probe; - probe.connectToServer(socket); - return probe.waitForConnected(100); - }(), 10000); - QByteArray out; - QCOMPARE(run({}, &out), 0); - QCOMPARE(app.state(), QProcess::Running); // the first instance kept running - - QCOMPARE(run({u"--capture"_s, u"Delivered to the running app"_s}, &out), 0); - QVERIFY(out.contains("Saved")); - QCOMPARE(run({u"--new"_s}), 0); - QCOMPARE(run({u"--quick-note"_s}), 0); - QCOMPARE(app.state(), QProcess::Running); - - app.terminate(); - if (!app.waitForFinished(5000)) { - app.kill(); - app.waitForFinished(); - } - QVERIFY(titles().contains(u"Delivered to the running app"_s)); - } -}; - -QTEST_MAIN(TestLaunch) -#include "tst_launch.moc" diff --git a/tests/tst_store.cpp b/tests/tst_store.cpp deleted file mode 100644 index f1a7895..0000000 --- a/tests/tst_store.cpp +++ /dev/null @@ -1,760 +0,0 @@ -#include "Database.h" -#include "LibraryBackup.h" -#include "LibraryService.h" -#include "NoteStore.h" -#include "SampleLibrary.h" - -#include <QDateTime> -#include <QDirIterator> -#include <QFile> -#include <QFileInfo> -#include <QProcess> -#include <QRandomGenerator> -#include <QSignalSpy> -#include <QTemporaryDir> -#include <QTest> - -#include <csignal> -#include <unistd.h> - -using namespace onotes; -using namespace Qt::StringLiterals; - -namespace { - -RichDocument textDoc(const QString &text) -{ - RichDocument doc; - doc.blocks = {Block::paragraph({Span::plain(text)})}; - doc.assignMissingIds(); - return doc; -} - -QStringList titles(const QList<NoteSummary> ¬es) -{ - QStringList out; - for (const NoteSummary &n : notes) - out << n.title; - return out; -} - -constexpr qint64 kFarFuture = qint64(4102444800000); // 2100-01-01 - -} // namespace - -class TestStore : public QObject -{ - Q_OBJECT - -private slots: - void createSaveLoad() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QString error; - QVERIFY2(store.open(&error), qPrintable(error)); - - auto note = store.createNote(textDoc(u"First line\nsecond"_s)); - QVERIFY(note); - QCOMPARE(note->revision, 1); - - SaveRequest save{note->id, note->revision, textDoc(u"Updated title"_s)}; - const SaveResult result = store.saveNote(save); - QVERIFY2(result.status == SaveResult::Status::Saved, qPrintable(result.error)); - QCOMPARE(result.revision, 2); - - const auto loaded = store.loadNote(note->id); - QVERIFY(loaded); - QCOMPARE(loaded->body, save.body); - QCOMPARE(loaded->revision, 2); - - const auto list = store.listNotes(); - QCOMPARE(list.size(), 1); - QCOMPARE(list[0].title, u"Updated title"_s); - QVERIFY(store.verify().isEmpty()); - } - - void staleRevisionIsAConflict() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - auto note = store.createNote(textDoc(u"a"_s)); - QCOMPARE(store.saveNote({note->id, 1, textDoc(u"b"_s)}).status, SaveResult::Status::Saved); - const SaveResult stale = store.saveNote({note->id, 1, textDoc(u"c"_s)}); - QCOMPARE(stale.status, SaveResult::Status::Conflict); - QCOMPARE(store.loadNote(note->id)->body.plainText(), u"b"_s); - } - - void revisionSnapshotsAreThrottled() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - auto note = store.createNote(textDoc(u"a"_s)); - qint64 rev = note->revision; - for (int i = 0; i < 20; ++i) - rev = store.saveNote({note->id, rev, textDoc(QString::number(i))}).revision; - QCOMPARE(store.revisionCount(note->id), 1); - } - - void attachmentsAndImages() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - auto note = store.createNote(textDoc(u"a"_s)); - - const QString source = dir.filePath(u"report.pdf"_s); - QVERIFY(SampleLibrary::writeSamplePdf(source)); - QString error; - const auto attachment = store.addAttachment(note->id, source, &error); - QVERIFY2(attachment, qPrintable(error)); - QCOMPARE(attachment->fileName, u"report.pdf"_s); - QCOMPARE(attachment->mimeType, u"application/pdf"_s); - QVERIFY(QFile::exists(store.blobPath(attachment->blobHash))); - - const auto image = store.addImage(SampleLibrary::chartPng()); - QVERIFY(image); - // Same bytes, same blob. - QCOMPARE(*store.addImage(SampleLibrary::chartPng()), *image); - - RichDocument body = textDoc(u"with media"_s); - body.blocks[0].spans << Span::image(*image, 800, 360) << Span::attachment(attachment->id) - << Span::image(QString(64, u'0'), 1, 1); // unknown blob - QCOMPARE(store.saveNote({note->id, note->revision, body}).status, SaveResult::Status::Saved); - QVERIFY(store.verify().isEmpty()); - QVERIFY(QDir(dir.filePath(u"staging"_s)).isEmpty()); - } - - void rejectsNewerSchema() - { - QTemporaryDir dir; - { - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - } - { - Database db; - QVERIFY(db.open(dir.filePath(u"library.sqlite3"_s), nullptr)); - QVERIFY(db.exec("PRAGMA user_version=99")); - } - NoteStore store(LibraryPaths::at(dir.path())); - QString error; - QVERIFY(!store.open(&error)); - QVERIFY(error.contains(u"newer version"_s)); - } - - void backup() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - auto note = store.createNote(textDoc(u"keep me"_s)); - QTemporaryDir out; - QString error; - QVERIFY2(store.backupDatabase(out.filePath(u"library.sqlite3"_s), &error), qPrintable(error)); - QDir().mkpath(out.filePath(u"blobs"_s)); - NoteStore restored(LibraryPaths::at(out.path())); - QVERIFY(restored.open(&error)); - QCOMPARE(restored.loadNote(note->id)->body.plainText(), u"keep me"_s); - } - - void serviceSavesOffThread() - { - QTemporaryDir dir; - LibraryService library(LibraryPaths::at(dir.path())); - QString error; - QVERIFY2(library.start(&error), qPrintable(error)); - const QString mixedId = SampleLibrary::seed(library, &error); - QVERIFY2(!mixedId.isEmpty(), qPrintable(error)); - QCOMPARE(library.listNotes().size(), 3); - const auto mixed = library.loadNote(mixedId); - QVERIFY(mixed); - QCOMPARE(mixed->body.title(), u"Q3 planning — product sync"_s); - - auto resultFor = [&](quint64 ticket) { - QSignalSpy spy(&library, &LibraryService::saveFinished); - for (;;) { - for (const auto &args : spy) { - if (args.at(0).toULongLong() == ticket) - return args.at(2).value<SaveResult>(); - } - if (!spy.wait(5000)) - return SaveResult{}; - } - }; - library.setSimulatedSaveFailure(true); - const SaveResult failed = resultFor(library.saveNote({mixedId, mixed->revision, textDoc(u"x"_s)})); - QCOMPARE(failed.status, SaveResult::Status::Failed); - QVERIFY(!failed.error.isEmpty()); - library.setSimulatedSaveFailure(false); - const SaveResult saved = resultFor(library.saveNote({mixedId, mixed->revision, textDoc(u"x"_s)})); - QCOMPARE(saved.status, SaveResult::Status::Saved); - QVERIFY(library.verify().isEmpty()); - } - - void foldersAndMoves() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - QString error; - const auto work = store.createFolder(u" Work "_s, {}, &error); - QVERIFY2(work, qPrintable(error)); - QCOMPARE(work->name, u"Work"_s); - const auto clients = store.createFolder(u"Clients"_s, work->id); - QVERIFY(clients); - QVERIFY(!store.createFolder(u"work"_s, {}, &error)); // siblings must differ - QVERIFY(error.contains(u"already"_s)); - QVERIFY(store.createFolder(u"Clients"_s)); // same name elsewhere is fine - QVERIFY(!store.createFolder(u" "_s, {}, &error)); - - const auto loose = store.createNote(textDoc(u"Loose"_s)); - const auto filed = store.createNote(textDoc(u"Filed"_s), nullptr, clients->id); - QVERIFY(loose && filed); - QCOMPARE(titles(store.listNotes(NoteQuery::folder({}))), QStringList{u"Loose"_s}); - QCOMPARE(titles(store.listNotes(NoteQuery::folder(clients->id))), QStringList{u"Filed"_s}); - QCOMPARE(store.listNotes().size(), 2); - - QVERIFY(store.moveNote(loose->id, work->id)); - QCOMPARE(store.listNotes(NoteQuery::folder({})).size(), 0); - QVERIFY(store.renameFolder(work->id, u"Office"_s)); - QVERIFY(!store.renameFolder(clients->id, u" "_s, &error)); - - int workCount = -1; - for (const FolderInfo &f : store.listFolders()) { - if (f.id == work->id) { - QCOMPARE(f.name, u"Office"_s); - workCount = f.noteCount; - } - if (f.id == clients->id) - QCOMPARE(f.parentId, work->id); - } - QCOMPARE(workCount, 1); - QVERIFY(!store.moveNote(loose->id, u"8d1c3f0e-6b8a-4f7e-9d2c-1a2b3c4d5e6f"_s, &error)); - } - - void sortingKeepsPinnedFirst() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - const auto banana = store.createNote(textDoc(u"banana"_s)); - QTest::qWait(5); - const auto apple = store.createNote(textDoc(u"Apple"_s)); - QTest::qWait(5); - const auto cherry = store.createNote(textDoc(u"cherry"_s)); - QTest::qWait(5); - // Editing banana makes it the most recently edited. - QVERIFY(store.saveNote({banana->id, banana->revision, textDoc(u"banana split"_s)}).status - == SaveResult::Status::Saved); - - QCOMPARE(titles(store.listNotes(NoteQuery::all(NoteSort::Edited))), - (QStringList{u"banana split"_s, u"cherry"_s, u"Apple"_s})); - QCOMPARE(titles(store.listNotes(NoteQuery::all(NoteSort::Created))), - (QStringList{u"cherry"_s, u"Apple"_s, u"banana split"_s})); - QCOMPARE(titles(store.listNotes(NoteQuery::all(NoteSort::Title))), - (QStringList{u"Apple"_s, u"banana split"_s, u"cherry"_s})); - QVERIFY(store.setPinned(cherry->id, true)); - QCOMPARE(titles(store.listNotes(NoteQuery::all(NoteSort::Title))), - (QStringList{u"cherry"_s, u"Apple"_s, u"banana split"_s})); - Q_UNUSED(apple); - } - - void trashLifecycle() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - const auto folder = store.createFolder(u"Ideas"_s); - const auto note = store.createNote(textDoc(u"Idea"_s), nullptr, folder->id); - const auto other = store.createNote(textDoc(u"Other"_s)); - - QString error; - QVERIFY(!store.deleteNotePermanently(note->id, &error)); // must be in the trash first - QVERIFY(store.trashNote(note->id)); - QVERIFY(!store.trashNote(note->id)); - QCOMPARE(store.noteCount(), 1); - QCOMPARE(store.trashCount(), 1); - const auto trashed = store.listNotes(NoteQuery::trash()); - QCOMPARE(trashed.size(), 1); - QVERIFY(trashed[0].deletedAt > 0); - QVERIFY(store.loadNote(note->id)->deletedAt > 0); - - QVERIFY(store.recoverNote(note->id)); - QCOMPARE(titles(store.listNotes(NoteQuery::folder(folder->id))), QStringList{u"Idea"_s}); - - QVERIFY(store.trashNote(note->id)); - QVERIFY(store.deleteNotePermanently(note->id)); - QVERIFY(!store.loadNote(note->id)); - - QVERIFY(store.trashNote(other->id)); - QCOMPARE(store.purgeExpiredTrash(QDateTime::currentMSecsSinceEpoch()), 0); // not old enough - QCOMPARE(store.purgeExpiredTrash(kFarFuture), 1); - QCOMPARE(store.trashCount(), 0); - QVERIFY(store.verify().isEmpty()); - } - - void deletingAFolderTrashesItsNotes() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - const auto top = store.createFolder(u"Projects"_s); - const auto sub = store.createFolder(u"Old"_s, top->id); - const auto deeper = store.createFolder(u"Older"_s, sub->id); - store.createNote(textDoc(u"A"_s), nullptr, top->id); - const auto b = store.createNote(textDoc(u"B"_s), nullptr, deeper->id); - const auto kept = store.createNote(textDoc(u"Kept"_s)); - - QVERIFY(store.deleteFolder(top->id)); - QVERIFY(store.listFolders().isEmpty()); - QCOMPARE(titles(store.listNotes()), QStringList{u"Kept"_s}); - QCOMPARE(store.trashCount(), 2); - // Their folder is gone, so recovered notes land in Notes. - QVERIFY(store.recoverNote(b->id)); - QCOMPARE(store.loadNote(b->id)->folderId, QString()); - QVERIFY(store.verify().isEmpty()); - Q_UNUSED(kept); - } - - void searchMatchesPrefixesAndSkipsTrash() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - RichDocument meeting; - meeting.blocks = {Block::heading(1, {Span::plain(u"Q3 planning"_s)}), - Block::paragraph({Span::plain(u"Benchmark search on the reference ThinkPad."_s)})}; - meeting.assignMissingIds(); - store.createNote(meeting); - store.createNote(textDoc(u"Groceries: lemons, basil, café au lait"_s)); - const auto old = store.createNote(textDoc(u"Benchmark results from last year"_s)); - QVERIFY(store.trashNote(old->id)); - - auto hits = store.search(u"bench"_s); - QCOMPARE(hits.size(), 1); - QCOMPARE(hits[0].title, u"Q3 planning"_s); - QVERIFY(hits[0].snippet.contains(QChar(2)) && hits[0].snippet.contains(QChar(3))); - QCOMPARE(store.search(u"lem GRO"_s).size(), 1); // every word, any order, any case - QCOMPARE(store.search(u"cafe"_s).size(), 1); // diacritics ignored - QCOMPARE(store.search(u"lemons planning"_s).size(), 0); - // FTS syntax is treated as plain text, never an error. - for (const QString &odd : {u"\""_s, u"-"_s, u"*"_s, u"NEAR("_s, u"a OR"_s, u"\"unterminated"_s}) - QVERIFY(store.search(odd).size() >= 0); - QVERIFY(store.search(u" "_s).isEmpty()); - } - - void duplicateGetsItsOwnAttachments() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - const auto note = store.createNote(textDoc(u"With file"_s)); - const QString pdf = dir.filePath(u"plan.pdf"_s); - QVERIFY(SampleLibrary::writeSamplePdf(pdf)); - const auto attachment = store.addAttachment(note->id, pdf); - RichDocument body = textDoc(u"With file"_s); - body.blocks[0].spans << Span::attachment(attachment->id); - QVERIFY(store.saveNote({note->id, note->revision, body}).status == SaveResult::Status::Saved); - - const auto copy = store.duplicateNote(note->id); - QVERIFY(copy); - const QString copiedId = copy->body.referencedAttachments().value(0); - QVERIFY(!copiedId.isEmpty() && copiedId != attachment->id); - QCOMPARE(store.attachment(copiedId)->blobHash, attachment->blobHash); - - // Deleting the original must not break the copy, even after cleanup. - QVERIFY(store.trashNote(note->id)); - QVERIFY(store.deleteNotePermanently(note->id)); - store.collectGarbage(kFarFuture); - QVERIFY(store.attachment(copiedId)); - QVERIFY(QFile::exists(store.blobPath(attachment->blobHash))); - QVERIFY(store.verify().isEmpty()); - } - - void garbageCollectionKeepsWhatIsReferenced() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - const auto used = store.addImage(SampleLibrary::chartPng()); - const auto unused = store.addImage(QByteArray("not really an image")); - const auto note = store.createNote(textDoc(u"chart"_s)); - RichDocument body = textDoc(u"chart"_s); - body.blocks[0].spans << Span::image(*used, 800, 360); - QVERIFY(store.saveNote({note->id, note->revision, body}).status == SaveResult::Status::Saved); - // An orphan file from an interrupted install. - QFile orphan(dir.filePath(u"blobs/ff/"_s) + QString(64, u'f')); - QDir().mkpath(dir.filePath(u"blobs/ff"_s)); - QVERIFY(orphan.open(QIODevice::WriteOnly)); - orphan.write("x"); - orphan.close(); - - // Within the grace period nothing is removed. - QCOMPARE(store.collectGarbage().blobsRemoved, 0); - const GarbageReport report = store.collectGarbage(kFarFuture); - QCOMPARE(report.blobsRemoved, 2); - QVERIFY(QFile::exists(store.blobPath(*used))); - QVERIFY(!QFile::exists(store.blobPath(*unused))); - QVERIFY(!orphan.exists()); - QVERIFY(store.verify().isEmpty()); - } - - void backupAndRestore() - { - QTemporaryDir dir; - QTemporaryDir backups; - LibraryService library(LibraryPaths::at(dir.filePath(u"library"_s))); - QString error; - QVERIFY2(library.start(&error), qPrintable(error)); - QVERIFY(!SampleLibrary::seed(library, &error).isEmpty()); - const QStringList before = titles(library.listNotes()); - - const QString target = backups.filePath(defaultBackupName()); - const auto manifest = library.backupTo(target, &error); - QVERIFY2(manifest, qPrintable(error)); - QCOMPARE(manifest->notes, 3); - QCOMPARE(manifest->blobs, 2); // chart image + PDF - QVERIFY(!QFileInfo::exists(target + u".partial"_s)); - QVERIFY(library.inspectBackup(target, &error)); - QVERIFY(!library.backupTo(target, &error)); // never overwrites - - // Change things, then restore. - library.createNote(textDoc(u"Written after the backup"_s)); - library.trashNote(library.listNotes().last().id); - QString safety; - QVERIFY2(library.restoreFrom(target, &safety, &error), qPrintable(error)); - QCOMPARE(titles(library.listNotes()), before); - QCOMPARE(library.trashCount(), 0); - QVERIFY(library.verify().isEmpty()); - QVERIFY(QFileInfo::exists(safety + u"/library.sqlite3"_s)); // the replaced library is kept - // The restored library is live: it saves normally. - const auto note = library.createNote(textDoc(u"After restore"_s)); - QVERIFY(note); - QVERIFY(library.inspectBackup(target)); // the backup itself is untouched - } - - void restoreRejectsBadBackups() - { - QTemporaryDir dir; - QTemporaryDir backups; - LibraryService library(LibraryPaths::at(dir.filePath(u"library"_s))); - QString error; - QVERIFY(library.start(&error)); - QVERIFY(!SampleLibrary::seed(library, &error).isEmpty()); - const QString good = backups.filePath(u"good"_s); - QVERIFY(library.backupTo(good)); - - QVERIFY(!library.inspectBackup(backups.path(), &error)); // not a backup - QVERIFY(error.contains(u"isn't"_s)); - - // Remove one attachment from a copy of the backup. - const QString broken = backups.filePath(u"broken"_s); - QVERIFY(QDir().mkpath(broken)); - QVERIFY(QProcess::execute(u"cp"_s, {u"-a"_s, good + u"/."_s, broken}) == 0); - QDirIterator blobs(broken + u"/blobs"_s, QDir::Files, QDirIterator::Subdirectories); - QVERIFY(blobs.hasNext()); - QVERIFY(QFile::remove(blobs.next())); - QVERIFY(!library.inspectBackup(broken, &error)); - QVERIFY(error.contains(u"incomplete"_s)); - - const QStringList before = titles(library.listNotes()); - QString safety; - QVERIFY(!library.restoreFrom(broken, &safety, &error)); - QCOMPARE(titles(library.listNotes()), before); // nothing changed - QVERIFY(safety.isEmpty()); - QVERIFY(library.verify().isEmpty()); - } - - void tagsFollowTheText() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - const auto a = store.createNote(textDoc(u"Launch plan #work #Launch"_s)); - const auto b = store.createNote(textDoc(u"Groceries #errands #work"_s)); - QCOMPARE(store.listTags().size(), 3); - QCOMPARE(store.listNotes(NoteQuery::tagged(u"WORK"_s)).size(), 2); - - // Editing the text updates the tags. - QVERIFY(store.saveNote({a->id, a->revision, textDoc(u"Launch plan #personal"_s)}).status - == SaveResult::Status::Saved); - QStringList names; - for (const TagInfo &t : store.listTags()) - names << u"%1:%2"_s.arg(t.name).arg(t.noteCount); - QCOMPARE(names, (QStringList{u"errands:1"_s, u"personal:1"_s, u"work:1"_s})); - - // Deleted notes don't count. - QVERIFY(store.trashNote(b->id)); - QCOMPARE(store.listTags().size(), 1); - QCOMPARE(store.listNotes(NoteQuery::tagged(u"work"_s)).size(), 0); - } - - void smartFolders() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - RichDocument checklist; - checklist.blocks = {Block::listItem(ListKind::Check, 0, {Span::plain(u"Pack #travel #work"_s)})}; - checklist.assignMissingIds(); - const auto trip = store.createNote(checklist); - store.createNote(textDoc(u"Notes from #work"_s)); - const auto pinned = store.createNote(textDoc(u"Passport #travel"_s)); - store.setPinned(pinned->id, true); - - SmartCriteria any; - any.tags = {u"travel"_s, u"work"_s}; - QCOMPARE(store.listNotes(NoteQuery::smart(any)).size(), 3); - SmartCriteria all = any; - all.matchAllTags = true; - QCOMPARE(store.listNotes(NoteQuery::smart(all)).size(), 1); - SmartCriteria checklistOnly; - checklistOnly.hasChecklist = true; - QCOMPARE(store.listNotes(NoteQuery::smart(checklistOnly)).value(0).id, trip->id); - SmartCriteria pinnedTravel; - pinnedTravel.tags = {u"travel"_s}; - pinnedTravel.pinnedOnly = true; - QCOMPARE(store.listNotes(NoteQuery::smart(pinnedTravel)).size(), 1); - SmartCriteria recent; - recent.editedWithinDays = 7; - QCOMPARE(store.listNotes(NoteQuery::smart(recent)).size(), 3); - - QString error; - QVERIFY(!store.createSmartFolder(u"Nothing"_s, SmartCriteria{}, &error)); // needs a filter - const auto travel = store.createSmartFolder(u"Travel & work"_s, all, &error); - QVERIFY2(travel, qPrintable(error)); - QCOMPARE(travel->noteCount, 1); - QVERIFY(!store.createSmartFolder(u"travel & WORK"_s, any, &error)); // unique names - QVERIFY(store.updateSmartFolder(travel->id, u"Everything tagged"_s, any)); - const auto folders = store.listSmartFolders(); - QCOMPARE(folders.size(), 1); - QCOMPARE(folders[0].name, u"Everything tagged"_s); - QCOMPARE(folders[0].criteria, any); - QCOMPARE(folders[0].noteCount, 3); - QVERIFY(store.deleteSmartFolder(travel->id)); - QVERIFY(store.listSmartFolders().isEmpty()); - } - - void attachmentBrowserItems() - { - QTemporaryDir dir; - LibraryService library(LibraryPaths::at(dir.path())); - QString error; - QVERIFY(library.start(&error)); - const QString mixed = SampleLibrary::seed(library, &error); - const QList<AttachmentItem> items = library.listAttachmentItems(); - QCOMPARE(items.size(), 2); - int images = 0; - for (const AttachmentItem &item : items) { - QCOMPARE(item.noteId, mixed); - images += item.isImage; - if (!item.isImage) - QCOMPARE(item.fileName, u"Q3 roadmap draft.pdf"_s); - } - QCOMPARE(images, 1); - QVERIFY(!library.listNotes().first().thumbnail.isEmpty() || !library.listNotes().last().thumbnail.isEmpty()); - library.trashNote(mixed); - QVERIFY(library.listAttachmentItems().isEmpty()); - } - - // Turn a current library back into a real v1 database. - static void downgradeToV1(const QString &databasePath) - { - Database db; - QVERIFY(db.open(databasePath, nullptr)); - QVERIFY(db.exec("DROP TABLE note_tags; DROP TABLE note_attachment_refs; DROP TABLE smart_folders;")); - QVERIFY(db.exec("ALTER TABLE notes DROP COLUMN thumbnail")); - QVERIFY(db.exec("PRAGMA user_version=1")); - } - - void migratesVersion1Libraries() - { - QTemporaryDir dir; - QString mixed; - { - LibraryService library(LibraryPaths::at(dir.path())); - QString error; - QVERIFY(library.start(&error)); - mixed = SampleLibrary::seed(library, &error); - library.createNote(textDoc(u"Old note with #legacy tag"_s)); - } - downgradeToV1(dir.filePath(u"library.sqlite3"_s)); - - NoteStore store(LibraryPaths::at(dir.path())); - QString error; - QVERIFY2(store.open(&error), qPrintable(error)); - QCOMPARE(store.listNotes(NoteQuery::tagged(u"legacy"_s)).size(), 1); - QCOMPARE(store.listAttachmentItems().size(), 2); - bool thumbnail = false; - for (const NoteSummary &n : store.listNotes()) - thumbnail = thumbnail || (n.id == mixed && !n.thumbnail.isEmpty()); - QVERIFY(thumbnail); - QVERIFY(store.verify().isEmpty()); - Database check; - QVERIFY(check.open(dir.filePath(u"library.sqlite3"_s), nullptr)); - QCOMPARE(check.userVersion(), NoteStore::SchemaVersion); - } - - void restoresVersion1Backups() - { - QTemporaryDir dir; - QTemporaryDir backups; - LibraryService library(LibraryPaths::at(dir.filePath(u"library"_s))); - QString error; - QVERIFY(library.start(&error)); - QVERIFY(!SampleLibrary::seed(library, &error).isEmpty()); - library.createNote(textDoc(u"From an older app #vintage"_s)); - const QString target = backups.filePath(u"old"_s); - QVERIFY(library.backupTo(target)); - downgradeToV1(target + u"/library.sqlite3"_s); - QFile manifest(target + u"/manifest.json"_s); - QVERIFY(manifest.open(QIODevice::ReadWrite)); - QByteArray json = manifest.readAll().replace("\"schemaVersion\": 2", "\"schemaVersion\": 1"); - manifest.resize(0); - manifest.write(json); - manifest.close(); - - QString safety; - QVERIFY2(library.restoreFrom(target, &safety, &error), qPrintable(error)); - QCOMPARE(library.listNotes(NoteQuery::tagged(u"vintage"_s)).size(), 1); - QVERIFY(library.verify().isEmpty()); - QDir(safety).removeRecursively(); - } - - void fullDiskKeepsTheLastGoodVersion() - { - QTemporaryDir dir; - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - const auto note = store.createNote(textDoc(u"small"_s)); - // Cap the database at its current size, like a full disk. - Statement pages = store.database().prepare("PRAGMA page_count"); - QVERIFY(pages.next()); - const QByteArray cap = "PRAGMA max_page_count=" + QByteArray::number(pages.int64(0)); - QVERIFY(store.database().exec(cap.constData())); - - const SaveResult result = store.saveNote({note->id, note->revision, textDoc(QString(200000, u'x'))}); - QCOMPARE(result.status, SaveResult::Status::Failed); - QVERIFY2(result.error.contains(u"disk is full"_s), qPrintable(result.error)); - QCOMPARE(store.loadNote(note->id)->body.plainText(), u"small"_s); // nothing half-written - QVERIFY(store.verify().isEmpty()); - } - - void readOnlyLibraryIsExplained() - { - if (::geteuid() == 0) - QSKIP("root can write to read-only folders"); - QTemporaryDir dir; - { - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - store.createNote(textDoc(u"keep"_s)); - } - QFile::setPermissions(dir.path(), QFileDevice::ReadOwner | QFileDevice::ExeOwner); - NoteStore store(LibraryPaths::at(dir.path())); - QString error; - const bool opened = store.open(&error); - QFile::setPermissions(dir.path(), QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner); - QVERIFY(!opened); - QVERIFY2(error.contains(u"can't write"_s), qPrintable(error)); - } - - void failedMigrationLeavesTheLibraryAsItWas() - { - QTemporaryDir dir; - QString id; - { - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - id = store.createNote(textDoc(u"Precious #data"_s))->id; - } - downgradeToV1(dir.filePath(u"library.sqlite3"_s)); - { - // Something in the way of the upgrade: v2 can't create this table. - Database db; - QVERIFY(db.open(dir.filePath(u"library.sqlite3"_s), nullptr)); - QVERIFY(db.exec("CREATE TABLE smart_folders (x)")); - } - { - NoteStore store(LibraryPaths::at(dir.path())); - QString error; - QVERIFY(!store.open(&error)); - QVERIFY(error.contains(u"upgrade"_s)); - } - Database db; - QVERIFY(db.open(dir.filePath(u"library.sqlite3"_s), nullptr)); - QCOMPARE(db.userVersion(), 1); // rolled back, still usable by the old app - Statement check = db.prepare("SELECT body FROM notes WHERE id = ?1"); - check.bind(1, id); - QVERIFY(check.next()); - QVERIFY(check.text(0).contains(u"Precious"_s)); - Statement noTags = db.prepare("SELECT COUNT(*) FROM sqlite_master WHERE name = 'note_tags'"); - QVERIFY(noTags.next()); - QCOMPARE(noTags.int64(0), 0); - } - - // Kill the writer with SIGKILL at random points; every save it - // acknowledged must be present afterwards and the library consistent. - void acknowledgedSavesSurviveKill() - { - QTemporaryDir dir; - QString noteId; - { - NoteStore store(LibraryPaths::at(dir.path())); - QVERIFY(store.open(nullptr)); - noteId = store.createNote(textDoc(u"0"_s))->id; - } - - for (int round = 0; round < 8; ++round) { - QProcess child; - child.setProcessChannelMode(QProcess::SeparateChannels); - child.start(QStringLiteral(CRASH_HELPER_PATH), {dir.path(), noteId}); - QVERIFY(child.waitForStarted()); - - qint64 lastAck = 0; - const int acksBeforeKill = 5 + int(QRandomGenerator::global()->bounded(40)); - int acks = 0; - QByteArray pending; - while (acks < acksBeforeKill) { - QVERIFY2(child.waitForReadyRead(5000), child.readAllStandardError().constData()); - pending += child.readAllStandardOutput(); - qsizetype nl; - while ((nl = pending.indexOf('\n')) >= 0) { - const QByteArray line = pending.left(nl); - pending.remove(0, nl + 1); - if (line.startsWith("ACK ")) { - lastAck = line.mid(4).toLongLong(); - ++acks; - } - } - } - // Let it get partway into the next transaction. - QThread::usleep(QRandomGenerator::global()->bounded(3000)); - ::kill(pid_t(child.processId()), SIGKILL); - child.waitForFinished(); - // Anything acknowledged after our last read also counts. - pending += child.readAllStandardOutput(); - for (const QByteArray &line : pending.split('\n')) { - if (line.startsWith("ACK ")) - lastAck = line.mid(4).toLongLong(); - } - - NoteStore store(LibraryPaths::at(dir.path())); - QString error; - QVERIFY2(store.open(&error), qPrintable(error)); - const auto note = store.loadNote(noteId, &error); - QVERIFY2(note, qPrintable(error)); - const qint64 stored = note->body.blocks.value(1).plainText().toLongLong(); - QVERIFY2(stored >= lastAck, - qPrintable(u"round %1: stored %2 < acknowledged %3"_s.arg(round).arg(stored).arg(lastAck))); - const QStringList problems = store.verify(); - QVERIFY2(problems.isEmpty(), qPrintable(problems.join(u'\n'))); - } - } -}; - -QTEST_MAIN(TestStore) -#include "tst_store.moc" diff --git a/tests/tst_theme.cpp b/tests/tst_theme.cpp deleted file mode 100644 index 778fdc2..0000000 --- a/tests/tst_theme.cpp +++ /dev/null @@ -1,147 +0,0 @@ -#include "ThemePalette.h" - -#include <QFile> -#include <QTemporaryDir> -#include <QTest> - -using namespace onotes; -using namespace Qt::StringLiterals; - -namespace { - -void write(const QString &path, const QByteArray &content) -{ - QFile file(path); - QVERIFY(file.open(QIODevice::WriteOnly)); - file.write(content); -} - -void verifyContrast(const ThemePalette &p) -{ - QVERIFY2(contrastRatio(p.text, p.canvas) >= 4.5, qPrintable(p.name)); - QVERIFY2(contrastRatio(p.secondaryText, p.canvas) >= 4.5, qPrintable(p.name)); - QVERIFY2(contrastRatio(p.secondaryText, p.sidebar) >= 4.5, qPrintable(p.name)); - QVERIFY2(contrastRatio(p.selectionText, p.selection) >= 4.5, qPrintable(p.name)); - QVERIFY2(contrastRatio(p.link, p.canvas) >= 4.5, qPrintable(p.name)); - QVERIFY2(contrastRatio(p.error, p.canvas) >= 4.5, qPrintable(p.name)); - QVERIFY2(contrastRatio(p.accent, p.canvas) >= 3.0, qPrintable(p.name)); - QVERIFY2(contrastRatio(p.accentText, p.accent) >= 3.0, qPrintable(p.name)); - QVERIFY2(contrastRatio(p.text, composite(p.highlight, p.canvas)) >= 4.5, qPrintable(p.name)); -} - -// Kanagawa as shipped with Omarchy 4.0 alpha: accent equals foreground and -// dark_foreground is below text contrast on the background. -const QByteArray kKanagawa = R"(mode = "dark" - -accent = "#dcd7ba" -selection = "#363646" -muted = "#54546D" - -background = "#1f1f28" -dark_background = "#17171e" -foreground = "#dcd7ba" -dark_foreground = "#727169" - -red = "#c34043" -yellow = "#c0a36e" -blue = "#7e9cd8" -)"; - -const QByteArray kLight = R"(mode = "light" -accent = "#d7827e" -selection = "#dfdad9" -background = "#faf4ed" -foreground = "#575279" -red = "#b4637a" -yellow = "#ea9d34" -blue = "#286983" -)"; - -} // namespace - -class TestTheme : public QObject -{ - Q_OBJECT - -private slots: - void parsesToml() - { - const auto keys = parseSimpleToml( - u"# comment\nname = \"x # not a comment\"\n[colors.primary]\nbackground = '0x1f1f28' \n" - "bare = 12 # trailing\n"_s); - QCOMPARE(keys.value(u"name"_s), u"x # not a comment"_s); - QCOMPARE(keys.value(u"colors.primary.background"_s), u"0x1f1f28"_s); - QCOMPARE(keys.value(u"colors.primary.bare"_s), u"12"_s); - } - - void kanagawa() - { - QTemporaryDir dir; - write(dir.filePath(u"colors.toml"_s), kKanagawa); - const auto p = ThemePalette::fromColorsToml(dir.filePath(u"colors.toml"_s)); - QVERIFY(p); - QVERIFY(p->dark); - QCOMPARE(p->canvas, QColor(u"#1f1f28"_s)); - QCOMPARE(p->sidebar, QColor(u"#17171e"_s)); - // accent == foreground, so the blue is used for selection states. - QCOMPARE(p->accent, QColor(u"#7e9cd8"_s)); - verifyContrast(*p); - QVERIFY(!p->adjustments.isEmpty()); // dark_foreground was corrected - } - - void light() - { - QTemporaryDir dir; - write(dir.filePath(u"colors.toml"_s), kLight); - const auto p = ThemePalette::fromColorsToml(dir.filePath(u"colors.toml"_s)); - QVERIFY(p); - QVERIFY(!p->dark); - verifyContrast(*p); - } - - void builtIns() - { - verifyContrast(ThemePalette::builtIn(true)); - verifyContrast(ThemePalette::builtIn(false)); - } - - void alacrittyFallback() - { - QTemporaryDir dir; - write(dir.filePath(u"alacritty.toml"_s), R"([colors.primary] -background = "0x24273a" -foreground = "0xcad3f5" -[colors.normal] -red = "0xed8796" -yellow = "0xeed49f" -blue = "0x8aadf4" -)"); - const ThemePalette p = ThemePalette::loadFromDirectory(dir.path()); - QCOMPARE(p.source, dir.filePath(u"alacritty.toml"_s)); - QCOMPARE(p.canvas, QColor(u"#24273a"_s)); - verifyContrast(p); - } - - void invalidFilesFallBack() - { - QTemporaryDir dir; - write(dir.filePath(u"colors.toml"_s), "background = \"not a color\"\n"); - const ThemePalette p = ThemePalette::loadFromDirectory(dir.path()); - QCOMPARE(p.source, u"built-in"_s); - verifyContrast(p); - QCOMPARE(ThemePalette::loadFromDirectory(dir.filePath(u"missing"_s)).source, u"built-in"_s); - } - - void unreadableContrastIsRepaired() - { - QTemporaryDir dir; - write(dir.filePath(u"colors.toml"_s), - "background = \"#808080\"\nforeground = \"#8a8a8a\"\nselection = \"#858585\"\n"); - const auto p = ThemePalette::fromColorsToml(dir.filePath(u"colors.toml"_s)); - QVERIFY(p); - verifyContrast(*p); - } -}; - -QTEST_MAIN(TestTheme) -#include "tst_theme.moc" diff --git a/tools/capture-qt-fixture.py b/tools/capture-qt-fixture.py deleted file mode 100644 index 7f55325..0000000 --- a/tools/capture-qt-fixture.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python3 -"""Capture synthetic Qt data for the Rust compatibility suite, never a user's library.""" -import argparse -import hashlib -import json -import os -from pathlib import Path -import shutil -import sqlite3 -import subprocess -import tempfile -import time - - -def capture(binary: Path, destination: Path) -> None: - if destination.exists(): - raise SystemExit(f"Refusing to overwrite {destination}") - with tempfile.TemporaryDirectory(prefix="omarchy-notes-qt-fixture-") as temporary: - root = Path(temporary) - library = root / "library" - runtime = root / "runtime" - runtime.mkdir(mode=0o700) - env = dict(os.environ, QT_QPA_PLATFORM="offscreen", QT_QUICK_BACKEND="software", QT_QPA_PLATFORMTHEME="", - XDG_RUNTIME_DIR=str(runtime)) - with (root / "app.log").open("w+") as log: - process = subprocess.Popen([str(binary.resolve()), "--data-dir", str(library), "--samples"], - env=env, stdout=log, stderr=log) - try: - deadline = time.monotonic() + 20 - while time.monotonic() < deadline: - if process.poll() is not None: - log.seek(0) - raise RuntimeError("Qt exited before completing its sample library:\n" + log.read()) - try: - with sqlite3.connect(f"file:{library / 'library.sqlite3'}?mode=ro", uri=True) as db: - ready = db.execute("SELECT COUNT(*) FROM notes WHERE title <> ''").fetchone()[0] == 3 - if ready: - break - except sqlite3.Error: - pass - time.sleep(0.1) - else: - raise RuntimeError("Timed out waiting for committed sample notes") - - staged = root / "fixture" - staged.mkdir() - with sqlite3.connect(f"file:{library / 'library.sqlite3'}?mode=ro", uri=True) as source: - with sqlite3.connect(staged / "library.sqlite3") as snapshot: - source.backup(snapshot) - snapshot.execute("PRAGMA journal_mode=DELETE") - rows = snapshot.execute("SELECT id, title, body FROM notes ORDER BY title").fetchall() - blobs = snapshot.execute("SELECT hash, size FROM blobs ORDER BY hash").fetchall() - assert snapshot.execute("PRAGMA user_version").fetchone()[0] == 2 - assert snapshot.execute("PRAGMA integrity_check").fetchone()[0] == "ok" - assert not snapshot.execute("PRAGMA foreign_key_check").fetchall() - (staged / "documents.json").write_text(json.dumps([ - {"id": note_id, "title": title, "body": json.loads(body)} for note_id, title, body in rows - ], indent=2, ensure_ascii=False) + "\n") - for digest, size in blobs: - relative = Path("blobs") / digest[:2] / digest - data = (library / relative).read_bytes() - assert len(data) == size and hashlib.sha256(data).hexdigest() == digest - (staged / relative).parent.mkdir(parents=True, exist_ok=True) - (staged / relative).write_bytes(data) - (staged / "manifest.json").write_text(json.dumps({ - "fixture": "Qt sample library, not the application backup format", - "database_schema": 2, "document_schema": 1, - "notes": len(rows), "blobs": len(blobs), - "files": {str(p.relative_to(staged)): hashlib.sha256(p.read_bytes()).hexdigest() - for p in sorted(staged.rglob("*")) if p.is_file()}, - }, indent=2) + "\n") - destination.parent.mkdir(parents=True, exist_ok=True) - shutil.copytree(staged, destination) - print(f"Captured {len(rows)} notes and {len(blobs)} blobs in {destination}") - finally: - if process.poll() is None: - process.terminate() - try: - process.wait(timeout=5) - except subprocess.TimeoutExpired: - process.kill() - process.wait() - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("binary", type=Path) - parser.add_argument("destination", type=Path) - args = parser.parse_args() - capture(args.binary, args.destination) diff --git a/tools/capture-screenshots.sh b/tools/capture-screenshots.sh deleted file mode 100755 index 3f997b8..0000000 --- a/tools/capture-screenshots.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash -# Captures the website/README screenshots from the real app with the sample -# library, in stock Omarchy themes. Usage: tools/capture-screenshots.sh BUILD_DIR -set -euo pipefail - -build_dir="$(realpath "${1:?usage: capture-screenshots.sh BUILD_DIR}")" -project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -out="$project_dir/docs/images" -themes="${OMARCHY_PATH:-/usr/share/omarchy}/themes" -work="$(mktemp -d)" -trap 'rm -rf "$work"' EXIT -mkdir -p "$out" - -shot() { # name theme gallery view - local name="$1" theme="$2" gallery="$3" view="$4" - local home="$work/$name" - mkdir -p "$home/config/omarchy-notes" "$home/runtime" - chmod 700 "$home/runtime" - printf '[list]\ngallery=%s\nview=%s\n' "$gallery" "$view" > "$home/config/omarchy-notes/settings.ini" - env -u QT_QPA_PLATFORMTHEME -u HYPRLAND_INSTANCE_SIGNATURE \ - QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software \ - XDG_CONFIG_HOME="$home/config" XDG_RUNTIME_DIR="$home/runtime" \ - OMARCHY_NOTES_THEME_DIR="$themes/$theme" \ - ONOTES_SCREENSHOT="$out/$name.png" \ - "$build_dir/src/app/omarchy-notes" --data-dir "$home/library" --samples >/dev/null - echo "wrote docs/images/$name.png ($theme)" -} - -shot screenshot-dark kanagawa false all -shot screenshot-light catppuccin-latte false all -shot screenshot-gallery rose-pine true all