diff --git a/.claude/hooks/stop-check.sh b/.claude/hooks/stop-check.sh index f78831e..68dcb0c 100755 --- a/.claude/hooks/stop-check.sh +++ b/.claude/hooks/stop-check.sh @@ -6,7 +6,8 @@ if [ -f Cargo.toml ]; then out=$(cargo clippy --workspace --all-targets -q -- -D warnings 2>&1) || fail clippy "$out" out=$(cargo test --workspace -q 2>&1) || fail "cargo test" "$out" fi -if [ -f app/pubspec.yaml ] && command -v flutter >/dev/null; then - out=$(cd app && flutter analyze 2>&1) || fail "flutter analyze" "$out" +if [ -f app/pubspec.yaml ] && command -v dart >/dev/null; then + # dart analyze: flutter analyze crashes on non-ASCII project paths. + out=$(cd app && dart analyze 2>&1) || fail "dart analyze" "$out" fi exit 0 diff --git a/CLAUDE.md b/CLAUDE.md index fc9c60f..d7d427a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,11 +8,14 @@ and an optional self-hosted sync server. Local-only (standalone graph) or client ## Commands - Format: `cargo fmt --all` (Rust), `dart format app/` (Flutter) -- Lint: `cargo clippy --workspace --all-targets -- -D warnings`, `cd app && flutter analyze` +- Lint: `cargo clippy --workspace --all-targets -- -D warnings`, `cd app && dart analyze` + (`flutter analyze` crashes on non-ASCII paths like `Darío/`) - Test: `cargo test --workspace`, `cd app && flutter test` - Run server: `cargo run -p synapse-server` -- Run app: `cd app && flutter run -d linux` (or `-d windows`, an Android device) -- Regenerate FFI bindings: `cd app && flutter_rust_bridge_codegen generate` +- Run app: `cd app && flutter run -d linux` (or `-d windows`, an Android device); Flutter SDK + in `~/development/flutter/bin`. Graph dir override: `SYNAPSE_GRAPH=/path`. See `docs/app.md`. +- Regenerate FFI bindings: `cd app && flutter_rust_bridge_codegen generate` (frb 2.13.0; commit + the generated Rust and Dart files) ## Architecture Cargo workspace under `crates/`, Flutter app under `app/`. Details in `docs/architecture.md`, @@ -28,6 +31,8 @@ roadmap in `docs/plan.md`. ## Conventions - The Flutter app never touches storage directly; everything goes through `synapse-ffi`. + UI code depends on the `GraphBackend` interface, not the generated FFI class (tests use an + in-memory backend). - Core crates are sync-free of UI concerns and must compile for Android (no desktop-only deps in `synapse-core`). - IDs are UUIDv7 (time-ordered). Journals are keyed by local date `YYYY-MM-DD`. diff --git a/Cargo.lock b/Cargo.lock index 6db513a..d79aaf3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "addr2line" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +dependencies = [ + "gimli", +] + [[package]] name = "adler2" version = "2.0.1" @@ -17,12 +26,40 @@ dependencies = [ "memchr", ] +[[package]] +name = "allo-isolate" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "449e356a4864c017286dbbec0e12767ea07efba29e3b7d984194c2a7ff3c4550" +dependencies = [ + "anyhow", + "atomic", + "backtrace", +] + [[package]] name = "allocator-api2" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "android_log-sys" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d" + +[[package]] +name = "android_logger" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbb4e440d04be07da1f1bf44fb4495ebd58669372fe0cffa6e48595ac5bd88a3" +dependencies = [ + "android_log-sys", + "env_filter", + "log", +] + [[package]] name = "android_system_properties" version = "0.1.6" @@ -32,6 +69,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "arc-swap" version = "1.9.3" @@ -68,6 +111,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "atomic" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -80,6 +129,21 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "backtrace" +version = "0.3.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide 0.8.9", + "object", + "rustc-demangle", + "windows-link", +] + [[package]] name = "base64" version = "0.22.1" @@ -126,6 +190,15 @@ dependencies = [ "cpufeatures", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "bon" version = "3.10.2" @@ -160,12 +233,24 @@ dependencies = [ "serde_core", ] +[[package]] +name = "build-target" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "832133bbabbbaa9fbdba793456a2827627a7d2b8fb96032fa1e7666d7895832b" + [[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "byteorder" version = "1.5.0" @@ -243,6 +328,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + [[package]] name = "constant_time_eq" version = "0.4.2" @@ -329,6 +424,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "darling" version = "0.24.1" @@ -363,6 +468,28 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "dart-sys" +version = "4.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57967e4b200d767d091b961d6ab42cc7d0cc14fe9e052e75d0d3cf9eb732d895" +dependencies = [ + "cc", +] + +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + [[package]] name = "deadpool" version = "0.12.3" @@ -421,6 +548,17 @@ dependencies = [ "thiserror", ] +[[package]] +name = "delegate-attr" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a84c9a9c129b98e707ac9a31e204c10c064dd9f949b7da362310ff1a8b137d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "deranged" version = "0.5.9" @@ -430,6 +568,16 @@ dependencies = [ "serde_core", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -473,6 +621,16 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "env_filter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" +dependencies = [ + "log", + "regex", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -538,7 +696,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.9.1", +] + +[[package]] +name = "flutter_rust_bridge" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24a973d15b8fc7de9fb29cdfbec58a2ac41f6252492d3b882abfdc603e32b34f" +dependencies = [ + "allo-isolate", + "android_logger", + "anyhow", + "build-target", + "bytemuck", + "byteorder", + "console_error_panic_hook", + "dart-sys", + "delegate-attr", + "flutter_rust_bridge_macros", + "futures", + "js-sys", + "lazy_static", + "log", + "oslog", + "portable-atomic", + "threadpool", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "flutter_rust_bridge_macros" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901eec2d226107dad1c55b30f7421c4687bebcf70ed43ca44d1b447ca087b238" +dependencies = [ + "hex", + "md-5", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -666,6 +866,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -688,6 +898,12 @@ dependencies = [ "r-efi", ] +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" + [[package]] name = "gix" version = "0.89.0" @@ -1354,6 +1570,12 @@ dependencies = [ "byteorder", ] +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.15.5" @@ -1407,6 +1629,12 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "htmlescape" version = "0.3.1" @@ -1884,6 +2112,16 @@ version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "measure_time" version = "0.9.0" @@ -1914,6 +2152,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", +] + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -1989,6 +2236,15 @@ dependencies = [ "libc", ] +[[package]] +name = "object" +version = "0.37.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2007,6 +2263,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "oslog" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d2043d1f61d77cb2f4b1f7b7b2295f40507f5f8e9d1c8bf10a1ca5f97a3969" +dependencies = [ + "cc", + "dashmap", + "log", +] + [[package]] name = "ownedbytes" version = "0.9.0" @@ -2355,6 +2622,12 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2738,6 +3011,18 @@ dependencies = [ "uuid", ] +[[package]] +name = "synapse-ffi" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "flutter_rust_bridge", + "synapse-core", + "tempfile", + "uuid", +] + [[package]] name = "synapse-history" version = "0.1.0" @@ -2979,6 +3264,15 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + [[package]] name = "time" version = "0.3.55" @@ -3145,6 +3439,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-bom" version = "2.0.3" @@ -3249,6 +3549,12 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "walkdir" version = "2.5.0" diff --git a/LESSONS.md b/LESSONS.md index 8592c36..c01b51c 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -1,3 +1,9 @@ # Lessons Recurring mistakes and how to avoid them. Add an entry when a mistake repeats. + +- `flutter analyze` crashes ("FormatException: Unexpected end of input" from the analysis + server) when the project path has non-ASCII characters (`~/Hacking/Darío/...`). Use + `dart analyze` locally; CI paths are ASCII so `flutter analyze` is fine there. +- Generated FFI types share a namespace with Flutter widgets in Dart: avoid DTO names such as + `PageView`, `Page`, `Route` in `synapse-ffi`. diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..79f7eca --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,48 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Widget Preview related +.widget_preview/ diff --git a/app/.metadata b/app/.metadata new file mode 100644 index 0000000..4494c73 --- /dev/null +++ b/app/.metadata @@ -0,0 +1,36 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "abaf9c523780a608bd46686fd5e53740a07077f8" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + base_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + - platform: android + create_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + base_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + - platform: linux + create_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + base_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + - platform: windows + create_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + base_revision: abaf9c523780a608bd46686fd5e53740a07077f8 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/app/analysis_options.yaml b/app/analysis_options.yaml new file mode 100644 index 0000000..ea6a8f3 --- /dev/null +++ b/app/analysis_options.yaml @@ -0,0 +1,9 @@ +include: package:flutter_lints/flutter.yaml + +analyzer: + exclude: + - build/** + - android/** + - windows/** + - linux/** + - rust_builder/cargokit/** diff --git a/app/android/.gitignore b/app/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/app/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts new file mode 100644 index 0000000..37c27c0 --- /dev/null +++ b/app/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "es.zenvairo.synapse" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "es.zenvairo.synapse" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION + // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) + // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` + // flag during build. + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/app/android/app/src/debug/AndroidManifest.xml b/app/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/app/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..7620421 --- /dev/null +++ b/app/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/app/android/app/src/main/kotlin/es/zenvairo/synapse/MainActivity.kt b/app/android/app/src/main/kotlin/es/zenvairo/synapse/MainActivity.kt new file mode 100644 index 0000000..395e4e1 --- /dev/null +++ b/app/android/app/src/main/kotlin/es/zenvairo/synapse/MainActivity.kt @@ -0,0 +1,5 @@ +package es.zenvairo.synapse + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/app/android/app/src/main/res/drawable-v21/launch_background.xml b/app/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/app/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/drawable/launch_background.xml b/app/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/app/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/values-night/styles.xml b/app/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/app/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/android/app/src/main/res/values/styles.xml b/app/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/app/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/android/app/src/profile/AndroidManifest.xml b/app/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/app/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/android/build.gradle.kts b/app/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/app/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/app/android/gradle.properties b/app/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/app/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/app/android/gradle/wrapper/gradle-wrapper.properties b/app/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a20f2c4 --- /dev/null +++ b/app/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip diff --git a/app/android/settings.gradle.kts b/app/android/settings.gradle.kts new file mode 100644 index 0000000..b28021a --- /dev/null +++ b/app/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false +} + +include(":app") diff --git a/app/assets/fonts/Inter-Bold.ttf b/app/assets/fonts/Inter-Bold.ttf new file mode 100644 index 0000000..9fb9b75 Binary files /dev/null and b/app/assets/fonts/Inter-Bold.ttf differ diff --git a/app/assets/fonts/Inter-BoldItalic.ttf b/app/assets/fonts/Inter-BoldItalic.ttf new file mode 100644 index 0000000..8d05000 Binary files /dev/null and b/app/assets/fonts/Inter-BoldItalic.ttf differ diff --git a/app/assets/fonts/Inter-Italic.ttf b/app/assets/fonts/Inter-Italic.ttf new file mode 100644 index 0000000..e7ed211 Binary files /dev/null and b/app/assets/fonts/Inter-Italic.ttf differ diff --git a/app/assets/fonts/Inter-Medium.ttf b/app/assets/fonts/Inter-Medium.ttf new file mode 100644 index 0000000..458cd06 Binary files /dev/null and b/app/assets/fonts/Inter-Medium.ttf differ diff --git a/app/assets/fonts/Inter-OFL.txt b/app/assets/fonts/Inter-OFL.txt new file mode 100644 index 0000000..9b2ca37 --- /dev/null +++ b/app/assets/fonts/Inter-OFL.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/assets/fonts/Inter-Regular.ttf b/app/assets/fonts/Inter-Regular.ttf new file mode 100644 index 0000000..b7aaca8 Binary files /dev/null and b/app/assets/fonts/Inter-Regular.ttf differ diff --git a/app/assets/fonts/Inter-SemiBold.ttf b/app/assets/fonts/Inter-SemiBold.ttf new file mode 100644 index 0000000..47f8ab1 Binary files /dev/null and b/app/assets/fonts/Inter-SemiBold.ttf differ diff --git a/app/assets/fonts/NotoSerif-OFL.txt b/app/assets/fonts/NotoSerif-OFL.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/app/assets/fonts/NotoSerif-OFL.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/app/assets/fonts/NotoSerif-Variable.ttf b/app/assets/fonts/NotoSerif-Variable.ttf new file mode 100644 index 0000000..2c49f57 Binary files /dev/null and b/app/assets/fonts/NotoSerif-Variable.ttf differ diff --git a/app/assets/fonts/SourceCodePro-OFL.md b/app/assets/fonts/SourceCodePro-OFL.md new file mode 100644 index 0000000..70288a8 --- /dev/null +++ b/app/assets/fonts/SourceCodePro-OFL.md @@ -0,0 +1,93 @@ +© 2023 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/assets/fonts/SourceCodePro-Regular.otf b/app/assets/fonts/SourceCodePro-Regular.otf new file mode 100644 index 0000000..16c7b0b Binary files /dev/null and b/app/assets/fonts/SourceCodePro-Regular.otf differ diff --git a/app/assets/fonts/SourceCodePro-Semibold.otf b/app/assets/fonts/SourceCodePro-Semibold.otf new file mode 100644 index 0000000..11e64fb Binary files /dev/null and b/app/assets/fonts/SourceCodePro-Semibold.otf differ diff --git a/app/flutter_rust_bridge.yaml b/app/flutter_rust_bridge.yaml new file mode 100644 index 0000000..bad4d6e --- /dev/null +++ b/app/flutter_rust_bridge.yaml @@ -0,0 +1,3 @@ +rust_input: crate::api +rust_root: ../crates/synapse-ffi/ +dart_output: lib/src/rust diff --git a/app/lib/main.dart b/app/lib/main.dart new file mode 100644 index 0000000..1a1e79b --- /dev/null +++ b/app/lib/main.dart @@ -0,0 +1,24 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import 'src/app.dart'; +import 'src/backend/graph_backend.dart'; +import 'src/editor/block_row.dart' as editor; +import 'src/rust/frb_generated.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await RustLib.init(); + editor.openUrl = (url) { + final uri = Uri.tryParse(url); + if (uri != null) launchUrl(uri, mode: LaunchMode.externalApplication); + }; + final dir = + Platform.environment['SYNAPSE_GRAPH'] ?? + '${(await getApplicationSupportDirectory()).path}${Platform.pathSeparator}graph'; + final backend = await FfiGraphBackend.open(dir); + runApp(SynapseApp(backend: backend)); +} diff --git a/app/lib/src/app.dart b/app/lib/src/app.dart new file mode 100644 index 0000000..982cad8 --- /dev/null +++ b/app/lib/src/app.dart @@ -0,0 +1,42 @@ +import 'package:flutter/material.dart'; + +import 'backend/graph_backend.dart'; +import 'state/app_state.dart'; +import 'theme/theme.dart'; +import 'views/shell.dart'; + +class SynapseApp extends StatefulWidget { + const SynapseApp({super.key, required this.backend}); + final GraphBackend backend; + + @override + State createState() => _SynapseAppState(); +} + +class _SynapseAppState extends State { + late final AppState _state = AppState(widget.backend)..loadRecent(); + + @override + void dispose() { + _state.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AppScope( + state: _state, + child: ListenableBuilder( + listenable: _state, + builder: (context, _) => MaterialApp( + title: 'Synapse', + debugShowCheckedModeBanner: false, + theme: buildTheme(Brightness.light), + darkTheme: buildTheme(Brightness.dark), + themeMode: _state.themeMode, + home: const Shell(), + ), + ), + ); + } +} diff --git a/app/lib/src/backend/graph_backend.dart b/app/lib/src/backend/graph_backend.dart new file mode 100644 index 0000000..be4a4ec --- /dev/null +++ b/app/lib/src/backend/graph_backend.dart @@ -0,0 +1,148 @@ +import '../rust/api/dto.dart'; +import '../rust/api/graph.dart'; + +export '../rust/api/dto.dart'; + +/// What the UI needs from a graph. [FfiGraphBackend] talks to the Rust core; tests use an +/// in-memory implementation. Keeping the UI on this interface (instead of the generated +/// opaque class) is what makes the editor testable without the native library. +abstract class GraphBackend { + /// Today's date in the graph clock, `YYYY-MM-DD`. + String today(); + + Future> journals({String? before, required int limit}); + Future journal(String date); + Future page(String id); + Future pageByTitle(String title); + + /// Page by title or alias, created if missing. + Future openPage(String title); + Future> listPages({ + bool includeJournals = false, + required int limit, + int offset = 0, + }); + Future renamePage(String id, String newTitle); + Future deletePage(String id); + Future addAlias(String pageId, String alias); + Future removeAlias(String alias); + + Future insertBlock(String pageId, Place place, String content); + Future updateBlock(String id, String content); + Future setCollapsed(String id, bool collapsed); + Future> deleteBlock(String id); + Future> moveBlock(String id, String pageId, Place place); + Future> indentBlock(String id); + Future> outdentBlock(String id); + Future> mergeBlock(String id, String into); + Future> outline(String pageId); + + Future> backlinks(String pageId); + Future> related(String pageId, {int limit = 12}); + Future recordVisit(String? from, String to); + Future blockRef(String id); + Future timeline(String from, String to); + + Future> searchTitles(String query, {int limit = 20}); + Future> searchBlocks(String query, {int limit = 20}); + + /// Local path of an `asset://` blob, if present. + String? assetPath(String hash); + Future putAssetFile(String path, {String? mime}); +} + +class FfiGraphBackend implements GraphBackend { + FfiGraphBackend(this._g); + + final SynapseGraph _g; + + static Future open(String dir) async => + FfiGraphBackend(await SynapseGraph.open(dir: dir)); + + @override + String today() => _g.today(); + + @override + Future> journals({String? before, required int limit}) => + _g.journals(before: before, limit: limit); + @override + Future journal(String date) => _g.journal(date: date); + @override + Future page(String id) => _g.page(id: id); + @override + Future pageByTitle(String title) => _g.pageByTitle(title: title); + @override + Future openPage(String title) => _g.openPage(title: title); + @override + Future> listPages({ + bool includeJournals = false, + required int limit, + int offset = 0, + }) => _g.listPages( + includeJournals: includeJournals, + limit: limit, + offset: offset, + ); + @override + Future renamePage(String id, String newTitle) => + _g.renamePage(id: id, newTitle: newTitle); + @override + Future deletePage(String id) => _g.deletePage(id: id); + @override + Future addAlias(String pageId, String alias) => + _g.addAlias(pageId: pageId, alias: alias); + @override + Future removeAlias(String alias) => _g.removeAlias(alias: alias); + + @override + Future insertBlock(String pageId, Place place, String content) => + _g.insertBlock(pageId: pageId, place: place, content: content); + @override + Future updateBlock(String id, String content) => + _g.updateBlock(id: id, content: content); + @override + Future setCollapsed(String id, bool collapsed) => + _g.setCollapsed(id: id, collapsed: collapsed); + @override + Future> deleteBlock(String id) => _g.deleteBlock(id: id); + @override + Future> moveBlock(String id, String pageId, Place place) => + _g.moveBlock(id: id, pageId: pageId, place: place); + @override + Future> indentBlock(String id) => _g.indentBlock(id: id); + @override + Future> outdentBlock(String id) => _g.outdentBlock(id: id); + @override + Future> mergeBlock(String id, String into) => + _g.mergeBlock(id: id, into: into); + @override + Future> outline(String pageId) => _g.outline(pageId: pageId); + + @override + Future> backlinks(String pageId) => + _g.backlinks(pageId: pageId); + @override + Future> related(String pageId, {int limit = 12}) => + _g.related(pageId: pageId, limit: limit); + @override + Future recordVisit(String? from, String to) => + _g.recordVisit(from: from, to: to); + @override + Future blockRef(String id) => _g.blockRef(id: id); + @override + Future timeline(String from, String to) => + _g.timeline(from: from, to: to); + + @override + Future> searchTitles(String query, {int limit = 20}) => + _g.searchTitles(query: query, limit: limit); + @override + Future> searchBlocks(String query, {int limit = 20}) => + _g.searchBlocks(query: query, limit: limit); + + @override + String? assetPath(String hash) => _g.assetPath(hash: hash); + @override + Future putAssetFile(String path, {String? mime}) => + _g.putAssetFile(path: path, mime: mime); +} diff --git a/app/lib/src/editor/block_row.dart b/app/lib/src/editor/block_row.dart new file mode 100644 index 0000000..127b2e5 --- /dev/null +++ b/app/lib/src/editor/block_row.dart @@ -0,0 +1,879 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; + +import '../backend/graph_backend.dart'; +import '../state/app_state.dart'; +import '../state/outline_controller.dart'; +import '../state/outline_ops.dart'; +import '../theme/theme.dart'; +import 'completion.dart'; +import 'markdown.dart'; + +const indentWidth = 24.0; +const _gutter = 18.0; +const _bulletBox = 18.0; + +/// What a bullet drag carries. +class BlockDrag { + const BlockDrag(this.controller, this.node); + final OutlineController controller; + final OutlineNode node; +} + +enum _Drop { before, after, child } + +/// One outline row: guides, collapse arrow, bullet (drag handle) and the block itself, +/// rendered when idle and a raw-Markdown editor when focused. +class BlockRow extends StatefulWidget { + const BlockRow({ + super.key, + required this.controller, + required this.node, + required this.editing, + required this.hasChildren, + }); + + final OutlineController controller; + final OutlineNode node; + final bool editing; + final bool hasChildren; + + @override + State createState() => _BlockRowState(); +} + +class _BlockRowState extends State { + bool _hover = false; + _Drop? _drop; + + OutlineController get c => widget.controller; + OutlineNode get n => widget.node; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + final depth = n.depth; + final lineH = blockFontSize * blockLineHeight; + return DragTarget( + onWillAcceptWithDetails: (d) => + d.data.controller == c && d.data.node != n, + onMove: (d) => _updateDrop(d.offset), + onLeave: (_) => setState(() => _drop = null), + onAcceptWithDetails: (d) { + final drop = _drop; + setState(() => _drop = null); + if (drop == null) return; + c.moveTo(d.data.node, switch (drop) { + _Drop.before => PlaceKind.before, + _Drop.after => PlaceKind.after, + _Drop.child => PlaceKind.firstChildOf, + }, n); + }, + builder: (context, _, _) => MouseRegion( + onEnter: (_) => setState(() => _hover = true), + onExit: (_) => setState(() => _hover = false), + child: CustomPaint( + painter: _GuidesPainter(depth, colors.line, _drop, colors.accent), + child: Padding( + padding: EdgeInsets.only(left: depth * indentWidth), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: _gutter, + height: lineH + 4, + child: (widget.hasChildren && (_hover || n.collapsed)) + ? _Arrow( + collapsed: n.collapsed, + onTap: () => c.toggleCollapsed(n), + ) + : null, + ), + _bullet(colors, lineH), + const SizedBox(width: 6), + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: widget.editing + ? BlockEditor( + key: ValueKey('edit-${identityHashCode(n)}'), + controller: c, + node: n, + ) + : BlockView(controller: c, node: n), + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _bullet(SynapseColors colors, double lineH) { + final collapsedWithKids = n.collapsed && widget.hasChildren; + final dot = SizedBox( + width: _bulletBox, + height: lineH + 4, + child: Center( + child: AnimatedContainer( + duration: const Duration(milliseconds: 120), + width: 16, + height: 16, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: collapsedWithKids ? colors.line : Colors.transparent, + ), + child: Center( + child: Container( + width: 6, + height: 6, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: _hover ? colors.muted : colors.faint, + ), + ), + ), + ), + ), + ); + return Draggable( + data: BlockDrag(c, n), + dragAnchorStrategy: pointerDragAnchorStrategy, + feedback: _DragFeedback(text: n.content), + childWhenDragging: Opacity(opacity: 0.3, child: dot), + child: MouseRegion( + cursor: SystemMouseCursors.grab, + child: GestureDetector( + onTap: widget.hasChildren ? () => c.toggleCollapsed(n) : null, + child: dot, + ), + ), + ); + } + + void _updateDrop(Offset global) { + final box = context.findRenderObject() as RenderBox?; + if (box == null) return; + final p = box.globalToLocal(global); + final contentX = n.depth * indentWidth + _gutter + _bulletBox; + final _Drop d; + if (p.dy < box.size.height / 2) { + d = _Drop.before; + } else { + // Below an expanded parent the gap is above its first child: drop there. + final expandedParent = widget.hasChildren && !n.collapsed; + d = expandedParent || p.dx > contentX + 28 ? _Drop.child : _Drop.after; + } + if (d != _drop) setState(() => _drop = d); + } +} + +class _Arrow extends StatelessWidget { + const _Arrow({required this.collapsed, required this.onTap}); + final bool collapsed; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) => MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: onTap, + child: Center( + child: AnimatedRotation( + turns: collapsed ? 0 : 0.25, + duration: const Duration(milliseconds: 140), + child: Icon( + Icons.chevron_right_rounded, + size: 16, + color: context.colors.faint, + ), + ), + ), + ), + ); +} + +class _DragFeedback extends StatelessWidget { + const _DragFeedback({required this.text}); + final String text; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return Material( + color: Colors.transparent, + child: Container( + constraints: const BoxConstraints(maxWidth: 320), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: colors.paper, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: colors.line), + boxShadow: [ + BoxShadow( + color: Colors.black.withAlpha(0x22), + blurRadius: 16, + offset: const Offset(0, 6), + ), + ], + ), + child: Text( + text.split('\n').first, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: colors.ink), + ), + ), + ); + } +} + +/// Vertical indent guides plus the drop indicator. +class _GuidesPainter extends CustomPainter { + _GuidesPainter(this.depth, this.color, this.drop, this.accent); + final int depth; + final Color color; + final _Drop? drop; + final Color accent; + + @override + void paint(Canvas canvas, Size size) { + final p = Paint() + ..color = color + ..strokeWidth = 1; + for (var k = 0; k < depth; k++) { + final x = k * indentWidth + _gutter + _bulletBox / 2; + canvas.drawLine(Offset(x, 0), Offset(x, size.height), p); + } + if (drop != null) { + final a = Paint() + ..color = accent + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round; + var x = depth * indentWidth + _gutter; + if (drop == _Drop.child) x += indentWidth; + final y = drop == _Drop.before ? 1.0 : size.height - 1; + canvas.drawLine(Offset(x, y), Offset(size.width - 8, y), a); + } + } + + @override + bool shouldRepaint(_GuidesPainter old) => + old.depth != depth || + old.drop != drop || + old.color != color || + old.accent != accent; +} + +TextStyle blockTextStyle(BuildContext context) => TextStyle( + fontFamily: uiFont, + fontSize: blockFontSize, + height: blockLineHeight, + color: context.colors.ink, +); + +/// Rendered (read) mode of a block. A tap places the caret at the matching source offset. +class BlockView extends StatefulWidget { + const BlockView({super.key, required this.controller, required this.node}); + final OutlineController controller; + final OutlineNode node; + + @override + State createState() => _BlockViewState(); +} + +class _BlockViewState extends State { + final _key = GlobalKey(); + RenderedBlock? _rendered; + String? _renderedFor; + Object? _renderedTheme; + double _width = 0; + + @override + void dispose() { + _rendered?.dispose(); + super.dispose(); + } + + RenderedBlock _render(BuildContext context, double width) { + final content = widget.node.content; + final theme = Theme.of(context); + if (_rendered != null && + _renderedFor == content && + _renderedTheme == theme && + _width == width) { + return _rendered!; + } + _rendered?.dispose(); + final app = AppScope.read(context); + final ctx = RenderContext( + colors: context.colors, + base: blockTextStyle(context), + refs: app.refs, + assetPath: app.backend.assetPath, + onPage: app.openTitle, + onBlockRef: (r) => app.openId(r.pageId), + onUrl: openUrl, + onToggleTodo: () => widget.controller.cycleTodo(widget.node), + maxWidth: width, + ); + _renderedFor = content; + _renderedTheme = theme; + _width = width; + return _rendered = BlockRenderer(ctx).render(content); + } + + void _tap(TapUpDetails d) { + final rp = _key.currentContext?.findRenderObject(); + var caret = widget.node.content.length; + if (rp is RenderParagraph && _rendered != null) { + final local = rp.globalToLocal(d.globalPosition); + if (local.dy <= rp.size.height) { + caret = _rendered!.toSource(rp.getPositionForOffset(local).offset); + } + } + widget.controller.focus(widget.node.id, caret: caret); + } + + @override + Widget build(BuildContext context) { + final app = AppScope.read(context); + final hasRef = widget.node.content.contains('(('); + Widget build(double width) { + final r = _render(context, width); + return Text.rich(r.span, key: _key); + } + + return LayoutBuilder( + builder: (context, box) => MouseRegion( + cursor: SystemMouseCursors.text, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTapUp: _tap, + child: ConstrainedBox( + constraints: const BoxConstraints( + minHeight: blockFontSize * blockLineHeight, + ), + child: hasRef + ? ListenableBuilder( + listenable: app.refs, + builder: (context, _) { + _renderedFor = null; + return build(box.maxWidth); + }, + ) + : build(box.maxWidth), + ), + ), + ), + ); + } +} + +/// Opens an external link. Replaced at startup with a platform launcher. +void Function(String url) openUrl = (url) {}; + +/// Edit mode of a block: raw Markdown with outliner key handling and autocomplete. +class BlockEditor extends StatefulWidget { + const BlockEditor({super.key, required this.controller, required this.node}); + final OutlineController controller; + final OutlineNode node; + + @override + State createState() => _BlockEditorState(); +} + +class _BlockEditorState extends State { + late final TextEditingController _text; + late final FocusNode _focus; + final _fieldKey = GlobalKey(); + final _link = LayerLink(); + final _portal = OverlayPortalController(); + TextEditingValue _last = TextEditingValue.empty; + bool _allowNewline = false; + + CompletionQuery? _query; + List _items = const []; + int _selected = 0; + int _searchSeq = 0; + + OutlineController get c => widget.controller; + OutlineNode get n => widget.node; + + @override + void initState() { + super.initState(); + final caret = (c.pendingCaret ?? n.content.length).clamp( + 0, + n.content.length, + ); + c.pendingCaret = null; + _text = TextEditingController.fromValue( + TextEditingValue( + text: n.content, + selection: TextSelection.collapsed(offset: caret), + ), + ); + _last = _text.value; + _focus = FocusNode(debugLabel: 'block', onKeyEvent: _onKey); + _focus.addListener(_focusChanged); + c.addListener(_controllerChanged); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) _focus.requestFocus(); + }); + } + + @override + void dispose() { + c.removeListener(_controllerChanged); + _focus.removeListener(_focusChanged); + _focus.dispose(); + _text.dispose(); + super.dispose(); + } + + void _focusChanged() { + if (!_focus.hasFocus) { + _closeCompletion(); + // Defer: focus may be moving to another block of the same outline. + scheduleMicrotask(() { + if (mounted && !_focus.hasFocus) c.blurred(n.id); + }); + } + } + + /// Applies caret requests and external content changes (merges, todo toggles). + void _controllerChanged() { + if (!mounted || c.focusedId != n.id) return; + final caret = c.pendingCaret; + if (n.content != _text.text || caret != null) { + c.pendingCaret = null; + final off = (caret ?? _text.selection.extentOffset).clamp( + 0, + n.content.length, + ); + _text.value = TextEditingValue( + text: n.content, + selection: TextSelection.collapsed(offset: off), + ); + _last = _text.value; + } + if (!_focus.hasFocus) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && c.focusedId == n.id) _focus.requestFocus(); + }); + } + } + + void _onChanged(String _) { + var v = _text.value; + // A newline that did not come from Shift+Enter (soft keyboards send Enter as text): + // split the block instead. + if (!_allowNewline && + v.text.length == _last.text.length + 1 && + v.selection.isCollapsed && + v.selection.baseOffset > 0 && + v.text[v.selection.baseOffset - 1] == '\n') { + final at = v.selection.baseOffset - 1; + final restored = v.text.substring(0, at) + v.text.substring(at + 1); + c.setText(n, restored); + c.split(n, at); + return; + } + _allowNewline = false; + final paired = autoPair(_last, v); + if (paired != null) { + _text.value = paired; + v = paired; + } + _last = v; + c.setText(n, v.text); + _updateCompletion(); + } + + // -------------------------------------------------------- completion + + void _updateCompletion() { + final sel = _text.selection; + final q = sel.isCollapsed + ? detectCompletion(_text.text, sel.baseOffset) + : null; + if (q == null || (q.kind == CompletionKind.tag && q.query.isEmpty)) { + _closeCompletion(); + return; + } + if (q == _query) return; + _query = q; + final seq = ++_searchSeq; + final backend = c.backend; + Future> search() async { + if (q.kind == CompletionKind.block) { + final hits = await backend.searchBlocks(q.query, limit: 8); + return [ + for (final h in hits) + if (h.id != n.id) + CompletionItem( + h.content.split('\n').first, + h.id, + detail: h.pageTitle, + ), + ]; + } + final hits = await backend.searchTitles(q.query, limit: 8); + final items = [ + for (final h in hits) + CompletionItem(h.title, h.title, detail: h.isAlias ? 'alias' : null), + ]; + final query = q.query.trim(); + if (query.isNotEmpty && + !items.any((i) => i.value.toLowerCase() == query.toLowerCase())) { + items.add(CompletionItem(query, query, isNew: true)); + } + return items; + } + + search().then((items) { + if (!mounted || seq != _searchSeq) return; + setState(() { + _items = items; + _selected = 0; + }); + if (items.isEmpty) { + _portal.hide(); + } else { + _portal.show(); + } + }, onError: (Object _) {}); + } + + void _closeCompletion() { + _searchSeq++; + _query = null; + if (_items.isNotEmpty && mounted) setState(() => _items = const []); + if (_portal.isShowing) _portal.hide(); + } + + bool get _completing => _query != null && _items.isNotEmpty; + + void _accept(int i) { + final q = _query; + if (q == null || i >= _items.length) return; + final v = applyCompletion(_text.text, q, _items[i]); + _closeCompletion(); + _text.value = v; + _last = v; + c.setText(n, v.text); + } + + // -------------------------------------------------------------- keys + + RenderEditable? _editable() { + RenderEditable? found; + void visit(RenderObject o) { + if (found != null) return; + if (o is RenderEditable) { + found = o; + return; + } + o.visitChildren(visit); + } + + final ro = _fieldKey.currentContext?.findRenderObject(); + if (ro != null) visit(ro); + return found; + } + + /// Whether the caret is on the first (or last) visual line, wrapping included. + bool _onEdgeLine({required bool top}) { + final re = _editable(); + if (re == null || !re.hasSize) return true; + final caret = _text.selection.extentOffset; + final rect = re.getLocalRectForCaret(TextPosition(offset: caret)); + final lh = re.preferredLineHeight; + return top ? rect.top < lh * 0.5 : rect.bottom > re.size.height - lh * 0.5; + } + + int get _column { + final caret = _text.selection.extentOffset; + final lineStart = + _text.text.lastIndexOf('\n', caret == 0 ? 0 : caret - 1) + 1; + return caret - lineStart; + } + + KeyEventResult _onKey(FocusNode _, KeyEvent e) { + if (e is! KeyDownEvent && e is! KeyRepeatEvent) { + return KeyEventResult.ignored; + } + final kb = HardwareKeyboard.instance; + final shift = kb.isShiftPressed; + final ctrl = kb.isControlPressed || kb.isMetaPressed; + final alt = kb.isAltPressed; + final key = e.logicalKey; + final sel = _text.selection; + final collapsed = sel.isValid && sel.isCollapsed; + final caret = sel.isValid ? sel.extentOffset : _text.text.length; + final len = _text.text.length; + + if (_completing) { + if (key == LogicalKeyboardKey.arrowDown) { + setState(() => _selected = (_selected + 1) % _items.length); + return KeyEventResult.handled; + } + if (key == LogicalKeyboardKey.arrowUp) { + setState( + () => _selected = (_selected - 1 + _items.length) % _items.length, + ); + return KeyEventResult.handled; + } + if (key == LogicalKeyboardKey.enter || + key == LogicalKeyboardKey.numpadEnter || + key == LogicalKeyboardKey.tab) { + _accept(_selected); + return KeyEventResult.handled; + } + if (key == LogicalKeyboardKey.escape) { + _closeCompletion(); + return KeyEventResult.handled; + } + // Moving the caret elsewhere ends the completion. + if (key == LogicalKeyboardKey.arrowLeft || + key == LogicalKeyboardKey.arrowRight || + key == LogicalKeyboardKey.home || + key == LogicalKeyboardKey.end) { + _closeCompletion(); + } + } + + if (key == LogicalKeyboardKey.enter || + key == LogicalKeyboardKey.numpadEnter) { + if (shift) { + _allowNewline = true; + return KeyEventResult.ignored; + } + if (ctrl) { + final shiftBy = c.cycleTodo(n); + c.pendingCaret = (caret + shiftBy).clamp(0, n.content.length); + _controllerChanged(); + return KeyEventResult.handled; + } + if (sel.isValid && !collapsed) { + c.setText(n, _text.text.replaceRange(sel.start, sel.end, '')); + } + c.split(n, sel.isValid ? sel.start : len); + return KeyEventResult.handled; + } + if (key == LogicalKeyboardKey.tab) { + if (shift) { + c.outdent(n, caret: caret); + } else { + c.indent(n, caret: caret); + } + return KeyEventResult.handled; + } + if (key == LogicalKeyboardKey.backspace && + collapsed && + caret == 0 && + !ctrl) { + return c.mergeIntoPrevious(n) + ? KeyEventResult.handled + : KeyEventResult.ignored; + } + if (key == LogicalKeyboardKey.delete && + collapsed && + caret == len && + !ctrl) { + return c.mergeNext(n) ? KeyEventResult.handled : KeyEventResult.ignored; + } + if (key == LogicalKeyboardKey.arrowUp || + key == LogicalKeyboardKey.arrowDown) { + final up = key == LogicalKeyboardKey.arrowUp; + if (alt && shift) { + c.moveAmongSiblings(n, up: up, caret: caret); + return KeyEventResult.handled; + } + if (ctrl && !shift && !alt) { + if (up != n.collapsed && c.hasChildren(n)) c.toggleCollapsed(n); + return KeyEventResult.handled; + } + if (shift || alt || ctrl) return KeyEventResult.ignored; + if (!_onEdgeLine(top: up)) return KeyEventResult.ignored; + final other = up ? c.previousVisible(n) : c.nextVisible(n); + if (other == null) return KeyEventResult.ignored; + final col = _column; + final t = other.content; + final int target; + if (up) { + final ls = t.lastIndexOf('\n') + 1; + target = ls + col.clamp(0, t.length - ls); + } else { + final le = t.indexOf('\n'); + target = col.clamp(0, le < 0 ? t.length : le); + } + c.focus(other.id, caret: target); + return KeyEventResult.handled; + } + if (!shift && !ctrl && !alt && collapsed) { + if (key == LogicalKeyboardKey.arrowLeft && caret == 0) { + final prev = c.previousVisible(n); + if (prev != null) { + c.focus(prev.id, caret: prev.content.length); + return KeyEventResult.handled; + } + } + if (key == LogicalKeyboardKey.arrowRight && caret == len) { + final next = c.nextVisible(n); + if (next != null) { + c.focus(next.id, caret: 0); + return KeyEventResult.handled; + } + } + } + if (key == LogicalKeyboardKey.escape) { + _focus.unfocus(); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + } + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return CompositedTransformTarget( + link: _link, + child: OverlayPortal( + controller: _portal, + overlayChildBuilder: (context) => CompositedTransformFollower( + link: _link, + targetAnchor: Alignment.bottomLeft, + offset: const Offset(0, 4), + child: Align( + alignment: Alignment.topLeft, + child: TextFieldTapRegion( + child: CompletionPopup( + items: _items, + selected: _selected, + kind: _query?.kind ?? CompletionKind.page, + onSelect: _accept, + ), + ), + ), + ), + child: TextField( + key: _fieldKey, + controller: _text, + focusNode: _focus, + onChanged: _onChanged, + maxLines: null, + keyboardType: TextInputType.multiline, + textInputAction: TextInputAction.newline, + style: blockTextStyle(context).copyWith(fontFamily: uiFont), + cursorColor: colors.accent, + cursorWidth: 1.6, + decoration: const InputDecoration.collapsed(hintText: null), + ), + ), + ); + } +} + +class CompletionPopup extends StatelessWidget { + const CompletionPopup({ + super.key, + required this.items, + required this.selected, + required this.kind, + required this.onSelect, + }); + + final List items; + final int selected; + final CompletionKind kind; + final void Function(int) onSelect; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return Material( + color: colors.paper, + elevation: 0, + borderRadius: BorderRadius.circular(10), + child: Container( + width: 340, + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: colors.paper, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: colors.line), + boxShadow: [ + BoxShadow( + color: Colors.black.withAlpha(0x1F), + blurRadius: 24, + offset: const Offset(0, 8), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var i = 0; i < items.length; i++) + MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: () => onSelect(i), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 7, + ), + decoration: BoxDecoration( + color: i == selected ? colors.accentSoft : null, + borderRadius: BorderRadius.circular(7), + ), + child: Row( + children: [ + Icon( + items[i].isNew + ? Icons.add_rounded + : kind == CompletionKind.block + ? Icons.notes_rounded + : kind == CompletionKind.tag + ? Icons.tag_rounded + : Icons.description_outlined, + size: 15, + color: i == selected ? colors.accent : colors.muted, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + items[i].isNew + ? 'New page “${items[i].label}”' + : items[i].label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 13.5, color: colors.ink), + ), + ), + if (items[i].detail != null) ...[ + const SizedBox(width: 8), + Text( + items[i].detail!, + style: TextStyle(fontSize: 12, color: colors.faint), + ), + ], + ], + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/src/editor/completion.dart b/app/lib/src/editor/completion.dart new file mode 100644 index 0000000..486d341 --- /dev/null +++ b/app/lib/src/editor/completion.dart @@ -0,0 +1,147 @@ +import 'package:flutter/services.dart'; + +enum CompletionKind { page, tag, block } + +/// An autocomplete trigger under the caret: `[[query`, `#query` or `((query`. +class CompletionQuery { + const CompletionQuery(this.kind, this.start, this.query); + + final CompletionKind kind; + + /// Index where the query text starts (right after the trigger). + final int start; + final String query; + + @override + bool operator ==(Object other) => + other is CompletionQuery && + other.kind == kind && + other.start == start && + other.query == query; + + @override + int get hashCode => Object.hash(kind, start, query); +} + +/// One suggestion. `value` is the page title or the block id to insert. +class CompletionItem { + const CompletionItem( + this.label, + this.value, { + this.detail, + this.isNew = false, + }); + final String label; + final String value; + final String? detail; + final bool isNew; +} + +bool _ws(String c) => c.trim().isEmpty; + +/// Finds the autocomplete trigger that the caret is in, if any. +CompletionQuery? detectCompletion(String text, int caret) { + if (caret < 0 || caret > text.length) return null; + final lineStart = text.lastIndexOf('\n', caret == 0 ? 0 : caret - 1) + 1; + final before = text.substring(lineStart, caret); + CompletionQuery? best; + void consider(CompletionQuery q) { + if (best == null || q.start > best!.start) best = q; + } + + final link = before.lastIndexOf('[['); + if (link >= 0 && !before.substring(link + 2).contains(']]')) { + consider( + CompletionQuery( + CompletionKind.page, + lineStart + link + 2, + before.substring(link + 2), + ), + ); + } + final ref = before.lastIndexOf('(('); + if (ref >= 0 && !before.substring(ref + 2).contains('))')) { + consider( + CompletionQuery( + CompletionKind.block, + lineStart + ref + 2, + before.substring(ref + 2), + ), + ); + } + final hash = before.lastIndexOf('#'); + if (hash >= 0 && (hash == 0 || _ws(before[hash - 1]))) { + final q = before.substring(hash + 1); + if (!q.startsWith('[') && + !q.contains(RegExp(r'\s')) && + !q.startsWith('#')) { + // A bare `#` followed by a space is a heading, not a tag. + consider(CompletionQuery(CompletionKind.tag, lineStart + hash + 1, q)); + } + } + return best; +} + +/// Text after accepting `item` for `q` (replacing the query text, wherever the caret is). +TextEditingValue applyCompletion( + String text, + CompletionQuery q, + CompletionItem item, +) { + final end = q.start + q.query.length; + if (end > text.length || text.substring(q.start, end) != q.query) { + return TextEditingValue( + text: text, + selection: TextSelection.collapsed(offset: text.length), + ); + } + final head = text.substring(0, q.start); + var tail = text.substring(end); + switch (q.kind) { + case CompletionKind.page: + if (tail.startsWith(']]')) tail = tail.substring(2); + final t = '$head${item.value}]]'; + return TextEditingValue( + text: t + tail, + selection: TextSelection.collapsed(offset: t.length), + ); + case CompletionKind.block: + if (tail.startsWith('))')) tail = tail.substring(2); + final t = '$head${item.value}))'; + return TextEditingValue( + text: t + tail, + selection: TextSelection.collapsed(offset: t.length), + ); + case CompletionKind.tag: + final v = item.value.contains(RegExp(r'\s')) + ? '[[${item.value}]]' + : item.value; + final sep = tail.startsWith(' ') ? '' : ' '; + final t = '$head$v$sep'; + return TextEditingValue( + text: t + tail, + selection: TextSelection.collapsed(offset: t.length), + ); + } +} + +/// Auto-pairs `[[` → `[[]]` and `((` → `(())` right after the second bracket is typed. +TextEditingValue? autoPair(TextEditingValue old, TextEditingValue now) { + if (now.text.length != old.text.length + 1 || !now.selection.isCollapsed) { + return null; + } + final c = now.selection.baseOffset; + if (c < 2) return null; + final typed = now.text[c - 1]; + final close = switch (typed) { + '[' => ']]', + '(' => '))', + _ => null, + }; + if (close == null || now.text[c - 2] != typed) return null; + if (now.text.substring(c).startsWith(close[0])) return null; + return TextEditingValue( + text: now.text.substring(0, c) + close + now.text.substring(c), + selection: TextSelection.collapsed(offset: c), + ); +} diff --git a/app/lib/src/editor/markdown.dart b/app/lib/src/editor/markdown.dart new file mode 100644 index 0000000..d773882 --- /dev/null +++ b/app/lib/src/editor/markdown.dart @@ -0,0 +1,638 @@ +import 'dart:io'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../state/app_state.dart'; +import '../theme/theme.dart'; + +/// Maps a run of rendered text back to its Markdown source, so a tap on rendered text can +/// place the caret at the matching spot of the raw text. +class SourceRun { + const SourceRun( + this.r0, + this.rLen, + this.s0, + this.sLen, { + this.atomic = false, + }); + final int r0; + final int rLen; + final int s0; + final int sLen; + + /// Rendered differently from the source (widgets, resolved refs): maps to its end. + final bool atomic; +} + +/// A rendered block: its span tree, the source mapping and the recognizers to dispose. +class RenderedBlock { + RenderedBlock(this.span, this.runs, this.recognizers); + + final InlineSpan span; + final List runs; + final List recognizers; + + /// Source offset for a rendered text offset. + int toSource(int rendered) { + SourceRun? best; + for (final r in runs) { + if (rendered < r.r0) break; + best = r; + if (rendered < r.r0 + r.rLen) break; + } + if (best == null) return 0; + if (best.atomic) return best.s0 + best.sLen; + final d = (rendered - best.r0).clamp(0, best.sLen); + return best.s0 + d; + } + + void dispose() { + for (final r in recognizers) { + r.dispose(); + } + } +} + +/// Callbacks and context for rendering. +class RenderContext { + const RenderContext({ + required this.colors, + required this.base, + required this.refs, + required this.assetPath, + required this.onPage, + required this.onBlockRef, + required this.onUrl, + this.onToggleTodo, + this.maxWidth = 600, + }); + + final SynapseColors colors; + final TextStyle base; + final BlockRefCache refs; + final String? Function(String hash) assetPath; + final void Function(String title) onPage; + final void Function(BlockRefDtoLike ref) onBlockRef; + final void Function(String url) onUrl; + final VoidCallback? onToggleTodo; + final double maxWidth; +} + +/// The bits of a block ref the renderer needs (keeps this file free of FFI types). +class BlockRefDtoLike { + const BlockRefDtoLike(this.id, this.pageId); + final String id; + final String pageId; +} + +final _marker = RegExp(r'^(TODO|DOING|NOW|LATER|DONE|CANCELED|CANCELLED) '); +final _heading = RegExp(r'^(#{1,6}) '); +final _uuid = RegExp( + r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$', +); +final _property = RegExp(r'^([A-Za-z0-9_\-]+):: ?(.*)$'); + +/// Renders Logseq-flavoured Markdown of one block into a single [InlineSpan] tree. +class BlockRenderer { + BlockRenderer(this.ctx); + + final RenderContext ctx; + final _spans = []; + final _runs = []; + final _recognizers = []; + int _r = 0; + + RenderedBlock render(String src) { + final lines = src.split('\n'); + var off = 0; + var fenceStart = -1; + final fence = StringBuffer(); + for (var li = 0; li < lines.length; li++) { + final line = lines[li]; + final lineStart = off; + off += line.length + 1; + if (fenceStart >= 0) { + if (line.trimLeft().startsWith('```')) { + _codeBlock(fence.toString(), fenceStart, off - 1 - fenceStart); + fenceStart = -1; + fence.clear(); + } else { + if (fence.isNotEmpty) fence.write('\n'); + fence.write(line); + } + continue; + } + if (li > 0) _text('\n', lineStart - 1, ctx.base); + if (line.trimLeft().startsWith('```')) { + fenceStart = lineStart; + continue; + } + _line(line, lineStart, first: li == 0); + } + if (fenceStart >= 0) { + _codeBlock(fence.toString(), fenceStart, src.length - fenceStart); + } + return RenderedBlock( + TextSpan(style: ctx.base, children: List.of(_spans)), + List.of(_runs), + List.of(_recognizers), + ); + } + + void _line(String line, int off, {required bool first}) { + var style = ctx.base; + var i = 0; + if (first) { + final m = _marker.firstMatch(line); + if (m != null) { + final done = m.group(1) == 'DONE'; + final canceled = m.group(1)!.startsWith('CANCEL'); + _atomic(_checkbox(done || canceled), 1, off, m.end); + if (done || canceled) { + style = style.copyWith( + color: ctx.colors.muted, + decoration: TextDecoration.lineThrough, + decorationColor: ctx.colors.faint, + ); + } else if (m.group(1) != 'TODO' && m.group(1) != 'LATER') { + _text( + '${m.group(1)} ', + off, + style.copyWith( + color: ctx.colors.accent, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ); + } + i = m.end; + } + } + final rest = line.substring(i); + final h = _heading.firstMatch(rest); + if (h != null) { + final level = h.group(1)!.length; + const sizes = [26.0, 22.0, 19.0, 17.0, 16.0, 15.0]; + style = style.copyWith( + fontSize: sizes[level - 1], + fontWeight: level <= 2 ? FontWeight.w700 : FontWeight.w600, + height: 1.35, + letterSpacing: level <= 2 ? -0.2 : 0, + ); + _inline(rest.substring(h.end), off + i + h.end, style); + return; + } + final p = _property.firstMatch(rest); + if (p != null) { + final small = style.copyWith(fontSize: 13, color: ctx.colors.muted); + _text( + '${p.group(1)}: ', + off + i, + small.copyWith(fontWeight: FontWeight.w600), + ); + _inline(p.group(2)!, off + i + rest.length - p.group(2)!.length, small); + return; + } + if (rest.startsWith('> ')) { + _atomic( + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Container( + width: 3, + height: 18, + margin: const EdgeInsets.only(right: 8), + color: ctx.colors.line, + ), + ), + 1, + off + i, + 2, + ); + _inline( + rest.substring(2), + off + i + 2, + style.copyWith(color: ctx.colors.muted, fontStyle: FontStyle.italic), + ); + return; + } + final list = RegExp(r'^(\s*)([-*+]|\d+\.) ').firstMatch(rest); + if (list != null) { + final bullet = list.group(2)!.endsWith('.') ? list.group(2)! : '•'; + _atomic( + TextSpan( + text: '${list.group(1)}$bullet ', + style: style.copyWith(color: ctx.colors.muted), + ), + list.group(1)!.length + bullet.length + 1, + off + i, + list.end, + ); + _inline(rest.substring(list.end), off + i + list.end, style); + return; + } + _inline(rest, off + i, style); + } + + void _inline(String s, int off, TextStyle style) { + var i = 0; + var plain = 0; + void flush(int to) { + if (to > plain) _text(s.substring(plain, to), off + plain, style); + } + + bool ws(int k) => k < 0 || k >= s.length || s[k].trim().isEmpty; + + while (i < s.length) { + final c = s[i]; + // `code` + if (c == '`') { + final j = s.indexOf('`', i + 1); + if (j > i + 1) { + flush(i); + _text( + s.substring(i + 1, j), + off + i + 1, + style.copyWith( + fontFamily: monoFont, + fontSize: (style.fontSize ?? blockFontSize) - 1.5, + backgroundColor: ctx.colors.codeBg, + color: ctx.colors.ink, + ), + ); + i = plain = j + 1; + continue; + } + } + // ![alt](src) + if (s.startsWith('![', i)) { + final link = _mdLink(s, i + 1); + if (link != null) { + flush(i); + _atomic(_image(link.$2, link.$1), 1, off + i, link.$3 - i); + i = plain = link.$3; + continue; + } + } + // [[Page]] + if (s.startsWith('[[', i)) { + final close = _findClose(s, i + 2); + if (close != null && close > i + 2) { + flush(i); + final title = s.substring(i + 2, close); + _text( + title, + off + i + 2, + style.copyWith( + color: ctx.colors.accent, + fontWeight: FontWeight.w500, + ), + onTap: () => ctx.onPage(title), + ); + i = plain = close + 2; + continue; + } + } + // ((block ref)) + if (s.startsWith('((', i)) { + final j = s.indexOf('))', i + 2); + if (j > 0 && _uuid.hasMatch(s.substring(i + 2, j))) { + flush(i); + _blockRef(s.substring(i + 2, j), off + i, j + 2 - i, style); + i = plain = j + 2; + continue; + } + } + // #tag, #[[tag]] + if (c == '#' && ws(i - 1) && i + 1 < s.length) { + String? tag; + var end = i; + if (s.startsWith('#[[', i)) { + final close = _findClose(s, i + 3); + if (close != null && close > i + 3) { + tag = s.substring(i + 3, close); + end = close + 2; + } + } else { + var j = i + 1; + while (j < s.length && !_tagStop(s[j])) { + j++; + } + // Trailing punctuation is not part of the tag. + while (j > i + 1 && '.!?;:'.contains(s[j - 1])) { + j--; + } + if (j > i + 1) { + tag = s.substring(i + 1, j); + end = j; + } + } + if (tag != null) { + flush(i); + final t = tag; + final tagStyle = style.copyWith( + color: ctx.colors.accent.withAlpha(0xCC), + ); + if (end - i == t.length + 1) { + _text('#$t', off + i, tagStyle, onTap: () => ctx.onPage(t)); + } else { + _text('#', off + i, tagStyle, onTap: () => ctx.onPage(t)); + _text(t, off + i + 3, tagStyle, onTap: () => ctx.onPage(t)); + } + i = plain = end; + continue; + } + } + // **bold**, __bold__, ~~strike~~, ==highlight== + final pair = s.length > i + 1 ? s.substring(i, i + 2) : ''; + if (pair == '**' || pair == '__' || pair == '~~' || pair == '==') { + final j = s.indexOf(pair, i + 2); + if (j > i + 2) { + flush(i); + final inner = switch (pair) { + '~~' => style.copyWith( + decoration: TextDecoration.lineThrough, + color: ctx.colors.muted, + ), + '==' => style.copyWith(backgroundColor: ctx.colors.highlight), + _ => style.copyWith(fontWeight: FontWeight.w700), + }; + _inline(s.substring(i + 2, j), off + i + 2, inner); + i = plain = j + 2; + continue; + } + } + // *italic*, _italic_ + if ((c == '*' || (c == '_' && ws(i - 1))) && + i + 1 < s.length && + !ws(i + 1)) { + var j = s.indexOf(c, i + 1); + while (j > 0 && (ws(j - 1) || (c == '_' && !ws(j + 1)))) { + j = s.indexOf(c, j + 1); + } + if (j > i + 1) { + flush(i); + _inline( + s.substring(i + 1, j), + off + i + 1, + style.copyWith(fontStyle: FontStyle.italic), + ); + i = plain = j + 1; + continue; + } + } + // [label](url) + if (c == '[') { + final link = _mdLink(s, i); + if (link != null) { + flush(i); + final url = link.$2; + _text( + link.$1, + off + i + 1, + style.copyWith( + color: ctx.colors.accent, + decoration: TextDecoration.underline, + decorationColor: ctx.colors.accent.withAlpha(0x66), + ), + onTap: () => ctx.onUrl(url), + ); + i = plain = link.$3; + continue; + } + } + // bare URL + if ((s.startsWith('https://', i) || s.startsWith('http://', i)) && + ws(i - 1)) { + var j = i; + while (j < s.length && !ws(j)) { + j++; + } + while (j > i && '.,;:!?)'.contains(s[j - 1])) { + j--; + } + flush(i); + final url = s.substring(i, j); + _text( + url, + off + i, + style.copyWith( + color: ctx.colors.accent, + decoration: TextDecoration.underline, + decorationColor: ctx.colors.accent.withAlpha(0x66), + ), + onTap: () => ctx.onUrl(url), + ); + i = plain = j; + continue; + } + i++; + } + flush(s.length); + } + + static bool _tagStop(String ch) => + ch.trim().isEmpty || ',()[]{}"\'`#'.contains(ch); + + /// `[label](target)` starting at `i` (the `[`): (label, target, end). + static (String, String, int)? _mdLink(String s, int i) { + if (i >= s.length || s[i] != '[') return null; + final close = s.indexOf('](', i + 1); + if (close < 0 || s.substring(i + 1, close).contains('\n')) return null; + final end = s.indexOf(')', close + 2); + if (end < 0) return null; + final target = s.substring(close + 2, end).trim(); + if (target.isEmpty || target.contains(' ')) return null; + return (s.substring(i + 1, close), target, end + 1); + } + + /// Index of the `]]` closing a `[[` whose content starts at `from` (nesting aware). + static int? _findClose(String s, int from) { + var depth = 1; + var i = from; + while (i < s.length - 1) { + if (s.startsWith('[[', i)) { + depth++; + i += 2; + } else if (s.startsWith(']]', i)) { + depth--; + if (depth == 0) return i; + i += 2; + } else { + if (s[i] == '\n') return null; + i++; + } + } + return null; + } + + void _text(String t, int s0, TextStyle style, {VoidCallback? onTap}) { + if (t.isEmpty) return; + TapGestureRecognizer? rec; + if (onTap != null) { + rec = TapGestureRecognizer()..onTap = onTap; + _recognizers.add(rec); + } + _spans.add( + TextSpan( + text: t, + style: style, + recognizer: rec, + mouseCursor: rec == null ? null : SystemMouseCursors.click, + ), + ); + _runs.add(SourceRun(_r, t.length, s0, t.length)); + _r += t.length; + } + + void _atomic(InlineSpan span, int rLen, int s0, int sLen) { + _spans.add(span); + _runs.add(SourceRun(_r, rLen, s0, sLen, atomic: true)); + _r += rLen; + } + + void _blockRef(String id, int s0, int sLen, TextStyle style) { + final ref = ctx.refs.get(id); + final String text; + if (ref != null) { + final first = ref.content.split('\n').first.replaceFirst(_marker, ''); + text = first.isEmpty ? '(empty block)' : first; + } else { + text = ctx.refs.isMissing(id) ? '((missing block))' : '…'; + } + TapGestureRecognizer? rec; + if (ref != null) { + rec = TapGestureRecognizer() + ..onTap = () => ctx.onBlockRef(BlockRefDtoLike(ref.id, ref.pageId)); + _recognizers.add(rec); + } + _spans.add( + TextSpan( + text: text, + recognizer: rec, + mouseCursor: rec == null ? null : SystemMouseCursors.click, + style: style.copyWith( + decoration: TextDecoration.underline, + decorationStyle: TextDecorationStyle.dotted, + decorationColor: ctx.colors.ref, + color: ref == null ? ctx.colors.faint : null, + ), + ), + ); + _runs.add(SourceRun(_r, text.length, s0, sLen, atomic: true)); + _r += text.length; + } + + InlineSpan _checkbox(bool checked) { + final c = ctx.colors; + return WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsets.only(right: 7), + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: ctx.onToggleTodo, + child: AnimatedContainer( + duration: const Duration(milliseconds: 140), + width: 15, + height: 15, + decoration: BoxDecoration( + color: checked ? c.done : Colors.transparent, + borderRadius: BorderRadius.circular(4), + border: Border.all( + color: checked ? c.done : c.faint, + width: 1.5, + ), + ), + child: checked + ? Icon(Icons.check_rounded, size: 12, color: c.paper) + : null, + ), + ), + ), + ), + ); + } + + InlineSpan _image(String src, String alt) { + Widget img; + if (src.startsWith('asset://')) { + final path = ctx.assetPath(src.substring(8)); + img = path == null + ? _missing(alt.isEmpty ? 'missing asset' : alt) + : Image.file( + File(path), + fit: BoxFit.contain, + cacheWidth: (ctx.maxWidth * 2).round(), + errorBuilder: (_, _, _) => _missing(alt), + ); + } else if (src.startsWith('http://') || src.startsWith('https://')) { + img = Image.network( + src, + fit: BoxFit.contain, + errorBuilder: (_, _, _) => _missing(alt), + ); + } else { + img = _missing(alt.isEmpty ? src : alt); + } + return WidgetSpan( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: 360, maxWidth: ctx.maxWidth), + child: ClipRRect(borderRadius: BorderRadius.circular(8), child: img), + ), + ), + ); + } + + Widget _missing(String label) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: ctx.colors.surface, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: ctx.colors.line), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.image_not_supported_outlined, + size: 14, + color: ctx.colors.muted, + ), + const SizedBox(width: 6), + Text(label, style: TextStyle(fontSize: 12, color: ctx.colors.muted)), + ], + ), + ); + + void _codeBlock(String code, int s0, int sLen) { + _atomic( + WidgetSpan( + child: Container( + width: ctx.maxWidth, + margin: const EdgeInsets.symmetric(vertical: 2), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: ctx.colors.codeBg, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + code, + style: TextStyle( + fontFamily: monoFont, + fontSize: 13, + height: 1.5, + color: ctx.colors.ink, + ), + ), + ), + ), + 1, + s0, + sLen, + ); + } +} diff --git a/app/lib/src/editor/outline_view.dart b/app/lib/src/editor/outline_view.dart new file mode 100644 index 0000000..6780b1b --- /dev/null +++ b/app/lib/src/editor/outline_view.dart @@ -0,0 +1,91 @@ +import 'package:flutter/material.dart'; + +import '../state/outline_controller.dart'; +import '../state/outline_ops.dart'; +import '../theme/theme.dart'; +import 'block_row.dart'; + +/// The outline of one page as a lazily built sliver (only visible rows are built). +class OutlineSliver extends StatelessWidget { + const OutlineSliver({super.key, required this.controller}); + + final OutlineController controller; + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: controller, + builder: (context, _) { + final nodes = controller.nodes; + if (nodes.isEmpty) { + return SliverToBoxAdapter( + child: _EmptyOutline(onTap: controller.insertFirst), + ); + } + final vis = controller.visible; + final keys = { + for (var k = 0; k < vis.length; k++) nodes[vis[k]]: k, + }; + return SliverList.builder( + itemCount: vis.length, + findChildIndexCallback: (key) => + key is ObjectKey ? keys[key.value] : null, + itemBuilder: (context, k) { + final i = vis[k]; + final n = nodes[i]; + return BlockRow( + key: ObjectKey(n), + controller: controller, + node: n, + editing: controller.focusedId == n.id, + hasChildren: OutlineOps.hasChildren(nodes, i), + ); + }, + ); + }, + ); + } +} + +class _EmptyOutline extends StatelessWidget { + const _EmptyOutline({required this.onTap}); + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return MouseRegion( + cursor: SystemMouseCursors.text, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + children: [ + const SizedBox(width: 18), + SizedBox( + width: 18, + child: Center( + child: Container( + width: 6, + height: 6, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: colors.line, + ), + ), + ), + ), + const SizedBox(width: 6), + Text( + 'Click to start writing…', + style: blockTextStyle(context).copyWith(color: colors.faint), + ), + ], + ), + ), + ), + ); + } +} diff --git a/app/lib/src/rust/api/dto.dart b/app/lib/src/rust/api/dto.dart new file mode 100644 index 0000000..27e62c8 --- /dev/null +++ b/app/lib/src/rust/api/dto.dart @@ -0,0 +1,415 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import + +import '../frb_generated.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; + +// These functions are ignored because they are not marked as `pub`: `new` +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from` + +class AssetDto { + final String hash; + final BigInt size; + final String? mime; + final String? originalName; + + const AssetDto({ + required this.hash, + required this.size, + this.mime, + this.originalName, + }); + + @override + int get hashCode => + hash.hashCode ^ size.hashCode ^ mime.hashCode ^ originalName.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is AssetDto && + runtimeType == other.runtimeType && + hash == other.hash && + size == other.size && + mime == other.mime && + originalName == other.originalName; +} + +/// Blocks of one page referencing the queried page. +class BacklinkGroup { + final String pageId; + final String pageTitle; + final bool isJournal; + final List blocks; + + const BacklinkGroup({ + required this.pageId, + required this.pageTitle, + required this.isJournal, + required this.blocks, + }); + + @override + int get hashCode => + pageId.hashCode ^ + pageTitle.hashCode ^ + isJournal.hashCode ^ + blocks.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is BacklinkGroup && + runtimeType == other.runtimeType && + pageId == other.pageId && + pageTitle == other.pageTitle && + isJournal == other.isJournal && + blocks == other.blocks; +} + +/// One row of the outline, in pre-order. +class BlockDto { + final String id; + final String? parentId; + final int depth; + final String content; + final bool collapsed; + final bool hasChildren; + + const BlockDto({ + required this.id, + this.parentId, + required this.depth, + required this.content, + required this.collapsed, + required this.hasChildren, + }); + + @override + int get hashCode => + id.hashCode ^ + parentId.hashCode ^ + depth.hashCode ^ + content.hashCode ^ + collapsed.hashCode ^ + hasChildren.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is BlockDto && + runtimeType == other.runtimeType && + id == other.id && + parentId == other.parentId && + depth == other.depth && + content == other.content && + collapsed == other.collapsed && + hasChildren == other.hasChildren; +} + +/// `((` autocomplete hit. +class BlockHit { + final String id; + final String content; + final String pageTitle; + + const BlockHit({ + required this.id, + required this.content, + required this.pageTitle, + }); + + @override + int get hashCode => id.hashCode ^ content.hashCode ^ pageTitle.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is BlockHit && + runtimeType == other.runtimeType && + id == other.id && + content == other.content && + pageTitle == other.pageTitle; +} + +/// Target of a `((block ref))`. +class BlockRefDto { + final String id; + final String content; + final String pageId; + final String pageTitle; + + const BlockRefDto({ + required this.id, + required this.content, + required this.pageId, + required this.pageTitle, + }); + + @override + int get hashCode => + id.hashCode ^ content.hashCode ^ pageId.hashCode ^ pageTitle.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is BlockRefDto && + runtimeType == other.runtimeType && + id == other.id && + content == other.content && + pageId == other.pageId && + pageTitle == other.pageTitle; +} + +class EditDto { + final String pageId; + final int edits; + + const EditDto({required this.pageId, required this.edits}); + + @override + int get hashCode => pageId.hashCode ^ edits.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is EditDto && + runtimeType == other.runtimeType && + pageId == other.pageId && + edits == other.edits; +} + +class PageBrief { + final String id; + final String title; + final bool isJournal; + + const PageBrief({ + required this.id, + required this.title, + required this.isJournal, + }); + + @override + int get hashCode => id.hashCode ^ title.hashCode ^ isJournal.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is PageBrief && + runtimeType == other.runtimeType && + id == other.id && + title == other.title && + isJournal == other.isJournal; +} + +/// Everything the page view needs in one call. +class PageData { + final PageDto page; + final List blocks; + final List aliases; + + /// Previous/next existing journal (journal pages only). + final String? prevJournal; + final String? nextJournal; + + const PageData({ + required this.page, + required this.blocks, + required this.aliases, + this.prevJournal, + this.nextJournal, + }); + + @override + int get hashCode => + page.hashCode ^ + blocks.hashCode ^ + aliases.hashCode ^ + prevJournal.hashCode ^ + nextJournal.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is PageData && + runtimeType == other.runtimeType && + page == other.page && + blocks == other.blocks && + aliases == other.aliases && + prevJournal == other.prevJournal && + nextJournal == other.nextJournal; +} + +/// Page header data. +class PageDto { + final String id; + final String title; + + /// Set for journal pages. + final String? journalDate; + + /// Journal day the page was born in. + final String? originJournal; + final PlatformInt64 createdAt; + final PlatformInt64 updatedAt; + + const PageDto({ + required this.id, + required this.title, + this.journalDate, + this.originJournal, + required this.createdAt, + required this.updatedAt, + }); + + @override + int get hashCode => + id.hashCode ^ + title.hashCode ^ + journalDate.hashCode ^ + originJournal.hashCode ^ + createdAt.hashCode ^ + updatedAt.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is PageDto && + runtimeType == other.runtimeType && + id == other.id && + title == other.title && + journalDate == other.journalDate && + originJournal == other.originJournal && + createdAt == other.createdAt && + updatedAt == other.updatedAt; +} + +class Place { + final PlaceKind kind; + final String? anchor; + + const Place({required this.kind, this.anchor}); + + @override + int get hashCode => kind.hashCode ^ anchor.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is Place && + runtimeType == other.runtimeType && + kind == other.kind && + anchor == other.anchor; +} + +/// Where a block goes, relative to `anchor`. +enum PlaceKind { + after, + before, + + /// Last child of `anchor`, or last root block when `anchor` is `None`. + lastChildOf, + + /// First child of `anchor`, or first root block when `anchor` is `None`. + firstChildOf, +} + +class RelatedDto { + final PageBrief page; + final double score; + + const RelatedDto({required this.page, required this.score}); + + @override + int get hashCode => page.hashCode ^ score.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is RelatedDto && + runtimeType == other.runtimeType && + page == other.page && + score == other.score; +} + +class TimelineDayDto { + final String date; + final String? journalId; + + /// Pages born on this day. + final List created; + + /// Pages edited on this day. + final List edited; + + const TimelineDayDto({ + required this.date, + this.journalId, + required this.created, + required this.edited, + }); + + @override + int get hashCode => + date.hashCode ^ journalId.hashCode ^ created.hashCode ^ edited.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is TimelineDayDto && + runtimeType == other.runtimeType && + date == other.date && + journalId == other.journalId && + created == other.created && + edited == other.edited; +} + +/// Timeline slice plus the titles of every page it mentions. +class TimelineDto { + final List days; + final List pages; + + const TimelineDto({required this.days, required this.pages}); + + @override + int get hashCode => days.hashCode ^ pages.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is TimelineDto && + runtimeType == other.runtimeType && + days == other.days && + pages == other.pages; +} + +/// Quick switcher / `[[` autocomplete hit. +class TitleHit { + final String pageId; + + /// The matched title or alias. + final String title; + final bool isAlias; + + const TitleHit({ + required this.pageId, + required this.title, + required this.isAlias, + }); + + @override + int get hashCode => pageId.hashCode ^ title.hashCode ^ isAlias.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is TitleHit && + runtimeType == other.runtimeType && + pageId == other.pageId && + title == other.title && + isAlias == other.isAlias; +} diff --git a/app/lib/src/rust/api/graph.dart b/app/lib/src/rust/api/graph.dart new file mode 100644 index 0000000..c0a4780 --- /dev/null +++ b/app/lib/src/rust/api/graph.dart @@ -0,0 +1,139 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import + +import '../frb_generated.dart'; +import 'dto.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; + +// These functions are ignored because they are not marked as `pub`: `asset_dto`, `lock`, `outline`, `page_view`, `parse_date`, `parse_day`, `parse_id` + +// Rust type: RustOpaqueMoi> +abstract class SynapseGraph implements RustOpaqueInterface { + Future addAlias({required String pageId, required String alias}); + + Future> aliases({required String pageId}); + + /// Local file path of an asset (for `asset://` images), if present. + String? assetPath({required String hash}); + + /// Linked references grouped by page (most recently edited first). + Future> backlinks({required String pageId}); + + /// Target of a `((block ref))`. + Future blockRef({required String id}); + + /// Deletes a block and its subtree. + Future> deleteBlock({required String id}); + + Future deletePage({required String id}); + + /// Graph directory. + String dir(); + + /// Tab: the block becomes the last child of its previous sibling (no-op for a first child). + Future> indentBlock({required String id}); + + Future insertBlock({ + required String pageId, + required Place place, + required String content, + }); + + /// The journal of `date` (created if missing). + Future journal({required String date}); + + Future<(String?, String?)> journalNeighbors({required String date}); + + /// Journals feed, newest first. With `before = None` it starts at today (creating today's + /// journal); otherwise at the newest journal strictly before `before`. + Future> journals({String? before, required int limit}); + + /// Pages ordered by last update, most recent first. + Future> listPages({ + required bool includeJournals, + required int limit, + required int offset, + }); + + /// Backspace at the start of `id`: its text is appended to `into` (the previous visible + /// block) and the block is deleted. Its children keep their visual place: they take the + /// block's slot when `into` is its parent, otherwise they become last children of `into`. + Future> mergeBlock({required String id, required String into}); + + /// Moves a block with its subtree (drag and drop), possibly to another page. + Future> moveBlock({ + required String id, + required String pageId, + required Place place, + }); + + /// Opens (or creates) the graph stored in `dir`. + static Future open({required String dir}) => + RustLib.instance.api.crateApiGraphSynapseGraphOpen(dir: dir); + + /// Page by title or alias, created if missing (following a `[[link]]`). Date titles open + /// the journal of that day. + Future openPage({required String title}); + + /// Shift-Tab: the block moves right after its parent, adopting its following siblings as + /// children so it keeps its visual place (Logseq's default outdenting). + Future> outdentBlock({required String id}); + + /// Current outline of a page. + Future> outline({required String pageId}); + + Future page({required String id}); + + /// Page by title or alias, without creating it. + Future pageByTitle({required String title}); + + /// Stores in-memory bytes (clipboard, Android content URIs). + Future putAssetBytes({ + required List bytes, + String? name, + String? mime, + }); + + /// Copies a file into the blob store (streamed). + Future putAssetFile({required String path, String? mime}); + + /// Records navigation between pages (strengthens their synapse). + Future recordVisit({String? from, required String to}); + + /// Notes related to `page_id` by spreading activation. + Future> related({ + required String pageId, + required int limit, + }); + + Future removeAlias({required String alias}); + + Future renamePage({required String id, required String newTitle}); + + /// Blocks whose text contains `query` (for `((` autocomplete), most recent first. + Future> searchBlocks({ + required String query, + required int limit, + }); + + /// Page titles and aliases matching `query`: exact, then prefix, then word-prefix, then + /// substring; shorter titles first within a tier. Empty query returns recent pages. + Future> searchTitles({ + required String query, + required int limit, + }); + + Future setCollapsed({required String id, required bool collapsed}); + + /// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions. + Future timeline({required String from, required String to}); + + /// Today's date (graph clock) as `YYYY-MM-DD`. + String today(); + + /// Replaces a block's Markdown (the debounced save while typing). + Future updateBlock({required String id, required String content}); +} diff --git a/app/lib/src/rust/frb_generated.dart b/app/lib/src/rust/frb_generated.dart new file mode 100644 index 0000000..76bf6b1 --- /dev/null +++ b/app/lib/src/rust/frb_generated.dart @@ -0,0 +1,3191 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field + +import 'api/dto.dart'; +import 'api/graph.dart'; + +import 'dart:async'; +import 'dart:convert'; + +import 'frb_generated.dart'; +import 'frb_generated.io.dart' + if (dart.library.js_interop) 'frb_generated.web.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; + +/// Main entrypoint of the Rust API +class RustLib extends BaseEntrypoint { + @internal + static final instance = RustLib._(); + + RustLib._(); + + /// Initialize flutter_rust_bridge + static Future init({ + RustLibApi? api, + BaseHandler? handler, + ExternalLibrary? externalLibrary, + bool forceSameCodegenVersion = true, + }) async { + await instance.initImpl( + api: api, + handler: handler, + externalLibrary: externalLibrary, + forceSameCodegenVersion: forceSameCodegenVersion, + ); + } + + /// Initialize flutter_rust_bridge in mock mode. + /// No libraries for FFI are loaded. + static void initMock({required RustLibApi api}) { + instance.initMockImpl(api: api); + } + + /// Dispose flutter_rust_bridge + /// + /// The call to this function is optional, since flutter_rust_bridge (and everything else) + /// is automatically disposed when the app stops. + static void dispose() => instance.disposeImpl(); + + @override + ApiImplConstructor get apiImplConstructor => + RustLibApiImpl.new; + + @override + WireConstructor get wireConstructor => + RustLibWire.fromExternalLibrary; + + @override + Future executeRustInitializers() async {} + + @override + ExternalLibraryLoaderConfig get defaultExternalLibraryLoaderConfig => + kDefaultExternalLibraryLoaderConfig; + + @override + String get codegenVersion => '2.13.0'; + + @override + int get rustContentHash => 1980668428; + + static const kDefaultExternalLibraryLoaderConfig = + ExternalLibraryLoaderConfig( + stem: 'synapse_ffi', + ioDirectory: '../crates/synapse-ffi/target/release/', + webPrefix: 'pkg/', + wasmBindgenName: 'wasm_bindgen', + ); +} + +abstract class RustLibApi extends BaseApi { + Future crateApiGraphSynapseGraphAddAlias({ + required SynapseGraph that, + required String pageId, + required String alias, + }); + + Future> crateApiGraphSynapseGraphAliases({ + required SynapseGraph that, + required String pageId, + }); + + String? crateApiGraphSynapseGraphAssetPath({ + required SynapseGraph that, + required String hash, + }); + + Future> crateApiGraphSynapseGraphBacklinks({ + required SynapseGraph that, + required String pageId, + }); + + Future crateApiGraphSynapseGraphBlockRef({ + required SynapseGraph that, + required String id, + }); + + Future> crateApiGraphSynapseGraphDeleteBlock({ + required SynapseGraph that, + required String id, + }); + + Future crateApiGraphSynapseGraphDeletePage({ + required SynapseGraph that, + required String id, + }); + + String crateApiGraphSynapseGraphDir({required SynapseGraph that}); + + Future> crateApiGraphSynapseGraphIndentBlock({ + required SynapseGraph that, + required String id, + }); + + Future crateApiGraphSynapseGraphInsertBlock({ + required SynapseGraph that, + required String pageId, + required Place place, + required String content, + }); + + Future crateApiGraphSynapseGraphJournal({ + required SynapseGraph that, + required String date, + }); + + Future<(String?, String?)> crateApiGraphSynapseGraphJournalNeighbors({ + required SynapseGraph that, + required String date, + }); + + Future> crateApiGraphSynapseGraphJournals({ + required SynapseGraph that, + String? before, + required int limit, + }); + + Future> crateApiGraphSynapseGraphListPages({ + required SynapseGraph that, + required bool includeJournals, + required int limit, + required int offset, + }); + + Future> crateApiGraphSynapseGraphMergeBlock({ + required SynapseGraph that, + required String id, + required String into, + }); + + Future> crateApiGraphSynapseGraphMoveBlock({ + required SynapseGraph that, + required String id, + required String pageId, + required Place place, + }); + + Future crateApiGraphSynapseGraphOpen({required String dir}); + + Future crateApiGraphSynapseGraphOpenPage({ + required SynapseGraph that, + required String title, + }); + + Future> crateApiGraphSynapseGraphOutdentBlock({ + required SynapseGraph that, + required String id, + }); + + Future> crateApiGraphSynapseGraphOutline({ + required SynapseGraph that, + required String pageId, + }); + + Future crateApiGraphSynapseGraphPage({ + required SynapseGraph that, + required String id, + }); + + Future crateApiGraphSynapseGraphPageByTitle({ + required SynapseGraph that, + required String title, + }); + + Future crateApiGraphSynapseGraphPutAssetBytes({ + required SynapseGraph that, + required List bytes, + String? name, + String? mime, + }); + + Future crateApiGraphSynapseGraphPutAssetFile({ + required SynapseGraph that, + required String path, + String? mime, + }); + + Future crateApiGraphSynapseGraphRecordVisit({ + required SynapseGraph that, + String? from, + required String to, + }); + + Future> crateApiGraphSynapseGraphRelated({ + required SynapseGraph that, + required String pageId, + required int limit, + }); + + Future crateApiGraphSynapseGraphRemoveAlias({ + required SynapseGraph that, + required String alias, + }); + + Future crateApiGraphSynapseGraphRenamePage({ + required SynapseGraph that, + required String id, + required String newTitle, + }); + + Future> crateApiGraphSynapseGraphSearchBlocks({ + required SynapseGraph that, + required String query, + required int limit, + }); + + Future> crateApiGraphSynapseGraphSearchTitles({ + required SynapseGraph that, + required String query, + required int limit, + }); + + Future crateApiGraphSynapseGraphSetCollapsed({ + required SynapseGraph that, + required String id, + required bool collapsed, + }); + + Future crateApiGraphSynapseGraphTimeline({ + required SynapseGraph that, + required String from, + required String to, + }); + + String crateApiGraphSynapseGraphToday({required SynapseGraph that}); + + Future crateApiGraphSynapseGraphUpdateBlock({ + required SynapseGraph that, + required String id, + required String content, + }); + + RustArcIncrementStrongCountFnType + get rust_arc_increment_strong_count_SynapseGraph; + + RustArcDecrementStrongCountFnType + get rust_arc_decrement_strong_count_SynapseGraph; + + CrossPlatformFinalizerArg get rust_arc_decrement_strong_count_SynapseGraphPtr; +} + +class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { + RustLibApiImpl({ + required super.handler, + required super.wire, + required super.generalizedFrbRustBinding, + required super.portManager, + }); + + @override + Future crateApiGraphSynapseGraphAddAlias({ + required SynapseGraph that, + required String pageId, + required String alias, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_String(alias, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 1, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphAddAliasConstMeta, + argValues: [that, pageId, alias], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphAddAliasConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_add_alias", + argNames: ["that", "pageId", "alias"], + ); + + @override + Future> crateApiGraphSynapseGraphAliases({ + required SynapseGraph that, + required String pageId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 2, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_String, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphAliasesConstMeta, + argValues: [that, pageId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphAliasesConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_aliases", + argNames: ["that", "pageId"], + ); + + @override + String? crateApiGraphSynapseGraphAssetPath({ + required SynapseGraph that, + required String hash, + }) { + return handler.executeSync( + SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(hash, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 3)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_opt_String, + decodeErrorData: null, + ), + constMeta: kCrateApiGraphSynapseGraphAssetPathConstMeta, + argValues: [that, hash], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphAssetPathConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_asset_path", + argNames: ["that", "hash"], + ); + + @override + Future> crateApiGraphSynapseGraphBacklinks({ + required SynapseGraph that, + required String pageId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 4, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_backlink_group, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphBacklinksConstMeta, + argValues: [that, pageId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphBacklinksConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_backlinks", + argNames: ["that", "pageId"], + ); + + @override + Future crateApiGraphSynapseGraphBlockRef({ + required SynapseGraph that, + required String id, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 5, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_opt_box_autoadd_block_ref_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphBlockRefConstMeta, + argValues: [that, id], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphBlockRefConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_block_ref", + argNames: ["that", "id"], + ); + + @override + Future> crateApiGraphSynapseGraphDeleteBlock({ + required SynapseGraph that, + required String id, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 6, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_block_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphDeleteBlockConstMeta, + argValues: [that, id], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphDeleteBlockConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_delete_block", + argNames: ["that", "id"], + ); + + @override + Future crateApiGraphSynapseGraphDeletePage({ + required SynapseGraph that, + required String id, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 7, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphDeletePageConstMeta, + argValues: [that, id], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphDeletePageConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_delete_page", + argNames: ["that", "id"], + ); + + @override + String crateApiGraphSynapseGraphDir({required SynapseGraph that}) { + return handler.executeSync( + SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 8)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: null, + ), + constMeta: kCrateApiGraphSynapseGraphDirConstMeta, + argValues: [that], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphDirConstMeta => + const TaskConstMeta(debugName: "SynapseGraph_dir", argNames: ["that"]); + + @override + Future> crateApiGraphSynapseGraphIndentBlock({ + required SynapseGraph that, + required String id, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 9, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_block_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphIndentBlockConstMeta, + argValues: [that, id], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphIndentBlockConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_indent_block", + argNames: ["that", "id"], + ); + + @override + Future crateApiGraphSynapseGraphInsertBlock({ + required SynapseGraph that, + required String pageId, + required Place place, + required String content, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_box_autoadd_place(place, serializer); + sse_encode_String(content, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 10, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_block_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphInsertBlockConstMeta, + argValues: [that, pageId, place, content], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphInsertBlockConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_insert_block", + argNames: ["that", "pageId", "place", "content"], + ); + + @override + Future crateApiGraphSynapseGraphJournal({ + required SynapseGraph that, + required String date, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(date, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 11, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_data, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphJournalConstMeta, + argValues: [that, date], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphJournalConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_journal", + argNames: ["that", "date"], + ); + + @override + Future<(String?, String?)> crateApiGraphSynapseGraphJournalNeighbors({ + required SynapseGraph that, + required String date, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(date, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 12, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_record_opt_string_opt_string, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphJournalNeighborsConstMeta, + argValues: [that, date], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphJournalNeighborsConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_journal_neighbors", + argNames: ["that", "date"], + ); + + @override + Future> crateApiGraphSynapseGraphJournals({ + required SynapseGraph that, + String? before, + required int limit, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_opt_String(before, serializer); + sse_encode_u_32(limit, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 13, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_page_data, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphJournalsConstMeta, + argValues: [that, before, limit], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphJournalsConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_journals", + argNames: ["that", "before", "limit"], + ); + + @override + Future> crateApiGraphSynapseGraphListPages({ + required SynapseGraph that, + required bool includeJournals, + required int limit, + required int offset, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_bool(includeJournals, serializer); + sse_encode_u_32(limit, serializer); + sse_encode_u_32(offset, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 14, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphListPagesConstMeta, + argValues: [that, includeJournals, limit, offset], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphListPagesConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_list_pages", + argNames: ["that", "includeJournals", "limit", "offset"], + ); + + @override + Future> crateApiGraphSynapseGraphMergeBlock({ + required SynapseGraph that, + required String id, + required String into, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + sse_encode_String(into, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 15, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_block_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphMergeBlockConstMeta, + argValues: [that, id, into], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphMergeBlockConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_merge_block", + argNames: ["that", "id", "into"], + ); + + @override + Future> crateApiGraphSynapseGraphMoveBlock({ + required SynapseGraph that, + required String id, + required String pageId, + required Place place, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + sse_encode_String(pageId, serializer); + sse_encode_box_autoadd_place(place, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 16, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_block_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphMoveBlockConstMeta, + argValues: [that, id, pageId, place], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphMoveBlockConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_move_block", + argNames: ["that", "id", "pageId", "place"], + ); + + @override + Future crateApiGraphSynapseGraphOpen({required String dir}) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(dir, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 17, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: + sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphOpenConstMeta, + argValues: [dir], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphOpenConstMeta => + const TaskConstMeta(debugName: "SynapseGraph_open", argNames: ["dir"]); + + @override + Future crateApiGraphSynapseGraphOpenPage({ + required SynapseGraph that, + required String title, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(title, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 18, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_data, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphOpenPageConstMeta, + argValues: [that, title], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphOpenPageConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_open_page", + argNames: ["that", "title"], + ); + + @override + Future> crateApiGraphSynapseGraphOutdentBlock({ + required SynapseGraph that, + required String id, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 19, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_block_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphOutdentBlockConstMeta, + argValues: [that, id], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphOutdentBlockConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_outdent_block", + argNames: ["that", "id"], + ); + + @override + Future> crateApiGraphSynapseGraphOutline({ + required SynapseGraph that, + required String pageId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 20, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_block_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphOutlineConstMeta, + argValues: [that, pageId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphOutlineConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_outline", + argNames: ["that", "pageId"], + ); + + @override + Future crateApiGraphSynapseGraphPage({ + required SynapseGraph that, + required String id, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 21, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_opt_box_autoadd_page_data, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphPageConstMeta, + argValues: [that, id], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphPageConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_page", + argNames: ["that", "id"], + ); + + @override + Future crateApiGraphSynapseGraphPageByTitle({ + required SynapseGraph that, + required String title, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(title, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 22, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_opt_box_autoadd_page_data, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphPageByTitleConstMeta, + argValues: [that, title], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphPageByTitleConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_page_by_title", + argNames: ["that", "title"], + ); + + @override + Future crateApiGraphSynapseGraphPutAssetBytes({ + required SynapseGraph that, + required List bytes, + String? name, + String? mime, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_list_prim_u_8_loose(bytes, serializer); + sse_encode_opt_String(name, serializer); + sse_encode_opt_String(mime, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 23, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_asset_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphPutAssetBytesConstMeta, + argValues: [that, bytes, name, mime], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphPutAssetBytesConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_put_asset_bytes", + argNames: ["that", "bytes", "name", "mime"], + ); + + @override + Future crateApiGraphSynapseGraphPutAssetFile({ + required SynapseGraph that, + required String path, + String? mime, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(path, serializer); + sse_encode_opt_String(mime, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 24, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_asset_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphPutAssetFileConstMeta, + argValues: [that, path, mime], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphPutAssetFileConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_put_asset_file", + argNames: ["that", "path", "mime"], + ); + + @override + Future crateApiGraphSynapseGraphRecordVisit({ + required SynapseGraph that, + String? from, + required String to, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_opt_String(from, serializer); + sse_encode_String(to, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 25, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRecordVisitConstMeta, + argValues: [that, from, to], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRecordVisitConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_record_visit", + argNames: ["that", "from", "to"], + ); + + @override + Future> crateApiGraphSynapseGraphRelated({ + required SynapseGraph that, + required String pageId, + required int limit, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_u_32(limit, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 26, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_related_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRelatedConstMeta, + argValues: [that, pageId, limit], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRelatedConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_related", + argNames: ["that", "pageId", "limit"], + ); + + @override + Future crateApiGraphSynapseGraphRemoveAlias({ + required SynapseGraph that, + required String alias, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(alias, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 27, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRemoveAliasConstMeta, + argValues: [that, alias], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRemoveAliasConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_remove_alias", + argNames: ["that", "alias"], + ); + + @override + Future crateApiGraphSynapseGraphRenamePage({ + required SynapseGraph that, + required String id, + required String newTitle, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + sse_encode_String(newTitle, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 28, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRenamePageConstMeta, + argValues: [that, id, newTitle], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRenamePageConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_rename_page", + argNames: ["that", "id", "newTitle"], + ); + + @override + Future> crateApiGraphSynapseGraphSearchBlocks({ + required SynapseGraph that, + required String query, + required int limit, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(query, serializer); + sse_encode_u_32(limit, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 29, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_block_hit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphSearchBlocksConstMeta, + argValues: [that, query, limit], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphSearchBlocksConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_search_blocks", + argNames: ["that", "query", "limit"], + ); + + @override + Future> crateApiGraphSynapseGraphSearchTitles({ + required SynapseGraph that, + required String query, + required int limit, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(query, serializer); + sse_encode_u_32(limit, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 30, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_title_hit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphSearchTitlesConstMeta, + argValues: [that, query, limit], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphSearchTitlesConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_search_titles", + argNames: ["that", "query", "limit"], + ); + + @override + Future crateApiGraphSynapseGraphSetCollapsed({ + required SynapseGraph that, + required String id, + required bool collapsed, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + sse_encode_bool(collapsed, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 31, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphSetCollapsedConstMeta, + argValues: [that, id, collapsed], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphSetCollapsedConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_set_collapsed", + argNames: ["that", "id", "collapsed"], + ); + + @override + Future crateApiGraphSynapseGraphTimeline({ + required SynapseGraph that, + required String from, + required String to, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(from, serializer); + sse_encode_String(to, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 32, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_timeline_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphTimelineConstMeta, + argValues: [that, from, to], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphTimelineConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_timeline", + argNames: ["that", "from", "to"], + ); + + @override + String crateApiGraphSynapseGraphToday({required SynapseGraph that}) { + return handler.executeSync( + SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 33)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: null, + ), + constMeta: kCrateApiGraphSynapseGraphTodayConstMeta, + argValues: [that], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphTodayConstMeta => + const TaskConstMeta(debugName: "SynapseGraph_today", argNames: ["that"]); + + @override + Future crateApiGraphSynapseGraphUpdateBlock({ + required SynapseGraph that, + required String id, + required String content, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(id, serializer); + sse_encode_String(content, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 34, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphUpdateBlockConstMeta, + argValues: [that, id, content], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphUpdateBlockConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_update_block", + argNames: ["that", "id", "content"], + ); + + RustArcIncrementStrongCountFnType + get rust_arc_increment_strong_count_SynapseGraph => wire + .rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph; + + RustArcDecrementStrongCountFnType + get rust_arc_decrement_strong_count_SynapseGraph => wire + .rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph; + + @protected + AnyhowException dco_decode_AnyhowException(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return AnyhowException(raw as String); + } + + @protected + SynapseGraph + dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return SynapseGraphImpl.frbInternalDcoDecode(raw as List); + } + + @protected + SynapseGraph + dco_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return SynapseGraphImpl.frbInternalDcoDecode(raw as List); + } + + @protected + SynapseGraph + dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return SynapseGraphImpl.frbInternalDcoDecode(raw as List); + } + + @protected + String dco_decode_String(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as String; + } + + @protected + AssetDto dco_decode_asset_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return AssetDto( + hash: dco_decode_String(arr[0]), + size: dco_decode_u_64(arr[1]), + mime: dco_decode_opt_String(arr[2]), + originalName: dco_decode_opt_String(arr[3]), + ); + } + + @protected + BacklinkGroup dco_decode_backlink_group(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return BacklinkGroup( + pageId: dco_decode_String(arr[0]), + pageTitle: dco_decode_String(arr[1]), + isJournal: dco_decode_bool(arr[2]), + blocks: dco_decode_list_block_dto(arr[3]), + ); + } + + @protected + BlockDto dco_decode_block_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return BlockDto( + id: dco_decode_String(arr[0]), + parentId: dco_decode_opt_String(arr[1]), + depth: dco_decode_u_32(arr[2]), + content: dco_decode_String(arr[3]), + collapsed: dco_decode_bool(arr[4]), + hasChildren: dco_decode_bool(arr[5]), + ); + } + + @protected + BlockHit dco_decode_block_hit(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 3) + throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + return BlockHit( + id: dco_decode_String(arr[0]), + content: dco_decode_String(arr[1]), + pageTitle: dco_decode_String(arr[2]), + ); + } + + @protected + BlockRefDto dco_decode_block_ref_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return BlockRefDto( + id: dco_decode_String(arr[0]), + content: dco_decode_String(arr[1]), + pageId: dco_decode_String(arr[2]), + pageTitle: dco_decode_String(arr[3]), + ); + } + + @protected + bool dco_decode_bool(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as bool; + } + + @protected + BlockRefDto dco_decode_box_autoadd_block_ref_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_block_ref_dto(raw); + } + + @protected + PageData dco_decode_box_autoadd_page_data(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_page_data(raw); + } + + @protected + Place dco_decode_box_autoadd_place(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_place(raw); + } + + @protected + EditDto dco_decode_edit_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 2) + throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); + return EditDto( + pageId: dco_decode_String(arr[0]), + edits: dco_decode_u_32(arr[1]), + ); + } + + @protected + double dco_decode_f_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as double; + } + + @protected + int dco_decode_i_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + PlatformInt64 dco_decode_i_64(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dcoDecodeI64(raw); + } + + @protected + List dco_decode_list_String(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_String).toList(); + } + + @protected + List dco_decode_list_backlink_group(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_backlink_group).toList(); + } + + @protected + List dco_decode_list_block_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_block_dto).toList(); + } + + @protected + List dco_decode_list_block_hit(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_block_hit).toList(); + } + + @protected + List dco_decode_list_edit_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_edit_dto).toList(); + } + + @protected + List dco_decode_list_page_brief(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_page_brief).toList(); + } + + @protected + List dco_decode_list_page_data(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_page_data).toList(); + } + + @protected + List dco_decode_list_page_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_page_dto).toList(); + } + + @protected + List dco_decode_list_prim_u_8_loose(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as List; + } + + @protected + Uint8List dco_decode_list_prim_u_8_strict(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as Uint8List; + } + + @protected + List dco_decode_list_related_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_related_dto).toList(); + } + + @protected + List dco_decode_list_timeline_day_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_timeline_day_dto).toList(); + } + + @protected + List dco_decode_list_title_hit(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_title_hit).toList(); + } + + @protected + String? dco_decode_opt_String(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_String(raw); + } + + @protected + BlockRefDto? dco_decode_opt_box_autoadd_block_ref_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_block_ref_dto(raw); + } + + @protected + PageData? dco_decode_opt_box_autoadd_page_data(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_page_data(raw); + } + + @protected + PageBrief dco_decode_page_brief(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 3) + throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + return PageBrief( + id: dco_decode_String(arr[0]), + title: dco_decode_String(arr[1]), + isJournal: dco_decode_bool(arr[2]), + ); + } + + @protected + PageData dco_decode_page_data(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 5) + throw Exception('unexpected arr length: expect 5 but see ${arr.length}'); + return PageData( + page: dco_decode_page_dto(arr[0]), + blocks: dco_decode_list_block_dto(arr[1]), + aliases: dco_decode_list_String(arr[2]), + prevJournal: dco_decode_opt_String(arr[3]), + nextJournal: dco_decode_opt_String(arr[4]), + ); + } + + @protected + PageDto dco_decode_page_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return PageDto( + id: dco_decode_String(arr[0]), + title: dco_decode_String(arr[1]), + journalDate: dco_decode_opt_String(arr[2]), + originJournal: dco_decode_opt_String(arr[3]), + createdAt: dco_decode_i_64(arr[4]), + updatedAt: dco_decode_i_64(arr[5]), + ); + } + + @protected + Place dco_decode_place(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 2) + throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); + return Place( + kind: dco_decode_place_kind(arr[0]), + anchor: dco_decode_opt_String(arr[1]), + ); + } + + @protected + PlaceKind dco_decode_place_kind(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return PlaceKind.values[raw as int]; + } + + @protected + (String?, String?) dco_decode_record_opt_string_opt_string(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 2) { + throw Exception('Expected 2 elements, got ${arr.length}'); + } + return (dco_decode_opt_String(arr[0]), dco_decode_opt_String(arr[1])); + } + + @protected + RelatedDto dco_decode_related_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 2) + throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); + return RelatedDto( + page: dco_decode_page_brief(arr[0]), + score: dco_decode_f_32(arr[1]), + ); + } + + @protected + TimelineDayDto dco_decode_timeline_day_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return TimelineDayDto( + date: dco_decode_String(arr[0]), + journalId: dco_decode_opt_String(arr[1]), + created: dco_decode_list_String(arr[2]), + edited: dco_decode_list_edit_dto(arr[3]), + ); + } + + @protected + TimelineDto dco_decode_timeline_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 2) + throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); + return TimelineDto( + days: dco_decode_list_timeline_day_dto(arr[0]), + pages: dco_decode_list_page_brief(arr[1]), + ); + } + + @protected + TitleHit dco_decode_title_hit(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 3) + throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + return TitleHit( + pageId: dco_decode_String(arr[0]), + title: dco_decode_String(arr[1]), + isAlias: dco_decode_bool(arr[2]), + ); + } + + @protected + int dco_decode_u_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + BigInt dco_decode_u_64(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dcoDecodeU64(raw); + } + + @protected + int dco_decode_u_8(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + void dco_decode_unit(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return; + } + + @protected + BigInt dco_decode_usize(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dcoDecodeU64(raw); + } + + @protected + AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var inner = sse_decode_String(deserializer); + return AnyhowException(inner); + } + + @protected + SynapseGraph + sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + return SynapseGraphImpl.frbInternalSseDecode( + sse_decode_usize(deserializer), + sse_decode_i_32(deserializer), + ); + } + + @protected + SynapseGraph + sse_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + return SynapseGraphImpl.frbInternalSseDecode( + sse_decode_usize(deserializer), + sse_decode_i_32(deserializer), + ); + } + + @protected + SynapseGraph + sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + return SynapseGraphImpl.frbInternalSseDecode( + sse_decode_usize(deserializer), + sse_decode_i_32(deserializer), + ); + } + + @protected + String sse_decode_String(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var inner = sse_decode_list_prim_u_8_strict(deserializer); + return utf8.decoder.convert(inner); + } + + @protected + AssetDto sse_decode_asset_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_hash = sse_decode_String(deserializer); + var var_size = sse_decode_u_64(deserializer); + var var_mime = sse_decode_opt_String(deserializer); + var var_originalName = sse_decode_opt_String(deserializer); + return AssetDto( + hash: var_hash, + size: var_size, + mime: var_mime, + originalName: var_originalName, + ); + } + + @protected + BacklinkGroup sse_decode_backlink_group(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_pageId = sse_decode_String(deserializer); + var var_pageTitle = sse_decode_String(deserializer); + var var_isJournal = sse_decode_bool(deserializer); + var var_blocks = sse_decode_list_block_dto(deserializer); + return BacklinkGroup( + pageId: var_pageId, + pageTitle: var_pageTitle, + isJournal: var_isJournal, + blocks: var_blocks, + ); + } + + @protected + BlockDto sse_decode_block_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_id = sse_decode_String(deserializer); + var var_parentId = sse_decode_opt_String(deserializer); + var var_depth = sse_decode_u_32(deserializer); + var var_content = sse_decode_String(deserializer); + var var_collapsed = sse_decode_bool(deserializer); + var var_hasChildren = sse_decode_bool(deserializer); + return BlockDto( + id: var_id, + parentId: var_parentId, + depth: var_depth, + content: var_content, + collapsed: var_collapsed, + hasChildren: var_hasChildren, + ); + } + + @protected + BlockHit sse_decode_block_hit(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_id = sse_decode_String(deserializer); + var var_content = sse_decode_String(deserializer); + var var_pageTitle = sse_decode_String(deserializer); + return BlockHit(id: var_id, content: var_content, pageTitle: var_pageTitle); + } + + @protected + BlockRefDto sse_decode_block_ref_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_id = sse_decode_String(deserializer); + var var_content = sse_decode_String(deserializer); + var var_pageId = sse_decode_String(deserializer); + var var_pageTitle = sse_decode_String(deserializer); + return BlockRefDto( + id: var_id, + content: var_content, + pageId: var_pageId, + pageTitle: var_pageTitle, + ); + } + + @protected + bool sse_decode_bool(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getUint8() != 0; + } + + @protected + BlockRefDto sse_decode_box_autoadd_block_ref_dto( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_block_ref_dto(deserializer)); + } + + @protected + PageData sse_decode_box_autoadd_page_data(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_page_data(deserializer)); + } + + @protected + Place sse_decode_box_autoadd_place(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_place(deserializer)); + } + + @protected + EditDto sse_decode_edit_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_pageId = sse_decode_String(deserializer); + var var_edits = sse_decode_u_32(deserializer); + return EditDto(pageId: var_pageId, edits: var_edits); + } + + @protected + double sse_decode_f_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getFloat32(); + } + + @protected + int sse_decode_i_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getInt32(); + } + + @protected + PlatformInt64 sse_decode_i_64(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getPlatformInt64(); + } + + @protected + List sse_decode_list_String(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_String(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_backlink_group( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_backlink_group(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_block_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_block_dto(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_block_hit(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_block_hit(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_edit_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_edit_dto(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_page_brief(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_page_brief(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_page_data(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_page_data(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_page_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_page_dto(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_prim_u_8_loose(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var len_ = sse_decode_i_32(deserializer); + return deserializer.buffer.getUint8List(len_); + } + + @protected + Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var len_ = sse_decode_i_32(deserializer); + return deserializer.buffer.getUint8List(len_); + } + + @protected + List sse_decode_list_related_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_related_dto(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_timeline_day_dto( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_timeline_day_dto(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_title_hit(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_title_hit(deserializer)); + } + return ans_; + } + + @protected + String? sse_decode_opt_String(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_String(deserializer)); + } else { + return null; + } + } + + @protected + BlockRefDto? sse_decode_opt_box_autoadd_block_ref_dto( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_block_ref_dto(deserializer)); + } else { + return null; + } + } + + @protected + PageData? sse_decode_opt_box_autoadd_page_data(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_page_data(deserializer)); + } else { + return null; + } + } + + @protected + PageBrief sse_decode_page_brief(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_id = sse_decode_String(deserializer); + var var_title = sse_decode_String(deserializer); + var var_isJournal = sse_decode_bool(deserializer); + return PageBrief(id: var_id, title: var_title, isJournal: var_isJournal); + } + + @protected + PageData sse_decode_page_data(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_page = sse_decode_page_dto(deserializer); + var var_blocks = sse_decode_list_block_dto(deserializer); + var var_aliases = sse_decode_list_String(deserializer); + var var_prevJournal = sse_decode_opt_String(deserializer); + var var_nextJournal = sse_decode_opt_String(deserializer); + return PageData( + page: var_page, + blocks: var_blocks, + aliases: var_aliases, + prevJournal: var_prevJournal, + nextJournal: var_nextJournal, + ); + } + + @protected + PageDto sse_decode_page_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_id = sse_decode_String(deserializer); + var var_title = sse_decode_String(deserializer); + var var_journalDate = sse_decode_opt_String(deserializer); + var var_originJournal = sse_decode_opt_String(deserializer); + var var_createdAt = sse_decode_i_64(deserializer); + var var_updatedAt = sse_decode_i_64(deserializer); + return PageDto( + id: var_id, + title: var_title, + journalDate: var_journalDate, + originJournal: var_originJournal, + createdAt: var_createdAt, + updatedAt: var_updatedAt, + ); + } + + @protected + Place sse_decode_place(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_kind = sse_decode_place_kind(deserializer); + var var_anchor = sse_decode_opt_String(deserializer); + return Place(kind: var_kind, anchor: var_anchor); + } + + @protected + PlaceKind sse_decode_place_kind(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var inner = sse_decode_i_32(deserializer); + return PlaceKind.values[inner]; + } + + @protected + (String?, String?) sse_decode_record_opt_string_opt_string( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_field0 = sse_decode_opt_String(deserializer); + var var_field1 = sse_decode_opt_String(deserializer); + return (var_field0, var_field1); + } + + @protected + RelatedDto sse_decode_related_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_page = sse_decode_page_brief(deserializer); + var var_score = sse_decode_f_32(deserializer); + return RelatedDto(page: var_page, score: var_score); + } + + @protected + TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_date = sse_decode_String(deserializer); + var var_journalId = sse_decode_opt_String(deserializer); + var var_created = sse_decode_list_String(deserializer); + var var_edited = sse_decode_list_edit_dto(deserializer); + return TimelineDayDto( + date: var_date, + journalId: var_journalId, + created: var_created, + edited: var_edited, + ); + } + + @protected + TimelineDto sse_decode_timeline_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_days = sse_decode_list_timeline_day_dto(deserializer); + var var_pages = sse_decode_list_page_brief(deserializer); + return TimelineDto(days: var_days, pages: var_pages); + } + + @protected + TitleHit sse_decode_title_hit(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_pageId = sse_decode_String(deserializer); + var var_title = sse_decode_String(deserializer); + var var_isAlias = sse_decode_bool(deserializer); + return TitleHit(pageId: var_pageId, title: var_title, isAlias: var_isAlias); + } + + @protected + int sse_decode_u_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getUint32(); + } + + @protected + BigInt sse_decode_u_64(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getBigUint64(); + } + + @protected + int sse_decode_u_8(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getUint8(); + } + + @protected + void sse_decode_unit(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + } + + @protected + BigInt sse_decode_usize(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getBigUint64(); + } + + @protected + void sse_encode_AnyhowException( + AnyhowException self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.message, serializer); + } + + @protected + void + sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_usize( + (self as SynapseGraphImpl).frbInternalSseEncode(move: true), + serializer, + ); + } + + @protected + void + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_usize( + (self as SynapseGraphImpl).frbInternalSseEncode(move: false), + serializer, + ); + } + + @protected + void + sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_usize( + (self as SynapseGraphImpl).frbInternalSseEncode(move: null), + serializer, + ); + } + + @protected + void sse_encode_String(String self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_list_prim_u_8_strict(utf8.encoder.convert(self), serializer); + } + + @protected + void sse_encode_asset_dto(AssetDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.hash, serializer); + sse_encode_u_64(self.size, serializer); + sse_encode_opt_String(self.mime, serializer); + sse_encode_opt_String(self.originalName, serializer); + } + + @protected + void sse_encode_backlink_group(BacklinkGroup self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.pageId, serializer); + sse_encode_String(self.pageTitle, serializer); + sse_encode_bool(self.isJournal, serializer); + sse_encode_list_block_dto(self.blocks, serializer); + } + + @protected + void sse_encode_block_dto(BlockDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.id, serializer); + sse_encode_opt_String(self.parentId, serializer); + sse_encode_u_32(self.depth, serializer); + sse_encode_String(self.content, serializer); + sse_encode_bool(self.collapsed, serializer); + sse_encode_bool(self.hasChildren, serializer); + } + + @protected + void sse_encode_block_hit(BlockHit self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.id, serializer); + sse_encode_String(self.content, serializer); + sse_encode_String(self.pageTitle, serializer); + } + + @protected + void sse_encode_block_ref_dto(BlockRefDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.id, serializer); + sse_encode_String(self.content, serializer); + sse_encode_String(self.pageId, serializer); + sse_encode_String(self.pageTitle, serializer); + } + + @protected + void sse_encode_bool(bool self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putUint8(self ? 1 : 0); + } + + @protected + void sse_encode_box_autoadd_block_ref_dto( + BlockRefDto self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_block_ref_dto(self, serializer); + } + + @protected + void sse_encode_box_autoadd_page_data( + PageData self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_page_data(self, serializer); + } + + @protected + void sse_encode_box_autoadd_place(Place self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_place(self, serializer); + } + + @protected + void sse_encode_edit_dto(EditDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.pageId, serializer); + sse_encode_u_32(self.edits, serializer); + } + + @protected + void sse_encode_f_32(double self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putFloat32(self); + } + + @protected + void sse_encode_i_32(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putInt32(self); + } + + @protected + void sse_encode_i_64(PlatformInt64 self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putPlatformInt64(self); + } + + @protected + void sse_encode_list_String(List self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_String(item, serializer); + } + } + + @protected + void sse_encode_list_backlink_group( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_backlink_group(item, serializer); + } + } + + @protected + void sse_encode_list_block_dto( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_block_dto(item, serializer); + } + } + + @protected + void sse_encode_list_block_hit( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_block_hit(item, serializer); + } + } + + @protected + void sse_encode_list_edit_dto(List self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_edit_dto(item, serializer); + } + } + + @protected + void sse_encode_list_page_brief( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_page_brief(item, serializer); + } + } + + @protected + void sse_encode_list_page_data( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_page_data(item, serializer); + } + } + + @protected + void sse_encode_list_page_dto(List self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_page_dto(item, serializer); + } + } + + @protected + void sse_encode_list_prim_u_8_loose( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + serializer.buffer.putUint8List( + self is Uint8List ? self : Uint8List.fromList(self), + ); + } + + @protected + void sse_encode_list_prim_u_8_strict( + Uint8List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + serializer.buffer.putUint8List(self); + } + + @protected + void sse_encode_list_related_dto( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_related_dto(item, serializer); + } + } + + @protected + void sse_encode_list_timeline_day_dto( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_timeline_day_dto(item, serializer); + } + } + + @protected + void sse_encode_list_title_hit( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_title_hit(item, serializer); + } + } + + @protected + void sse_encode_opt_String(String? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_String(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_block_ref_dto( + BlockRefDto? self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_block_ref_dto(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_page_data( + PageData? self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_page_data(self, serializer); + } + } + + @protected + void sse_encode_page_brief(PageBrief self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.id, serializer); + sse_encode_String(self.title, serializer); + sse_encode_bool(self.isJournal, serializer); + } + + @protected + void sse_encode_page_data(PageData self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_page_dto(self.page, serializer); + sse_encode_list_block_dto(self.blocks, serializer); + sse_encode_list_String(self.aliases, serializer); + sse_encode_opt_String(self.prevJournal, serializer); + sse_encode_opt_String(self.nextJournal, serializer); + } + + @protected + void sse_encode_page_dto(PageDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.id, serializer); + sse_encode_String(self.title, serializer); + sse_encode_opt_String(self.journalDate, serializer); + sse_encode_opt_String(self.originJournal, serializer); + sse_encode_i_64(self.createdAt, serializer); + sse_encode_i_64(self.updatedAt, serializer); + } + + @protected + void sse_encode_place(Place self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_place_kind(self.kind, serializer); + sse_encode_opt_String(self.anchor, serializer); + } + + @protected + void sse_encode_place_kind(PlaceKind self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.index, serializer); + } + + @protected + void sse_encode_record_opt_string_opt_string( + (String?, String?) self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_opt_String(self.$1, serializer); + sse_encode_opt_String(self.$2, serializer); + } + + @protected + void sse_encode_related_dto(RelatedDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_page_brief(self.page, serializer); + sse_encode_f_32(self.score, serializer); + } + + @protected + void sse_encode_timeline_day_dto( + TimelineDayDto self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.date, serializer); + sse_encode_opt_String(self.journalId, serializer); + sse_encode_list_String(self.created, serializer); + sse_encode_list_edit_dto(self.edited, serializer); + } + + @protected + void sse_encode_timeline_dto(TimelineDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_list_timeline_day_dto(self.days, serializer); + sse_encode_list_page_brief(self.pages, serializer); + } + + @protected + void sse_encode_title_hit(TitleHit self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.pageId, serializer); + sse_encode_String(self.title, serializer); + sse_encode_bool(self.isAlias, serializer); + } + + @protected + void sse_encode_u_32(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putUint32(self); + } + + @protected + void sse_encode_u_64(BigInt self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putBigUint64(self); + } + + @protected + void sse_encode_u_8(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putUint8(self); + } + + @protected + void sse_encode_unit(void self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + } + + @protected + void sse_encode_usize(BigInt self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putBigUint64(self); + } +} + +@sealed +class SynapseGraphImpl extends RustOpaque implements SynapseGraph { + // Not to be used by end users + SynapseGraphImpl.frbInternalDcoDecode(List wire) + : super.frbInternalDcoDecode(wire, _kStaticData); + + // Not to be used by end users + SynapseGraphImpl.frbInternalSseDecode(BigInt ptr, int externalSizeOnNative) + : super.frbInternalSseDecode(ptr, externalSizeOnNative, _kStaticData); + + static final _kStaticData = RustArcStaticData( + rustArcIncrementStrongCount: + RustLib.instance.api.rust_arc_increment_strong_count_SynapseGraph, + rustArcDecrementStrongCount: + RustLib.instance.api.rust_arc_decrement_strong_count_SynapseGraph, + rustArcDecrementStrongCountPtr: + RustLib.instance.api.rust_arc_decrement_strong_count_SynapseGraphPtr, + ); + + Future addAlias({required String pageId, required String alias}) => + RustLib.instance.api.crateApiGraphSynapseGraphAddAlias( + that: this, + pageId: pageId, + alias: alias, + ); + + Future> aliases({required String pageId}) => RustLib.instance.api + .crateApiGraphSynapseGraphAliases(that: this, pageId: pageId); + + /// Local file path of an asset (for `asset://` images), if present. + String? assetPath({required String hash}) => RustLib.instance.api + .crateApiGraphSynapseGraphAssetPath(that: this, hash: hash); + + /// Linked references grouped by page (most recently edited first). + Future> backlinks({required String pageId}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphBacklinks(that: this, pageId: pageId); + + /// Target of a `((block ref))`. + Future blockRef({required String id}) => RustLib.instance.api + .crateApiGraphSynapseGraphBlockRef(that: this, id: id); + + /// Deletes a block and its subtree. + Future> deleteBlock({required String id}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphDeleteBlock(that: this, id: id); + + Future deletePage({required String id}) => RustLib.instance.api + .crateApiGraphSynapseGraphDeletePage(that: this, id: id); + + /// Graph directory. + String dir() => RustLib.instance.api.crateApiGraphSynapseGraphDir(that: this); + + /// Tab: the block becomes the last child of its previous sibling (no-op for a first child). + Future> indentBlock({required String id}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphIndentBlock(that: this, id: id); + + Future insertBlock({ + required String pageId, + required Place place, + required String content, + }) => RustLib.instance.api.crateApiGraphSynapseGraphInsertBlock( + that: this, + pageId: pageId, + place: place, + content: content, + ); + + /// The journal of `date` (created if missing). + Future journal({required String date}) => RustLib.instance.api + .crateApiGraphSynapseGraphJournal(that: this, date: date); + + Future<(String?, String?)> journalNeighbors({required String date}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphJournalNeighbors(that: this, date: date); + + /// Journals feed, newest first. With `before = None` it starts at today (creating today's + /// journal); otherwise at the newest journal strictly before `before`. + Future> journals({String? before, required int limit}) => + RustLib.instance.api.crateApiGraphSynapseGraphJournals( + that: this, + before: before, + limit: limit, + ); + + /// Pages ordered by last update, most recent first. + Future> listPages({ + required bool includeJournals, + required int limit, + required int offset, + }) => RustLib.instance.api.crateApiGraphSynapseGraphListPages( + that: this, + includeJournals: includeJournals, + limit: limit, + offset: offset, + ); + + /// Backspace at the start of `id`: its text is appended to `into` (the previous visible + /// block) and the block is deleted. Its children keep their visual place: they take the + /// block's slot when `into` is its parent, otherwise they become last children of `into`. + Future> mergeBlock({ + required String id, + required String into, + }) => RustLib.instance.api.crateApiGraphSynapseGraphMergeBlock( + that: this, + id: id, + into: into, + ); + + /// Moves a block with its subtree (drag and drop), possibly to another page. + Future> moveBlock({ + required String id, + required String pageId, + required Place place, + }) => RustLib.instance.api.crateApiGraphSynapseGraphMoveBlock( + that: this, + id: id, + pageId: pageId, + place: place, + ); + + /// Page by title or alias, created if missing (following a `[[link]]`). Date titles open + /// the journal of that day. + Future openPage({required String title}) => RustLib.instance.api + .crateApiGraphSynapseGraphOpenPage(that: this, title: title); + + /// Shift-Tab: the block moves right after its parent, adopting its following siblings as + /// children so it keeps its visual place (Logseq's default outdenting). + Future> outdentBlock({required String id}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphOutdentBlock(that: this, id: id); + + /// Current outline of a page. + Future> outline({required String pageId}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphOutline(that: this, pageId: pageId); + + Future page({required String id}) => + RustLib.instance.api.crateApiGraphSynapseGraphPage(that: this, id: id); + + /// Page by title or alias, without creating it. + Future pageByTitle({required String title}) => RustLib.instance.api + .crateApiGraphSynapseGraphPageByTitle(that: this, title: title); + + /// Stores in-memory bytes (clipboard, Android content URIs). + Future putAssetBytes({ + required List bytes, + String? name, + String? mime, + }) => RustLib.instance.api.crateApiGraphSynapseGraphPutAssetBytes( + that: this, + bytes: bytes, + name: name, + mime: mime, + ); + + /// Copies a file into the blob store (streamed). + Future putAssetFile({required String path, String? mime}) => + RustLib.instance.api.crateApiGraphSynapseGraphPutAssetFile( + that: this, + path: path, + mime: mime, + ); + + /// Records navigation between pages (strengthens their synapse). + Future recordVisit({String? from, required String to}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphRecordVisit(that: this, from: from, to: to); + + /// Notes related to `page_id` by spreading activation. + Future> related({ + required String pageId, + required int limit, + }) => RustLib.instance.api.crateApiGraphSynapseGraphRelated( + that: this, + pageId: pageId, + limit: limit, + ); + + Future removeAlias({required String alias}) => RustLib.instance.api + .crateApiGraphSynapseGraphRemoveAlias(that: this, alias: alias); + + Future renamePage({required String id, required String newTitle}) => + RustLib.instance.api.crateApiGraphSynapseGraphRenamePage( + that: this, + id: id, + newTitle: newTitle, + ); + + /// Blocks whose text contains `query` (for `((` autocomplete), most recent first. + Future> searchBlocks({ + required String query, + required int limit, + }) => RustLib.instance.api.crateApiGraphSynapseGraphSearchBlocks( + that: this, + query: query, + limit: limit, + ); + + /// Page titles and aliases matching `query`: exact, then prefix, then word-prefix, then + /// substring; shorter titles first within a tier. Empty query returns recent pages. + Future> searchTitles({ + required String query, + required int limit, + }) => RustLib.instance.api.crateApiGraphSynapseGraphSearchTitles( + that: this, + query: query, + limit: limit, + ); + + Future setCollapsed({required String id, required bool collapsed}) => + RustLib.instance.api.crateApiGraphSynapseGraphSetCollapsed( + that: this, + id: id, + collapsed: collapsed, + ); + + /// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions. + Future timeline({required String from, required String to}) => + RustLib.instance.api.crateApiGraphSynapseGraphTimeline( + that: this, + from: from, + to: to, + ); + + /// Today's date (graph clock) as `YYYY-MM-DD`. + String today() => + RustLib.instance.api.crateApiGraphSynapseGraphToday(that: this); + + /// Replaces a block's Markdown (the debounced save while typing). + Future updateBlock({required String id, required String content}) => + RustLib.instance.api.crateApiGraphSynapseGraphUpdateBlock( + that: this, + id: id, + content: content, + ); +} diff --git a/app/lib/src/rust/frb_generated.io.dart b/app/lib/src/rust/frb_generated.io.dart new file mode 100644 index 0000000..554419e --- /dev/null +++ b/app/lib/src/rust/frb_generated.io.dart @@ -0,0 +1,594 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field + +import 'api/dto.dart'; +import 'api/graph.dart'; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi' as ffi; + +import 'frb_generated.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_io.dart'; + +abstract class RustLibApiImplPlatform extends BaseApiImpl { + RustLibApiImplPlatform({ + required super.handler, + required super.wire, + required super.generalizedFrbRustBinding, + required super.portManager, + }); + + CrossPlatformFinalizerArg + get rust_arc_decrement_strong_count_SynapseGraphPtr => wire + ._rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr; + + @protected + AnyhowException dco_decode_AnyhowException(dynamic raw); + + @protected + SynapseGraph + dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ); + + @protected + SynapseGraph + dco_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ); + + @protected + SynapseGraph + dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ); + + @protected + String dco_decode_String(dynamic raw); + + @protected + AssetDto dco_decode_asset_dto(dynamic raw); + + @protected + BacklinkGroup dco_decode_backlink_group(dynamic raw); + + @protected + BlockDto dco_decode_block_dto(dynamic raw); + + @protected + BlockHit dco_decode_block_hit(dynamic raw); + + @protected + BlockRefDto dco_decode_block_ref_dto(dynamic raw); + + @protected + bool dco_decode_bool(dynamic raw); + + @protected + BlockRefDto dco_decode_box_autoadd_block_ref_dto(dynamic raw); + + @protected + PageData dco_decode_box_autoadd_page_data(dynamic raw); + + @protected + Place dco_decode_box_autoadd_place(dynamic raw); + + @protected + EditDto dco_decode_edit_dto(dynamic raw); + + @protected + double dco_decode_f_32(dynamic raw); + + @protected + int dco_decode_i_32(dynamic raw); + + @protected + PlatformInt64 dco_decode_i_64(dynamic raw); + + @protected + List dco_decode_list_String(dynamic raw); + + @protected + List dco_decode_list_backlink_group(dynamic raw); + + @protected + List dco_decode_list_block_dto(dynamic raw); + + @protected + List dco_decode_list_block_hit(dynamic raw); + + @protected + List dco_decode_list_edit_dto(dynamic raw); + + @protected + List dco_decode_list_page_brief(dynamic raw); + + @protected + List dco_decode_list_page_data(dynamic raw); + + @protected + List dco_decode_list_page_dto(dynamic raw); + + @protected + List dco_decode_list_prim_u_8_loose(dynamic raw); + + @protected + Uint8List dco_decode_list_prim_u_8_strict(dynamic raw); + + @protected + List dco_decode_list_related_dto(dynamic raw); + + @protected + List dco_decode_list_timeline_day_dto(dynamic raw); + + @protected + List dco_decode_list_title_hit(dynamic raw); + + @protected + String? dco_decode_opt_String(dynamic raw); + + @protected + BlockRefDto? dco_decode_opt_box_autoadd_block_ref_dto(dynamic raw); + + @protected + PageData? dco_decode_opt_box_autoadd_page_data(dynamic raw); + + @protected + PageBrief dco_decode_page_brief(dynamic raw); + + @protected + PageData dco_decode_page_data(dynamic raw); + + @protected + PageDto dco_decode_page_dto(dynamic raw); + + @protected + Place dco_decode_place(dynamic raw); + + @protected + PlaceKind dco_decode_place_kind(dynamic raw); + + @protected + (String?, String?) dco_decode_record_opt_string_opt_string(dynamic raw); + + @protected + RelatedDto dco_decode_related_dto(dynamic raw); + + @protected + TimelineDayDto dco_decode_timeline_day_dto(dynamic raw); + + @protected + TimelineDto dco_decode_timeline_dto(dynamic raw); + + @protected + TitleHit dco_decode_title_hit(dynamic raw); + + @protected + int dco_decode_u_32(dynamic raw); + + @protected + BigInt dco_decode_u_64(dynamic raw); + + @protected + int dco_decode_u_8(dynamic raw); + + @protected + void dco_decode_unit(dynamic raw); + + @protected + BigInt dco_decode_usize(dynamic raw); + + @protected + AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer); + + @protected + SynapseGraph + sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ); + + @protected + SynapseGraph + sse_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ); + + @protected + SynapseGraph + sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ); + + @protected + String sse_decode_String(SseDeserializer deserializer); + + @protected + AssetDto sse_decode_asset_dto(SseDeserializer deserializer); + + @protected + BacklinkGroup sse_decode_backlink_group(SseDeserializer deserializer); + + @protected + BlockDto sse_decode_block_dto(SseDeserializer deserializer); + + @protected + BlockHit sse_decode_block_hit(SseDeserializer deserializer); + + @protected + BlockRefDto sse_decode_block_ref_dto(SseDeserializer deserializer); + + @protected + bool sse_decode_bool(SseDeserializer deserializer); + + @protected + BlockRefDto sse_decode_box_autoadd_block_ref_dto( + SseDeserializer deserializer, + ); + + @protected + PageData sse_decode_box_autoadd_page_data(SseDeserializer deserializer); + + @protected + Place sse_decode_box_autoadd_place(SseDeserializer deserializer); + + @protected + EditDto sse_decode_edit_dto(SseDeserializer deserializer); + + @protected + double sse_decode_f_32(SseDeserializer deserializer); + + @protected + int sse_decode_i_32(SseDeserializer deserializer); + + @protected + PlatformInt64 sse_decode_i_64(SseDeserializer deserializer); + + @protected + List sse_decode_list_String(SseDeserializer deserializer); + + @protected + List sse_decode_list_backlink_group( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_block_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_block_hit(SseDeserializer deserializer); + + @protected + List sse_decode_list_edit_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_page_brief(SseDeserializer deserializer); + + @protected + List sse_decode_list_page_data(SseDeserializer deserializer); + + @protected + List sse_decode_list_page_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_prim_u_8_loose(SseDeserializer deserializer); + + @protected + Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer); + + @protected + List sse_decode_list_related_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_timeline_day_dto( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_title_hit(SseDeserializer deserializer); + + @protected + String? sse_decode_opt_String(SseDeserializer deserializer); + + @protected + BlockRefDto? sse_decode_opt_box_autoadd_block_ref_dto( + SseDeserializer deserializer, + ); + + @protected + PageData? sse_decode_opt_box_autoadd_page_data(SseDeserializer deserializer); + + @protected + PageBrief sse_decode_page_brief(SseDeserializer deserializer); + + @protected + PageData sse_decode_page_data(SseDeserializer deserializer); + + @protected + PageDto sse_decode_page_dto(SseDeserializer deserializer); + + @protected + Place sse_decode_place(SseDeserializer deserializer); + + @protected + PlaceKind sse_decode_place_kind(SseDeserializer deserializer); + + @protected + (String?, String?) sse_decode_record_opt_string_opt_string( + SseDeserializer deserializer, + ); + + @protected + RelatedDto sse_decode_related_dto(SseDeserializer deserializer); + + @protected + TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer); + + @protected + TimelineDto sse_decode_timeline_dto(SseDeserializer deserializer); + + @protected + TitleHit sse_decode_title_hit(SseDeserializer deserializer); + + @protected + int sse_decode_u_32(SseDeserializer deserializer); + + @protected + BigInt sse_decode_u_64(SseDeserializer deserializer); + + @protected + int sse_decode_u_8(SseDeserializer deserializer); + + @protected + void sse_decode_unit(SseDeserializer deserializer); + + @protected + BigInt sse_decode_usize(SseDeserializer deserializer); + + @protected + void sse_encode_AnyhowException( + AnyhowException self, + SseSerializer serializer, + ); + + @protected + void + sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ); + + @protected + void + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ); + + @protected + void + sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ); + + @protected + void sse_encode_String(String self, SseSerializer serializer); + + @protected + void sse_encode_asset_dto(AssetDto self, SseSerializer serializer); + + @protected + void sse_encode_backlink_group(BacklinkGroup self, SseSerializer serializer); + + @protected + void sse_encode_block_dto(BlockDto self, SseSerializer serializer); + + @protected + void sse_encode_block_hit(BlockHit self, SseSerializer serializer); + + @protected + void sse_encode_block_ref_dto(BlockRefDto self, SseSerializer serializer); + + @protected + void sse_encode_bool(bool self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_block_ref_dto( + BlockRefDto self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_page_data( + PageData self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_place(Place self, SseSerializer serializer); + + @protected + void sse_encode_edit_dto(EditDto self, SseSerializer serializer); + + @protected + void sse_encode_f_32(double self, SseSerializer serializer); + + @protected + void sse_encode_i_32(int self, SseSerializer serializer); + + @protected + void sse_encode_i_64(PlatformInt64 self, SseSerializer serializer); + + @protected + void sse_encode_list_String(List self, SseSerializer serializer); + + @protected + void sse_encode_list_backlink_group( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_block_dto(List self, SseSerializer serializer); + + @protected + void sse_encode_list_block_hit(List self, SseSerializer serializer); + + @protected + void sse_encode_list_edit_dto(List self, SseSerializer serializer); + + @protected + void sse_encode_list_page_brief( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_page_data(List self, SseSerializer serializer); + + @protected + void sse_encode_list_page_dto(List self, SseSerializer serializer); + + @protected + void sse_encode_list_prim_u_8_loose(List self, SseSerializer serializer); + + @protected + void sse_encode_list_prim_u_8_strict( + Uint8List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_related_dto( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_timeline_day_dto( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_title_hit(List self, SseSerializer serializer); + + @protected + void sse_encode_opt_String(String? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_block_ref_dto( + BlockRefDto? self, + SseSerializer serializer, + ); + + @protected + void sse_encode_opt_box_autoadd_page_data( + PageData? self, + SseSerializer serializer, + ); + + @protected + void sse_encode_page_brief(PageBrief self, SseSerializer serializer); + + @protected + void sse_encode_page_data(PageData self, SseSerializer serializer); + + @protected + void sse_encode_page_dto(PageDto self, SseSerializer serializer); + + @protected + void sse_encode_place(Place self, SseSerializer serializer); + + @protected + void sse_encode_place_kind(PlaceKind self, SseSerializer serializer); + + @protected + void sse_encode_record_opt_string_opt_string( + (String?, String?) self, + SseSerializer serializer, + ); + + @protected + void sse_encode_related_dto(RelatedDto self, SseSerializer serializer); + + @protected + void sse_encode_timeline_day_dto( + TimelineDayDto self, + SseSerializer serializer, + ); + + @protected + void sse_encode_timeline_dto(TimelineDto self, SseSerializer serializer); + + @protected + void sse_encode_title_hit(TitleHit self, SseSerializer serializer); + + @protected + void sse_encode_u_32(int self, SseSerializer serializer); + + @protected + void sse_encode_u_64(BigInt self, SseSerializer serializer); + + @protected + void sse_encode_u_8(int self, SseSerializer serializer); + + @protected + void sse_encode_unit(void self, SseSerializer serializer); + + @protected + void sse_encode_usize(BigInt self, SseSerializer serializer); +} + +// Section: wire_class + +class RustLibWire implements BaseWire { + factory RustLibWire.fromExternalLibrary(ExternalLibrary lib) => + RustLibWire(lib.ffiDynamicLibrary); + + /// Holds the symbol lookup function. + final ffi.Pointer Function(String symbolName) + _lookup; + + /// The symbols are looked up in [dynamicLibrary]. + RustLibWire(ffi.DynamicLibrary dynamicLibrary) + : _lookup = dynamicLibrary.lookup; + + void + rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ffi.Pointer ptr, + ) { + return _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ptr, + ); + } + + late final _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr = + _lookup)>>( + 'frbgen_synapse_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph', + ); + late final _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph = + _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr + .asFunction)>(); + + void + rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ffi.Pointer ptr, + ) { + return _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ptr, + ); + } + + late final _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr = + _lookup)>>( + 'frbgen_synapse_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph', + ); + late final _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph = + _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr + .asFunction)>(); +} diff --git a/app/lib/src/rust/frb_generated.web.dart b/app/lib/src/rust/frb_generated.web.dart new file mode 100644 index 0000000..3d5b7bb --- /dev/null +++ b/app/lib/src/rust/frb_generated.web.dart @@ -0,0 +1,586 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field + +// Static analysis wrongly picks the IO variant, thus ignore this +// ignore_for_file: argument_type_not_assignable + +import 'api/dto.dart'; +import 'api/graph.dart'; + +import 'dart:async'; +import 'dart:convert'; + +import 'frb_generated.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_web.dart'; + +abstract class RustLibApiImplPlatform extends BaseApiImpl { + RustLibApiImplPlatform({ + required super.handler, + required super.wire, + required super.generalizedFrbRustBinding, + required super.portManager, + }); + + CrossPlatformFinalizerArg + get rust_arc_decrement_strong_count_SynapseGraphPtr => wire + .rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph; + + @protected + AnyhowException dco_decode_AnyhowException(dynamic raw); + + @protected + SynapseGraph + dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ); + + @protected + SynapseGraph + dco_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ); + + @protected + SynapseGraph + dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + dynamic raw, + ); + + @protected + String dco_decode_String(dynamic raw); + + @protected + AssetDto dco_decode_asset_dto(dynamic raw); + + @protected + BacklinkGroup dco_decode_backlink_group(dynamic raw); + + @protected + BlockDto dco_decode_block_dto(dynamic raw); + + @protected + BlockHit dco_decode_block_hit(dynamic raw); + + @protected + BlockRefDto dco_decode_block_ref_dto(dynamic raw); + + @protected + bool dco_decode_bool(dynamic raw); + + @protected + BlockRefDto dco_decode_box_autoadd_block_ref_dto(dynamic raw); + + @protected + PageData dco_decode_box_autoadd_page_data(dynamic raw); + + @protected + Place dco_decode_box_autoadd_place(dynamic raw); + + @protected + EditDto dco_decode_edit_dto(dynamic raw); + + @protected + double dco_decode_f_32(dynamic raw); + + @protected + int dco_decode_i_32(dynamic raw); + + @protected + PlatformInt64 dco_decode_i_64(dynamic raw); + + @protected + List dco_decode_list_String(dynamic raw); + + @protected + List dco_decode_list_backlink_group(dynamic raw); + + @protected + List dco_decode_list_block_dto(dynamic raw); + + @protected + List dco_decode_list_block_hit(dynamic raw); + + @protected + List dco_decode_list_edit_dto(dynamic raw); + + @protected + List dco_decode_list_page_brief(dynamic raw); + + @protected + List dco_decode_list_page_data(dynamic raw); + + @protected + List dco_decode_list_page_dto(dynamic raw); + + @protected + List dco_decode_list_prim_u_8_loose(dynamic raw); + + @protected + Uint8List dco_decode_list_prim_u_8_strict(dynamic raw); + + @protected + List dco_decode_list_related_dto(dynamic raw); + + @protected + List dco_decode_list_timeline_day_dto(dynamic raw); + + @protected + List dco_decode_list_title_hit(dynamic raw); + + @protected + String? dco_decode_opt_String(dynamic raw); + + @protected + BlockRefDto? dco_decode_opt_box_autoadd_block_ref_dto(dynamic raw); + + @protected + PageData? dco_decode_opt_box_autoadd_page_data(dynamic raw); + + @protected + PageBrief dco_decode_page_brief(dynamic raw); + + @protected + PageData dco_decode_page_data(dynamic raw); + + @protected + PageDto dco_decode_page_dto(dynamic raw); + + @protected + Place dco_decode_place(dynamic raw); + + @protected + PlaceKind dco_decode_place_kind(dynamic raw); + + @protected + (String?, String?) dco_decode_record_opt_string_opt_string(dynamic raw); + + @protected + RelatedDto dco_decode_related_dto(dynamic raw); + + @protected + TimelineDayDto dco_decode_timeline_day_dto(dynamic raw); + + @protected + TimelineDto dco_decode_timeline_dto(dynamic raw); + + @protected + TitleHit dco_decode_title_hit(dynamic raw); + + @protected + int dco_decode_u_32(dynamic raw); + + @protected + BigInt dco_decode_u_64(dynamic raw); + + @protected + int dco_decode_u_8(dynamic raw); + + @protected + void dco_decode_unit(dynamic raw); + + @protected + BigInt dco_decode_usize(dynamic raw); + + @protected + AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer); + + @protected + SynapseGraph + sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ); + + @protected + SynapseGraph + sse_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ); + + @protected + SynapseGraph + sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SseDeserializer deserializer, + ); + + @protected + String sse_decode_String(SseDeserializer deserializer); + + @protected + AssetDto sse_decode_asset_dto(SseDeserializer deserializer); + + @protected + BacklinkGroup sse_decode_backlink_group(SseDeserializer deserializer); + + @protected + BlockDto sse_decode_block_dto(SseDeserializer deserializer); + + @protected + BlockHit sse_decode_block_hit(SseDeserializer deserializer); + + @protected + BlockRefDto sse_decode_block_ref_dto(SseDeserializer deserializer); + + @protected + bool sse_decode_bool(SseDeserializer deserializer); + + @protected + BlockRefDto sse_decode_box_autoadd_block_ref_dto( + SseDeserializer deserializer, + ); + + @protected + PageData sse_decode_box_autoadd_page_data(SseDeserializer deserializer); + + @protected + Place sse_decode_box_autoadd_place(SseDeserializer deserializer); + + @protected + EditDto sse_decode_edit_dto(SseDeserializer deserializer); + + @protected + double sse_decode_f_32(SseDeserializer deserializer); + + @protected + int sse_decode_i_32(SseDeserializer deserializer); + + @protected + PlatformInt64 sse_decode_i_64(SseDeserializer deserializer); + + @protected + List sse_decode_list_String(SseDeserializer deserializer); + + @protected + List sse_decode_list_backlink_group( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_block_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_block_hit(SseDeserializer deserializer); + + @protected + List sse_decode_list_edit_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_page_brief(SseDeserializer deserializer); + + @protected + List sse_decode_list_page_data(SseDeserializer deserializer); + + @protected + List sse_decode_list_page_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_prim_u_8_loose(SseDeserializer deserializer); + + @protected + Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer); + + @protected + List sse_decode_list_related_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_timeline_day_dto( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_title_hit(SseDeserializer deserializer); + + @protected + String? sse_decode_opt_String(SseDeserializer deserializer); + + @protected + BlockRefDto? sse_decode_opt_box_autoadd_block_ref_dto( + SseDeserializer deserializer, + ); + + @protected + PageData? sse_decode_opt_box_autoadd_page_data(SseDeserializer deserializer); + + @protected + PageBrief sse_decode_page_brief(SseDeserializer deserializer); + + @protected + PageData sse_decode_page_data(SseDeserializer deserializer); + + @protected + PageDto sse_decode_page_dto(SseDeserializer deserializer); + + @protected + Place sse_decode_place(SseDeserializer deserializer); + + @protected + PlaceKind sse_decode_place_kind(SseDeserializer deserializer); + + @protected + (String?, String?) sse_decode_record_opt_string_opt_string( + SseDeserializer deserializer, + ); + + @protected + RelatedDto sse_decode_related_dto(SseDeserializer deserializer); + + @protected + TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer); + + @protected + TimelineDto sse_decode_timeline_dto(SseDeserializer deserializer); + + @protected + TitleHit sse_decode_title_hit(SseDeserializer deserializer); + + @protected + int sse_decode_u_32(SseDeserializer deserializer); + + @protected + BigInt sse_decode_u_64(SseDeserializer deserializer); + + @protected + int sse_decode_u_8(SseDeserializer deserializer); + + @protected + void sse_decode_unit(SseDeserializer deserializer); + + @protected + BigInt sse_decode_usize(SseDeserializer deserializer); + + @protected + void sse_encode_AnyhowException( + AnyhowException self, + SseSerializer serializer, + ); + + @protected + void + sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ); + + @protected + void + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ); + + @protected + void + sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + SynapseGraph self, + SseSerializer serializer, + ); + + @protected + void sse_encode_String(String self, SseSerializer serializer); + + @protected + void sse_encode_asset_dto(AssetDto self, SseSerializer serializer); + + @protected + void sse_encode_backlink_group(BacklinkGroup self, SseSerializer serializer); + + @protected + void sse_encode_block_dto(BlockDto self, SseSerializer serializer); + + @protected + void sse_encode_block_hit(BlockHit self, SseSerializer serializer); + + @protected + void sse_encode_block_ref_dto(BlockRefDto self, SseSerializer serializer); + + @protected + void sse_encode_bool(bool self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_block_ref_dto( + BlockRefDto self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_page_data( + PageData self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_place(Place self, SseSerializer serializer); + + @protected + void sse_encode_edit_dto(EditDto self, SseSerializer serializer); + + @protected + void sse_encode_f_32(double self, SseSerializer serializer); + + @protected + void sse_encode_i_32(int self, SseSerializer serializer); + + @protected + void sse_encode_i_64(PlatformInt64 self, SseSerializer serializer); + + @protected + void sse_encode_list_String(List self, SseSerializer serializer); + + @protected + void sse_encode_list_backlink_group( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_block_dto(List self, SseSerializer serializer); + + @protected + void sse_encode_list_block_hit(List self, SseSerializer serializer); + + @protected + void sse_encode_list_edit_dto(List self, SseSerializer serializer); + + @protected + void sse_encode_list_page_brief( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_page_data(List self, SseSerializer serializer); + + @protected + void sse_encode_list_page_dto(List self, SseSerializer serializer); + + @protected + void sse_encode_list_prim_u_8_loose(List self, SseSerializer serializer); + + @protected + void sse_encode_list_prim_u_8_strict( + Uint8List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_related_dto( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_timeline_day_dto( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_title_hit(List self, SseSerializer serializer); + + @protected + void sse_encode_opt_String(String? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_block_ref_dto( + BlockRefDto? self, + SseSerializer serializer, + ); + + @protected + void sse_encode_opt_box_autoadd_page_data( + PageData? self, + SseSerializer serializer, + ); + + @protected + void sse_encode_page_brief(PageBrief self, SseSerializer serializer); + + @protected + void sse_encode_page_data(PageData self, SseSerializer serializer); + + @protected + void sse_encode_page_dto(PageDto self, SseSerializer serializer); + + @protected + void sse_encode_place(Place self, SseSerializer serializer); + + @protected + void sse_encode_place_kind(PlaceKind self, SseSerializer serializer); + + @protected + void sse_encode_record_opt_string_opt_string( + (String?, String?) self, + SseSerializer serializer, + ); + + @protected + void sse_encode_related_dto(RelatedDto self, SseSerializer serializer); + + @protected + void sse_encode_timeline_day_dto( + TimelineDayDto self, + SseSerializer serializer, + ); + + @protected + void sse_encode_timeline_dto(TimelineDto self, SseSerializer serializer); + + @protected + void sse_encode_title_hit(TitleHit self, SseSerializer serializer); + + @protected + void sse_encode_u_32(int self, SseSerializer serializer); + + @protected + void sse_encode_u_64(BigInt self, SseSerializer serializer); + + @protected + void sse_encode_u_8(int self, SseSerializer serializer); + + @protected + void sse_encode_unit(void self, SseSerializer serializer); + + @protected + void sse_encode_usize(BigInt self, SseSerializer serializer); +} + +// Section: wire_class + +class RustLibWire implements BaseWire { + RustLibWire.fromExternalLibrary(ExternalLibrary lib); + + void + rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + int ptr, + ) => wasmModule + .rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ptr, + ); + + void + rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + int ptr, + ) => wasmModule + .rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ptr, + ); +} + +@JS('wasm_bindgen') +external RustLibWasmModule get wasmModule; + +@JS() +@anonymous +extension type RustLibWasmModule._(JSObject _) implements JSObject { + external void + rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + int ptr, + ); + + external void + rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + int ptr, + ); +} diff --git a/app/lib/src/state/app_state.dart b/app/lib/src/state/app_state.dart new file mode 100644 index 0000000..6faf9d2 --- /dev/null +++ b/app/lib/src/state/app_state.dart @@ -0,0 +1,200 @@ +import 'package:flutter/material.dart'; + +import '../backend/graph_backend.dart'; +import 'write_queue.dart'; + +sealed class AppRoute { + const AppRoute(); +} + +class JournalsRoute extends AppRoute { + const JournalsRoute(); +} + +class TimelineRoute extends AppRoute { + const TimelineRoute(); +} + +class AllPagesRoute extends AppRoute { + const AllPagesRoute(); +} + +/// A page, by id or (for links that may not exist yet) by title. +class PageTarget extends AppRoute { + const PageTarget({this.id, this.title}) : assert(id != null || title != null); + final String? id; + final String? title; +} + +/// App-wide state: the open graph, navigation history, recents and theme. +/// +/// State management is plain `ChangeNotifier`s: one for the app, one per open outline +/// (`OutlineController`) and a block-ref cache. The state is small and mostly local to a +/// page, so a framework (Riverpod, Bloc) would add a dependency and indirection without +/// paying for itself; rebuilds are scoped with `ListenableBuilder`. +class AppState extends ChangeNotifier { + AppState(this.backend, {WriteQueue? queue}) + : refs = BlockRefCache(backend), + queue = queue ?? WriteQueue() { + this.queue.onError = _writeFailed; + } + + final GraphBackend backend; + final WriteQueue queue; + final BlockRefCache refs; + + AppRoute _route = const JournalsRoute(); + final _back = []; + final _forward = []; + ThemeMode themeMode = ThemeMode.system; + final List recent = []; + + /// Last page shown (for synapse reinforcement on navigation). + String? _lastPageId; + + /// Bumped to make the current view reload from the core (failed writes, renames). + int generation = 0; + + /// Last write error, shown once by the shell. + String? writeError; + + AppRoute get route => _route; + bool get canGoBack => _back.isNotEmpty; + bool get canGoForward => _forward.isNotEmpty; + + /// A failed write leaves the optimistic UI out of sync: reload the view from the core. + void _writeFailed(Object e, StackTrace st) { + debugPrint('graph write failed: $e\n$st'); + writeError = '$e'; + reload(); + } + + /// Rebuilds the current view from the core (after queued writes have run). + void reload() { + generation++; + notifyListeners(); + } + + void go(AppRoute r) { + _back.add(_route); + if (_back.length > 100) _back.removeAt(0); + _forward.clear(); + _route = r; + notifyListeners(); + } + + void back() { + if (_back.isEmpty) return; + _forward.add(_route); + _route = _back.removeLast(); + notifyListeners(); + } + + void forward() { + if (_forward.isEmpty) return; + _back.add(_route); + _route = _forward.removeLast(); + notifyListeners(); + } + + void openTitle(String title) => go(PageTarget(title: title)); + void openId(String id) => go(PageTarget(id: id)); + + /// Called by the page view once it knows which page it shows. + void pageShown(PageDto page) { + final from = _lastPageId; + _lastPageId = page.id; + if (from != page.id) { + queue.run(() => backend.recordVisit(from, page.id)).ignore(); + } + recent.removeWhere((p) => p.id == page.id); + recent.insert( + 0, + PageBrief( + id: page.id, + title: page.title, + isJournal: page.journalDate != null, + ), + ); + if (recent.length > 12) recent.removeLast(); + notifyListeners(); + } + + /// Seeds the recents list with recently edited pages. + Future loadRecent() async { + final pages = await backend.listPages(limit: 8); + for (final p in pages) { + if (!recent.any((r) => r.id == p.id)) { + recent.add(PageBrief(id: p.id, title: p.title, isJournal: false)); + } + } + notifyListeners(); + } + + void renamed(String id, String title) { + final i = recent.indexWhere((p) => p.id == id); + if (i >= 0) { + recent[i] = PageBrief( + id: id, + title: title, + isJournal: recent[i].isJournal, + ); + } + notifyListeners(); + } + + void toggleTheme(Brightness current) { + themeMode = current == Brightness.dark ? ThemeMode.light : ThemeMode.dark; + notifyListeners(); + } +} + +/// Resolved `((block refs))`, loaded lazily and shared by every rendered block. +class BlockRefCache extends ChangeNotifier { + BlockRefCache(this._backend); + + final GraphBackend _backend; + final _cache = {}; + final _loading = {}; + + /// Cached target, or null while loading / when missing ([isMissing] tells them apart). + BlockRefDto? get(String id) { + if (_cache.containsKey(id)) return _cache[id]; + if (_loading.add(id)) { + _backend + .blockRef(id) + .then( + (r) { + _cache[id] = r; + _loading.remove(id); + notifyListeners(); + }, + onError: (Object _) { + _cache[id] = null; + _loading.remove(id); + notifyListeners(); + }, + ); + } + return null; + } + + bool isMissing(String id) => _cache.containsKey(id) && _cache[id] == null; + + void invalidate(String id) { + if (_cache.remove(id) != null) notifyListeners(); + } +} + +/// Gives widgets access to the [AppState]. +class AppScope extends InheritedNotifier { + const AppScope({super.key, required AppState state, required super.child}) + : super(notifier: state); + + static AppState of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()!.notifier!; + + /// Access without subscribing to changes. + static AppState read(BuildContext context) => + context.getInheritedWidgetOfExactType()!.notifier!; +} diff --git a/app/lib/src/state/outline_controller.dart b/app/lib/src/state/outline_controller.dart new file mode 100644 index 0000000..16d740f --- /dev/null +++ b/app/lib/src/state/outline_controller.dart @@ -0,0 +1,370 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../backend/graph_backend.dart'; +import 'outline_ops.dart'; +import 'write_queue.dart'; + +/// Editing state of one page's outline. +/// +/// Edits are applied to [nodes] immediately (optimistic) and sent to the core through the +/// shared [WriteQueue]. Text is saved with a debounce; structural edits flush pending text +/// first. Blocks created locally carry a temporary id until the core assigns the real one; +/// queued tasks read ids from the node objects when they run, so they always see the real id. +/// After structural edits settle, the outline is re-read and adopted if it disagrees. +class OutlineController extends ChangeNotifier { + OutlineController({ + required this.backend, + required this.queue, + required this.pageId, + required List blocks, + this.saveDelay = const Duration(milliseconds: 350), + }) : nodes = blocks.map(OutlineNode.fromDto).toList(); + + final GraphBackend backend; + final WriteQueue queue; + final String pageId; + final Duration saveDelay; + final List nodes; + + /// Block being edited, if any. + String? focusedId; + + /// Caret requested for the focused block; consumed by the row once applied. + int? pendingCaret; + + final _timers = {}; + Timer? _reconcile; + int _structuralEdits = 0; + static int _tmpSeq = 0; + bool _disposed = false; + + // ------------------------------------------------------------- queries + + List get visible => OutlineOps.visible(nodes); + + int indexOf(String id) => nodes.indexWhere((n) => n.id == id); + + OutlineNode? byId(String id) { + final i = indexOf(id); + return i < 0 ? null : nodes[i]; + } + + bool hasChildren(OutlineNode n) => + OutlineOps.hasChildren(nodes, nodes.indexOf(n)); + + OutlineNode? _visibleNeighbour(OutlineNode n, int step) { + final vis = visible; + final pos = vis.indexOf(nodes.indexOf(n)); + final k = pos + step; + return pos < 0 || k < 0 || k >= vis.length ? null : nodes[vis[k]]; + } + + OutlineNode? previousVisible(OutlineNode n) => _visibleNeighbour(n, -1); + OutlineNode? nextVisible(OutlineNode n) => _visibleNeighbour(n, 1); + + // --------------------------------------------------------------- focus + + void focus(String id, {int? caret}) { + focusedId = id; + pendingCaret = caret; + notifyListeners(); + } + + /// Called by a row when it loses focus. + void blurred(String id) { + final n = byId(id); + if (n != null) _flush(n); + if (focusedId == id) { + focusedId = null; + pendingCaret = null; + notifyListeners(); + } + } + + // ---------------------------------------------------------------- text + + /// Text changed while typing (debounced save). + void setText(OutlineNode n, String text) { + if (n.content == text) return; + n.content = text; + _timers[n]?.cancel(); + _timers[n] = Timer(saveDelay, () => _flush(n)); + } + + void _flush(OutlineNode n) { + final t = _timers.remove(n); + if (t == null) return; + t.cancel(); + final content = n.content; + _enqueue(() => backend.updateBlock(n.id, content)); + } + + void flushAll() { + for (final n in _timers.keys.toList()) { + _flush(n); + } + } + + /// Replaces a block's text right away (e.g. toggling TODO from a checkbox). + void replaceText(OutlineNode n, String text, {int? caret}) { + setText(n, text); + _flush(n); + if (caret != null && focusedId == n.id) pendingCaret = caret; + notifyListeners(); + } + + // ----------------------------------------------------------- structure + + /// Creates the first block of an empty page and focuses it. + void insertFirst() { + final node = _newNode(''); + OutlineOps.insert(nodes, node, PlaceKind.lastChildOf, null); + _sendInsert(node, PlaceKind.lastChildOf, null); + focus(node.id, caret: 0); + } + + /// Enter at `caret`: splits the block. At the very start of a non-empty block a new empty + /// block is inserted above and the caret stays put. + void split(OutlineNode n, int caret) { + final text = n.content; + caret = caret.clamp(0, text.length); + final i = nodes.indexOf(n); + if (caret == 0 && text.isNotEmpty) { + final node = _newNode(''); + OutlineOps.insert(nodes, node, PlaceKind.before, i); + _sendInsert(node, PlaceKind.before, n); + focus(n.id, caret: 0); + return; + } + final before = text.substring(0, caret); + var after = text.substring(caret); + if (after.isEmpty && + RegExp(r'^(TODO|DOING|DONE|LATER|NOW) ').hasMatch(before)) { + after = 'TODO '; + } + setText(n, before); + _flush(n); + final intoChildren = !n.collapsed && OutlineOps.hasChildren(nodes, i); + final kind = intoChildren ? PlaceKind.firstChildOf : PlaceKind.after; + final node = _newNode(after); + OutlineOps.insert(nodes, node, kind, i); + _sendInsert(node, kind, n); + focus(node.id, caret: after == 'TODO ' ? after.length : 0); + } + + void indent(OutlineNode n, {int? caret}) { + if (!OutlineOps.indent(nodes, nodes.indexOf(n))) return; + flushAll(); + _structural(() => backend.indentBlock(n.id)); + _refocus(n, caret); + } + + void outdent(OutlineNode n, {int? caret}) { + if (!OutlineOps.outdent(nodes, nodes.indexOf(n))) return; + flushAll(); + _structural(() => backend.outdentBlock(n.id)); + _refocus(n, caret); + } + + /// Backspace at the start of a block: merge into the previous visible block. + /// Returns false when there is nothing to merge into. + bool mergeIntoPrevious(OutlineNode n) { + final prev = previousVisible(n); + if (prev == null) return false; + _merge(n, prev); + return true; + } + + /// Delete at the end of a block: pull the next visible block into it. + bool mergeNext(OutlineNode n) { + final next = nextVisible(n); + if (next == null) return false; + _merge(next, n); + return true; + } + + void _merge(OutlineNode n, OutlineNode into) { + final caret = into.content.length; + flushAll(); + OutlineOps.merge(nodes, nodes.indexOf(n), nodes.indexOf(into)); + _structural(() => backend.mergeBlock(n.id, into.id)); + focus(into.id, caret: caret); + } + + /// Alt+Shift+Up/Down: swap with the previous/next sibling. + void moveAmongSiblings(OutlineNode n, {required bool up, int? caret}) { + final i = nodes.indexOf(n); + final s = up + ? OutlineOps.prevSibling(nodes, i) + : OutlineOps.nextSibling(nodes, i); + if (s == null) return; + final kind = up ? PlaceKind.before : PlaceKind.after; + moveTo(n, kind, nodes[s], caret: caret); + } + + /// Drag and drop (or keyboard move) relative to `anchor`. + void moveTo( + OutlineNode n, + PlaceKind kind, + OutlineNode? anchor, { + int? caret, + }) { + final a = anchor == null ? null : nodes.indexOf(anchor); + if (!OutlineOps.move(nodes, nodes.indexOf(n), kind, a)) return; + flushAll(); + final expand = + anchor != null && + (kind == PlaceKind.firstChildOf || kind == PlaceKind.lastChildOf); + _structural(() async { + if (expand) await backend.setCollapsed(anchor.id, false); + return backend.moveBlock( + n.id, + pageId, + Place(kind: kind, anchor: anchor?.id), + ); + }); + if (focusedId == n.id) { + _refocus(n, caret); + } else { + notifyListeners(); + } + } + + void delete(OutlineNode n) { + final prev = previousVisible(n); + flushAll(); + OutlineOps.delete(nodes, nodes.indexOf(n)); + _structural(() => backend.deleteBlock(n.id)); + if (focusedId == n.id && prev != null) { + focus(prev.id, caret: prev.content.length); + } else { + notifyListeners(); + } + } + + void toggleCollapsed(OutlineNode n) { + if (!hasChildren(n) && !n.collapsed) return; + n.collapsed = !n.collapsed; + final collapsed = n.collapsed; + _enqueue(() => backend.setCollapsed(n.id, collapsed)); + if (collapsed && focusedId != null) { + final f = byId(focusedId!); + if (f != null && !visible.contains(nodes.indexOf(f))) focus(n.id); + } + notifyListeners(); + } + + /// Ctrl+Enter: none → TODO → DONE → none. Returns the caret shift. + int cycleTodo(OutlineNode n) { + final t = n.content; + String next; + int shift; + if (t.startsWith('TODO ') || + t.startsWith('DOING ') || + t.startsWith('NOW ') || + t.startsWith('LATER ')) { + final rest = t.substring(t.indexOf(' ') + 1); + next = 'DONE $rest'; + shift = next.length - t.length; + } else if (t.startsWith('DONE ')) { + next = t.substring(5); + shift = -5; + } else { + next = 'TODO $t'; + shift = 5; + } + replaceText(n, next); + return shift; + } + + // ------------------------------------------------------------ plumbing + + OutlineNode _newNode(String content) => + OutlineNode(id: '_tmp${_tmpSeq++}', depth: 0, content: content); + + void _sendInsert(OutlineNode node, PlaceKind kind, OutlineNode? anchor) { + final content = node.content; + _enqueue(() async { + final b = await backend.insertBlock( + pageId, + Place(kind: kind, anchor: anchor?.id), + content, + ); + final wasFocused = focusedId == node.id; + node.id = b.id; + OutlineOps.fixParents(nodes); + if (wasFocused) focusedId = b.id; + if (!_disposed) notifyListeners(); + }); + _scheduleVerify(); + } + + void _refocus(OutlineNode n, int? caret) { + if (focusedId == n.id) { + pendingCaret = caret; + } + notifyListeners(); + } + + void _structural(Future> Function() op) { + _enqueue(() async { + await op(); + }); + _scheduleVerify(); + } + + void _scheduleVerify() { + _structuralEdits++; + final seen = _structuralEdits; + _reconcile?.cancel(); + _reconcile = Timer(const Duration(milliseconds: 600), () { + if (seen == _structuralEdits) _verify(); + }); + } + + /// Re-reads the outline and adopts the core's structure if it differs from ours. + void _verify() { + final seen = _structuralEdits; + _enqueue(() async { + final server = await backend.outline(pageId); + if (_disposed || seen != _structuralEdits) return; + if (nodes.any((n) => n.id.startsWith('_tmp'))) return; + final same = + server.length == nodes.length && + List.generate(server.length, (i) => i).every( + (i) => + server[i].id == nodes[i].id && + server[i].depth == nodes[i].depth, + ); + if (same) return; + debugPrint('outline: adopting core structure for page $pageId'); + final local = {for (final n in nodes) n.id: n}; + final adopted = server.map((b) { + final n = local[b.id] ?? OutlineNode.fromDto(b); + n + ..depth = b.depth + ..parentId = b.parentId + ..collapsed = b.collapsed; + return n; + }).toList(); + nodes + ..clear() + ..addAll(adopted); + notifyListeners(); + }); + } + + void _enqueue(Future Function() task) { + queue.run(task).ignore(); + } + + @override + void dispose() { + flushAll(); + _reconcile?.cancel(); + _disposed = true; + super.dispose(); + } +} diff --git a/app/lib/src/state/outline_ops.dart b/app/lib/src/state/outline_ops.dart new file mode 100644 index 0000000..8f438b9 --- /dev/null +++ b/app/lib/src/state/outline_ops.dart @@ -0,0 +1,208 @@ +import '../backend/graph_backend.dart'; + +/// One outline row held by the editor. Mutable on purpose: the editor applies edits in place +/// and rebuilds only what changed. +class OutlineNode { + OutlineNode({ + required this.id, + this.parentId, + required this.depth, + required this.content, + this.collapsed = false, + }); + + factory OutlineNode.fromDto(BlockDto b) => OutlineNode( + id: b.id, + parentId: b.parentId, + depth: b.depth, + content: b.content, + collapsed: b.collapsed, + ); + + String id; + String? parentId; + int depth; + String content; + bool collapsed; + + OutlineNode copy() => OutlineNode( + id: id, + parentId: parentId, + depth: depth, + content: content, + collapsed: collapsed, + ); + + @override + String toString() => '$depth:$content'; +} + +/// Outline algorithms on a pre-order list of nodes. They mirror `synapse-ffi`'s outline +/// module so the editor can apply edits optimistically and agree with the core. +class OutlineOps { + OutlineOps._(); + + /// Index right after the subtree rooted at `i`. + static int subtreeEnd(List l, int i) { + var j = i + 1; + while (j < l.length && l[j].depth > l[i].depth) { + j++; + } + return j; + } + + static bool hasChildren(List l, int i) => + i + 1 < l.length && l[i + 1].depth > l[i].depth; + + static int? prevSibling(List l, int i) { + for (var j = i - 1; j >= 0; j--) { + if (l[j].depth == l[i].depth) return j; + if (l[j].depth < l[i].depth) return null; + } + return null; + } + + static int? nextSibling(List l, int i) { + final j = subtreeEnd(l, i); + return j < l.length && l[j].depth == l[i].depth ? j : null; + } + + static int? parent(List l, int i) { + for (var j = i - 1; j >= 0; j--) { + if (l[j].depth < l[i].depth) return j; + } + return null; + } + + /// Indices of rows not hidden under a collapsed ancestor. + static List visible(List l) { + final out = []; + var i = 0; + while (i < l.length) { + out.add(i); + i = l[i].collapsed ? subtreeEnd(l, i) : i + 1; + } + return out; + } + + /// Recomputes `parentId` from depths. + static void fixParents(List l) { + final stack = []; + for (final n in l) { + while (stack.isNotEmpty && stack.last.depth >= n.depth) { + stack.removeLast(); + } + n.parentId = stack.isEmpty ? null : stack.last.id; + stack.add(n); + } + } + + static void _shift(List l, int from, int to, int by) { + for (var k = from; k < to; k++) { + l[k].depth += by; + } + } + + /// Tab. Returns false when there is no previous sibling. + static bool indent(List l, int i) { + final p = prevSibling(l, i); + if (p == null) return false; + l[p].collapsed = false; + _shift(l, i, subtreeEnd(l, i), 1); + fixParents(l); + return true; + } + + /// Shift-Tab with direct outdenting: following siblings become children of the block. + static bool outdent(List l, int i) { + if (l[i].depth == 0) return false; + final end = subtreeEnd(l, i); + final hadFollowing = end < l.length && l[end].depth == l[i].depth; + _shift(l, i, end, -1); + if (hadFollowing) l[i].collapsed = false; + fixParents(l); + return true; + } + + /// Merges row `i` into row `into` (its previous visible row). + static void merge(List l, int i, int into) { + final target = l[into]; + final isParent = parent(l, i) == into; + target.content += l[i].content; + final end = subtreeEnd(l, i); + if (end > i + 1) { + if (isParent) { + _shift(l, i + 1, end, -1); + } else { + target.collapsed = false; + _shift(l, i + 1, end, target.depth - l[i].depth); + } + } + l.removeAt(i); + fixParents(l); + } + + /// Deletes row `i` with its subtree. + static void delete(List l, int i) { + l.removeRange(i, subtreeEnd(l, i)); + fixParents(l); + } + + /// Insertion index and depth for a placement, or null when the anchor is unknown. + static (int, int)? slot(List l, PlaceKind kind, int? anchor) { + switch (kind) { + case PlaceKind.before: + if (anchor == null) return null; + return (anchor, l[anchor].depth); + case PlaceKind.after: + if (anchor == null) return null; + return (subtreeEnd(l, anchor), l[anchor].depth); + case PlaceKind.firstChildOf: + if (anchor == null) return (0, 0); + return (anchor + 1, l[anchor].depth + 1); + case PlaceKind.lastChildOf: + if (anchor == null) return (l.length, 0); + return (subtreeEnd(l, anchor), l[anchor].depth + 1); + } + } + + static int insert( + List l, + OutlineNode node, + PlaceKind kind, + int? anchor, + ) { + final (at, depth) = slot(l, kind, anchor)!; + if (anchor != null && + (kind == PlaceKind.firstChildOf || kind == PlaceKind.lastChildOf)) { + l[anchor].collapsed = false; + } + node.depth = depth; + l.insert(at, node); + fixParents(l); + return at; + } + + /// Moves row `i` with its subtree. Returns false for moves into its own subtree. + static bool move(List l, int i, PlaceKind kind, int? anchor) { + final end = subtreeEnd(l, i); + if (anchor != null && anchor >= i && anchor < end) return false; + final s = slot(l, kind, anchor); + if (s == null) return false; + if (anchor != null && + (kind == PlaceKind.firstChildOf || kind == PlaceKind.lastChildOf)) { + l[anchor].collapsed = false; + } + var (at, depth) = s; + final moved = l.sublist(i, end); + final delta = depth - moved.first.depth; + for (final n in moved) { + n.depth += delta; + } + l.removeRange(i, end); + if (at > i) at -= moved.length; + l.insertAll(at, moved); + fixParents(l); + return true; + } +} diff --git a/app/lib/src/state/write_queue.dart b/app/lib/src/state/write_queue.dart new file mode 100644 index 0000000..976085e --- /dev/null +++ b/app/lib/src/state/write_queue.dart @@ -0,0 +1,55 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:flutter/foundation.dart'; + +/// Runs graph writes one at a time, in submission order. FFI calls are async and run on a +/// Rust thread pool, so without this two quick edits could reach the core out of order. +class WriteQueue { + WriteQueue({this.onError}); + + /// Called with any error a task throws; the task's own future also completes with it. + void Function(Object error, StackTrace stack)? onError; + + final _tasks = Queue Function()>(); + bool _running = false; + Completer? _idle; + + bool get isIdle => !_running && _tasks.isEmpty; + + /// Completes when every queued task has run. + Future get idle { + if (isIdle) return Future.value(); + return (_idle ??= Completer()).future; + } + + /// Queues `task`. Reads pass `report: false` so their errors do not reach [onError]. + Future run(Future Function() task, {bool report = true}) { + final done = Completer(); + _tasks.add(() async { + try { + done.complete(await task()); + } catch (e, st) { + if (report) onError?.call(e, st); + done.completeError(e, st); + } + }); + _pump(); + return done.future; + } + + Future _pump() async { + if (_running) return; + _running = true; + while (_tasks.isNotEmpty) { + await _tasks.removeFirst()(); + } + _running = false; + final idle = _idle; + _idle = null; + idle?.complete(); + } + + @visibleForTesting + int get pending => _tasks.length; +} diff --git a/app/lib/src/theme/theme.dart b/app/lib/src/theme/theme.dart new file mode 100644 index 0000000..24dc17f --- /dev/null +++ b/app/lib/src/theme/theme.dart @@ -0,0 +1,198 @@ +import 'package:flutter/material.dart'; + +/// Synapse's design tokens. +/// +/// Typography: Inter for UI and note text (designed for screens, clear at small sizes, wide +/// language coverage), Noto Serif for page and journal titles (a quiet, bookish voice that +/// separates "the document" from the chrome), Source Code Pro for code. All three are bundled +/// (OFL) so the app looks the same offline on every platform. +/// +/// Colour: warm paper neutrals instead of pure white/black to keep long reading calm, one +/// accent (deep teal) for links and focus, amber for block references and a muted green for +/// done tasks. Dark mode mirrors the same hues at lower saturation. +@immutable +class SynapseColors extends ThemeExtension { + const SynapseColors({ + required this.paper, + required this.surface, + required this.ink, + required this.muted, + required this.faint, + required this.line, + required this.accent, + required this.accentSoft, + required this.ref, + required this.done, + required this.codeBg, + required this.highlight, + }); + + final Color paper; + final Color surface; + final Color ink; + final Color muted; + final Color faint; + final Color line; + final Color accent; + final Color accentSoft; + final Color ref; + final Color done; + final Color codeBg; + final Color highlight; + + static const light = SynapseColors( + paper: Color(0xFFFAF8F4), + surface: Color(0xFFF3F0EA), + ink: Color(0xFF23262B), + muted: Color(0xFF6B6F76), + faint: Color(0xFFA9A69F), + line: Color(0xFFE4E0D8), + accent: Color(0xFF1F7A74), + accentSoft: Color(0x1A1F7A74), + ref: Color(0xFFB0741E), + done: Color(0xFF6F8F5E), + codeBg: Color(0xFFEFEBE3), + highlight: Color(0x66F3D86B), + ); + + static const dark = SynapseColors( + paper: Color(0xFF16181B), + surface: Color(0xFF1D2024), + ink: Color(0xFFE4E2DD), + muted: Color(0xFF9A9FA6), + faint: Color(0xFF61666D), + line: Color(0xFF2B2F35), + accent: Color(0xFF63C2B8), + accentSoft: Color(0x2263C2B8), + ref: Color(0xFFD9A55A), + done: Color(0xFF8DAF7B), + codeBg: Color(0xFF23272C), + highlight: Color(0x55B89B2E), + ); + + @override + SynapseColors copyWith() => this; + + @override + SynapseColors lerp(SynapseColors? other, double t) { + if (other == null) return this; + Color l(Color a, Color b) => Color.lerp(a, b, t)!; + return SynapseColors( + paper: l(paper, other.paper), + surface: l(surface, other.surface), + ink: l(ink, other.ink), + muted: l(muted, other.muted), + faint: l(faint, other.faint), + line: l(line, other.line), + accent: l(accent, other.accent), + accentSoft: l(accentSoft, other.accentSoft), + ref: l(ref, other.ref), + done: l(done, other.done), + codeBg: l(codeBg, other.codeBg), + highlight: l(highlight, other.highlight), + ); + } +} + +const uiFont = 'Inter'; +const titleFont = 'NotoSerif'; +const monoFont = 'SourceCodePro'; + +/// Text metrics of the outliner, shared by rendering and editing so a block does not jump +/// when it switches between the two. +const blockFontSize = 15.0; +const blockLineHeight = 1.55; + +extension SynapseThemeX on BuildContext { + SynapseColors get colors => Theme.of(this).extension()!; +} + +ThemeData buildTheme(Brightness brightness) { + final c = brightness == Brightness.light + ? SynapseColors.light + : SynapseColors.dark; + final scheme = + ColorScheme.fromSeed( + seedColor: c.accent, + brightness: brightness, + ).copyWith( + primary: c.accent, + surface: c.paper, + onSurface: c.ink, + surfaceContainerLowest: c.paper, + surfaceContainerLow: c.surface, + surfaceContainer: c.surface, + surfaceContainerHigh: c.surface, + outline: c.line, + outlineVariant: c.line, + ); + final base = ThemeData( + useMaterial3: true, + brightness: brightness, + colorScheme: scheme, + fontFamily: uiFont, + scaffoldBackgroundColor: c.paper, + canvasColor: c.paper, + dividerColor: c.line, + splashFactory: NoSplash.splashFactory, + visualDensity: VisualDensity.compact, + extensions: [c], + ); + final t = base.textTheme.apply(bodyColor: c.ink, displayColor: c.ink); + return base.copyWith( + textTheme: t.copyWith( + bodyMedium: t.bodyMedium?.copyWith( + fontSize: blockFontSize, + height: blockLineHeight, + ), + headlineLarge: TextStyle( + fontFamily: titleFont, + fontSize: 30, + fontWeight: FontWeight.w600, + height: 1.25, + color: c.ink, + letterSpacing: -0.2, + ), + headlineSmall: TextStyle( + fontFamily: titleFont, + fontSize: 22, + fontWeight: FontWeight.w600, + height: 1.3, + color: c.ink, + ), + labelSmall: TextStyle( + fontFamily: uiFont, + fontSize: 11, + fontWeight: FontWeight.w600, + letterSpacing: 0.8, + color: c.muted, + ), + ), + textSelectionTheme: TextSelectionThemeData( + cursorColor: c.accent, + selectionColor: c.accentSoft.withAlpha(0x55), + selectionHandleColor: c.accent, + ), + tooltipTheme: TooltipThemeData( + waitDuration: const Duration(milliseconds: 500), + decoration: BoxDecoration( + color: c.ink, + borderRadius: BorderRadius.circular(6), + ), + textStyle: TextStyle(color: c.paper, fontSize: 12), + ), + dialogTheme: DialogThemeData( + backgroundColor: c.paper, + surfaceTintColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + side: BorderSide(color: c.line), + ), + ), + scrollbarTheme: ScrollbarThemeData( + thickness: const WidgetStatePropertyAll(6), + radius: const Radius.circular(3), + thumbColor: WidgetStatePropertyAll(c.faint.withAlpha(0x66)), + ), + ); +} diff --git a/app/lib/src/views/all_pages_view.dart b/app/lib/src/views/all_pages_view.dart new file mode 100644 index 0000000..3cea414 --- /dev/null +++ b/app/lib/src/views/all_pages_view.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; + +import '../backend/graph_backend.dart'; +import '../state/app_state.dart'; +import '../theme/theme.dart'; +import '../widgets/common.dart'; +import '../widgets/dates.dart'; + +/// Every non-journal page, most recently edited first, loaded in pages of 100. +class AllPagesView extends StatefulWidget { + const AllPagesView({super.key}); + + @override + State createState() => _AllPagesViewState(); +} + +class _AllPagesViewState extends State { + final _pages = []; + bool _loading = false; + bool _done = false; + + @override + void initState() { + super.initState(); + _more(); + } + + Future _more() async { + if (_loading || _done) return; + _loading = true; + final batch = await AppScope.read(context).backend + .listPages(limit: 100, offset: _pages.length); + if (!mounted) return; + setState(() { + _pages.addAll(batch); + _done = batch.length < 100; + _loading = false; + }); + } + + @override + Widget build(BuildContext context) { + final app = AppScope.read(context); + final colors = context.colors; + return LayoutBuilder( + builder: (context, box) => NotificationListener( + onNotification: (n) { + if (n.metrics.extentAfter < 600) _more(); + return false; + }, + child: ListView.builder( + padding: EdgeInsets.fromLTRB( + sidePadding(box.maxWidth), + 36, + sidePadding(box.maxWidth), + 80, + ), + itemCount: _pages.length + 1, + itemBuilder: (context, i) { + if (i == 0) { + return Padding( + padding: const EdgeInsets.only(bottom: 20), + child: Text( + 'All pages', + style: Theme.of(context).textTheme.headlineLarge, + ), + ); + } + final p = _pages[i - 1]; + final edited = DateTime.fromMillisecondsSinceEpoch( + p.updatedAt.toInt(), + ); + return InkWell( + borderRadius: BorderRadius.circular(8), + onTap: () => app.openId(p.id), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8), + child: Row( + children: [ + Expanded( + child: Text( + p.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14.5, color: colors.ink), + ), + ), + if (p.originJournal != null) + Text( + 'born ${shortDate(parseDay(p.originJournal!))}', + style: TextStyle(fontSize: 12, color: colors.faint), + ), + const SizedBox(width: 16), + SizedBox( + width: 70, + child: Text( + shortDate(edited), + textAlign: TextAlign.right, + style: TextStyle(fontSize: 12, color: colors.muted), + ), + ), + ], + ), + ), + ); + }, + ), + ), + ); + } +} diff --git a/app/lib/src/views/journals_view.dart b/app/lib/src/views/journals_view.dart new file mode 100644 index 0000000..ba2c51d --- /dev/null +++ b/app/lib/src/views/journals_view.dart @@ -0,0 +1,233 @@ +import 'package:flutter/material.dart'; + +import '../backend/graph_backend.dart'; +import '../editor/outline_view.dart'; +import '../state/app_state.dart'; +import '../state/outline_controller.dart'; +import '../theme/theme.dart'; +import '../widgets/common.dart'; +import '../widgets/dates.dart'; + +/// Continuous feed of journals, today on top, loading older days as you scroll. +class JournalsView extends StatefulWidget { + const JournalsView({super.key}); + + @override + State createState() => _JournalsViewState(); +} + +class _Day { + _Day(this.view, this.controller); + final PageData view; + final OutlineController controller; +} + +class _JournalsViewState extends State { + static const _batch = 7; + final _days = <_Day>[]; + bool _loading = false; + bool _exhausted = false; + Object? _error; + + @override + void initState() { + super.initState(); + _loadMore(); + } + + @override + void dispose() { + for (final d in _days) { + d.controller.dispose(); + } + super.dispose(); + } + + Future _loadMore() async { + if (_loading || _exhausted) return; + setState(() => _loading = true); + final app = AppScope.read(context); + try { + final before = _days.isEmpty ? null : _days.last.view.page.journalDate; + if (_days.isEmpty) await WidgetsBinding.instance.endOfFrame; + final views = await app.queue.run( + () => app.backend.journals(before: before, limit: _batch), + report: false, + ); + if (!mounted) return; + setState(() { + for (final v in views) { + _days.add( + _Day( + v, + OutlineController( + backend: app.backend, + queue: app.queue, + pageId: v.page.id, + blocks: v.blocks, + ), + ), + ); + } + _exhausted = views.length < _batch; + _loading = false; + }); + } catch (e) { + if (mounted) { + setState(() { + _error = e; + _loading = false; + }); + } + } + } + + @override + Widget build(BuildContext context) { + final app = AppScope.read(context); + final today = app.backend.today(); + return LayoutBuilder( + builder: (context, box) { + final pad = sidePadding(box.maxWidth); + return NotificationListener( + onNotification: (n) { + if (n.metrics.extentAfter < 800) _loadMore(); + return false; + }, + child: CustomScrollView( + slivers: [ + const SliverToBoxAdapter(child: SizedBox(height: 28)), + for (final d in _days) + SliverPadding( + padding: EdgeInsets.symmetric(horizontal: pad), + sliver: SliverMainAxisGroup( + slivers: [ + SliverToBoxAdapter( + child: _JournalHeader(view: d.view, today: today), + ), + OutlineSliver(controller: d.controller), + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 36), + child: Divider(height: 1, color: context.colors.line), + ), + ), + ], + ), + ), + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.only(bottom: 80), + child: Center( + child: _error != null + ? Text('Could not load journals: $_error') + : _exhausted + ? Text( + 'The beginning of your journals', + style: TextStyle( + color: context.colors.faint, + fontSize: 13, + ), + ) + : const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ), + ), + ], + ), + ); + }, + ); + } +} + +class _JournalHeader extends StatelessWidget { + const _JournalHeader({required this.view, required this.today}); + final PageData view; + final String today; + + @override + Widget build(BuildContext context) { + final app = AppScope.read(context); + final date = view.page.journalDate!; + final colors = context.colors; + final rel = relativeDay(date, today); + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Flexible( + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: () => app.openId(view.page.id), + child: Text( + longDate(date), + style: Theme.of(context).textTheme.headlineSmall, + ), + ), + ), + ), + const SizedBox(width: 12), + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + rel == null ? weekday(date) : '$rel · ${weekday(date)}', + style: TextStyle(color: colors.muted, fontSize: 13), + ), + ), + ], + ), + const SizedBox(height: 4), + JournalChain(view: view), + ], + ), + ); + } +} + +/// Previous / next journal links (the episodic chain). +class JournalChain extends StatelessWidget { + const JournalChain({super.key, required this.view}); + final PageData view; + + @override + Widget build(BuildContext context) { + final app = AppScope.read(context); + final prev = view.prevJournal; + final next = view.nextJournal; + if (prev == null && next == null) return const SizedBox.shrink(); + return Row( + children: [ + if (prev != null) + TextLink( + shortDate(parseDay(prev)), + icon: Icons.west_rounded, + onTap: () => app.openTitle(prev), + style: const TextStyle(fontSize: 12), + ), + if (prev != null && next != null) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: Text('·', style: TextStyle(color: context.colors.faint)), + ), + if (next != null) + TextLink( + shortDate(parseDay(next)), + icon: Icons.east_rounded, + iconAfter: true, + onTap: () => app.openTitle(next), + style: const TextStyle(fontSize: 12), + ), + ], + ); + } +} diff --git a/app/lib/src/views/page_screen.dart b/app/lib/src/views/page_screen.dart new file mode 100644 index 0000000..d236c4a --- /dev/null +++ b/app/lib/src/views/page_screen.dart @@ -0,0 +1,481 @@ +import 'package:flutter/material.dart'; + +import '../backend/graph_backend.dart'; +import '../editor/outline_view.dart'; +import '../state/app_state.dart'; +import '../state/outline_controller.dart'; +import '../theme/theme.dart'; +import '../widgets/common.dart'; +import '../widgets/dates.dart'; +import 'journals_view.dart'; + +/// A single page: title, aliases, outline, linked references and related notes. +class PageScreen extends StatefulWidget { + const PageScreen({super.key, required this.target}); + final PageTarget target; + + @override + State createState() => _PageScreenState(); +} + +class _PageScreenState extends State { + PageData? _view; + OutlineController? _outline; + List? _backlinks; + List? _related; + Object? _error; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _outline?.dispose(); + super.dispose(); + } + + Future _load() async { + final app = AppScope.read(context); + try { + final t = widget.target; + // Read after the previous view's pending saves (flushed when it is disposed at the + // end of this frame) have reached the core. + await WidgetsBinding.instance.endOfFrame; + final v = await app.queue.run( + () => t.id != null + ? app.backend.page(t.id!) + : app.backend.openPage(t.title!).then((p) => p), + report: false, + ); + if (!mounted) return; + if (v == null) { + setState(() => _error = 'This page no longer exists.'); + return; + } + final view = v; + setState(() { + _view = view; + _outline = OutlineController( + backend: app.backend, + queue: app.queue, + pageId: view.page.id, + blocks: view.blocks, + ); + }); + app.pageShown(view.page); + // Make sure pending writes (e.g. a link just typed elsewhere) are visible. + await app.queue.idle; + final results = await Future.wait([ + app.backend.backlinks(view.page.id), + app.backend.related(view.page.id), + ]); + if (!mounted) return; + setState(() { + _backlinks = results[0] as List; + _related = results[1] as List; + }); + } catch (e) { + if (mounted) setState(() => _error = e); + } + } + + @override + Widget build(BuildContext context) { + if (_error != null) { + return Center( + child: Text('$_error', style: TextStyle(color: context.colors.muted)), + ); + } + final view = _view; + if (view == null) return const SizedBox.shrink(); + return LayoutBuilder( + builder: (context, box) { + final wide = box.maxWidth >= 1180; + final mainWidth = wide ? box.maxWidth - 300 : box.maxWidth; + final pad = sidePadding(mainWidth); + final scroll = CustomScrollView( + slivers: [ + const SliverToBoxAdapter(child: SizedBox(height: 36)), + SliverPadding( + padding: EdgeInsets.symmetric(horizontal: pad), + sliver: SliverMainAxisGroup( + slivers: [ + SliverToBoxAdapter(child: _Header(view: view)), + OutlineSliver(controller: _outline!), + SliverToBoxAdapter( + child: _LinkedReferences(groups: _backlinks), + ), + if (!wide) + SliverToBoxAdapter(child: RelatedPanel(related: _related)), + const SliverToBoxAdapter(child: SizedBox(height: 120)), + ], + ), + ), + ], + ); + if (!wide) return scroll; + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: scroll), + Container( + width: 300, + decoration: BoxDecoration( + border: Border(left: BorderSide(color: context.colors.line)), + ), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(20, 44, 20, 40), + child: RelatedPanel(related: _related, compact: true), + ), + ), + ], + ); + }, + ); + } +} + +class _Header extends StatelessWidget { + const _Header({required this.view}); + final PageData view; + + @override + Widget build(BuildContext context) { + final page = view.page; + final colors = context.colors; + final journal = page.journalDate; + final app = AppScope.read(context); + return Padding( + padding: const EdgeInsets.only(bottom: 18), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (journal != null) ...[ + Text( + longDate(journal), + style: Theme.of(context).textTheme.headlineLarge, + ), + const SizedBox(height: 4), + Row( + children: [ + Text( + weekday(journal), + style: TextStyle(color: colors.muted, fontSize: 13), + ), + const SizedBox(width: 14), + JournalChain(view: view), + ], + ), + ] else ...[ + _TitleField(page: page), + const SizedBox(height: 6), + Wrap( + spacing: 14, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + if (page.originJournal != null) + TextLink( + 'Born ${longDate(page.originJournal!)}', + icon: Icons.spa_outlined, + onTap: () => app.openTitle(page.originJournal!), + style: const TextStyle(fontSize: 12), + ), + _Aliases(page: page, initial: view.aliases), + ], + ), + ], + ], + ), + ); + } +} + +/// Page title; editing it renames the page (and rewrites every link to it). +class _TitleField extends StatefulWidget { + const _TitleField({required this.page}); + final PageDto page; + + @override + State<_TitleField> createState() => _TitleFieldState(); +} + +class _TitleFieldState extends State<_TitleField> { + late final _text = TextEditingController(text: widget.page.title); + late final _focus = FocusNode()..addListener(_blur); + late String _committed = widget.page.title; + + @override + void dispose() { + _text.dispose(); + _focus.dispose(); + super.dispose(); + } + + void _blur() { + if (!_focus.hasFocus) _commit(); + } + + Future _commit() async { + final title = _text.text.trim(); + if (title.isEmpty || title == _committed) { + _text.text = _committed; + return; + } + final app = AppScope.read(context); + final messenger = ScaffoldMessenger.of(context); + try { + await app.queue.run(() => app.backend.renamePage(widget.page.id, title)); + _committed = title; + app.renamed(widget.page.id, title); + // The core rewrote links in other blocks, possibly on this page: reload them. + app.reload(); + } catch (e) { + _text.text = _committed; + messenger.showSnackBar(SnackBar(content: Text('Rename failed: $e'))); + } + } + + @override + Widget build(BuildContext context) => TextField( + controller: _text, + focusNode: _focus, + style: Theme.of(context).textTheme.headlineLarge, + decoration: const InputDecoration.collapsed(hintText: 'Untitled'), + maxLines: null, + onSubmitted: (_) => _focus.unfocus(), + textInputAction: TextInputAction.done, + ); +} + +class _Aliases extends StatefulWidget { + const _Aliases({required this.page, required this.initial}); + final PageDto page; + final List initial; + + @override + State<_Aliases> createState() => _AliasesState(); +} + +class _AliasesState extends State<_Aliases> { + late final List _aliases = List.of(widget.initial); + bool _adding = false; + final _text = TextEditingController(); + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + Future _add() async { + final alias = _text.text.trim(); + setState(() => _adding = false); + _text.clear(); + if (alias.isEmpty || _aliases.contains(alias)) return; + final app = AppScope.read(context); + await app.queue.run(() => app.backend.addAlias(widget.page.id, alias)); + if (mounted) setState(() => _aliases.add(alias)); + } + + Future _remove(String alias) async { + final app = AppScope.read(context); + await app.queue.run(() => app.backend.removeAlias(alias)); + if (mounted) setState(() => _aliases.remove(alias)); + } + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return Wrap( + spacing: 6, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + for (final a in _aliases) + Container( + padding: const EdgeInsets.only(left: 8, right: 2), + decoration: BoxDecoration( + color: colors.surface, + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(a, style: TextStyle(fontSize: 12, color: colors.muted)), + InkResponse( + radius: 10, + onTap: () => _remove(a), + child: Padding( + padding: const EdgeInsets.all(3), + child: Icon( + Icons.close_rounded, + size: 12, + color: colors.faint, + ), + ), + ), + ], + ), + ), + if (_adding) + SizedBox( + width: 140, + child: TextField( + controller: _text, + autofocus: true, + style: TextStyle(fontSize: 12, color: colors.ink), + decoration: const InputDecoration.collapsed(hintText: 'alias'), + onSubmitted: (_) => _add(), + onTapOutside: (_) => _add(), + ), + ) + else + TextLink( + _aliases.isEmpty ? 'Add alias' : 'Alias', + icon: Icons.add_rounded, + onTap: () => setState(() => _adding = true), + style: const TextStyle(fontSize: 12), + ), + ], + ); + } +} + +class _LinkedReferences extends StatelessWidget { + const _LinkedReferences({required this.groups}); + final List? groups; + + @override + Widget build(BuildContext context) { + final g = groups; + if (g == null || g.isEmpty) return const SizedBox(height: 40); + final app = AppScope.read(context); + final colors = context.colors; + final count = g.fold(0, (n, x) => n + x.blocks.length); + return Padding( + padding: const EdgeInsets.only(top: 56), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SectionLabel( + 'Linked references', + trailing: Text( + '$count', + style: TextStyle(fontSize: 11, color: colors.faint), + ), + ), + const SizedBox(height: 12), + for (final group in g) + Container( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.fromLTRB(14, 10, 14, 10), + decoration: BoxDecoration( + color: colors.surface, + borderRadius: BorderRadius.circular(10), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextLink( + group.isJournal + ? longDate(group.pageTitle) + : group.pageTitle, + onTap: () => app.openId(group.pageId), + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: colors.ink, + ), + ), + const SizedBox(height: 4), + for (final b in group.blocks) + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Dot(), + const SizedBox(width: 4), + Expanded( + child: StaticBlock( + content: b.content, + onTap: () => app.openId(group.pageId), + ), + ), + ], + ), + ], + ), + ), + ], + ), + ); + } +} + +/// Notes related by spreading activation over links, synapses and time. +class RelatedPanel extends StatelessWidget { + const RelatedPanel({super.key, required this.related, this.compact = false}); + final List? related; + final bool compact; + + @override + Widget build(BuildContext context) { + final r = related; + final colors = context.colors; + final app = AppScope.read(context); + final top = (r == null || r.isEmpty) ? 1.0 : r.first.score; + return Padding( + padding: EdgeInsets.only(top: compact ? 0 : 40), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SectionLabel('Related'), + const SizedBox(height: 4), + Text( + 'Strengthened by links, visits and shared days', + style: TextStyle(fontSize: 12, color: colors.faint), + ), + const SizedBox(height: 14), + if (r == null) + const SizedBox.shrink() + else if (r.isEmpty) + Text( + 'Nothing yet. Link this note to others.', + style: TextStyle(fontSize: 13, color: colors.muted), + ) + else + for (final x in r) + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextLink( + x.page.isJournal ? longDate(x.page.title) : x.page.title, + icon: x.page.isJournal + ? Icons.calendar_today_outlined + : Icons.description_outlined, + onTap: () => app.openId(x.page.id), + style: TextStyle(fontSize: 13.5, color: colors.ink), + ), + const SizedBox(height: 4), + ClipRRect( + borderRadius: BorderRadius.circular(2), + child: LinearProgressIndicator( + value: (x.score / top).clamp(0.05, 1.0), + minHeight: 3, + backgroundColor: colors.line, + color: colors.accent.withAlpha(0x99), + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/src/views/quick_switcher.dart b/app/lib/src/views/quick_switcher.dart new file mode 100644 index 0000000..0ab331e --- /dev/null +++ b/app/lib/src/views/quick_switcher.dart @@ -0,0 +1,215 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../backend/graph_backend.dart'; +import '../state/app_state.dart'; +import '../theme/theme.dart'; + +/// Ctrl+K: jump to a page by title or alias, or create it. +Future showQuickSwitcher(BuildContext context) => showDialog( + context: context, + barrierColor: Colors.black.withAlpha(0x33), + builder: (_) => + AppScope(state: AppScope.read(context), child: const QuickSwitcher()), +); + +class QuickSwitcher extends StatefulWidget { + const QuickSwitcher({super.key}); + + @override + State createState() => _QuickSwitcherState(); +} + +class _QuickSwitcherState extends State { + final _text = TextEditingController(); + List _hits = const []; + int _selected = 0; + int _seq = 0; + + @override + void initState() { + super.initState(); + _search(''); + } + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + String get _query => _text.text.trim(); + + bool get _offerCreate => + _query.isNotEmpty && + !_hits.any((h) => h.title.toLowerCase() == _query.toLowerCase()); + + int get _count => _hits.length + (_offerCreate ? 1 : 0); + + Future _search(String q) async { + final seq = ++_seq; + final hits = await AppScope.read(context).backend + .searchTitles(q, limit: 12); + if (!mounted || seq != _seq) return; + setState(() { + _hits = hits; + _selected = 0; + }); + } + + void _open(int i) { + final app = AppScope.read(context); + Navigator.of(context).pop(); + if (i < _hits.length) { + app.openId(_hits[i].pageId); + } else if (_query.isNotEmpty) { + app.openTitle(_query); + } + } + + KeyEventResult _key(FocusNode _, KeyEvent e) { + if (e is! KeyDownEvent && e is! KeyRepeatEvent) { + return KeyEventResult.ignored; + } + if (_count == 0) return KeyEventResult.ignored; + if (e.logicalKey == LogicalKeyboardKey.arrowDown) { + setState(() => _selected = (_selected + 1) % _count); + return KeyEventResult.handled; + } + if (e.logicalKey == LogicalKeyboardKey.arrowUp) { + setState(() => _selected = (_selected - 1 + _count) % _count); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + } + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return Align( + alignment: const Alignment(0, -0.55), + child: Material( + color: colors.paper, + borderRadius: BorderRadius.circular(14), + clipBehavior: Clip.antiAlias, + child: Container( + width: 560, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(14), + border: Border.all(color: colors.line), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(18, 14, 18, 12), + child: Row( + children: [ + Icon(Icons.search_rounded, size: 18, color: colors.muted), + const SizedBox(width: 10), + Expanded( + child: Focus( + onKeyEvent: _key, + child: TextField( + controller: _text, + autofocus: true, + style: TextStyle(fontSize: 16, color: colors.ink), + decoration: const InputDecoration.collapsed( + hintText: 'Search or create a page', + ), + onChanged: (q) => _search(q), + onSubmitted: (_) => _open(_selected), + ), + ), + ), + ], + ), + ), + if (_count > 0) Divider(height: 1, color: colors.line), + ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 380), + child: ListView( + shrinkWrap: true, + padding: const EdgeInsets.all(6), + children: [ + for (var i = 0; i < _count; i++) + _Item( + selected: i == _selected, + onTap: () => _open(i), + icon: i < _hits.length + ? Icons.description_outlined + : Icons.add_rounded, + title: i < _hits.length + ? _hits[i].title + : 'Create page “$_query”', + detail: i < _hits.length && _hits[i].isAlias + ? 'alias' + : null, + ), + ], + ), + ), + ], + ), + ), + ), + ); + } +} + +class _Item extends StatelessWidget { + const _Item({ + required this.selected, + required this.onTap, + required this.icon, + required this.title, + this.detail, + }); + final bool selected; + final VoidCallback onTap; + final IconData icon; + final String title; + final String? detail; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: onTap, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9), + decoration: BoxDecoration( + color: selected ? colors.accentSoft : null, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Icon( + icon, + size: 16, + color: selected ? colors.accent : colors.muted, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: colors.ink), + ), + ), + if (detail != null) + Text( + detail!, + style: TextStyle(fontSize: 12, color: colors.faint), + ), + ], + ), + ), + ), + ); + } +} diff --git a/app/lib/src/views/shell.dart b/app/lib/src/views/shell.dart new file mode 100644 index 0000000..673c17c --- /dev/null +++ b/app/lib/src/views/shell.dart @@ -0,0 +1,402 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../state/app_state.dart'; +import '../theme/theme.dart'; +import '../widgets/dates.dart'; +import 'all_pages_view.dart'; +import 'journals_view.dart'; +import 'page_screen.dart'; +import 'quick_switcher.dart'; +import 'timeline_view.dart'; + +/// App frame: sidebar (navigation, recents, theme), top bar and the current view. +class Shell extends StatefulWidget { + const Shell({super.key}); + + @override + State createState() => _ShellState(); +} + +class _ShellState extends State { + bool _sidebar = true; + final _scaffold = GlobalKey(); + + @override + Widget build(BuildContext context) { + final app = AppScope.of(context); + final colors = context.colors; + final route = app.route; + final error = app.writeError; + if (error != null) { + app.writeError = null; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Could not save a change; reloaded. ($error)'), + ), + ); + }); + } + return CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.keyK, control: true): () => + showQuickSwitcher(context), + const SingleActivator(LogicalKeyboardKey.keyK, meta: true): () => + showQuickSwitcher(context), + const SingleActivator( + LogicalKeyboardKey.keyJ, + control: true, + shift: true, + ): () => + app.go(const JournalsRoute()), + const SingleActivator( + LogicalKeyboardKey.keyT, + control: true, + shift: true, + ): () => + app.go(const TimelineRoute()), + const SingleActivator( + LogicalKeyboardKey.backslash, + control: true, + ): () => + setState(() => _sidebar = !_sidebar), + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): + app.back, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): + app.forward, + }, + child: Focus( + autofocus: true, + child: LayoutBuilder( + builder: (context, box) { + final narrow = box.maxWidth < 760; + final sidebar = _Sidebar( + onNavigate: () { + if (narrow) _scaffold.currentState?.closeDrawer(); + }, + ); + return Scaffold( + key: _scaffold, + drawer: narrow + ? Drawer(backgroundColor: colors.surface, child: sidebar) + : null, + body: Row( + children: [ + if (!narrow) + AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + width: _sidebar ? 248 : 0, + child: ClipRect( + child: OverflowBox( + alignment: Alignment.topLeft, + minWidth: 248, + maxWidth: 248, + child: sidebar, + ), + ), + ), + Expanded( + child: Column( + children: [ + _TopBar( + onMenu: () => narrow + ? _scaffold.currentState?.openDrawer() + : setState(() => _sidebar = !_sidebar), + ), + Expanded( + child: KeyedSubtree( + key: ValueKey((route, app.generation)), + child: switch (route) { + JournalsRoute() => const JournalsView(), + TimelineRoute() => const TimelineView(), + AllPagesRoute() => const AllPagesView(), + PageTarget() => PageScreen(target: route), + }, + ), + ), + ], + ), + ), + ], + ), + ); + }, + ), + ), + ); + } +} + +class _TopBar extends StatelessWidget { + const _TopBar({required this.onMenu}); + final VoidCallback onMenu; + + @override + Widget build(BuildContext context) { + final app = AppScope.of(context); + final colors = context.colors; + final brightness = Theme.of(context).brightness; + Widget icon(IconData i, String tip, VoidCallback? f) => IconButton( + tooltip: tip, + onPressed: f, + iconSize: 18, + color: colors.muted, + disabledColor: colors.line, + icon: Icon(i), + ); + return Container( + height: 48, + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + children: [ + icon(Icons.menu_rounded, 'Toggle sidebar (Ctrl+\\)', onMenu), + icon( + Icons.arrow_back_rounded, + 'Back (Alt+←)', + app.canGoBack ? app.back : null, + ), + icon( + Icons.arrow_forward_rounded, + 'Forward (Alt+→)', + app.canGoForward ? app.forward : null, + ), + const Spacer(), + _SearchPill(onTap: () => showQuickSwitcher(context)), + const SizedBox(width: 4), + icon( + brightness == Brightness.dark + ? Icons.light_mode_outlined + : Icons.dark_mode_outlined, + 'Toggle theme', + () => app.toggleTheme(brightness), + ), + ], + ), + ); + } +} + +class _SearchPill extends StatelessWidget { + const _SearchPill({required this.onTap}); + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + border: Border.all(color: colors.line), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.search_rounded, size: 16, color: colors.muted), + const SizedBox(width: 8), + Text('Search', style: TextStyle(fontSize: 13, color: colors.muted)), + const SizedBox(width: 18), + Text('Ctrl K', style: TextStyle(fontSize: 11, color: colors.faint)), + ], + ), + ), + ); + } +} + +class _Sidebar extends StatelessWidget { + const _Sidebar({required this.onNavigate}); + final VoidCallback onNavigate; + + @override + Widget build(BuildContext context) { + final app = AppScope.of(context); + final colors = context.colors; + final route = app.route; + void go(AppRoute r) { + app.go(r); + onNavigate(); + } + + return Container( + color: colors.surface, + child: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(20, 18, 20, 22), + child: Row( + children: [ + CustomPaint( + size: const Size(20, 20), + painter: _Logo(colors.accent), + ), + const SizedBox(width: 10), + Text( + 'Synapse', + style: TextStyle( + fontFamily: titleFont, + fontSize: 18, + fontWeight: FontWeight.w600, + color: colors.ink, + ), + ), + ], + ), + ), + _NavItem( + icon: Icons.calendar_today_outlined, + label: 'Journals', + selected: route is JournalsRoute, + onTap: () => go(const JournalsRoute()), + ), + _NavItem( + icon: Icons.timeline_rounded, + label: 'Timeline', + selected: route is TimelineRoute, + onTap: () => go(const TimelineRoute()), + ), + _NavItem( + icon: Icons.description_outlined, + label: 'All pages', + selected: route is AllPagesRoute, + onTap: () => go(const AllPagesRoute()), + ), + const SizedBox(height: 22), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Text( + 'RECENT', + style: Theme.of(context).textTheme.labelSmall, + ), + ), + const SizedBox(height: 6), + Expanded( + child: ListView( + padding: EdgeInsets.zero, + children: [ + for (final p in app.recent) + _NavItem( + label: p.isJournal ? longDate(p.title) : p.title, + selected: route is PageTarget && route.id == p.id, + dense: true, + onTap: () => go(PageTarget(id: p.id)), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _NavItem extends StatefulWidget { + const _NavItem({ + this.icon, + required this.label, + required this.selected, + required this.onTap, + this.dense = false, + }); + final IconData? icon; + final String label; + final bool selected; + final VoidCallback onTap; + final bool dense; + + @override + State<_NavItem> createState() => _NavItemState(); +} + +class _NavItemState extends State<_NavItem> { + bool _hover = false; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + final active = widget.selected; + return MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (_) => setState(() => _hover = true), + onExit: (_) => setState(() => _hover = false), + child: GestureDetector( + onTap: widget.onTap, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 1), + padding: EdgeInsets.symmetric( + horizontal: 10, + vertical: widget.dense ? 6 : 8, + ), + decoration: BoxDecoration( + color: active + ? colors.accentSoft + : _hover + ? colors.line.withAlpha(0x66) + : null, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + if (widget.icon != null) ...[ + Icon( + widget.icon, + size: 16, + color: active ? colors.accent : colors.muted, + ), + const SizedBox(width: 10), + ], + Expanded( + child: Text( + widget.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: widget.dense ? 13 : 14, + fontWeight: active ? FontWeight.w600 : FontWeight.w500, + color: active + ? colors.ink + : (widget.dense ? colors.muted : colors.ink), + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +/// Two linked nodes: the mark. +class _Logo extends CustomPainter { + _Logo(this.color); + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final p = Paint()..color = color; + final a = Offset(size.width * 0.25, size.height * 0.68); + final b = Offset(size.width * 0.75, size.height * 0.32); + canvas.drawLine( + a, + b, + Paint() + ..color = color.withAlpha(0x99) + ..strokeWidth = 2, + ); + canvas.drawCircle(a, size.width * 0.18, p); + canvas.drawCircle(b, size.width * 0.14, p); + } + + @override + bool shouldRepaint(_Logo old) => old.color != color; +} diff --git a/app/lib/src/views/timeline_view.dart b/app/lib/src/views/timeline_view.dart new file mode 100644 index 0000000..00ffb5b --- /dev/null +++ b/app/lib/src/views/timeline_view.dart @@ -0,0 +1,507 @@ +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../backend/graph_backend.dart'; +import '../state/app_state.dart'; +import '../theme/theme.dart'; +import '../widgets/dates.dart'; + +/// Loaded timeline data, fetched in fixed chunks of days as the view pans. +class TimelineModel extends ChangeNotifier { + TimelineModel(this.backend, this.today); + + static const chunkDays = 32; + final GraphBackend backend; + + /// Day index 0. + final DateTime today; + + final _loaded = {}; + final days = {}; + final titles = {}; + + /// Where each page hangs: (day index, row). + final born = {}; + + DateTime dayAt(int index) => today.add(Duration(days: index)); + int indexOf(String ymd) => parseDay(ymd).difference(today).inDays; + + void ensure(int from, int to) { + final c0 = (from / chunkDays).floor(); + final c1 = (to / chunkDays).floor(); + for (var c = c0; c <= c1; c++) { + if (_loaded.add(c)) _load(c); + } + } + + Future _load(int chunk) async { + final start = chunk * chunkDays; + try { + final t = await backend.timeline( + formatDay(dayAt(start)), + formatDay(dayAt(start + chunkDays - 1)), + ); + for (final p in t.pages) { + titles[p.id] = p; + } + for (final d in t.days) { + final i = indexOf(d.date); + days[i] = d; + for (var k = 0; k < d.created.length; k++) { + born[d.created[k]] = (i, k); + } + } + notifyListeners(); + } catch (e) { + _loaded.remove(chunk); + debugPrint('timeline chunk $chunk failed: $e'); + } + } +} + +/// Journals on a horizontal line, each linked to the next; pages hang below the journal +/// they were born in, with faint edges to the days they were edited. Pan by dragging, zoom +/// with the wheel or a pinch, tap a node to open it. +class TimelineView extends StatefulWidget { + const TimelineView({super.key}); + + @override + State createState() => _TimelineViewState(); +} + +class _TimelineViewState extends State { + late final TimelineModel _model; + final _view = _Viewport(); + final _hits = <(Rect, String)>[]; + double _startDayWidth = 0; + bool _placed = false; + + @override + void initState() { + super.initState(); + final backend = AppScope.read(context).backend; + _model = TimelineModel(backend, parseDay(backend.today())); + } + + @override + void dispose() { + _model.dispose(); + _view.dispose(); + super.dispose(); + } + + void _zoom(double factor, double focalX) { + final dw = (_view.dayWidth * factor).clamp(4.0, 260.0); + // Keep the day under the focal point fixed. + final day = (focalX - _view.x) / _view.dayWidth; + _view.update(dayWidth: dw, x: focalX - day * dw); + } + + void _tap(Offset p) { + for (final (r, id) in _hits.reversed) { + if (r.inflate(3).contains(p)) { + AppScope.read(context).openId(id); + return; + } + } + } + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return LayoutBuilder( + builder: (context, box) { + if (!_placed) { + _placed = true; + _view.x = box.maxWidth - 140; + } + return Stack( + children: [ + Positioned.fill( + child: ClipRect( + child: Listener( + onPointerSignal: (e) { + if (e is PointerScrollEvent) { + if (HardwareKeyboard.instance.isShiftPressed) { + _view.update(x: _view.x - e.scrollDelta.dy); + } else { + _zoom( + math.pow(1.0015, -e.scrollDelta.dy).toDouble(), + e.localPosition.dx, + ); + } + } + }, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTapUp: (d) => _tap(d.localPosition), + onScaleStart: (_) => _startDayWidth = _view.dayWidth, + onScaleUpdate: (d) { + if (d.scale != 1.0) { + final target = _startDayWidth * d.scale; + _zoom(target / _view.dayWidth, d.localFocalPoint.dx); + } + _view.update( + x: _view.x + d.focalPointDelta.dx, + y: math.min(0, _view.y + d.focalPointDelta.dy), + ); + }, + child: CustomPaint( + painter: _TimelinePainter( + model: _model, + view: _view, + colors: colors, + hits: _hits, + textScaler: MediaQuery.textScalerOf(context), + ), + size: Size.infinite, + ), + ), + ), + ), + ), + Positioned( + right: 20, + top: 16, + child: _Toolbar( + onToday: () => _view.update(x: box.maxWidth - 140, y: 0), + onZoomIn: () => _zoom(1.4, box.maxWidth / 2), + onZoomOut: () => _zoom(1 / 1.4, box.maxWidth / 2), + ), + ), + Positioned(left: 24, bottom: 18, child: _Legend(colors: colors)), + ], + ); + }, + ); + } +} + +class _Viewport extends ChangeNotifier { + double dayWidth = 64; + + /// Screen x of day 0 (today). + double x = 0; + + /// Vertical scroll of the hanging pages (<= 0). + double y = 0; + + void update({double? dayWidth, double? x, double? y}) { + this.dayWidth = dayWidth ?? this.dayWidth; + this.x = x ?? this.x; + this.y = y ?? this.y; + notifyListeners(); + } +} + +class _TimelinePainter extends CustomPainter { + _TimelinePainter({ + required this.model, + required this.view, + required this.colors, + required this.hits, + required this.textScaler, + }) : super(repaint: Listenable.merge([model, view])); + + final TimelineModel model; + final _Viewport view; + final SynapseColors colors; + final List<(Rect, String)> hits; + final TextScaler textScaler; + + static const axisY = 120.0; + static const rowH = 28.0; + + double xOf(int day) => view.x + day * view.dayWidth; + + TextPainter _label(String text, TextStyle style, double maxWidth) { + return TextPainter( + text: TextSpan(text: text, style: style), + textDirection: TextDirection.ltr, + maxLines: 1, + ellipsis: '…', + textScaler: textScaler, + )..layout(maxWidth: math.max(0, maxWidth)); + } + + @override + void paint(Canvas canvas, Size size) { + hits.clear(); + final dw = view.dayWidth; + final first = ((0 - view.x) / dw).floor() - 1; + final last = ((size.width - view.x) / dw).ceil() + 1; + // Load a margin around the viewport so edges to nearby days can be drawn. + final margin = (size.width / dw).ceil(); + model.ensure(first - margin, last + margin); + + // Axis. + canvas.drawLine( + Offset(0, axisY), + Offset(size.width, axisY), + Paint() + ..color = colors.line + ..strokeWidth = 1, + ); + + // Month and day ticks. + final labelStyle = TextStyle( + fontFamily: uiFont, + fontSize: 11, + color: colors.muted, + ); + for (var d = first; d <= last; d++) { + final date = model.dayAt(d); + final x = xOf(d); + if (date.day == 1) { + canvas.drawLine( + Offset(x, axisY - 40), + Offset(x, axisY - 8), + Paint()..color = colors.line, + ); + final tp = _label( + '${monthName(date.month)} ${date.year}', + labelStyle.copyWith(fontWeight: FontWeight.w600, color: colors.ink), + 200, + ); + tp.paint(canvas, Offset(x + 6, axisY - 44)); + } + if (dw >= 22) { + final tp = _label( + '${date.day}', + labelStyle.copyWith(color: colors.faint), + dw, + ); + tp.paint(canvas, Offset(x - tp.width / 2, axisY - 24)); + } + } + + // Month of the first visible day, pinned to the left edge. + final firstDate = model.dayAt(first + 1); + final sticky = _label( + '${monthName(firstDate.month)} ${firstDate.year}', + labelStyle.copyWith(fontWeight: FontWeight.w600, color: colors.ink), + 200, + ); + final nextMonth = DateTime.utc(firstDate.year, firstDate.month + 1); + final nextX = xOf(nextMonth.difference(model.today).inDays); + final stickyX = math.min(24.0, nextX - sticky.width - 12); + canvas.drawRect( + Rect.fromLTWH(stickyX - 6, axisY - 48, sticky.width + 12, 22), + Paint()..color = colors.paper, + ); + sticky.paint(canvas, Offset(stickyX, axisY - 44)); + + // Today marker. + final tx = xOf(0); + if (tx >= 0 && tx <= size.width) { + canvas.drawLine( + Offset(tx, axisY - 30), + Offset(tx, size.height), + Paint() + ..color = colors.accent.withAlpha(0x33) + ..strokeWidth = 1, + ); + } + + final journalDays = + model.days.entries + .where((e) => e.value.journalId != null) + .map((e) => e.key) + .toList() + ..sort(); + + // Episodic chain: each journal linked to the next. + final chain = Paint() + ..color = colors.accent.withAlpha(0x88) + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round; + for (var k = 0; k + 1 < journalDays.length; k++) { + final a = journalDays[k], b = journalDays[k + 1]; + if (b < first || a > last) continue; + canvas.drawLine(Offset(xOf(a), axisY), Offset(xOf(b), axisY), chain); + } + + final y0 = axisY + 44 + view.y; + final showLabels = dw >= 34; + // Labels may run until the next day that also has pages hanging from it. + final withPages = + model.days.entries + .where((e) => e.value.created.isNotEmpty) + .map((e) => e.key) + .toList() + ..sort(); + double labelWidth(int d) { + final next = withPages.where((x) => x > d).firstOrNull; + final room = next == null ? 220.0 : (next - d) * dw - 18; + return room.clamp(40.0, 220.0); + } + + // Edges from pages to the days they were edited. + final edge = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1; + for (final e in model.days.entries) { + final d = e.key; + for (final ed in e.value.edited) { + final b = model.born[ed.pageId]; + if (b == null || b.$1 == d) continue; + if ((b.$1 < first && d < first) || (b.$1 > last && d > last)) continue; + final from = Offset(xOf(b.$1) + 4, y0 + b.$2 * rowH); + final to = Offset(xOf(d), axisY); + edge.color = colors.ref.withAlpha( + (30 + 20 * math.min(ed.edits, 6)).toInt(), + ); + final mid = Offset( + (from.dx + to.dx) / 2, + from.dy + 24 + (from.dx - to.dx).abs() * 0.08, + ); + canvas.drawPath( + Path() + ..moveTo(from.dx, from.dy) + ..quadraticBezierTo(mid.dx, mid.dy, to.dx, to.dy), + edge, + ); + } + } + + // Pages hanging from their birth day, and journal nodes. + for (var d = first; d <= last; d++) { + final day = model.days[d]; + if (day == null) continue; + final x = xOf(d); + if (day.created.isNotEmpty) { + canvas.drawLine( + Offset(x, axisY), + Offset(x, y0 + (day.created.length - 1) * rowH), + Paint() + ..color = colors.line + ..strokeWidth = 1, + ); + } + for (var k = 0; k < day.created.length; k++) { + final id = day.created[k]; + final c = Offset(x, y0 + k * rowH); + if (c.dy < axisY + 8) continue; + canvas.drawCircle(c, 4, Paint()..color = colors.paper); + canvas.drawCircle( + c, + 4, + Paint() + ..color = colors.muted + ..style = PaintingStyle.stroke + ..strokeWidth = 1.5, + ); + var hit = Rect.fromCircle(center: c, radius: 6); + if (showLabels) { + final title = model.titles[id]?.title ?? '…'; + final tp = _label( + title, + TextStyle(fontFamily: uiFont, fontSize: 12, color: colors.ink), + labelWidth(d), + ); + final at = Offset(c.dx + 9, c.dy - tp.height / 2); + tp.paint(canvas, at); + hit = hit.expandToInclude(at & tp.size); + } + hits.add((hit, id)); + } + final jid = day.journalId; + if (jid != null) { + final c = Offset(x, axisY); + final r = day.created.isNotEmpty || day.edited.isNotEmpty ? 6.0 : 4.5; + canvas.drawCircle(c, r + 2, Paint()..color = colors.paper); + canvas.drawCircle(c, r, Paint()..color = colors.accent); + hits.add((Rect.fromCircle(center: c, radius: r + 6), jid)); + } + } + } + + @override + bool shouldRepaint(_TimelinePainter old) => + old.colors != colors || old.model != model || old.view != view; +} + +class _Toolbar extends StatelessWidget { + const _Toolbar({ + required this.onToday, + required this.onZoomIn, + required this.onZoomOut, + }); + final VoidCallback onToday; + final VoidCallback onZoomIn; + final VoidCallback onZoomOut; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + Widget btn(IconData i, String tip, VoidCallback f) => IconButton( + tooltip: tip, + onPressed: f, + icon: Icon(i, size: 18, color: colors.muted), + ); + return Container( + decoration: BoxDecoration( + color: colors.paper, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: colors.line), + ), + child: Row( + children: [ + btn(Icons.today_outlined, 'Today', onToday), + btn(Icons.remove_rounded, 'Zoom out', onZoomOut), + btn(Icons.add_rounded, 'Zoom in', onZoomIn), + ], + ), + ); + } +} + +class _Legend extends StatelessWidget { + const _Legend({required this.colors}); + final SynapseColors colors; + + @override + Widget build(BuildContext context) { + Widget item(Widget mark, String text) => Padding( + padding: const EdgeInsets.only(right: 16), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + mark, + const SizedBox(width: 6), + Text(text, style: TextStyle(fontSize: 12, color: colors.muted)), + ], + ), + ); + return Row( + children: [ + item( + Container( + width: 9, + height: 9, + decoration: BoxDecoration( + color: colors.accent, + shape: BoxShape.circle, + ), + ), + 'Journal', + ), + item( + Container( + width: 9, + height: 9, + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: colors.muted, width: 1.5), + ), + ), + 'Page born that day', + ), + item(Container(width: 16, height: 1.5, color: colors.ref), 'Edited on'), + ], + ); + } +} diff --git a/app/lib/src/widgets/common.dart b/app/lib/src/widgets/common.dart new file mode 100644 index 0000000..97adf40 --- /dev/null +++ b/app/lib/src/widgets/common.dart @@ -0,0 +1,168 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../editor/block_row.dart'; +import '../editor/markdown.dart'; +import '../state/app_state.dart'; +import '../theme/theme.dart'; + +/// Max width of the reading column. +const contentWidth = 780.0; + +/// Horizontal padding that centres a [contentWidth] column in `width`. +double sidePadding(double width) => math.max(20, (width - contentWidth) / 2); + +/// Small caps section label. +class SectionLabel extends StatelessWidget { + const SectionLabel(this.text, {super.key, this.trailing}); + final String text; + final Widget? trailing; + + @override + Widget build(BuildContext context) => Row( + children: [ + Text(text.toUpperCase(), style: Theme.of(context).textTheme.labelSmall), + if (trailing != null) ...[const SizedBox(width: 8), trailing!], + ], + ); +} + +/// A link-like text button. +class TextLink extends StatefulWidget { + const TextLink( + this.text, { + super.key, + required this.onTap, + this.style, + this.icon, + this.iconAfter = false, + }); + final String text; + final VoidCallback onTap; + final TextStyle? style; + final IconData? icon; + final bool iconAfter; + + @override + State createState() => _TextLinkState(); +} + +class _TextLinkState extends State { + bool _hover = false; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + final color = _hover + ? colors.accent + : (widget.style?.color ?? colors.muted); + final style = (widget.style ?? const TextStyle(fontSize: 13)).copyWith( + color: color, + ); + final icon = widget.icon == null + ? null + : Icon(widget.icon, size: (style.fontSize ?? 13) + 2, color: color); + return MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (_) => setState(() => _hover = true), + onExit: (_) => setState(() => _hover = false), + child: GestureDetector( + onTap: widget.onTap, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null && !widget.iconAfter) ...[ + icon, + const SizedBox(width: 4), + ], + Flexible( + child: Text( + widget.text, + style: style, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + if (icon != null && widget.iconAfter) ...[ + const SizedBox(width: 4), + icon, + ], + ], + ), + ), + ); + } +} + +/// Read-only rendered block (linked references). Taps on links navigate; a tap elsewhere +/// calls [onTap]. +class StaticBlock extends StatefulWidget { + const StaticBlock({super.key, required this.content, this.onTap}); + final String content; + final VoidCallback? onTap; + + @override + State createState() => _StaticBlockState(); +} + +class _StaticBlockState extends State { + RenderedBlock? _r; + + @override + void dispose() { + _r?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final app = AppScope.read(context); + return LayoutBuilder( + builder: (context, box) => ListenableBuilder( + listenable: app.refs, + builder: (context, _) { + _r?.dispose(); + _r = BlockRenderer( + RenderContext( + colors: context.colors, + base: blockTextStyle(context), + refs: app.refs, + assetPath: app.backend.assetPath, + onPage: app.openTitle, + onBlockRef: (r) => app.openId(r.pageId), + onUrl: openUrl, + maxWidth: box.maxWidth, + ), + ).render(widget.content); + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: widget.onTap, + child: Text.rich(_r!.span), + ); + }, + ), + ); + } +} + +/// Bullet dot used outside the editor. +class Dot extends StatelessWidget { + const Dot({super.key}); + + @override + Widget build(BuildContext context) => SizedBox( + width: 18, + height: blockFontSize * blockLineHeight, + child: Center( + child: Container( + width: 5, + height: 5, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: context.colors.faint, + ), + ), + ), + ); +} diff --git a/app/lib/src/widgets/dates.dart b/app/lib/src/widgets/dates.dart new file mode 100644 index 0000000..9c54d8b --- /dev/null +++ b/app/lib/src/widgets/dates.dart @@ -0,0 +1,48 @@ +const _months = [ + 'January', 'February', 'March', 'April', 'May', 'June', 'July', // + 'August', 'September', 'October', 'November', 'December', +]; +const _days = [ + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', +]; + +DateTime parseDay(String ymd) { + final p = ymd.split('-'); + return DateTime.utc(int.parse(p[0]), int.parse(p[1]), int.parse(p[2])); +} + +String formatDay(DateTime d) => + '${d.year.toString().padLeft(4, '0')}-${d.month.toString().padLeft(2, '0')}-' + '${d.day.toString().padLeft(2, '0')}'; + +/// "21 October 2026" +String longDate(String ymd) { + final d = parseDay(ymd); + return '${d.day} ${_months[d.month - 1]} ${d.year}'; +} + +/// "Tuesday" +String weekday(String ymd) => _days[parseDay(ymd).weekday - 1]; + +/// "21 Oct" +String shortDate(DateTime d) => + '${d.day} ${_months[d.month - 1].substring(0, 3)}'; + +String monthName(int month) => _months[month - 1]; + +/// "Today", "Yesterday" or null. +String? relativeDay(String ymd, String today) { + final diff = parseDay(today).difference(parseDay(ymd)).inDays; + return switch (diff) { + 0 => 'Today', + 1 => 'Yesterday', + -1 => 'Tomorrow', + _ => null, + }; +} diff --git a/app/linux/.gitignore b/app/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/app/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/app/linux/CMakeLists.txt b/app/linux/CMakeLists.txt new file mode 100644 index 0000000..43c5543 --- /dev/null +++ b/app/linux/CMakeLists.txt @@ -0,0 +1,130 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "synapse") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "es.zenvairo.synapse") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +# Flutter does not create it when the project path has non-ASCII characters. +file(MAKE_DIRECTORY "${NATIVE_ASSETS_DIR}") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/app/linux/flutter/CMakeLists.txt b/app/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/app/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/app/linux/flutter/generated_plugin_registrant.cc b/app/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..f6f23bf --- /dev/null +++ b/app/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/app/linux/flutter/generated_plugin_registrant.h b/app/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/app/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/app/linux/flutter/generated_plugins.cmake b/app/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..115cc7c --- /dev/null +++ b/app/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni + synapse_ffi +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/app/linux/runner/CMakeLists.txt b/app/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/app/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/app/linux/runner/main.cc b/app/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/app/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/app/linux/runner/my_application.cc b/app/linux/runner/my_application.cc new file mode 100644 index 0000000..14e4465 --- /dev/null +++ b/app/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "synapse"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "synapse"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/app/linux/runner/my_application.h b/app/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/app/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/app/pubspec.lock b/app/pubspec.lock new file mode 100644 index 0000000..c4b1744 --- /dev/null +++ b/app/pubspec.lock @@ -0,0 +1,497 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + build_cli_annotations: + dependency: transitive + description: + name: build_cli_annotations + sha256: e563c2e01de8974566a1998410d3f6f03521788160a02503b0b1f1a46c7b3d95 + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_rust_bridge: + dependency: "direct main" + description: + name: flutter_rust_bridge + sha256: ec69331e2335ab4d456c0a9fc700892c2c85b72b9c0cb39df3ecfe8833d5d5c8 + url: "https://pub.dev" + source: hosted + version: "2.13.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + jni: + dependency: transitive + description: + name: jni + sha256: "6b9ca0602fef0230e83149afbe3f9f8227e94f2bbe84a1da4f14d699742f402d" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" + url: "https://pub.dev" + source: hosted + version: "1.0.4+1" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d + url: "https://pub.dev" + source: hosted + version: "1.18.3" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e + url: "https://pub.dev" + source: hosted + version: "9.5.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + url: "https://pub.dev" + source: hosted + version: "3.0.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec + url: "https://pub.dev" + source: hosted + version: "3.2.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synapse_ffi: + dependency: "direct main" + description: + path: rust_builder + relative: true + source: path + version: "0.0.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + url: "https://pub.dev" + source: hosted + version: "0.7.12" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda + url: "https://pub.dev" + source: hosted + version: "6.3.3" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" + url: "https://pub.dev" + source: hosted + version: "6.3.33" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" + url: "https://pub.dev" + source: hosted + version: "6.4.2" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" + url: "https://pub.dev" + source: hosted + version: "3.2.3" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" + url: "https://pub.dev" + source: hosted + version: "3.2.6" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "1d774bbdf6b72a0b12122fc1560c9c2d2a67db5a4a4cc2bd8a5c990ab20e3188" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" + url: "https://pub.dev" + source: hosted + version: "15.4.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" +sdks: + dart: ">=3.13.5 <4.0.0" + flutter: ">=3.44.0" diff --git a/app/pubspec.yaml b/app/pubspec.yaml new file mode 100644 index 0000000..65200e1 --- /dev/null +++ b/app/pubspec.yaml @@ -0,0 +1,47 @@ +name: synapse +description: "Synapse: a native, Logseq-like second brain." +publish_to: 'none' +version: 0.1.0+1 + +environment: + sdk: ^3.13.5 + +dependencies: + flutter: + sdk: flutter + flutter_rust_bridge: 2.13.0 + path_provider: ^2.1.6 + synapse_ffi: + path: rust_builder + url_launcher: ^6.3.3 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + uses-material-design: true + fonts: + - family: Inter + fonts: + - asset: assets/fonts/Inter-Regular.ttf + - asset: assets/fonts/Inter-Italic.ttf + style: italic + - asset: assets/fonts/Inter-Medium.ttf + weight: 500 + - asset: assets/fonts/Inter-SemiBold.ttf + weight: 600 + - asset: assets/fonts/Inter-Bold.ttf + weight: 700 + - asset: assets/fonts/Inter-BoldItalic.ttf + weight: 700 + style: italic + - family: NotoSerif + fonts: + - asset: assets/fonts/NotoSerif-Variable.ttf + - family: SourceCodePro + fonts: + - asset: assets/fonts/SourceCodePro-Regular.otf + - asset: assets/fonts/SourceCodePro-Semibold.otf + weight: 600 diff --git a/app/rust_builder/.gitignore b/app/rust_builder/.gitignore new file mode 100644 index 0000000..ac5aa98 --- /dev/null +++ b/app/rust_builder/.gitignore @@ -0,0 +1,29 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +build/ diff --git a/app/rust_builder/README.md b/app/rust_builder/README.md new file mode 100644 index 0000000..922615f --- /dev/null +++ b/app/rust_builder/README.md @@ -0,0 +1 @@ +Please ignore this folder, which is just glue to build Rust with Flutter. \ No newline at end of file diff --git a/app/rust_builder/android/.gitignore b/app/rust_builder/android/.gitignore new file mode 100644 index 0000000..161bdcd --- /dev/null +++ b/app/rust_builder/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/app/rust_builder/android/build.gradle b/app/rust_builder/android/build.gradle new file mode 100644 index 0000000..a06313c --- /dev/null +++ b/app/rust_builder/android/build.gradle @@ -0,0 +1,56 @@ +// The Android Gradle Plugin builds the native code with the Android NDK. + +group 'com.flutter_rust_bridge.synapse_ffi' +version '1.0' + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + // The Android Gradle Plugin knows how to build native code with the NDK. + classpath 'com.android.tools.build:gradle:7.3.0' + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: 'com.android.library' + +android { + if (project.android.hasProperty("namespace")) { + namespace 'com.flutter_rust_bridge.synapse_ffi' + } + + // Bumping the plugin compileSdkVersion requires all clients of this plugin + // to bump the version in their app. + compileSdkVersion 36 + + // Use the NDK version + // declared in /android/app/build.gradle file of the Flutter project. + // Replace it with a version number if this plugin requires a specfic NDK version. + // (e.g. ndkVersion "23.1.7779620") + ndkVersion android.ndkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + minSdkVersion 19 + } +} + +apply from: "../cargokit/gradle/plugin.gradle" +cargokit { + manifestDir = "../../../crates/synapse-ffi" + libname = "synapse_ffi" +} diff --git a/app/rust_builder/android/settings.gradle b/app/rust_builder/android/settings.gradle new file mode 100644 index 0000000..bf3e013 --- /dev/null +++ b/app/rust_builder/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'synapse_ffi' diff --git a/app/rust_builder/android/src/main/AndroidManifest.xml b/app/rust_builder/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..b3a4f4c --- /dev/null +++ b/app/rust_builder/android/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/app/rust_builder/cargokit/.gitignore b/app/rust_builder/cargokit/.gitignore new file mode 100644 index 0000000..cf7bb86 --- /dev/null +++ b/app/rust_builder/cargokit/.gitignore @@ -0,0 +1,4 @@ +target +.dart_tool +*.iml +!pubspec.lock diff --git a/app/rust_builder/cargokit/LICENSE b/app/rust_builder/cargokit/LICENSE new file mode 100644 index 0000000..d33a5fe --- /dev/null +++ b/app/rust_builder/cargokit/LICENSE @@ -0,0 +1,42 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +Copyright 2022 Matej Knopp + +================================================================================ + +MIT LICENSE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================================================================================ + +APACHE LICENSE, VERSION 2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + diff --git a/app/rust_builder/cargokit/README b/app/rust_builder/cargokit/README new file mode 100644 index 0000000..398474d --- /dev/null +++ b/app/rust_builder/cargokit/README @@ -0,0 +1,11 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +Experimental repository to provide glue for seamlessly integrating cargo build +with flutter plugins and packages. + +See https://matejknopp.com/post/flutter_plugin_in_rust_with_no_prebuilt_binaries/ +for a tutorial on how to use Cargokit. + +Example plugin available at https://github.com/irondash/hello_rust_ffi_plugin. + diff --git a/app/rust_builder/cargokit/build_pod.sh b/app/rust_builder/cargokit/build_pod.sh new file mode 100755 index 0000000..ed0e0d9 --- /dev/null +++ b/app/rust_builder/cargokit/build_pod.sh @@ -0,0 +1,58 @@ +#!/bin/sh +set -e + +BASEDIR=$(dirname "$0") + +# Workaround for https://github.com/dart-lang/pub/issues/4010 +BASEDIR=$(cd "$BASEDIR" ; pwd -P) + +# Remove XCode SDK from path. Otherwise this breaks tool compilation when building iOS project +NEW_PATH=`echo $PATH | tr ":" "\n" | grep -v "Contents/Developer/" | tr "\n" ":"` + +export PATH=${NEW_PATH%?} # remove trailing : + +env + +# Platform name (macosx, iphoneos, iphonesimulator) +export CARGOKIT_DARWIN_PLATFORM_NAME=$PLATFORM_NAME + +# Arctive architectures (arm64, armv7, x86_64), space separated. +export CARGOKIT_DARWIN_ARCHS=$ARCHS + +# Current build configuration (Debug, Release) +export CARGOKIT_CONFIGURATION=$CONFIGURATION + +# Path to directory containing Cargo.toml. +export CARGOKIT_MANIFEST_DIR=$PODS_TARGET_SRCROOT/$1 + +# Temporary directory for build artifacts. +export CARGOKIT_TARGET_TEMP_DIR=$TARGET_TEMP_DIR + +# Output directory for final artifacts. +export CARGOKIT_OUTPUT_DIR=$PODS_CONFIGURATION_BUILD_DIR/$PRODUCT_NAME + +# Directory to store built tool artifacts. +export CARGOKIT_TOOL_TEMP_DIR=$TARGET_TEMP_DIR/build_tool + +# Directory inside root project. Not necessarily the top level directory of root project. +export CARGOKIT_ROOT_PROJECT_DIR=$SRCROOT + +FLUTTER_EXPORT_BUILD_ENVIRONMENT=( + "$PODS_ROOT/../Flutter/ephemeral/flutter_export_environment.sh" # macOS + "$PODS_ROOT/../Flutter/flutter_export_environment.sh" # iOS +) + +for path in "${FLUTTER_EXPORT_BUILD_ENVIRONMENT[@]}" +do + if [[ -f "$path" ]]; then + source "$path" + fi +done + +sh "$BASEDIR/run_build_tool.sh" build-pod "$@" + +# Make a symlink from built framework to phony file, which will be used as input to +# build script. This should force rebuild (podspec currently doesn't support alwaysOutOfDate +# attribute on custom build phase) +ln -fs "$OBJROOT/XCBuildData/build.db" "${BUILT_PRODUCTS_DIR}/cargokit_phony" +ln -fs "${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}" "${BUILT_PRODUCTS_DIR}/cargokit_phony_out" diff --git a/app/rust_builder/cargokit/build_tool/README.md b/app/rust_builder/cargokit/build_tool/README.md new file mode 100644 index 0000000..a878c27 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/README.md @@ -0,0 +1,5 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +A sample command-line application with an entrypoint in `bin/`, library code +in `lib/`, and example unit test in `test/`. diff --git a/app/rust_builder/cargokit/build_tool/analysis_options.yaml b/app/rust_builder/cargokit/build_tool/analysis_options.yaml new file mode 100644 index 0000000..0e16a8b --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/analysis_options.yaml @@ -0,0 +1,34 @@ +# This is copied from Cargokit (which is the official way to use it currently) +# Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +# This file configures the static analysis results for your project (errors, +# warnings, and lints). +# +# This enables the 'recommended' set of lints from `package:lints`. +# This set helps identify many issues that may lead to problems when running +# or consuming Dart code, and enforces writing Dart using a single, idiomatic +# style and format. +# +# If you want a smaller set of lints you can change this to specify +# 'package:lints/core.yaml'. These are just the most critical lints +# (the recommended set includes the core lints). +# The core lints are also what is used by pub.dev for scoring packages. + +include: package:lints/recommended.yaml + +# Uncomment the following section to specify additional rules. + +linter: + rules: + - prefer_relative_imports + - directives_ordering + +# analyzer: +# exclude: +# - path/to/excluded/files/** + +# For more information about the core and recommended set of lints, see +# https://dart.dev/go/core-lints + +# For additional information about configuring this file, see +# https://dart.dev/guides/language/analysis-options diff --git a/app/rust_builder/cargokit/build_tool/bin/build_tool.dart b/app/rust_builder/cargokit/build_tool/bin/build_tool.dart new file mode 100644 index 0000000..268eb52 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/bin/build_tool.dart @@ -0,0 +1,8 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'package:build_tool/build_tool.dart' as build_tool; + +void main(List arguments) { + build_tool.runMain(arguments); +} diff --git a/app/rust_builder/cargokit/build_tool/lib/build_tool.dart b/app/rust_builder/cargokit/build_tool/lib/build_tool.dart new file mode 100644 index 0000000..7c1bb75 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/build_tool.dart @@ -0,0 +1,8 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'src/build_tool.dart' as build_tool; + +Future runMain(List args) async { + return build_tool.runMain(args); +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/android_environment.dart b/app/rust_builder/cargokit/build_tool/lib/src/android_environment.dart new file mode 100644 index 0000000..37dec57 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/android_environment.dart @@ -0,0 +1,209 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; +import 'dart:isolate'; +import 'dart:math' as math; + +import 'package:collection/collection.dart'; +import 'package:path/path.dart' as path; +import 'package:version/version.dart'; + +import 'target.dart'; +import 'util.dart'; + +class AndroidEnvironment { + AndroidEnvironment({ + required this.sdkPath, + required this.ndkVersion, + required this.minSdkVersion, + required this.targetTempDir, + required this.target, + }); + + static void clangLinkerWrapper(List args) { + final clang = Platform.environment['_CARGOKIT_NDK_LINK_CLANG']; + if (clang == null) { + throw Exception( + "cargo-ndk rustc linker: didn't find _CARGOKIT_NDK_LINK_CLANG env var"); + } + final target = Platform.environment['_CARGOKIT_NDK_LINK_TARGET']; + if (target == null) { + throw Exception( + "cargo-ndk rustc linker: didn't find _CARGOKIT_NDK_LINK_TARGET env var"); + } + + runCommand(clang, [ + target, + ...args, + ]); + } + + /// Full path to Android SDK. + final String sdkPath; + + /// Full version of Android NDK. + final String ndkVersion; + + /// Minimum supported SDK version. + final int minSdkVersion; + + /// Target directory for build artifacts. + final String targetTempDir; + + /// Target being built. + final Target target; + + bool ndkIsInstalled() { + final ndkPath = path.join(sdkPath, 'ndk', ndkVersion); + final ndkPackageXml = File(path.join(ndkPath, 'package.xml')); + return ndkPackageXml.existsSync(); + } + + void installNdk({ + required String javaHome, + }) { + final sdkManagerExtension = Platform.isWindows ? '.bat' : ''; + final sdkManager = path.join( + sdkPath, + 'cmdline-tools', + 'latest', + 'bin', + 'sdkmanager$sdkManagerExtension', + ); + + log.info('Installing NDK $ndkVersion'); + runCommand(sdkManager, [ + '--install', + 'ndk;$ndkVersion', + ], environment: { + 'JAVA_HOME': javaHome, + }); + } + + Future> buildEnvironment() async { + final hostArch = Platform.isMacOS + ? "darwin-x86_64" + : (Platform.isLinux ? "linux-x86_64" : "windows-x86_64"); + + final ndkPath = path.join(sdkPath, 'ndk', ndkVersion); + final toolchainPath = path.join( + ndkPath, + 'toolchains', + 'llvm', + 'prebuilt', + hostArch, + 'bin', + ); + + final minSdkVersion = + math.max(target.androidMinSdkVersion!, this.minSdkVersion); + + final exe = Platform.isWindows ? '.exe' : ''; + + final arKey = 'AR_${target.rust}'; + final arValue = ['${target.rust}-ar', 'llvm-ar', 'llvm-ar.exe'] + .map((e) => path.join(toolchainPath, e)) + .firstWhereOrNull((element) => File(element).existsSync()); + if (arValue == null) { + throw Exception('Failed to find ar for $target in $toolchainPath'); + } + + final targetArg = '--target=${target.rust}$minSdkVersion'; + + final ccKey = 'CC_${target.rust}'; + final ccValue = path.join(toolchainPath, 'clang$exe'); + final cfFlagsKey = 'CFLAGS_${target.rust}'; + final cFlagsValue = targetArg; + + final cxxKey = 'CXX_${target.rust}'; + final cxxValue = path.join(toolchainPath, 'clang++$exe'); + final cxxFlagsKey = 'CXXFLAGS_${target.rust}'; + final cxxFlagsValue = targetArg; + + final linkerKey = + 'cargo_target_${target.rust.replaceAll('-', '_')}_linker'.toUpperCase(); + + final ranlibKey = 'RANLIB_${target.rust}'; + final ranlibValue = path.join(toolchainPath, 'llvm-ranlib$exe'); + + final ndkVersionParsed = Version.parse(ndkVersion); + final rustFlagsKey = 'CARGO_ENCODED_RUSTFLAGS'; + final rustFlagsValue = _libGccWorkaround(targetTempDir, ndkVersionParsed); + + final runRustTool = + Platform.isWindows ? 'run_build_tool.cmd' : 'run_build_tool.sh'; + + final packagePath = (await Isolate.resolvePackageUri( + Uri.parse('package:build_tool/buildtool.dart')))! + .toFilePath(); + final selfPath = path.canonicalize(path.join( + packagePath, + '..', + '..', + '..', + runRustTool, + )); + + // Make sure that run_build_tool is working properly even initially launched directly + // through dart run. + final toolTempDir = + Platform.environment['CARGOKIT_TOOL_TEMP_DIR'] ?? targetTempDir; + + return { + arKey: arValue, + ccKey: ccValue, + cfFlagsKey: cFlagsValue, + cxxKey: cxxValue, + cxxFlagsKey: cxxFlagsValue, + ranlibKey: ranlibValue, + rustFlagsKey: rustFlagsValue, + linkerKey: selfPath, + // Recognized by main() so we know when we're acting as a wrapper + '_CARGOKIT_NDK_LINK_TARGET': targetArg, + '_CARGOKIT_NDK_LINK_CLANG': ccValue, + 'CARGOKIT_TOOL_TEMP_DIR': toolTempDir, + }; + } + + // Workaround for libgcc missing in NDK23, inspired by cargo-ndk + String _libGccWorkaround(String buildDir, Version ndkVersion) { + final workaroundDir = path.join( + buildDir, + 'cargokit', + 'libgcc_workaround', + '${ndkVersion.major}', + ); + Directory(workaroundDir).createSync(recursive: true); + if (ndkVersion.major >= 23) { + File(path.join(workaroundDir, 'libgcc.a')) + .writeAsStringSync('INPUT(-lunwind)'); + } else { + // Other way around, untested, forward libgcc.a from libunwind once Rust + // gets updated for NDK23+. + File(path.join(workaroundDir, 'libunwind.a')) + .writeAsStringSync('INPUT(-lgcc)'); + } + + var rustFlags = Platform.environment['CARGO_ENCODED_RUSTFLAGS'] ?? ''; + if (rustFlags.isNotEmpty) { + rustFlags = '$rustFlags\x1f'; + } + if (["arm64-v8a", "x86_64"].contains(target.android)) { + rustFlags = '$rustFlags-L\x1f$workaroundDir\x1f'; + + const pageSizeArgs = [ + "-C", + "link-arg=-Wl,--hash-style=both", + "-C", + "link-arg=-Wl,-z,max-page-size=16384" + ]; + final pageSizeArgsString = pageSizeArgs.join("\x1f"); + + rustFlags = '$rustFlags$pageSizeArgsString'; + } else { + rustFlags = '$rustFlags-L\x1f$workaroundDir'; + } + return rustFlags; + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart b/app/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart new file mode 100644 index 0000000..2eb1166 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart @@ -0,0 +1,266 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:http/http.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'builder.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'rustup.dart'; +import 'target.dart'; + +class Artifact { + /// File system location of the artifact. + final String path; + + /// Actual file name that the artifact should have in destination folder. + final String finalFileName; + + AritifactType get type { + if (finalFileName.endsWith('.dll') || + finalFileName.endsWith('.dll.lib') || + finalFileName.endsWith('.pdb') || + finalFileName.endsWith('.so') || + finalFileName.endsWith('.dylib')) { + return AritifactType.dylib; + } else if (finalFileName.endsWith('.lib') || finalFileName.endsWith('.a')) { + return AritifactType.staticlib; + } else { + throw Exception('Unknown artifact type for $finalFileName'); + } + } + + Artifact({ + required this.path, + required this.finalFileName, + }); +} + +final _log = Logger('artifacts_provider'); + +class ArtifactProvider { + ArtifactProvider({ + required this.environment, + required this.userOptions, + }); + + final BuildEnvironment environment; + final CargokitUserOptions userOptions; + + Future>> getArtifacts(List targets) async { + final result = await _getPrecompiledArtifacts(targets); + + final pendingTargets = List.of(targets); + pendingTargets.removeWhere((element) => result.containsKey(element)); + + if (pendingTargets.isEmpty) { + return result; + } + + final rustup = Rustup(); + for (final target in targets) { + final builder = RustBuilder(target: target, environment: environment); + builder.prepare(rustup); + _log.info('Building ${environment.crateInfo.packageName} for $target'); + final targetDir = await builder.build(); + // For local build accept both static and dynamic libraries. + final artifactNames = { + ...getArtifactNames( + target: target, + libraryName: environment.crateInfo.libName, + aritifactType: AritifactType.dylib, + remote: false, + ), + ...getArtifactNames( + target: target, + libraryName: environment.crateInfo.libName, + aritifactType: AritifactType.staticlib, + remote: false, + ) + }; + final artifacts = artifactNames + .map((artifactName) => Artifact( + path: path.join(targetDir, artifactName), + finalFileName: artifactName, + )) + .where((element) => File(element.path).existsSync()) + .toList(); + result[target] = artifacts; + } + return result; + } + + Future>> _getPrecompiledArtifacts( + List targets) async { + if (userOptions.usePrecompiledBinaries == false) { + _log.info('Precompiled binaries are disabled'); + return {}; + } + if (environment.crateOptions.precompiledBinaries == null) { + _log.fine('Precompiled binaries not enabled for this crate'); + return {}; + } + + final start = Stopwatch()..start(); + final crateHash = CrateHash.compute(environment.manifestDir, + tempStorage: environment.targetTempDir); + _log.fine( + 'Computed crate hash $crateHash in ${start.elapsedMilliseconds}ms'); + + final downloadedArtifactsDir = + path.join(environment.targetTempDir, 'precompiled', crateHash); + Directory(downloadedArtifactsDir).createSync(recursive: true); + + final res = >{}; + + for (final target in targets) { + final requiredArtifacts = getArtifactNames( + target: target, + libraryName: environment.crateInfo.libName, + remote: true, + ); + final artifactsForTarget = []; + + for (final artifact in requiredArtifacts) { + final fileName = PrecompileBinaries.fileName(target, artifact); + final downloadedPath = path.join(downloadedArtifactsDir, fileName); + if (!File(downloadedPath).existsSync()) { + final signatureFileName = + PrecompileBinaries.signatureFileName(target, artifact); + await _tryDownloadArtifacts( + crateHash: crateHash, + fileName: fileName, + signatureFileName: signatureFileName, + finalPath: downloadedPath, + ); + } + if (File(downloadedPath).existsSync()) { + artifactsForTarget.add(Artifact( + path: downloadedPath, + finalFileName: artifact, + )); + } else { + break; + } + } + + // Only provide complete set of artifacts. + if (artifactsForTarget.length == requiredArtifacts.length) { + _log.fine('Found precompiled artifacts for $target'); + res[target] = artifactsForTarget; + } + } + + return res; + } + + static Future _get(Uri url, {Map? headers}) async { + int attempt = 0; + const maxAttempts = 10; + while (true) { + try { + return await get(url, headers: headers); + } on SocketException catch (e) { + // Try to detect reset by peer error and retry. + if (attempt++ < maxAttempts && + (e.osError?.errorCode == 54 || e.osError?.errorCode == 10054)) { + _log.severe( + 'Failed to download $url: $e, attempt $attempt of $maxAttempts, will retry...'); + await Future.delayed(Duration(seconds: 1)); + continue; + } else { + rethrow; + } + } + } + } + + Future _tryDownloadArtifacts({ + required String crateHash, + required String fileName, + required String signatureFileName, + required String finalPath, + }) async { + final precompiledBinaries = environment.crateOptions.precompiledBinaries!; + final prefix = precompiledBinaries.uriPrefix; + final url = Uri.parse('$prefix$crateHash/$fileName'); + final signatureUrl = Uri.parse('$prefix$crateHash/$signatureFileName'); + _log.fine('Downloading signature from $signatureUrl'); + final signature = await _get(signatureUrl); + if (signature.statusCode == 404) { + _log.warning( + 'Precompiled binaries not available for crate hash $crateHash ($fileName)'); + return; + } + if (signature.statusCode != 200) { + _log.severe( + 'Failed to download signature $signatureUrl: status ${signature.statusCode}'); + return; + } + _log.fine('Downloading binary from $url'); + final res = await _get(url); + if (res.statusCode != 200) { + _log.severe('Failed to download binary $url: status ${res.statusCode}'); + return; + } + if (verify( + precompiledBinaries.publicKey, res.bodyBytes, signature.bodyBytes)) { + File(finalPath).writeAsBytesSync(res.bodyBytes); + } else { + _log.shout('Signature verification failed! Ignoring binary.'); + } + } +} + +enum AritifactType { + staticlib, + dylib, +} + +AritifactType artifactTypeForTarget(Target target) { + if (target.darwinPlatform != null) { + return AritifactType.staticlib; + } else { + return AritifactType.dylib; + } +} + +List getArtifactNames({ + required Target target, + required String libraryName, + required bool remote, + AritifactType? aritifactType, +}) { + aritifactType ??= artifactTypeForTarget(target); + if (target.darwinArch != null) { + if (aritifactType == AritifactType.staticlib) { + return ['lib$libraryName.a']; + } else { + return ['lib$libraryName.dylib']; + } + } else if (target.rust.contains('-windows-')) { + if (aritifactType == AritifactType.staticlib) { + return ['$libraryName.lib']; + } else { + return [ + '$libraryName.dll', + '$libraryName.dll.lib', + if (!remote) '$libraryName.pdb' + ]; + } + } else if (target.rust.contains('-linux-')) { + if (aritifactType == AritifactType.staticlib) { + return ['lib$libraryName.a']; + } else { + return ['lib$libraryName.so']; + } + } else { + throw Exception("Unsupported target: ${target.rust}"); + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart b/app/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart new file mode 100644 index 0000000..6f3b2a4 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart @@ -0,0 +1,40 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; + +class BuildCMake { + final CargokitUserOptions userOptions; + + BuildCMake({required this.userOptions}); + + Future build() async { + final targetPlatform = Environment.targetPlatform; + final target = Target.forFlutterName(Environment.targetPlatform); + if (target == null) { + throw Exception("Unknown target platform: $targetPlatform"); + } + + final environment = BuildEnvironment.fromEnvironment(isAndroid: false); + final provider = + ArtifactProvider(environment: environment, userOptions: userOptions); + final artifacts = await provider.getArtifacts([target]); + + final libs = artifacts[target]!; + + for (final lib in libs) { + if (lib.type == AritifactType.dylib) { + File(lib.path) + .copySync(path.join(Environment.outputDir, lib.finalFileName)); + } + } + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart b/app/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart new file mode 100644 index 0000000..8d74d91 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart @@ -0,0 +1,55 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; + +final log = Logger('build_gradle'); + +class BuildGradle { + BuildGradle({required this.userOptions}); + + final CargokitUserOptions userOptions; + + Future build() async { + final targets = Environment.targetPlatforms + .map((arch) { + final target = Target.forFlutterName(arch); + if (target == null) { + throw Exception( + "Unknown darwin target or platform: $arch, ${Environment.darwinPlatformName}", + ); + } + return target; + }) + .toSet() + .toList(); + + final environment = BuildEnvironment.fromEnvironment(isAndroid: true); + final provider = ArtifactProvider( + environment: environment, + userOptions: userOptions, + ); + final artifacts = await provider.getArtifacts(targets); + + for (final target in targets) { + final libs = artifacts[target]!; + final outputDir = path.join(Environment.outputDir, target.android!); + Directory(outputDir).createSync(recursive: true); + + for (final lib in libs) { + if (lib.type == AritifactType.dylib) { + File(lib.path).copySync(path.join(outputDir, lib.finalFileName)); + } + } + } + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/build_pod.dart b/app/rust_builder/cargokit/build_tool/lib/src/build_pod.dart new file mode 100644 index 0000000..8a9c0db --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/build_pod.dart @@ -0,0 +1,89 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; +import 'util.dart'; + +class BuildPod { + BuildPod({required this.userOptions}); + + final CargokitUserOptions userOptions; + + Future build() async { + final targets = Environment.darwinArchs.map((arch) { + final target = Target.forDarwin( + platformName: Environment.darwinPlatformName, darwinAarch: arch); + if (target == null) { + throw Exception( + "Unknown darwin target or platform: $arch, ${Environment.darwinPlatformName}"); + } + return target; + }).toList(); + + final environment = BuildEnvironment.fromEnvironment(isAndroid: false); + final provider = + ArtifactProvider(environment: environment, userOptions: userOptions); + final artifacts = await provider.getArtifacts(targets); + + void performLipo(String targetFile, Iterable sourceFiles) { + runCommand("lipo", [ + '-create', + ...sourceFiles, + '-output', + targetFile, + ]); + } + + final outputDir = Environment.outputDir; + + Directory(outputDir).createSync(recursive: true); + + final staticLibs = artifacts.values + .expand((element) => element) + .where((element) => element.type == AritifactType.staticlib) + .toList(); + final dynamicLibs = artifacts.values + .expand((element) => element) + .where((element) => element.type == AritifactType.dylib) + .toList(); + + final libName = environment.crateInfo.packageName; + + // If there is static lib, use it and link it with pod + if (staticLibs.isNotEmpty) { + final finalTargetFile = path.join(outputDir, "lib$libName.a"); + performLipo(finalTargetFile, staticLibs.map((e) => e.path)); + } else { + // Otherwise try to replace bundle dylib with our dylib + final bundlePaths = [ + '$libName.framework/Versions/A/$libName', + '$libName.framework/$libName', + ]; + + for (final bundlePath in bundlePaths) { + final targetFile = path.join(outputDir, bundlePath); + if (File(targetFile).existsSync()) { + performLipo(targetFile, dynamicLibs.map((e) => e.path)); + + // Replace absolute id with @rpath one so that it works properly + // when moved to Frameworks. + runCommand("install_name_tool", [ + '-id', + '@rpath/$bundlePath', + targetFile, + ]); + return; + } + } + throw Exception('Unable to find bundle for dynamic library'); + } + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/build_tool.dart b/app/rust_builder/cargokit/build_tool/lib/src/build_tool.dart new file mode 100644 index 0000000..70dfe0e --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/build_tool.dart @@ -0,0 +1,276 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:args/command_runner.dart'; +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:github/github.dart'; +import 'package:hex/hex.dart'; +import 'package:logging/logging.dart'; + +import 'android_environment.dart'; +import 'build_cmake.dart'; +import 'build_gradle.dart'; +import 'build_pod.dart'; +import 'logging.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'target.dart'; +import 'util.dart'; +import 'verify_binaries.dart'; + +final log = Logger('build_tool'); + +abstract class BuildCommand extends Command { + Future runBuildCommand(CargokitUserOptions options); + + @override + Future run() async { + final options = CargokitUserOptions.load(); + + if (options.verboseLogging || + Platform.environment['CARGOKIT_VERBOSE'] == '1') { + enableVerboseLogging(); + } + + await runBuildCommand(options); + } +} + +class BuildPodCommand extends BuildCommand { + @override + final name = 'build-pod'; + + @override + final description = 'Build cocoa pod library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildPod(userOptions: options); + await build.build(); + } +} + +class BuildGradleCommand extends BuildCommand { + @override + final name = 'build-gradle'; + + @override + final description = 'Build android library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildGradle(userOptions: options); + await build.build(); + } +} + +class BuildCMakeCommand extends BuildCommand { + @override + final name = 'build-cmake'; + + @override + final description = 'Build CMake library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildCMake(userOptions: options); + await build.build(); + } +} + +class GenKeyCommand extends Command { + @override + final name = 'gen-key'; + + @override + final description = 'Generate key pair for signing precompiled binaries'; + + @override + void run() { + final kp = generateKey(); + final private = HEX.encode(kp.privateKey.bytes); + final public = HEX.encode(kp.publicKey.bytes); + print("Private Key: $private"); + print("Public Key: $public"); + } +} + +class PrecompileBinariesCommand extends Command { + PrecompileBinariesCommand() { + argParser + ..addOption( + 'repository', + mandatory: true, + help: 'Github repository slug in format owner/name', + ) + ..addOption( + 'manifest-dir', + mandatory: true, + help: 'Directory containing Cargo.toml', + ) + ..addMultiOption('target', + help: 'Rust target triple of artifact to build.\n' + 'Can be specified multiple times or omitted in which case\n' + 'all targets for current platform will be built.') + ..addOption( + 'android-sdk-location', + help: 'Location of Android SDK (if available)', + ) + ..addOption( + 'android-ndk-version', + help: 'Android NDK version (if available)', + ) + ..addOption( + 'android-min-sdk-version', + help: 'Android minimum rquired version (if available)', + ) + ..addOption( + 'temp-dir', + help: 'Directory to store temporary build artifacts', + ) + ..addOption( + 'glibc-version', + help: 'GLIBC version to use for linux builds', + ) + ..addFlag( + "verbose", + abbr: "v", + defaultsTo: false, + help: "Enable verbose logging", + ); + } + + @override + final name = 'precompile-binaries'; + + @override + final description = 'Prebuild and upload binaries\n' + 'Private key must be passed through PRIVATE_KEY environment variable. ' + 'Use gen_key through generate priave key.\n' + 'Github token must be passed as GITHUB_TOKEN environment variable.\n'; + + @override + Future run() async { + final verbose = argResults!['verbose'] as bool; + if (verbose) { + enableVerboseLogging(); + } + + final privateKeyString = Platform.environment['PRIVATE_KEY']; + if (privateKeyString == null) { + throw ArgumentError('Missing PRIVATE_KEY environment variable'); + } + final githubToken = Platform.environment['GITHUB_TOKEN']; + if (githubToken == null) { + throw ArgumentError('Missing GITHUB_TOKEN environment variable'); + } + final privateKey = HEX.decode(privateKeyString); + if (privateKey.length != 64) { + throw ArgumentError('Private key must be 64 bytes long'); + } + final manifestDir = argResults!['manifest-dir'] as String; + if (!Directory(manifestDir).existsSync()) { + throw ArgumentError('Manifest directory does not exist: $manifestDir'); + } + String? androidMinSdkVersionString = + argResults!['android-min-sdk-version'] as String?; + int? androidMinSdkVersion; + if (androidMinSdkVersionString != null) { + androidMinSdkVersion = int.tryParse(androidMinSdkVersionString); + if (androidMinSdkVersion == null) { + throw ArgumentError( + 'Invalid android-min-sdk-version: $androidMinSdkVersionString'); + } + } + final targetStrigns = argResults!['target'] as List; + final targets = targetStrigns.map((target) { + final res = Target.forRustTriple(target); + if (res == null) { + throw ArgumentError('Invalid target: $target'); + } + return res; + }).toList(growable: false); + final precompileBinaries = PrecompileBinaries( + privateKey: PrivateKey(privateKey), + githubToken: githubToken, + manifestDir: manifestDir, + repositorySlug: RepositorySlug.full(argResults!['repository'] as String), + targets: targets, + androidSdkLocation: argResults!['android-sdk-location'] as String?, + androidNdkVersion: argResults!['android-ndk-version'] as String?, + androidMinSdkVersion: androidMinSdkVersion, + tempDir: argResults!['temp-dir'] as String?, + glibcVersion: argResults!['glibc-version'] as String?, + ); + + await precompileBinaries.run(); + } +} + +class VerifyBinariesCommand extends Command { + VerifyBinariesCommand() { + argParser.addOption( + 'manifest-dir', + mandatory: true, + help: 'Directory containing Cargo.toml', + ); + } + + @override + final name = "verify-binaries"; + + @override + final description = 'Verifies published binaries\n' + 'Checks whether there is a binary published for each targets\n' + 'and checks the signature.'; + + @override + Future run() async { + final manifestDir = argResults!['manifest-dir'] as String; + final verifyBinaries = VerifyBinaries( + manifestDir: manifestDir, + ); + await verifyBinaries.run(); + } +} + +Future runMain(List args) async { + try { + // Init logging before options are loaded + initLogging(); + + if (Platform.environment['_CARGOKIT_NDK_LINK_TARGET'] != null) { + return AndroidEnvironment.clangLinkerWrapper(args); + } + + final runner = CommandRunner('build_tool', 'Cargokit built_tool') + ..addCommand(BuildPodCommand()) + ..addCommand(BuildGradleCommand()) + ..addCommand(BuildCMakeCommand()) + ..addCommand(GenKeyCommand()) + ..addCommand(PrecompileBinariesCommand()) + ..addCommand(VerifyBinariesCommand()); + + await runner.run(args); + } on ArgumentError catch (e) { + stderr.writeln(e.toString()); + exit(1); + } catch (e, s) { + log.severe(kDoubleSeparator); + log.severe('Cargokit BuildTool failed with error:'); + log.severe(kSeparator); + log.severe(e); + // This tells user to install Rust, there's no need to pollute the log with + // stack trace. + if (e is! RustupNotFoundException) { + log.severe(kSeparator); + log.severe(s); + log.severe(kSeparator); + log.severe('BuildTool arguments: $args'); + } + log.severe(kDoubleSeparator); + exit(1); + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/builder.dart b/app/rust_builder/cargokit/build_tool/lib/src/builder.dart new file mode 100644 index 0000000..c708917 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/builder.dart @@ -0,0 +1,261 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'android_environment.dart'; +import 'cargo.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'rustup.dart'; +import 'target.dart'; +import 'util.dart'; + +final _log = Logger('builder'); + +enum BuildConfiguration { + debug, + release, + profile, +} + +extension on BuildConfiguration { + bool get isDebug => this == BuildConfiguration.debug; + String get rustName => switch (this) { + BuildConfiguration.debug => 'debug', + BuildConfiguration.release => 'release', + BuildConfiguration.profile => 'release', + }; +} + +class BuildException implements Exception { + final String message; + + BuildException(this.message); + + @override + String toString() { + return 'BuildException: $message'; + } +} + +class BuildEnvironment { + final BuildConfiguration configuration; + final CargokitCrateOptions crateOptions; + final String targetTempDir; + final String manifestDir; + final CrateInfo crateInfo; + + final bool isAndroid; + final String? androidSdkPath; + final String? androidNdkVersion; + final int? androidMinSdkVersion; + final String? javaHome; + final String? ohosSdkHome; + + final String? glibcVersion; + + BuildEnvironment({ + required this.configuration, + required this.crateOptions, + required this.targetTempDir, + required this.manifestDir, + required this.crateInfo, + required this.isAndroid, + this.androidSdkPath, + this.androidNdkVersion, + this.androidMinSdkVersion, + this.javaHome, + this.glibcVersion, + this.ohosSdkHome, + }); + + static BuildConfiguration parseBuildConfiguration(String value) { + // XCode configuration adds the flavor to configuration name. + final firstSegment = value.split('-').first; + final buildConfiguration = BuildConfiguration.values.firstWhereOrNull( + (e) => e.name == firstSegment, + ); + if (buildConfiguration == null) { + _log.warning('Unknown build configuraiton $value, will assume release'); + return BuildConfiguration.release; + } + return buildConfiguration; + } + + static BuildEnvironment fromEnvironment({ + required bool isAndroid, + }) { + final buildConfiguration = + parseBuildConfiguration(Environment.configuration); + final manifestDir = Environment.manifestDir; + final crateOptions = CargokitCrateOptions.load( + manifestDir: manifestDir, + ); + final crateInfo = CrateInfo.load(manifestDir); + return BuildEnvironment( + configuration: buildConfiguration, + crateOptions: crateOptions, + targetTempDir: Environment.targetTempDir, + manifestDir: manifestDir, + crateInfo: crateInfo, + isAndroid: isAndroid, + androidSdkPath: isAndroid ? Environment.sdkPath : null, + androidNdkVersion: isAndroid ? Environment.ndkVersion : null, + androidMinSdkVersion: + isAndroid ? int.parse(Environment.minSdkVersion) : null, + javaHome: isAndroid ? Environment.javaHome : null, + ohosSdkHome: Environment.ohosSdkHome, + ); + } +} + +class RustBuilder { + final Target target; + final BuildEnvironment environment; + String? _resolvedToolchain; + + RustBuilder({ + required this.target, + required this.environment, + }); + + void prepare( + Rustup rustup, + ) { + final toolchain = _toolchain; + if (rustup.installedTargets(toolchain) == null) { + rustup.installToolchain(toolchain); + } + final resolvedToolchain = rustup.resolveToolchain(toolchain); + if (toolchain == 'nightly') { + rustup.installRustSrcForNightly(toolchain: resolvedToolchain); + } + if (!rustup.installedTargets(toolchain)!.contains(target.rust)) { + rustup.installTarget(target.rust, toolchain: resolvedToolchain); + } + if (environment.glibcVersion != null) { + rustup.installZigBuild(resolvedToolchain); + } + _resolvedToolchain = resolvedToolchain; + } + + CargoBuildOptions? get _buildOptions => + environment.crateOptions.cargo[environment.configuration]; + + String get _toolchain => _buildOptions?.toolchain.name ?? 'stable'; + String get _effectiveToolchain => _resolvedToolchain ?? _toolchain; + + /// Returns the path of directory containing build artifacts. + Future build() async { + final extraArgs = _buildOptions?.flags ?? []; + final manifestPath = path.join(environment.manifestDir, 'Cargo.toml'); + runCommand( + 'rustup', + [ + 'run', + _effectiveToolchain, + 'cargo', + (target.android == null && environment.glibcVersion != null) + ? 'zigbuild' + : 'build', + ...extraArgs, + '--manifest-path', + manifestPath, + '-p', + environment.crateInfo.packageName, + if (!environment.configuration.isDebug) '--release', + '--target', + target.rust + + ((target.android == null && environment.glibcVersion != null) + ? '.${environment.glibcVersion!}' + : ""), + '--target-dir', + environment.targetTempDir, + ], + environment: await _buildEnvironment(), + ); + return path.join( + environment.targetTempDir, + target.rust, + environment.configuration.rustName, + ); + } + + Future> _buildEnvironment() async { + if (target.ohos != null) { + return _buildOhosEnv(); + } + if (target.android != null) { + return _buildAndroidEnv(); + } + return {}; + } + + Future> _buildAndroidEnv() { + final sdkPath = environment.androidSdkPath; + final ndkVersion = environment.androidNdkVersion; + final minSdkVersion = environment.androidMinSdkVersion; + if (sdkPath == null) { + throw BuildException('androidSdkPath is not set'); + } + if (ndkVersion == null) { + throw BuildException('androidNdkVersion is not set'); + } + if (minSdkVersion == null) { + throw BuildException('androidMinSdkVersion is not set'); + } + final env = AndroidEnvironment( + sdkPath: sdkPath, + ndkVersion: ndkVersion, + minSdkVersion: minSdkVersion, + targetTempDir: environment.targetTempDir, + target: target, + ); + if (!env.ndkIsInstalled() && environment.javaHome != null) { + env.installNdk(javaHome: environment.javaHome!); + } + return env.buildEnvironment(); + } + + Map _buildOhosEnv() { + final sdkPath = environment.ohosSdkHome; + if (sdkPath == null) { + throw BuildException('OHOS SDK native path is not set'); + } + final exe = Platform.isWindows ? '.exe' : ''; + final clangPath = path.join(sdkPath, 'llvm', 'bin', 'clang$exe'); + final sysroot = path.join(sdkPath, 'sysroot'); + String clangTarget; + switch (target.ohos) { + case 'arm64-v8a': + clangTarget = 'aarch64-linux-ohos'; + break; + case 'armeabi-v7a': + clangTarget = 'arm-linux-ohos'; + break; + case 'x86_64': + clangTarget = 'x86_64-linux-ohos'; + break; + default: + clangTarget = 'aarch64-linux-ohos'; + } + final targetEnvName = target.rust.toUpperCase().replaceAll('-', '_'); + final linkerEnvVar = 'CARGO_TARGET_${targetEnvName}_LINKER'; + final rustFlagsEnvVar = 'CARGO_TARGET_${targetEnvName}_RUSTFLAGS'; + final rustFlags = '-C link-arg=--target=$clangTarget ' + '-C link-arg=-fuse-ld=lld ' + '-C link-arg=--sysroot=$sysroot ' + '-C link-arg=-D__MUSL__'; + return { + rustFlagsEnvVar: rustFlags, + linkerEnvVar: clangPath, + 'CC_${target.rust}': clangPath, + 'AR_${target.rust}': path.join(sdkPath, 'llvm', 'bin', 'llvm-ar$exe'), + }; + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/cargo.dart b/app/rust_builder/cargokit/build_tool/lib/src/cargo.dart new file mode 100644 index 0000000..56419aa --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/cargo.dart @@ -0,0 +1,51 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:path/path.dart' as path; +import 'package:toml/toml.dart'; + +class ManifestException { + ManifestException(this.message, {required this.fileName}); + + final String? fileName; + final String message; + + @override + String toString() { + if (fileName != null) { + return 'Failed to parse package manifest at $fileName: $message'; + } else { + return 'Failed to parse package manifest: $message'; + } + } +} + +class CrateInfo { + CrateInfo({required this.packageName}); + + final String packageName; + + /// Library (artifact) name: cargo turns `-` in the package name into `_`. + String get libName => packageName.replaceAll('-', '_'); + + static CrateInfo parseManifest(String manifest, {final String? fileName}) { + final toml = TomlDocument.parse(manifest); + final package = toml.toMap()['package']; + if (package == null) { + throw ManifestException('Missing package section', fileName: fileName); + } + final name = package['name']; + if (name == null) { + throw ManifestException('Missing package name', fileName: fileName); + } + return CrateInfo(packageName: name); + } + + static CrateInfo load(String manifestDir) { + final manifestFile = File(path.join(manifestDir, 'Cargo.toml')); + final manifest = manifestFile.readAsStringSync(); + return parseManifest(manifest, fileName: manifestFile.path); + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart b/app/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart new file mode 100644 index 0000000..0c4d88d --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart @@ -0,0 +1,124 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:collection/collection.dart'; +import 'package:convert/convert.dart'; +import 'package:crypto/crypto.dart'; +import 'package:path/path.dart' as path; + +class CrateHash { + /// Computes a hash uniquely identifying crate content. This takes into account + /// content all all .rs files inside the src directory, as well as Cargo.toml, + /// Cargo.lock, build.rs and cargokit.yaml. + /// + /// If [tempStorage] is provided, computed hash is stored in a file in that directory + /// and reused on subsequent calls if the crate content hasn't changed. + static String compute(String manifestDir, {String? tempStorage}) { + return CrateHash._( + manifestDir: manifestDir, + tempStorage: tempStorage, + )._compute(); + } + + CrateHash._({ + required this.manifestDir, + required this.tempStorage, + }); + + String _compute() { + final files = getFiles(); + final tempStorage = this.tempStorage; + if (tempStorage != null) { + final quickHash = _computeQuickHash(files); + final quickHashFolder = Directory(path.join(tempStorage, 'crate_hash')); + quickHashFolder.createSync(recursive: true); + final quickHashFile = File(path.join(quickHashFolder.path, quickHash)); + if (quickHashFile.existsSync()) { + return quickHashFile.readAsStringSync(); + } + final hash = _computeHash(files); + quickHashFile.writeAsStringSync(hash); + return hash; + } else { + return _computeHash(files); + } + } + + /// Computes a quick hash based on files stat (without reading contents). This + /// is used to cache the real hash, which is slower to compute since it involves + /// reading every single file. + String _computeQuickHash(List files) { + final output = AccumulatorSink(); + final input = sha256.startChunkedConversion(output); + + final data = ByteData(8); + for (final file in files) { + input.add(utf8.encode(file.path)); + final stat = file.statSync(); + data.setUint64(0, stat.size); + input.add(data.buffer.asUint8List()); + data.setUint64(0, stat.modified.millisecondsSinceEpoch); + input.add(data.buffer.asUint8List()); + } + + input.close(); + return base64Url.encode(output.events.single.bytes); + } + + String _computeHash(List files) { + final output = AccumulatorSink(); + final input = sha256.startChunkedConversion(output); + + void addTextFile(File file) { + // text Files are hashed by lines in case we're dealing with github checkout + // that auto-converts line endings. + final splitter = LineSplitter(); + if (file.existsSync()) { + final data = file.readAsStringSync(); + final lines = splitter.convert(data); + for (final line in lines) { + input.add(utf8.encode(line)); + } + } + } + + for (final file in files) { + addTextFile(file); + } + + input.close(); + final res = output.events.single; + + // Truncate to 128bits. + final hash = res.bytes.sublist(0, 16); + return hex.encode(hash); + } + + List getFiles() { + final src = Directory(path.join(manifestDir, 'src')); + final files = src + .listSync(recursive: true, followLinks: false) + .whereType() + .toList(); + files.sortBy((element) => element.path); + void addFile(String relative) { + final file = File(path.join(manifestDir, relative)); + if (file.existsSync()) { + files.add(file); + } + } + + addFile('Cargo.toml'); + addFile('Cargo.lock'); + addFile('build.rs'); + addFile('cargokit.yaml'); + return files; + } + + final String manifestDir; + final String? tempStorage; +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/environment.dart b/app/rust_builder/cargokit/build_tool/lib/src/environment.dart new file mode 100644 index 0000000..d235616 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/environment.dart @@ -0,0 +1,74 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +extension on String { + String resolveSymlink() => File(this).resolveSymbolicLinksSync(); +} + +class Environment { + /// Current build configuration (debug or release). + static String get configuration => + _getEnv("CARGOKIT_CONFIGURATION").toLowerCase(); + + static bool get isDebug => configuration == 'debug'; + static bool get isRelease => configuration == 'release'; + + /// Temporary directory where Rust build artifacts are placed. + static String get targetTempDir => _getEnv("CARGOKIT_TARGET_TEMP_DIR"); + + /// Final output directory where the build artifacts are placed. + static String get outputDir => _getEnvPath('CARGOKIT_OUTPUT_DIR'); + + /// Path to the crate manifest (containing Cargo.toml). + static String get manifestDir => _getEnvPath('CARGOKIT_MANIFEST_DIR'); + + /// Directory inside root project. Not necessarily root folder. Symlinks are + /// not resolved on purpose. + static String get rootProjectDir => _getEnv('CARGOKIT_ROOT_PROJECT_DIR'); + + // Pod + + /// Platform name (macosx, iphoneos, iphonesimulator). + static String get darwinPlatformName => + _getEnv("CARGOKIT_DARWIN_PLATFORM_NAME"); + + /// List of architectures to build for (arm64, armv7, x86_64). + static List get darwinArchs => + _getEnv("CARGOKIT_DARWIN_ARCHS").split(' '); + + // Gradle + static String get minSdkVersion => _getEnv("CARGOKIT_MIN_SDK_VERSION"); + static String get ndkVersion => _getEnv("CARGOKIT_NDK_VERSION"); + static String get sdkPath => _getEnvPath("CARGOKIT_SDK_DIR"); + static String get javaHome => _getEnvPath("CARGOKIT_JAVA_HOME"); + static List get targetPlatforms => + _getEnv("CARGOKIT_TARGET_PLATFORMS").split(','); + + static String? get ohosSdkHome => _getEnvOptional("CARGOKIT_OHOS_SDK_HOME"); + + // CMAKE + static String get targetPlatform => _getEnv("CARGOKIT_TARGET_PLATFORM"); + + static String _getEnv(String key) { + final res = Platform.environment[key]; + if (res == null) { + throw Exception("Missing environment variable $key"); + } + return res; + } + + static String _getEnvPath(String key) { + final res = _getEnv(key); + if (Directory(res).existsSync()) { + return res.resolveSymlink(); + } else { + return res; + } + } + + static String? _getEnvOptional(String key) { + return Platform.environment[key]; + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/logging.dart b/app/rust_builder/cargokit/build_tool/lib/src/logging.dart new file mode 100644 index 0000000..5edd4fd --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/logging.dart @@ -0,0 +1,52 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:logging/logging.dart'; + +const String kSeparator = "--"; +const String kDoubleSeparator = "=="; + +bool _lastMessageWasSeparator = false; + +void _log(LogRecord rec) { + final prefix = '${rec.level.name}: '; + final out = rec.level == Level.SEVERE ? stderr : stdout; + if (rec.message == kSeparator) { + if (!_lastMessageWasSeparator) { + out.write(prefix); + out.writeln('-' * 80); + _lastMessageWasSeparator = true; + } + return; + } else if (rec.message == kDoubleSeparator) { + out.write(prefix); + out.writeln('=' * 80); + _lastMessageWasSeparator = true; + return; + } + out.write(prefix); + out.writeln(rec.message); + _lastMessageWasSeparator = false; +} + +void initLogging() { + Logger.root.level = Level.INFO; + Logger.root.onRecord.listen((LogRecord rec) { + final lines = rec.message.split('\n'); + for (final line in lines) { + if (line.isNotEmpty || lines.length == 1 || line != lines.last) { + _log(LogRecord( + rec.level, + line, + rec.loggerName, + )); + } + } + }); +} + +void enableVerboseLogging() { + Logger.root.level = Level.ALL; +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/options.dart b/app/rust_builder/cargokit/build_tool/lib/src/options.dart new file mode 100644 index 0000000..22aef1d --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/options.dart @@ -0,0 +1,309 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:hex/hex.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; +import 'package:source_span/source_span.dart'; +import 'package:yaml/yaml.dart'; + +import 'builder.dart'; +import 'environment.dart'; +import 'rustup.dart'; + +final _log = Logger('options'); + +/// A class for exceptions that have source span information attached. +class SourceSpanException implements Exception { + // This is a getter so that subclasses can override it. + /// A message describing the exception. + String get message => _message; + final String _message; + + // This is a getter so that subclasses can override it. + /// The span associated with this exception. + /// + /// This may be `null` if the source location can't be determined. + SourceSpan? get span => _span; + final SourceSpan? _span; + + SourceSpanException(this._message, this._span); + + /// Returns a string representation of `this`. + /// + /// [color] may either be a [String], a [bool], or `null`. If it's a string, + /// it indicates an ANSI terminal color escape that should be used to + /// highlight the span's text. If it's `true`, it indicates that the text + /// should be highlighted using the default color. If it's `false` or `null`, + /// it indicates that the text shouldn't be highlighted. + @override + String toString({Object? color}) { + if (span == null) return message; + return 'Error on ${span!.message(message, color: color)}'; + } +} + +enum Toolchain { + stable, + beta, + nightly, +} + +class CargoBuildOptions { + final Toolchain toolchain; + final List flags; + + CargoBuildOptions({ + required this.toolchain, + required this.flags, + }); + + static Toolchain _toolchainFromNode(YamlNode node) { + if (node case YamlScalar(value: String name)) { + final toolchain = + Toolchain.values.firstWhereOrNull((element) => element.name == name); + if (toolchain != null) { + return toolchain; + } + } + throw SourceSpanException( + 'Unknown toolchain. Must be one of ${Toolchain.values.map((e) => e.name)}.', + node.span); + } + + static CargoBuildOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargo options must be a map', node.span); + } + Toolchain toolchain = Toolchain.stable; + List flags = []; + for (final MapEntry(:key, :value) in node.nodes.entries) { + if (key case YamlScalar(value: 'toolchain')) { + toolchain = _toolchainFromNode(value); + } else if (key case YamlScalar(value: 'extra_flags')) { + if (value case YamlList(nodes: List list)) { + if (list.every((element) { + if (element case YamlScalar(value: String _)) { + return true; + } + return false; + })) { + flags = list.map((e) => e.value as String).toList(); + continue; + } + } + throw SourceSpanException( + 'Extra flags must be a list of strings', value.span); + } else { + throw SourceSpanException( + 'Unknown cargo option type. Must be "toolchain" or "extra_flags".', + key.span); + } + } + return CargoBuildOptions(toolchain: toolchain, flags: flags); + } +} + +extension on YamlMap { + /// Map that extracts keys so that we can do map case check on them. + Map get valueMap => + nodes.map((key, value) => MapEntry(key.value, value)); +} + +class PrecompiledBinaries { + final String uriPrefix; + final PublicKey publicKey; + + PrecompiledBinaries({ + required this.uriPrefix, + required this.publicKey, + }); + + static PublicKey _publicKeyFromHex(String key, SourceSpan? span) { + final bytes = HEX.decode(key); + if (bytes.length != 32) { + throw SourceSpanException( + 'Invalid public key. Must be 32 bytes long.', span); + } + return PublicKey(bytes); + } + + static PrecompiledBinaries parse(YamlNode node) { + if (node case YamlMap(valueMap: Map map)) { + if (map + case { + 'url_prefix': YamlNode urlPrefixNode, + 'public_key': YamlNode publicKeyNode, + }) { + final urlPrefix = switch (urlPrefixNode) { + YamlScalar(value: String urlPrefix) => urlPrefix, + _ => throw SourceSpanException( + 'Invalid URL prefix value.', urlPrefixNode.span), + }; + final publicKey = switch (publicKeyNode) { + YamlScalar(value: String publicKey) => + _publicKeyFromHex(publicKey, publicKeyNode.span), + _ => throw SourceSpanException( + 'Invalid public key value.', publicKeyNode.span), + }; + return PrecompiledBinaries( + uriPrefix: urlPrefix, + publicKey: publicKey, + ); + } + } + throw SourceSpanException( + 'Invalid precompiled binaries value. ' + 'Expected Map with "url_prefix" and "public_key".', + node.span); + } +} + +/// Cargokit options specified for Rust crate. +class CargokitCrateOptions { + CargokitCrateOptions({ + this.cargo = const {}, + this.precompiledBinaries, + }); + + final Map cargo; + final PrecompiledBinaries? precompiledBinaries; + + static CargokitCrateOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargokit options must be a map', node.span); + } + final options = {}; + PrecompiledBinaries? precompiledBinaries; + + for (final entry in node.nodes.entries) { + if (entry + case MapEntry( + key: YamlScalar(value: 'cargo'), + value: YamlNode node, + )) { + if (node is! YamlMap) { + throw SourceSpanException('Cargo options must be a map', node.span); + } + for (final MapEntry(:YamlNode key, :value) in node.nodes.entries) { + if (key case YamlScalar(value: String name)) { + final configuration = BuildConfiguration.values + .firstWhereOrNull((element) => element.name == name); + if (configuration != null) { + options[configuration] = CargoBuildOptions.parse(value); + continue; + } + } + throw SourceSpanException( + 'Unknown build configuration. Must be one of ${BuildConfiguration.values.map((e) => e.name)}.', + key.span); + } + } else if (entry.key case YamlScalar(value: 'precompiled_binaries')) { + precompiledBinaries = PrecompiledBinaries.parse(entry.value); + } else { + throw SourceSpanException( + 'Unknown cargokit option type. Must be "cargo" or "precompiled_binaries".', + entry.key.span); + } + } + return CargokitCrateOptions( + cargo: options, + precompiledBinaries: precompiledBinaries, + ); + } + + static CargokitCrateOptions load({ + required String manifestDir, + }) { + final uri = Uri.file(path.join(manifestDir, "cargokit.yaml")); + final file = File.fromUri(uri); + if (file.existsSync()) { + final contents = loadYamlNode(file.readAsStringSync(), sourceUrl: uri); + return parse(contents); + } else { + return CargokitCrateOptions(); + } + } +} + +class CargokitUserOptions { + // When Rustup is installed always build locally unless user opts into + // using precompiled binaries. + static bool defaultUsePrecompiledBinaries() { + return Rustup.executablePath() == null; + } + + CargokitUserOptions({ + required this.usePrecompiledBinaries, + required this.verboseLogging, + }); + + CargokitUserOptions._() + : usePrecompiledBinaries = defaultUsePrecompiledBinaries(), + verboseLogging = false; + + static CargokitUserOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargokit options must be a map', node.span); + } + bool usePrecompiledBinaries = defaultUsePrecompiledBinaries(); + bool verboseLogging = false; + + for (final entry in node.nodes.entries) { + if (entry.key case YamlScalar(value: 'use_precompiled_binaries')) { + if (entry.value case YamlScalar(value: bool value)) { + usePrecompiledBinaries = value; + continue; + } + throw SourceSpanException( + 'Invalid value for "use_precompiled_binaries". Must be a boolean.', + entry.value.span); + } else if (entry.key case YamlScalar(value: 'verbose_logging')) { + if (entry.value case YamlScalar(value: bool value)) { + verboseLogging = value; + continue; + } + throw SourceSpanException( + 'Invalid value for "verbose_logging". Must be a boolean.', + entry.value.span); + } else { + throw SourceSpanException( + 'Unknown cargokit option type. Must be "use_precompiled_binaries" or "verbose_logging".', + entry.key.span); + } + } + return CargokitUserOptions( + usePrecompiledBinaries: usePrecompiledBinaries, + verboseLogging: verboseLogging, + ); + } + + static CargokitUserOptions load() { + String fileName = "cargokit_options.yaml"; + var userProjectDir = Directory(Environment.rootProjectDir); + + while (userProjectDir.parent.path != userProjectDir.path) { + final configFile = File(path.join(userProjectDir.path, fileName)); + if (configFile.existsSync()) { + final contents = loadYamlNode( + configFile.readAsStringSync(), + sourceUrl: configFile.uri, + ); + final res = parse(contents); + if (res.verboseLogging) { + _log.info('Found user options file at ${configFile.path}'); + } + return res; + } + userProjectDir = userProjectDir.parent; + } + return CargokitUserOptions._(); + } + + final bool usePrecompiledBinaries; + final bool verboseLogging; +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart b/app/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart new file mode 100644 index 0000000..00e71fd --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart @@ -0,0 +1,205 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:github/github.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'cargo.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'rustup.dart'; +import 'target.dart'; + +final _log = Logger('precompile_binaries'); + +class PrecompileBinaries { + PrecompileBinaries({ + required this.privateKey, + required this.githubToken, + required this.repositorySlug, + required this.manifestDir, + required this.targets, + this.androidSdkLocation, + this.androidNdkVersion, + this.androidMinSdkVersion, + this.tempDir, + this.glibcVersion, + }); + + final PrivateKey privateKey; + final String githubToken; + final RepositorySlug repositorySlug; + final String manifestDir; + final List targets; + final String? androidSdkLocation; + final String? androidNdkVersion; + final int? androidMinSdkVersion; + final String? tempDir; + final String? glibcVersion; + + static String fileName(Target target, String name) { + return '${target.rust}_$name'; + } + + static String signatureFileName(Target target, String name) { + return '${target.rust}_$name.sig'; + } + + Future run() async { + final crateInfo = CrateInfo.load(manifestDir); + + final targets = List.of(this.targets); + if (targets.isEmpty) { + targets.addAll([ + ...Target.buildableTargets(), + if (androidSdkLocation != null) ...Target.androidTargets(), + ]); + } + + _log.info('Precompiling binaries for $targets'); + + final hash = CrateHash.compute(manifestDir); + _log.info('Computed crate hash: $hash'); + + final String tagName = 'precompiled_$hash'; + + final github = GitHub(auth: Authentication.withToken(githubToken)); + final repo = github.repositories; + final release = await _getOrCreateRelease( + repo: repo, + tagName: tagName, + packageName: crateInfo.packageName, + hash: hash, + ); + + final tempDir = this.tempDir != null + ? Directory(this.tempDir!) + : Directory.systemTemp.createTempSync('precompiled_'); + + tempDir.createSync(recursive: true); + + final crateOptions = CargokitCrateOptions.load( + manifestDir: manifestDir, + ); + + final buildEnvironment = BuildEnvironment( + configuration: BuildConfiguration.release, + crateOptions: crateOptions, + targetTempDir: tempDir.path, + manifestDir: manifestDir, + crateInfo: crateInfo, + isAndroid: androidSdkLocation != null, + androidSdkPath: androidSdkLocation, + androidNdkVersion: androidNdkVersion, + androidMinSdkVersion: androidMinSdkVersion, + glibcVersion: glibcVersion, + ); + + final rustup = Rustup(); + + for (final target in targets) { + final artifactNames = getArtifactNames( + target: target, + libraryName: crateInfo.libName, + remote: true, + ); + + if (artifactNames.every((name) { + final fileName = PrecompileBinaries.fileName(target, name); + return (release.assets ?? []).any((e) => e.name == fileName); + })) { + _log.info("All artifacts for $target already exist - skipping"); + continue; + } + + _log.info('Building for $target'); + + final builder = + RustBuilder(target: target, environment: buildEnvironment); + builder.prepare(rustup); + final res = await builder.build(); + + final assets = []; + for (final name in artifactNames) { + final file = File(path.join(res, name)); + if (!file.existsSync()) { + throw Exception('Missing artifact: ${file.path}'); + } + + final data = file.readAsBytesSync(); + final create = CreateReleaseAsset( + name: PrecompileBinaries.fileName(target, name), + contentType: "application/octet-stream", + assetData: data, + ); + final signature = sign(privateKey, data); + final signatureCreate = CreateReleaseAsset( + name: signatureFileName(target, name), + contentType: "application/octet-stream", + assetData: signature, + ); + bool verified = verify(public(privateKey), data, signature); + if (!verified) { + throw Exception('Signature verification failed'); + } + assets.add(create); + assets.add(signatureCreate); + } + _log.info('Uploading assets: ${assets.map((e) => e.name)}'); + for (final asset in assets) { + // This seems to be failing on CI so do it one by one + int retryCount = 0; + while (true) { + try { + await repo.uploadReleaseAssets(release, [asset]); + break; + } on Exception catch (e) { + if (retryCount == 10) { + rethrow; + } + ++retryCount; + _log.shout( + 'Upload failed (attempt $retryCount, will retry): ${e.toString()}'); + await Future.delayed(Duration(seconds: 2)); + } + } + } + } + + _log.info('Cleaning up'); + tempDir.deleteSync(recursive: true); + } + + Future _getOrCreateRelease({ + required RepositoriesService repo, + required String tagName, + required String packageName, + required String hash, + }) async { + Release release; + try { + _log.info('Fetching release $tagName'); + release = await repo.getReleaseByTagName(repositorySlug, tagName); + } on ReleaseNotFound { + _log.info('Release not found - creating release $tagName'); + release = await repo.createRelease( + repositorySlug, + CreateRelease.from( + tagName: tagName, + name: 'Precompiled binaries ${hash.substring(0, 8)}', + targetCommitish: null, + isDraft: false, + isPrerelease: false, + body: 'Precompiled binaries for crate $packageName, ' + 'crate hash $hash.', + )); + } + return release; + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/rustup.dart b/app/rust_builder/cargokit/build_tool/lib/src/rustup.dart new file mode 100644 index 0000000..cfb88f0 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/rustup.dart @@ -0,0 +1,171 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:path/path.dart' as path; + +import 'util.dart'; + +class _Toolchain { + _Toolchain( + this.name, + this.targets, + ); + + final String name; + final List targets; +} + +class Rustup { + List? installedTargets(String toolchain) { + final targets = _installedTargets(toolchain); + return targets != null ? List.unmodifiable(targets) : null; + } + + String resolveToolchain(String toolchain) => + _installedToolchains + .firstWhereOrNull( + (e) => _matchesRequestedToolchain( + installedName: e.name, + requestedToolchain: toolchain, + ), + ) + ?.name ?? + toolchain; + + void installToolchain(String toolchain) { + log.info("Installing Rust toolchain: $toolchain"); + runCommand("rustup", ['toolchain', 'install', toolchain]); + _installedToolchains + .add(_Toolchain(toolchain, _getInstalledTargets(toolchain))); + } + + void installTarget( + String target, { + required String toolchain, + }) { + log.info("Installing Rust target: $target"); + runCommand("rustup", ['target', 'add', '--toolchain', toolchain, target]); + _installedTargets(toolchain)?.add(target); + } + + bool _didInstallZigBuild = false; + + void installZigBuild(String toolchain) { + if (_didInstallZigBuild) { + return; + } + + log.info("Installing Zig build"); + runCommand("rustup", [ + 'run', + toolchain, + 'cargo', + 'install', + '--locked', + 'cargo-zigbuild', + ]); + _didInstallZigBuild = true; + } + + final List<_Toolchain> _installedToolchains; + + Rustup() : _installedToolchains = _getInstalledToolchains(); + + bool _matchesRequestedToolchain({ + required String installedName, + required String requestedToolchain, + }) => + installedName == requestedToolchain || + installedName.startsWith('$requestedToolchain-'); + + List? _installedTargets(String toolchain) => _installedToolchains + .firstWhereOrNull( + (e) => _matchesRequestedToolchain( + installedName: e.name, + requestedToolchain: toolchain, + ), + ) + ?.targets; + + static List<_Toolchain> _getInstalledToolchains() { + String extractToolchainName(String line) { + // ignore (default) after toolchain name + final parts = line.split(' '); + return parts[0]; + } + + final res = runCommand("rustup", ['toolchain', 'list']); + + // To list all non-custom toolchains, we need to filter out lines that + // don't start with "stable", "beta", or "nightly". + final nonCustom = RegExp(r'^(stable|beta|nightly)'); + final lines = res.stdout + .toString() + .split('\n') + .where((e) => e.isNotEmpty && nonCustom.hasMatch(e)) + .map(extractToolchainName) + .toList(growable: true); + + return lines + .map( + (name) => _Toolchain( + name, + _getInstalledTargets(name), + ), + ) + .toList(growable: true); + } + + static List _getInstalledTargets(String toolchain) { + final res = runCommand("rustup", [ + 'target', + 'list', + '--toolchain', + toolchain, + '--installed', + ]); + final lines = res.stdout + .toString() + .split('\n') + .where((e) => e.isNotEmpty) + .toList(growable: true); + return lines; + } + + bool _didInstallRustSrcForNightly = false; + + void installRustSrcForNightly({String toolchain = 'nightly'}) { + if (_didInstallRustSrcForNightly) { + return; + } + // Useful for -Z build-std + runCommand( + "rustup", + ['component', 'add', 'rust-src', '--toolchain', toolchain], + ); + _didInstallRustSrcForNightly = true; + } + + static String? executablePath() { + final envPath = Platform.environment['PATH']; + final envPathSeparator = Platform.isWindows ? ';' : ':'; + final home = Platform.isWindows + ? Platform.environment['USERPROFILE'] + : Platform.environment['HOME']; + final paths = [ + if (home != null) path.join(home, '.cargo', 'bin'), + if (envPath != null) ...envPath.split(envPathSeparator), + ]; + for (final p in paths) { + final rustup = Platform.isWindows ? 'rustup.exe' : 'rustup'; + final rustupPath = path.join(p, rustup); + if (File(rustupPath).existsSync()) { + return rustupPath; + } + } + return null; + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/target.dart b/app/rust_builder/cargokit/build_tool/lib/src/target.dart new file mode 100644 index 0000000..7e9bb25 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/target.dart @@ -0,0 +1,178 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:collection/collection.dart'; + +import 'util.dart'; + +class Target { + Target({ + required this.rust, + this.flutter, + this.android, + this.androidMinSdkVersion, + this.darwinPlatform, + this.darwinArch, + this.ohos, + }); + + static final all = [ + Target( + rust: 'armv7-linux-androideabi', + flutter: 'android-arm', + android: 'armeabi-v7a', + androidMinSdkVersion: 16, + ), + Target( + rust: 'aarch64-linux-android', + flutter: 'android-arm64', + android: 'arm64-v8a', + androidMinSdkVersion: 21, + ), + Target( + rust: 'i686-linux-android', + flutter: 'android-x86', + android: 'x86', + androidMinSdkVersion: 16, + ), + Target( + rust: 'x86_64-linux-android', + flutter: 'android-x64', + android: 'x86_64', + androidMinSdkVersion: 21, + ), + Target( + rust: 'x86_64-pc-windows-msvc', + flutter: 'windows-x64', + ), + Target( + rust: 'aarch64-pc-windows-msvc', + flutter: 'windows-arm64', + ), + Target( + rust: 'x86_64-unknown-linux-gnu', + flutter: 'linux-x64', + ), + Target( + rust: 'aarch64-unknown-linux-gnu', + flutter: 'linux-arm64', + ), + Target(rust: 'riscv64gc-unknown-linux-gnu', flutter: 'linux-riscv64'), + Target( + rust: 'x86_64-apple-darwin', + darwinPlatform: 'macosx', + darwinArch: 'x86_64', + ), + Target( + rust: 'aarch64-apple-darwin', + darwinPlatform: 'macosx', + darwinArch: 'arm64', + ), + Target( + rust: 'aarch64-apple-ios', + darwinPlatform: 'iphoneos', + darwinArch: 'arm64', + ), + Target( + rust: 'aarch64-apple-ios-sim', + darwinPlatform: 'iphonesimulator', + darwinArch: 'arm64', + ), + Target( + rust: 'x86_64-apple-ios', + darwinPlatform: 'iphonesimulator', + darwinArch: 'x86_64', + ), + Target( + rust: 'aarch64-unknown-linux-ohos', + flutter: 'ohos-arm64', + ohos: 'arm64-v8a', + ), + Target( + rust: 'armv7-unknown-linux-ohos', + flutter: 'ohos-arm', + ohos: 'armeabi-v7a', + ), + Target( + rust: 'x86_64-unknown-linux-ohos', + flutter: 'ohos-x64', + ohos: 'x86_64', + ), + ]; + + static Target? forFlutterName(String flutterName) { + return all.firstWhereOrNull((element) => element.flutter == flutterName); + } + + static Target? forDarwin({ + required String platformName, + required String darwinAarch, + }) { + return all.firstWhereOrNull((element) => // + element.darwinPlatform == platformName && + element.darwinArch == darwinAarch); + } + + static Target? forRustTriple(String triple) { + return all.firstWhereOrNull((element) => element.rust == triple); + } + + static List androidTargets() { + return all + .where((element) => element.android != null) + .toList(growable: false); + } + + static List ohosTargets() { + return all.where((element) => element.ohos != null).toList(growable: false); + } + + /// Returns buildable targets on current host platform ignoring Android targets. + static List buildableTargets() { + if (Platform.operatingSystem == 'ohos') { + final arch = (runCommand('arch', []).stdout as String).trim(); + if (arch.trim() == 'aarch64') { + return [Target.forRustTriple('aarch64-unknown-linux-ohos')!]; + } + if (arch == 'armv7') { + return [Target.forRustTriple('armv7-unknown-linux-ohos')!]; + } + return [Target.forRustTriple('x86_64-unknown-linux-ohos')!]; + } + if (Platform.isLinux) { + // Right now we don't support cross-compiling on Linux. So we just return + // the host target. + final arch = (runCommand('arch', []).stdout as String).trim(); + if (arch == 'aarch64') { + return [Target.forRustTriple('aarch64-unknown-linux-gnu')!]; + } else if (arch == 'riscv64') { + return [Target.forRustTriple('riscv64gc-unknown-linux-gnu')!]; + } else { + return [Target.forRustTriple('x86_64-unknown-linux-gnu')!]; + } + } + return all.where((target) { + if (Platform.isWindows) { + return target.rust.contains('-windows-'); + } else if (Platform.isMacOS) { + return target.darwinPlatform != null; + } + return false; + }).toList(growable: false); + } + + @override + String toString() { + return rust; + } + + final String? flutter; + final String rust; + final String? android; + final int? androidMinSdkVersion; + final String? darwinPlatform; + final String? darwinArch; + final String? ohos; +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/util.dart b/app/rust_builder/cargokit/build_tool/lib/src/util.dart new file mode 100644 index 0000000..8bb6a87 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/util.dart @@ -0,0 +1,172 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:convert'; +import 'dart:io'; + +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'logging.dart'; +import 'rustup.dart'; + +final log = Logger("process"); + +class CommandFailedException implements Exception { + final String executable; + final List arguments; + final ProcessResult result; + + CommandFailedException({ + required this.executable, + required this.arguments, + required this.result, + }); + + @override + String toString() { + final stdout = result.stdout.toString().trim(); + final stderr = result.stderr.toString().trim(); + return [ + "External Command: $executable ${arguments.map((e) => '"$e"').join(' ')}", + "Returned Exit Code: ${result.exitCode}", + kSeparator, + "STDOUT:", + if (stdout.isNotEmpty) stdout, + kSeparator, + "STDERR:", + if (stderr.isNotEmpty) stderr, + ].join('\n'); + } +} + +class TestRunCommandArgs { + final String executable; + final List arguments; + final String? workingDirectory; + final Map? environment; + final bool includeParentEnvironment; + final bool runInShell; + final Encoding? stdoutEncoding; + final Encoding? stderrEncoding; + + TestRunCommandArgs({ + required this.executable, + required this.arguments, + this.workingDirectory, + this.environment, + this.includeParentEnvironment = true, + this.runInShell = false, + this.stdoutEncoding, + this.stderrEncoding, + }); +} + +class TestRunCommandResult { + TestRunCommandResult({ + this.pid = 1, + this.exitCode = 0, + this.stdout = '', + this.stderr = '', + }); + + final int pid; + final int exitCode; + final String stdout; + final String stderr; +} + +TestRunCommandResult Function(TestRunCommandArgs args)? testRunCommandOverride; + +ProcessResult runCommand( + String executable, + List arguments, { + String? workingDirectory, + Map? environment, + bool includeParentEnvironment = true, + bool runInShell = false, + Encoding? stdoutEncoding = systemEncoding, + Encoding? stderrEncoding = systemEncoding, +}) { + if (testRunCommandOverride != null) { + final result = testRunCommandOverride!(TestRunCommandArgs( + executable: executable, + arguments: arguments, + workingDirectory: workingDirectory, + environment: environment, + includeParentEnvironment: includeParentEnvironment, + runInShell: runInShell, + stdoutEncoding: stdoutEncoding, + stderrEncoding: stderrEncoding, + )); + return ProcessResult( + result.pid, + result.exitCode, + result.stdout, + result.stderr, + ); + } + log.finer('Running command $executable ${arguments.join(' ')}'); + final res = Process.runSync( + _resolveExecutable(executable), + arguments, + workingDirectory: workingDirectory, + environment: environment, + includeParentEnvironment: includeParentEnvironment, + runInShell: runInShell, + stderrEncoding: stderrEncoding, + stdoutEncoding: stdoutEncoding, + ); + if (res.exitCode != 0) { + throw CommandFailedException( + executable: executable, + arguments: arguments, + result: res, + ); + } else { + return res; + } +} + +class RustupNotFoundException implements Exception { + @override + String toString() { + return [ + ' ', + 'rustup not found in PATH.', + ' ', + 'Maybe you need to install Rust? It only takes a minute:', + ' ', + if (Platform.isWindows) 'https://www.rust-lang.org/tools/install', + if (hasHomebrewRustInPath()) ...[ + '\$ brew unlink rust # Unlink homebrew Rust from PATH', + ], + if (!Platform.isWindows) + "\$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh", + ' ', + ].join('\n'); + } + + static bool hasHomebrewRustInPath() { + if (!Platform.isMacOS) { + return false; + } + final envPath = Platform.environment['PATH'] ?? ''; + final paths = envPath.split(':'); + return paths.any((p) { + return p.contains('homebrew') && File(path.join(p, 'rustc')).existsSync(); + }); + } +} + +String _resolveExecutable(String executable) { + if (executable == 'rustup') { + final resolved = Rustup.executablePath(); + if (resolved != null) { + return resolved; + } + throw RustupNotFoundException(); + } else { + return executable; + } +} diff --git a/app/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart b/app/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart new file mode 100644 index 0000000..3d12017 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart @@ -0,0 +1,84 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:http/http.dart'; + +import 'artifacts_provider.dart'; +import 'cargo.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'target.dart'; + +class VerifyBinaries { + VerifyBinaries({ + required this.manifestDir, + }); + + final String manifestDir; + + Future run() async { + final crateInfo = CrateInfo.load(manifestDir); + + final config = CargokitCrateOptions.load(manifestDir: manifestDir); + final precompiledBinaries = config.precompiledBinaries; + if (precompiledBinaries == null) { + stdout.writeln('Crate does not support precompiled binaries.'); + } else { + final crateHash = CrateHash.compute(manifestDir); + stdout.writeln('Crate hash: $crateHash'); + + for (final target in Target.all) { + final message = 'Checking ${target.rust}...'; + stdout.write(message.padRight(40)); + stdout.flush(); + + final artifacts = getArtifactNames( + target: target, + libraryName: crateInfo.libName, + remote: true, + ); + + final prefix = precompiledBinaries.uriPrefix; + + bool ok = true; + + for (final artifact in artifacts) { + final fileName = PrecompileBinaries.fileName(target, artifact); + final signatureFileName = + PrecompileBinaries.signatureFileName(target, artifact); + + final url = Uri.parse('$prefix$crateHash/$fileName'); + final signatureUrl = + Uri.parse('$prefix$crateHash/$signatureFileName'); + + final signature = await get(signatureUrl); + if (signature.statusCode != 200) { + stdout.writeln('MISSING'); + ok = false; + break; + } + final asset = await get(url); + if (asset.statusCode != 200) { + stdout.writeln('MISSING'); + ok = false; + break; + } + + if (!verify(precompiledBinaries.publicKey, asset.bodyBytes, + signature.bodyBytes)) { + stdout.writeln('INVALID SIGNATURE'); + ok = false; + } + } + + if (ok) { + stdout.writeln('OK'); + } + } + } + } +} diff --git a/app/rust_builder/cargokit/build_tool/pubspec.lock b/app/rust_builder/cargokit/build_tool/pubspec.lock new file mode 100644 index 0000000..343bdd3 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/pubspec.lock @@ -0,0 +1,453 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 + url: "https://pub.dev" + source: hosted + version: "64.0.0" + adaptive_number: + dependency: transitive + description: + name: adaptive_number + sha256: "3a567544e9b5c9c803006f51140ad544aedc79604fd4f3f2c1380003f97c1d77" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" + url: "https://pub.dev" + source: hosted + version: "6.2.0" + args: + dependency: "direct main" + description: + name: args + sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + collection: + dependency: "direct main" + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + convert: + dependency: "direct main" + description: + name: convert + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + coverage: + dependency: transitive + description: + name: coverage + sha256: "2fb815080e44a09b85e0f2ca8a820b15053982b2e714b59267719e8a9ff17097" + url: "https://pub.dev" + source: hosted + version: "1.6.3" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + url: "https://pub.dev" + source: hosted + version: "3.0.3" + ed25519_edwards: + dependency: "direct main" + description: + name: ed25519_edwards + sha256: "6ce0112d131327ec6d42beede1e5dfd526069b18ad45dcf654f15074ad9276cd" + url: "https://pub.dev" + source: hosted + version: "0.3.1" + file: + dependency: transitive + description: + name: file + sha256: "1b92bec4fc2a72f59a8e15af5f52cd441e4a7860b49499d69dfa817af20e925d" + url: "https://pub.dev" + source: hosted + version: "6.1.4" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + github: + dependency: "direct main" + description: + name: github + sha256: "9966bc13bf612342e916b0a343e95e5f046c88f602a14476440e9b75d2295411" + url: "https://pub.dev" + source: hosted + version: "9.17.0" + glob: + dependency: transitive + description: + name: glob + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + hex: + dependency: "direct main" + description: + name: hex + sha256: "4e7cd54e4b59ba026432a6be2dd9d96e4c5205725194997193bf871703b82c4a" + url: "https://pub.dev" + source: hosted + version: "0.2.0" + http: + dependency: "direct main" + description: + name: http + sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + io: + dependency: transitive + description: + name: io + sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: b10a7b2ff83d83c777edba3c6a0f97045ddadd56c944e1a23a3fdf43a1bf4467 + url: "https://pub.dev" + source: hosted + version: "4.8.1" + lints: + dependency: "direct dev" + description: + name: lints + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + logging: + dependency: "direct main" + description: + name: logging + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" + url: "https://pub.dev" + source: hosted + version: "0.12.16" + meta: + dependency: transitive + description: + name: meta + sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + mime: + dependency: transitive + description: + name: mime + sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e + url: "https://pub.dev" + source: hosted + version: "1.0.4" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + package_config: + dependency: transitive + description: + name: package_config + sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + path: + dependency: "direct main" + description: + name: path + sha256: "2ad4cddff7f5cc0e2d13069f2a3f7a73ca18f66abd6f5ecf215219cdb3638edb" + url: "https://pub.dev" + source: hosted + version: "1.8.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: cb3798bef7fc021ac45b308f4b51208a152792445cce0448c9a4ba5879dd8750 + url: "https://pub.dev" + source: hosted + version: "5.4.0" + pool: + dependency: transitive + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + shelf: + dependency: transitive + description: + name: shelf + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.dev" + source: hosted + version: "1.4.1" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e + url: "https://pub.dev" + source: hosted + version: "1.1.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" + url: "https://pub.dev" + source: hosted + version: "0.10.12" + source_span: + dependency: "direct main" + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test: + dependency: "direct dev" + description: + name: test + sha256: "9b0dd8e36af4a5b1569029949d50a52cb2a2a2fdaa20cebb96e6603b9ae241f9" + url: "https://pub.dev" + source: hosted + version: "1.24.6" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + test_core: + dependency: transitive + description: + name: test_core + sha256: "4bef837e56375537055fdbbbf6dd458b1859881f4c7e6da936158f77d61ab265" + url: "https://pub.dev" + source: hosted + version: "0.5.6" + toml: + dependency: "direct main" + description: + name: toml + sha256: "157c5dca5160fced243f3ce984117f729c788bb5e475504f3dbcda881accee44" + url: "https://pub.dev" + source: hosted + version: "0.14.0" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.dev" + source: hosted + version: "1.3.2" + version: + dependency: "direct main" + description: + name: version + sha256: "2307e23a45b43f96469eeab946208ed63293e8afca9c28cd8b5241ff31c55f55" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0fae432c85c4ea880b33b497d32824b97795b04cdaa74d270219572a1f50268d" + url: "https://pub.dev" + source: hosted + version: "11.9.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b + url: "https://pub.dev" + source: hosted + version: "2.4.0" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "67d3a8b6c79e1987d19d848b0892e582dbb0c66c57cc1fef58a177dd2aa2823d" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + yaml: + dependency: "direct main" + description: + name: yaml + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + url: "https://pub.dev" + source: hosted + version: "3.1.2" +sdks: + dart: ">=3.0.0 <4.0.0" diff --git a/app/rust_builder/cargokit/build_tool/pubspec.yaml b/app/rust_builder/cargokit/build_tool/pubspec.yaml new file mode 100644 index 0000000..18c61e3 --- /dev/null +++ b/app/rust_builder/cargokit/build_tool/pubspec.yaml @@ -0,0 +1,33 @@ +# This is copied from Cargokit (which is the official way to use it currently) +# Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +name: build_tool +description: Cargokit build_tool. Facilitates the build of Rust crate during Flutter application build. +publish_to: none +version: 1.0.0 + +environment: + sdk: ">=3.0.0 <4.0.0" + +# Add regular dependencies here. +dependencies: + # these are pinned on purpose because the bundle_tool_runner doesn't have + # pubspec.lock. See run_build_tool.sh + logging: 1.2.0 + path: 1.8.0 + version: 3.0.0 + collection: 1.18.0 + ed25519_edwards: 0.3.1 + hex: 0.2.0 + yaml: 3.1.2 + source_span: 1.10.0 + github: 9.17.0 + args: 2.4.2 + crypto: 3.0.3 + convert: 3.1.1 + http: 1.1.0 + toml: 0.14.0 + +dev_dependencies: + lints: ^2.1.0 + test: ^1.24.0 diff --git a/app/rust_builder/cargokit/cmake/cargokit.cmake b/app/rust_builder/cargokit/cmake/cargokit.cmake new file mode 100644 index 0000000..3738bb4 --- /dev/null +++ b/app/rust_builder/cargokit/cmake/cargokit.cmake @@ -0,0 +1,126 @@ +SET(cargokit_cmake_root "${CMAKE_CURRENT_LIST_DIR}/..") + +# Workaround for https://github.com/dart-lang/pub/issues/4010 +get_filename_component(cargokit_cmake_root "${cargokit_cmake_root}" REALPATH) + +if(WIN32) + # REALPATH does not properly resolve symlinks on windows :-/ + execute_process(COMMAND powershell -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_LIST_DIR}/resolve_symlinks.ps1" "${cargokit_cmake_root}" OUTPUT_VARIABLE cargokit_cmake_root OUTPUT_STRIP_TRAILING_WHITESPACE) +endif() + +# Arguments +# - target: CMAKE target to which rust library is linked +# - manifest_dir: relative path from current folder to directory containing cargo manifest +# - lib_name: cargo package name +# - any_symbol_name: name of any exported symbol from the library. +# used on windows to force linking with library. +function(apply_cargokit target manifest_dir lib_name any_symbol_name) + + set(CARGOKIT_LIB_NAME "${lib_name}") + set(CARGOKIT_LIB_FULL_NAME "${CMAKE_SHARED_MODULE_PREFIX}${CARGOKIT_LIB_NAME}${CMAKE_SHARED_MODULE_SUFFIX}") + if (CMAKE_CONFIGURATION_TYPES) + set(CARGOKIT_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/$") + set(OUTPUT_LIB "${CMAKE_CURRENT_BINARY_DIR}/$/${CARGOKIT_LIB_FULL_NAME}") + else() + set(CARGOKIT_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}") + set(OUTPUT_LIB "${CMAKE_CURRENT_BINARY_DIR}/${CARGOKIT_LIB_FULL_NAME}") + endif() + set(CARGOKIT_TEMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/cargokit_build") + + if (FLUTTER_TARGET_PLATFORM) + set(CARGOKIT_TARGET_PLATFORM "${FLUTTER_TARGET_PLATFORM}") + else() + set(CARGOKIT_TARGET_PLATFORM "windows-x64") + endif() + set(CARGOKIT_OHOS_SDK_HOME $ENV{OHOS_SDK_HOME}) + + set(CARGOKIT_ENV + "CARGOKIT_CMAKE=${CMAKE_COMMAND}" + "CARGOKIT_CONFIGURATION=$" + "CARGOKIT_MANIFEST_DIR=${CMAKE_CURRENT_SOURCE_DIR}/${manifest_dir}" + "CARGOKIT_TARGET_TEMP_DIR=${CARGOKIT_TEMP_DIR}" + "CARGOKIT_OUTPUT_DIR=${CARGOKIT_OUTPUT_DIR}" + "CARGOKIT_TARGET_PLATFORM=${CARGOKIT_TARGET_PLATFORM}" + "CARGOKIT_TOOL_TEMP_DIR=${CARGOKIT_TEMP_DIR}/tool" + "CARGOKIT_ROOT_PROJECT_DIR=${CMAKE_SOURCE_DIR}" + "CARGOKIT_OHOS_SDK_HOME=${CARGOKIT_OHOS_SDK_HOME}" + ) + + if (WIN32) + set(SCRIPT_EXTENSION ".cmd") + set(IMPORT_LIB_EXTENSION ".lib") + elseif (CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-arm64" + OR CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-arm" + OR CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-x64") + if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") + set(SCRIPT_EXTENSION ".cmd") + else() + set(SCRIPT_EXTENSION ".sh") + execute_process(COMMAND chmod +x "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}") + endif() + set(IMPORT_LIB_EXTENSION "") + else() + set(SCRIPT_EXTENSION ".sh") + set(IMPORT_LIB_EXTENSION "") + execute_process(COMMAND chmod +x "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}") + endif() + + # Using generators in custom command is only supported in CMake 3.20+ + if (CMAKE_CONFIGURATION_TYPES AND ${CMAKE_VERSION} VERSION_LESS "3.20.0") + foreach(CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES) + add_custom_command( + OUTPUT + "${CMAKE_CURRENT_BINARY_DIR}/${CONFIG}/${CARGOKIT_LIB_FULL_NAME}" + "${CMAKE_CURRENT_BINARY_DIR}/_phony_" + COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV} + "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake + VERBATIM + ) + endforeach() + elseif (CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-arm64" + OR CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-arm" + OR CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-x64") + set(SOURCE_LIB "../../ohos/.cxx/default/default/debug/${OHOS_ARCH}/lib${PROJECT_NAME}.so") + set(DEST_LIB "${TARGET_LIB_DIR}/lib${PROJECT_NAME}.so") + add_custom_command( + OUTPUT + ${OUTPUT_LIB} + "${CMAKE_CURRENT_BINARY_DIR}/_phony_" + COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV} + "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake + COMMAND ${CMAKE_COMMAND} -E copy ${OUTPUT_LIB} ${DEST_LIB} + COMMENT "Building and copying ${OUTPUT_LIB} to ${DEST_LIB}" + VERBATIM + ) + else() + add_custom_command( + OUTPUT + ${OUTPUT_LIB} + "${CMAKE_CURRENT_BINARY_DIR}/_phony_" + COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV} + "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake + VERBATIM + ) + endif() + + + set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/_phony_" PROPERTIES SYMBOLIC TRUE) + + if (TARGET ${target}) + # If we have actual cmake target provided create target and make existing + # target depend on it + add_custom_target("${target}_cargokit" DEPENDS ${OUTPUT_LIB}) + add_dependencies("${target}" "${target}_cargokit") + target_link_libraries("${target}" PRIVATE "${OUTPUT_LIB}${IMPORT_LIB_EXTENSION}") + if(WIN32) + target_link_options(${target} PRIVATE "/INCLUDE:${any_symbol_name}") + endif() + else() + # Otherwise (FFI) just use ALL to force building always + add_custom_target("${target}_cargokit" ALL DEPENDS ${OUTPUT_LIB}) + endif() + + # Allow adding the output library to plugin bundled libraries + set("${target}_cargokit_lib" ${OUTPUT_LIB} PARENT_SCOPE) + +endfunction() diff --git a/app/rust_builder/cargokit/cmake/resolve_symlinks.ps1 b/app/rust_builder/cargokit/cmake/resolve_symlinks.ps1 new file mode 100644 index 0000000..2ac593a --- /dev/null +++ b/app/rust_builder/cargokit/cmake/resolve_symlinks.ps1 @@ -0,0 +1,34 @@ +function Resolve-Symlinks { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] + [string] $Path + ) + + [string] $separator = '/' + [string[]] $parts = $Path.Split($separator) + + [string] $realPath = '' + foreach ($part in $parts) { + if ($realPath -and !$realPath.EndsWith($separator)) { + $realPath += $separator + } + + $realPath += $part.Replace('\', '/') + + # The slash is important when using Get-Item on Drive letters in pwsh. + if (-not($realPath.Contains($separator)) -and $realPath.EndsWith(':')) { + $realPath += '/' + } + + $item = Get-Item $realPath + if ($item.LinkTarget) { + $realPath = $item.LinkTarget.Replace('\', '/') + } + } + $realPath +} + +$path = Resolve-Symlinks -Path $args[0] +Write-Host $path diff --git a/app/rust_builder/cargokit/gradle/plugin.gradle b/app/rust_builder/cargokit/gradle/plugin.gradle new file mode 100644 index 0000000..8c40086 --- /dev/null +++ b/app/rust_builder/cargokit/gradle/plugin.gradle @@ -0,0 +1,189 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import java.nio.file.Paths +import javax.inject.Inject +import org.apache.tools.ant.taskdefs.condition.Os +import org.gradle.process.ExecOperations + +CargoKitPlugin.file = buildscript.sourceFile + +apply plugin: CargoKitPlugin + +class CargoKitExtension { + String manifestDir; // Relative path to folder containing Cargo.toml + String libname; // Library name within Cargo.toml. Must be a cdylib +} + +abstract class CargoKitBuildTask extends DefaultTask { + + @Inject + abstract ExecOperations getExecOperations() + + @Input + String buildMode + + @Input + String buildDir + + @Input + String outputDir + + @Input + String ndkVersion + + @Input + String sdkDirectory + + @Input + int compileSdkVersion; + + @Input + int minSdkVersion; + + @Input + String pluginFile + + @Input + List targetPlatforms + + @TaskAction + def build() { + if (project.cargokit.manifestDir == null) { + throw new GradleException("Property 'manifestDir' must be set on cargokit extension"); + } + + if (project.cargokit.libname == null) { + throw new GradleException("Property 'libname' must be set on cargokit extension"); + } + + def executableName = Os.isFamily(Os.FAMILY_WINDOWS) ? "run_build_tool.cmd" : "run_build_tool.sh" + def path = Paths.get(new File(pluginFile).parent, "..", executableName); + + def manifestDir = Paths.get(project.buildscript.sourceFile.parent, project.cargokit.manifestDir) + + def rootProjectDir = project.rootProject.projectDir + + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { + execOperations.exec { + commandLine 'chmod', '+x', path + } + } + + execOperations.exec { + executable path + args "build-gradle" + environment "CARGOKIT_ROOT_PROJECT_DIR", rootProjectDir + environment "CARGOKIT_TOOL_TEMP_DIR", "${buildDir}/build_tool" + environment "CARGOKIT_MANIFEST_DIR", manifestDir + environment "CARGOKIT_CONFIGURATION", buildMode + environment "CARGOKIT_TARGET_TEMP_DIR", buildDir + environment "CARGOKIT_OUTPUT_DIR", outputDir + environment "CARGOKIT_NDK_VERSION", ndkVersion + environment "CARGOKIT_SDK_DIR", sdkDirectory + environment "CARGOKIT_COMPILE_SDK_VERSION", compileSdkVersion + environment "CARGOKIT_MIN_SDK_VERSION", minSdkVersion + environment "CARGOKIT_TARGET_PLATFORMS", targetPlatforms.join(",") + environment "CARGOKIT_JAVA_HOME", System.properties['java.home'] + } + } +} + +class CargoKitPlugin implements Plugin { + + static String file; + + private Plugin findFlutterPlugin(Project rootProject) { + _findFlutterPlugin(rootProject.childProjects) + } + + private Plugin _findFlutterPlugin(Map projects) { + for (project in projects) { + for (plugin in project.value.getPlugins()) { + if (plugin.class.name == "com.flutter.gradle.FlutterPlugin" || plugin.class.name == "FlutterPlugin") { + return plugin; + } + } + def plugin = _findFlutterPlugin(project.value.childProjects); + if (plugin != null) { + return plugin; + } + } + return null; + } + + @Override + void apply(Project project) { + def plugin = findFlutterPlugin(project.rootProject); + + project.extensions.create("cargokit", CargoKitExtension) + + if (plugin == null) { + print("Flutter plugin not found, CargoKit plugin will not be applied.") + return; + } + + def cargoBuildDir = "${project.buildDir}/build" + + // Determine if the project is an application or library + def isApplication = plugin.project.plugins.hasPlugin('com.android.application') + def variants = isApplication ? plugin.project.android.applicationVariants : plugin.project.android.libraryVariants + + variants.all { variant -> + + final buildType = variant.buildType.name + + def cargoOutputDir = "${project.buildDir}/jniLibs/${buildType}"; + def jniLibs = project.android.sourceSets.maybeCreate(buildType).jniLibs; + jniLibs.srcDir(new File(cargoOutputDir)) + + def List platforms + try { + platforms = com.flutter.gradle.FlutterPluginUtils.getTargetPlatforms(project).collect() + } catch (Exception ignored) { + platforms = plugin.getTargetPlatforms().collect() + } + + // Same thing addFlutterDependencies does in flutter.gradle + if (buildType == "debug") { + platforms.add("android-x86") + platforms.add("android-x64") + } + + // The task name depends on plugin properties, which are not available + // at this point + project.getGradle().afterProject { + def taskName = "cargokitCargoBuild${project.cargokit.libname.capitalize()}${buildType.capitalize()}"; + + if (project.tasks.findByName(taskName)) { + return + } + + if (plugin.project.android.ndkVersion == null) { + throw new GradleException("Please set 'android.ndkVersion' in 'app/build.gradle'.") + } + + def task = project.tasks.create(taskName, CargoKitBuildTask.class) { + buildMode = variant.buildType.name + buildDir = cargoBuildDir + outputDir = cargoOutputDir + ndkVersion = plugin.project.android.ndkVersion + sdkDirectory = plugin.project.android.sdkDirectory + minSdkVersion = plugin.project.android.defaultConfig.minSdkVersion.apiLevel as int + compileSdkVersion = plugin.project.android.compileSdkVersion.substring(8) as int + targetPlatforms = platforms + pluginFile = CargoKitPlugin.file + } + def onTask = { newTask -> + if (newTask.name == "merge${buildType.capitalize()}NativeLibs") { + newTask.dependsOn task + // Fix gradle 7.4.2 not picking up JNI library changes + newTask.outputs.upToDateWhen { false } + } + } + project.tasks.each onTask + project.tasks.whenTaskAdded onTask + } + } + } +} diff --git a/app/rust_builder/cargokit/run_build_tool.cmd b/app/rust_builder/cargokit/run_build_tool.cmd new file mode 100755 index 0000000..c45d0aa --- /dev/null +++ b/app/rust_builder/cargokit/run_build_tool.cmd @@ -0,0 +1,91 @@ +@echo off +setlocal + +setlocal ENABLEDELAYEDEXPANSION + +SET BASEDIR=%~dp0 + +if not exist "%CARGOKIT_TOOL_TEMP_DIR%" ( + mkdir "%CARGOKIT_TOOL_TEMP_DIR%" +) +cd /D "%CARGOKIT_TOOL_TEMP_DIR%" + +SET BUILD_TOOL_PKG_DIR=%BASEDIR%build_tool +SET DART=%FLUTTER_ROOT%\bin\cache\dart-sdk\bin\dart + +set BUILD_TOOL_PKG_DIR_POSIX=%BUILD_TOOL_PKG_DIR:\=/% + +( + echo name: build_tool_runner + echo version: 1.0.0 + echo publish_to: none + echo. + echo environment: + echo sdk: '^>=3.0.0 ^<4.0.0' + echo. + echo dependencies: + echo build_tool: + echo path: %BUILD_TOOL_PKG_DIR_POSIX% +) >pubspec.yaml + +if not exist bin ( + mkdir bin +) + +( + echo import 'package:build_tool/build_tool.dart' as build_tool; + echo void main^(List^ args^) ^{ + echo build_tool.runMain^(args^); + echo ^} +) >bin\build_tool_runner.dart + +SET PRECOMPILED=bin\build_tool_runner.dill + +REM To detect changes in package we compare output of DIR /s (recursive) +set PREV_PACKAGE_INFO=.dart_tool\package_info.prev +set CUR_PACKAGE_INFO=.dart_tool\package_info.cur + +DIR "%BUILD_TOOL_PKG_DIR%" /s > "%CUR_PACKAGE_INFO%_orig" + +REM Last line in dir output is free space on harddrive. That is bound to +REM change between invocation so we need to remove it +( + Set "Line=" + For /F "UseBackQ Delims=" %%A In ("%CUR_PACKAGE_INFO%_orig") Do ( + SetLocal EnableDelayedExpansion + If Defined Line Echo !Line! + EndLocal + Set "Line=%%A") +) >"%CUR_PACKAGE_INFO%" +DEL "%CUR_PACKAGE_INFO%_orig" + +REM Compare current directory listing with previous +FC /B "%CUR_PACKAGE_INFO%" "%PREV_PACKAGE_INFO%" > nul 2>&1 + +If %ERRORLEVEL% neq 0 ( + REM Changed - copy current to previous and remove precompiled kernel + if exist "%PREV_PACKAGE_INFO%" ( + DEL "%PREV_PACKAGE_INFO%" + ) + MOVE /Y "%CUR_PACKAGE_INFO%" "%PREV_PACKAGE_INFO%" + if exist "%PRECOMPILED%" ( + DEL "%PRECOMPILED%" + ) +) + +REM There is no CUR_PACKAGE_INFO it was renamed in previous step to %PREV_PACKAGE_INFO% +REM which means we need to do pub get and precompile +if not exist "%PRECOMPILED%" ( + echo Running pub get in "%cd%" + "%DART%" pub get --no-precompile + "%DART%" compile kernel bin/build_tool_runner.dart +) + +"%DART%" "%PRECOMPILED%" %* + +REM 253 means invalid snapshot version. +If %ERRORLEVEL% equ 253 ( + "%DART%" pub get --no-precompile + "%DART%" compile kernel bin/build_tool_runner.dart + "%DART%" "%PRECOMPILED%" %* +) diff --git a/app/rust_builder/cargokit/run_build_tool.sh b/app/rust_builder/cargokit/run_build_tool.sh new file mode 100755 index 0000000..24b0ed8 --- /dev/null +++ b/app/rust_builder/cargokit/run_build_tool.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash + +set -e + +BASEDIR=$(dirname "$0") + +mkdir -p "$CARGOKIT_TOOL_TEMP_DIR" + +cd "$CARGOKIT_TOOL_TEMP_DIR" + +# Write a very simple bin package in temp folder that depends on build_tool package +# from Cargokit. This is done to ensure that we don't pollute Cargokit folder +# with .dart_tool contents. + +BUILD_TOOL_PKG_DIR="$BASEDIR/build_tool" + +if [[ -z $FLUTTER_ROOT ]]; then # not defined + DART=dart +else + DART="$FLUTTER_ROOT/bin/cache/dart-sdk/bin/dart" +fi + +cat << EOF > "pubspec.yaml" +name: build_tool_runner +version: 1.0.0 +publish_to: none + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + build_tool: + path: "$BUILD_TOOL_PKG_DIR" +EOF + +mkdir -p "bin" + +cat << EOF > "bin/build_tool_runner.dart" +import 'package:build_tool/build_tool.dart' as build_tool; +void main(List args) { + build_tool.runMain(args); +} +EOF + +# Create alias for `shasum` if it does not exist and `sha1sum` exists +if ! [ -x "$(command -v shasum)" ] && [ -x "$(command -v sha1sum)" ]; then + shopt -s expand_aliases + alias shasum="sha1sum" +fi + +# Dart run will not cache any package that has a path dependency, which +# is the case for our build_tool_runner. So instead we precompile the package +# ourselves. +# To invalidate the cached kernel we use the hash of ls -LR of the build_tool +# package directory. This should be good enough, as the build_tool package +# itself is not meant to have any path dependencies. + +if [[ "$OSTYPE" == "darwin"* ]]; then + PACKAGE_HASH=$(ls -lTR "$BUILD_TOOL_PKG_DIR" | shasum) +else + PACKAGE_HASH=$(ls -lR --full-time "$BUILD_TOOL_PKG_DIR" | shasum) +fi + +PACKAGE_HASH_FILE=".package_hash" + +if [ -f "$PACKAGE_HASH_FILE" ]; then + EXISTING_HASH=$(cat "$PACKAGE_HASH_FILE") + if [ "$PACKAGE_HASH" != "$EXISTING_HASH" ]; then + rm "$PACKAGE_HASH_FILE" + fi +fi + +# Run pub get if needed. +if [ ! -f "$PACKAGE_HASH_FILE" ]; then + "$DART" pub get --no-precompile + "$DART" compile kernel bin/build_tool_runner.dart + echo "$PACKAGE_HASH" > "$PACKAGE_HASH_FILE" +fi + +# Rebuild the tool if it was deleted by Android Studio +if [ ! -f "bin/build_tool_runner.dill" ]; then + "$DART" compile kernel bin/build_tool_runner.dart +fi + +set +e + +"$DART" bin/build_tool_runner.dill "$@" + +exit_code=$? + +# 253 means invalid snapshot version. +if [ $exit_code == 253 ]; then + "$DART" pub get --no-precompile + "$DART" compile kernel bin/build_tool_runner.dart + "$DART" bin/build_tool_runner.dill "$@" + exit_code=$? +fi + +exit $exit_code diff --git a/app/rust_builder/linux/CMakeLists.txt b/app/rust_builder/linux/CMakeLists.txt new file mode 100644 index 0000000..59ac33e --- /dev/null +++ b/app/rust_builder/linux/CMakeLists.txt @@ -0,0 +1,21 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) +cmake_policy(SET CMP0079 NEW) + +# Project-level configuration. +set(PROJECT_NAME "synapse_ffi") +project(${PROJECT_NAME} LANGUAGES CXX) + +include("../cargokit/cmake/cargokit.cmake") +apply_cargokit(${PROJECT_NAME} ../../../crates/synapse-ffi synapse_ffi "") +target_link_libraries(${BINARY_NAME} PRIVATE "${${PROJECT_NAME}_cargokit_lib}") + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(synapse_ffi_bundled_libraries + "${${PROJECT_NAME}_cargokit_lib}" + PARENT_SCOPE +) diff --git a/app/rust_builder/pubspec.yaml b/app/rust_builder/pubspec.yaml new file mode 100644 index 0000000..d30a3b3 --- /dev/null +++ b/app/rust_builder/pubspec.yaml @@ -0,0 +1,30 @@ +name: synapse_ffi +description: "Utility to build Rust code" +version: 0.0.1 +publish_to: none + +environment: + sdk: '>=3.3.0 <4.0.0' + flutter: '>=3.3.0' + +dependencies: + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + +dev_dependencies: + ffi: ^2.0.2 + ffigen: ^20.1.1 + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + +flutter: + plugin: + platforms: + android: + ffiPlugin: true + linux: + ffiPlugin: true + windows: + ffiPlugin: true diff --git a/app/rust_builder/windows/.gitignore b/app/rust_builder/windows/.gitignore new file mode 100644 index 0000000..b3eb2be --- /dev/null +++ b/app/rust_builder/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/app/rust_builder/windows/CMakeLists.txt b/app/rust_builder/windows/CMakeLists.txt new file mode 100644 index 0000000..99b58db --- /dev/null +++ b/app/rust_builder/windows/CMakeLists.txt @@ -0,0 +1,20 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "synapse_ffi") +project(${PROJECT_NAME} LANGUAGES CXX) + +include("../cargokit/cmake/cargokit.cmake") +apply_cargokit(${PROJECT_NAME} ../../../../../../../crates/synapse-ffi synapse_ffi "") + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(synapse_ffi_bundled_libraries + "${${PROJECT_NAME}_cargokit_lib}" + PARENT_SCOPE +) diff --git a/app/test/editor_keys_test.dart b/app/test/editor_keys_test.dart new file mode 100644 index 0000000..9733459 --- /dev/null +++ b/app/test/editor_keys_test.dart @@ -0,0 +1,347 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:synapse/src/editor/outline_view.dart'; +import 'package:synapse/src/state/app_state.dart'; +import 'package:synapse/src/state/outline_controller.dart'; +import 'package:synapse/src/theme/theme.dart'; + +import 'support/memory_backend.dart'; + +class Harness { + Harness(this.backend, this.app, this.controller, this.pageId); + final MemoryBackend backend; + final AppState app; + final OutlineController controller; + final String pageId; + + List<(int, String)> get local => [ + for (final n in controller.nodes) (n.depth, n.content), + ]; + + List<(int, String)> get stored => [ + for (final n in backend.outlines[pageId]!) (n.depth, n.content), + ]; +} + +Future pumpOutline( + WidgetTester tester, + List<(int, String)> rows, { + List otherPages = const [], +}) async { + final backend = MemoryBackend(); + final page = backend.createPage('Test'); + for (final t in otherPages) { + backend.createPage(t); + } + backend.seed(page.id, rows); + final app = AppState(backend); + final view = await backend.page(page.id); + final controller = OutlineController( + backend: backend, + queue: app.queue, + pageId: page.id, + blocks: view!.blocks, + saveDelay: const Duration(milliseconds: 50), + ); + addTearDown(controller.dispose); + await tester.pumpWidget( + AppScope( + state: app, + child: MaterialApp( + theme: buildTheme(Brightness.light), + home: Scaffold( + body: CustomScrollView( + slivers: [OutlineSliver(controller: controller)], + ), + ), + ), + ), + ); + return Harness(backend, app, controller, page.id); +} + +/// Focuses the block with `content` and puts the caret at `caret` (end by default). +Future edit( + WidgetTester tester, + Harness h, + String content, { + int? caret, +}) async { + final n = h.controller.nodes.firstWhere((n) => n.content == content); + h.controller.focus(n.id, caret: caret ?? content.length); + await tester.pump(); + await tester.pump(); +} + +TextEditingController field(WidgetTester tester) => + tester.widget(find.byType(TextField)).controller!; + +String? focusedContent(Harness h) { + final id = h.controller.focusedId; + return id == null ? null : h.controller.byId(id)?.content; +} + +Future settle(WidgetTester tester, Harness h) async { + await tester.pump(const Duration(milliseconds: 100)); + await h.app.queue.idle; + await tester.pump(const Duration(seconds: 1)); + await h.app.queue.idle; + await tester.pump(); +} + +Future withShift(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.pump(); +} + +void main() { + testWidgets('Enter splits the block at the caret and focuses the new one', ( + tester, + ) async { + final h = await pumpOutline(tester, [(0, 'hello world')]); + await edit(tester, h, 'hello world', caret: 5); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + await tester.pump(); + + expect(h.local, [(0, 'hello'), (0, ' world')]); + expect(focusedContent(h), ' world'); + expect(field(tester).selection.baseOffset, 0); + + await settle(tester, h); + expect(h.stored, [(0, 'hello'), (0, ' world')]); + expect(h.controller.nodes.every((n) => !n.id.startsWith('_tmp')), isTrue); + }); + + testWidgets('Enter on a block with children inserts its first child', ( + tester, + ) async { + final h = await pumpOutline(tester, [(0, 'parent'), (1, 'child')]); + await edit(tester, h, 'parent'); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await settle(tester, h); + expect(h.stored, [(0, 'parent'), (1, ''), (1, 'child')]); + }); + + testWidgets('Shift+Enter inserts a newline inside the block', (tester) async { + final h = await pumpOutline(tester, [(0, 'a')]); + await edit(tester, h, 'a'); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + // The platform inserts the newline as text input. + await tester.enterText(find.byType(TextField), 'a\n'); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await settle(tester, h); + expect(h.stored, [(0, 'a\n')]); + }); + + testWidgets('a newline typed by a soft keyboard splits the block', ( + tester, + ) async { + final h = await pumpOutline(tester, [(0, 'ab')]); + await edit(tester, h, 'ab', caret: 1); + tester.testTextInput.updateEditingValue( + const TextEditingValue( + text: 'a\nb', + selection: TextSelection.collapsed(offset: 2), + ), + ); + await settle(tester, h); + expect(h.stored, [(0, 'a'), (0, 'b')]); + }); + + testWidgets('Tab indents and Shift+Tab outdents, keeping focus', ( + tester, + ) async { + final h = await pumpOutline(tester, [(0, 'a'), (0, 'b'), (0, 'c')]); + await edit(tester, h, 'b', caret: 1); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + expect(h.local, [(0, 'a'), (1, 'b'), (0, 'c')]); + expect(focusedContent(h), 'b'); + expect(field(tester).selection.baseOffset, 1); + + await edit(tester, h, 'c'); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + expect(h.local, [(0, 'a'), (1, 'b'), (1, 'c')]); + + // Outdenting `b` adopts `c` (Logseq's direct outdenting). + await edit(tester, h, 'b'); + await withShift(tester, LogicalKeyboardKey.tab); + expect(h.local, [(0, 'a'), (0, 'b'), (1, 'c')]); + + await settle(tester, h); + expect(h.stored, h.local); + expect(h.backend.calls.where((c) => c == 'indent').length, 2); + expect(h.backend.calls.where((c) => c == 'outdent').length, 1); + }); + + testWidgets('Tab on a first child does nothing', (tester) async { + final h = await pumpOutline(tester, [(0, 'a'), (1, 'b')]); + await edit(tester, h, 'b'); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await settle(tester, h); + expect(h.stored, [(0, 'a'), (1, 'b')]); + expect(h.backend.calls, isNot(contains('indent'))); + }); + + testWidgets('Backspace at the start merges into the previous block', ( + tester, + ) async { + final h = await pumpOutline(tester, [(0, 'foo'), (0, 'bar'), (1, 'kid')]); + await edit(tester, h, 'bar', caret: 0); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + await tester.pump(); + expect(h.local, [(0, 'foobar'), (1, 'kid')]); + expect(focusedContent(h), 'foobar'); + expect(field(tester).selection.baseOffset, 3); + await settle(tester, h); + expect(h.stored, [(0, 'foobar'), (1, 'kid')]); + }); + + testWidgets('Backspace in the middle of text edits normally', (tester) async { + final h = await pumpOutline(tester, [(0, 'foo'), (0, 'bar')]); + await edit(tester, h, 'bar', caret: 2); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await settle(tester, h); + expect(h.backend.calls, isNot(contains('merge'))); + }); + + testWidgets('Delete at the end pulls the next block in', (tester) async { + final h = await pumpOutline(tester, [(0, 'foo'), (0, 'bar')]); + await edit(tester, h, 'foo'); + await tester.sendKeyEvent(LogicalKeyboardKey.delete); + await settle(tester, h); + expect(h.stored, [(0, 'foobar')]); + expect(focusedContent(h), 'foobar'); + }); + + testWidgets('arrows move between blocks, skipping collapsed children', ( + tester, + ) async { + final h = await pumpOutline(tester, [ + (0, 'one'), + (1, 'hidden'), + (0, 'two'), + ]); + h.controller.nodes.first.collapsed = true; + await edit(tester, h, 'one', caret: 1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + await tester.pump(); + expect(focusedContent(h), 'two'); + expect(field(tester).selection.baseOffset, 1); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + await tester.pump(); + expect(focusedContent(h), 'one'); + + // Right at the end moves to the start of the next block. + field(tester).selection = const TextSelection.collapsed(offset: 3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + await tester.pump(); + expect(focusedContent(h), 'two'); + expect(field(tester).selection.baseOffset, 0); + await settle(tester, h); + }); + + testWidgets('Alt+Shift+Up swaps a block with its previous sibling', ( + tester, + ) async { + final h = await pumpOutline(tester, [(0, 'a'), (1, 'a1'), (0, 'b')]); + await edit(tester, h, 'b'); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await settle(tester, h); + expect(h.stored, [(0, 'b'), (0, 'a'), (1, 'a1')]); + }); + + testWidgets('Ctrl+Enter cycles TODO and DONE', (tester) async { + final h = await pumpOutline(tester, [(0, 'buy milk')]); + await edit(tester, h, 'buy milk'); + Future ctrlEnter() async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + } + + await ctrlEnter(); + expect(field(tester).text, 'TODO buy milk'); + await ctrlEnter(); + expect(field(tester).text, 'DONE buy milk'); + await ctrlEnter(); + expect(field(tester).text, 'buy milk'); + await settle(tester, h); + expect(h.stored, [(0, 'buy milk')]); + }); + + testWidgets('[[ autocompletes page titles', (tester) async { + final h = await pumpOutline( + tester, + [(0, '')], + otherPages: ['Rust', 'Ruby'], + ); + await edit(tester, h, ''); + final finder = find.byType(TextField); + // Typing the second bracket auto-pairs the closing ones. + await tester.enterText(finder, '['); + await tester.enterText(finder, '[['); + expect(field(tester).text, '[[]]'); + expect(field(tester).selection.baseOffset, 2); + + tester.testTextInput.updateEditingValue( + const TextEditingValue( + text: '[[Rus]]', + selection: TextSelection.collapsed(offset: 5), + ), + ); + await tester.pump(); + await tester.pump(); + expect(find.text('Rust'), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + expect(field(tester).text, '[[Rust]]'); + expect(field(tester).selection.baseOffset, 8); + expect( + h.controller.nodes, + hasLength(1), + reason: 'Enter was taken by the popup', + ); + await settle(tester, h); + expect(h.stored, [(0, '[[Rust]]')]); + }); + + testWidgets('Escape leaves editing and the block renders', (tester) async { + final h = await pumpOutline(tester, [(0, 'some **bold** text')]); + await edit(tester, h, 'some **bold** text'); + expect(find.byType(TextField), findsOneWidget); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await settle(tester, h); + expect(find.byType(TextField), findsNothing); + expect(h.controller.focusedId, isNull); + expect(find.textContaining('bold', findRichText: true), findsOneWidget); + }); + + testWidgets('tapping an empty page creates its first block', (tester) async { + final h = await pumpOutline(tester, []); + await tester.tap(find.text('Click to start writing…')); + await tester.pump(); + await tester.pump(); + expect(find.byType(TextField), findsOneWidget); + await tester.enterText(find.byType(TextField), 'first'); + await settle(tester, h); + expect(h.stored, [(0, 'first')]); + }); +} diff --git a/app/test/logic_test.dart b/app/test/logic_test.dart new file mode 100644 index 0000000..e209e54 --- /dev/null +++ b/app/test/logic_test.dart @@ -0,0 +1,192 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:synapse/src/backend/graph_backend.dart'; +import 'package:synapse/src/editor/completion.dart'; +import 'package:synapse/src/editor/markdown.dart'; +import 'package:synapse/src/state/app_state.dart'; +import 'package:synapse/src/state/outline_ops.dart'; +import 'package:synapse/src/state/write_queue.dart'; +import 'package:synapse/src/theme/theme.dart'; + +import 'support/memory_backend.dart'; + +List tree(List<(int, String)> rows) { + var k = 0; + final l = [ + for (final (d, c) in rows) OutlineNode(id: 'n${k++}', depth: d, content: c), + ]; + OutlineOps.fixParents(l); + return l; +} + +List<(int, String)> shape(List l) => [ + for (final n in l) (n.depth, n.content), +]; + +void main() { + group('OutlineOps', () { + test('merge into parent keeps grandchildren in place', () { + final l = tree([(0, 'p'), (1, 'c'), (2, 'gc'), (1, 's')]); + OutlineOps.merge(l, 1, 0); + expect(shape(l), [(0, 'pc'), (1, 'gc'), (1, 's')]); + expect(l[1].parentId, 'n0'); + }); + + test('merge into a deeper previous row re-parents children', () { + final l = tree([(0, 'a'), (1, 'a1'), (0, 'b'), (1, 'b1')]); + OutlineOps.merge(l, 2, 1); + expect(shape(l), [(0, 'a'), (1, 'a1b'), (2, 'b1')]); + }); + + test('move with subtree, before and as first child', () { + final l = tree([(0, 'a'), (1, 'a1'), (0, 'b')]); + expect(OutlineOps.move(l, 0, PlaceKind.after, 2), isTrue); + expect(shape(l), [(0, 'b'), (0, 'a'), (1, 'a1')]); + expect(OutlineOps.move(l, 0, PlaceKind.firstChildOf, 1), isTrue); + expect(shape(l), [(0, 'a'), (1, 'b'), (1, 'a1')]); + expect(OutlineOps.move(l, 0, PlaceKind.after, 1), isFalse); + }); + + test('visible skips collapsed subtrees', () { + final l = tree([(0, 'a'), (1, 'a1'), (2, 'a2'), (0, 'b')]); + l[0].collapsed = true; + expect(OutlineOps.visible(l), [0, 3]); + }); + }); + + group('completion', () { + test('detects page, tag and block triggers', () { + expect( + detectCompletion('see [[Ru', 8), + const CompletionQuery(CompletionKind.page, 6, 'Ru'), + ); + expect(detectCompletion('see [[Ru]] x', 12), isNull); + expect( + detectCompletion('a #pro', 6), + const CompletionQuery(CompletionKind.tag, 3, 'pro'), + ); + expect(detectCompletion('a#pro', 5), isNull); + expect( + detectCompletion('((abc', 5), + const CompletionQuery(CompletionKind.block, 2, 'abc'), + ); + }); + + test('applies completions', () { + final q = detectCompletion('#my ta', 6); + expect(q, isNull, reason: 'tags stop at whitespace'); + final tag = detectCompletion('x #se', 5)!; + final v = applyCompletion( + 'x #se', + tag, + const CompletionItem('Second Brain', 'Second Brain'), + ); + expect(v.text, 'x #[[Second Brain]] '); + final page = detectCompletion('[[Ru]]', 4)!; + expect( + applyCompletion( + '[[Ru]]', + page, + const CompletionItem('Rust', 'Rust'), + ).text, + '[[Rust]]', + ); + }); + + test('replaces only the query even if the caret moved', () { + final q = detectCompletion('[[foo]]', 5)!; + final v = applyCompletion( + '[[foo]]', + q, + const CompletionItem('Foo', 'Foo'), + ); + expect(v.text, '[[Foo]]'); + }); + + test('auto-pairs brackets', () { + final v = autoPair( + const TextEditingValue( + text: 'a[', + selection: TextSelection.collapsed(offset: 2), + ), + const TextEditingValue( + text: 'a[[', + selection: TextSelection.collapsed(offset: 3), + ), + ); + expect(v!.text, 'a[[]]'); + expect(v.selection.baseOffset, 3); + }); + }); + + group('markdown', () { + RenderedBlock render(String s) { + final backend = MemoryBackend(); + return BlockRenderer( + RenderContext( + colors: SynapseColors.light, + base: const TextStyle(fontSize: 15), + refs: BlockRefCache(backend), + assetPath: (_) => null, + onPage: (_) {}, + onBlockRef: (_) {}, + onUrl: (_) {}, + ), + ).render(s); + } + + String plain(RenderedBlock r) => r.span.toPlainText( + includePlaceholders: true, + includeSemanticsLabels: false, + ); + + test('hides markup and maps taps back to the source', () { + final r = render('a **bold** [[Page]] end'); + expect(plain(r), 'a bold Page end'); + // "b" of bold: rendered 2 → source 4. + expect(r.toSource(2), 4); + // "P" of Page: rendered 7 → source 13. + expect(r.toSource(7), 13); + expect(r.toSource(plain(r).length), 'a **bold** [[Page]] end'.length); + r.dispose(); + }); + + test('renders tags, headings and todo markers', () { + expect(plain(render('# Title')), 'Title'); + expect(plain(render('note #idea, ok')), 'note #idea, ok'); + final todo = render('DONE ship it'); + expect(plain(todo), 'ship it'); + expect(todo.toSource(0), 5); + }); + }); + + test('a failed write makes the app reload its view', () async { + final app = AppState(MemoryBackend()); + final gen = app.generation; + await app.queue + .run(() async => throw StateError('boom')) + .catchError((_) {}); + expect(app.generation, gen + 1); + expect(app.writeError, contains('boom')); + await app.queue + .run(() async => throw StateError('read'), report: false) + .catchError((_) {}); + expect(app.generation, gen + 1); + }); + + test( + 'WriteQueue runs tasks in order even when they finish out of order', + () async { + final q = WriteQueue(); + final log = []; + final f1 = q.run(() async { + await Future.delayed(const Duration(milliseconds: 20)); + log.add(1); + }); + final f2 = q.run(() async => log.add(2)); + await Future.wait([f1, f2]); + expect(log, [1, 2]); + expect(q.isIdle, isTrue); + }, + ); +} diff --git a/app/test/support/memory_backend.dart b/app/test/support/memory_backend.dart new file mode 100644 index 0000000..36e3c90 --- /dev/null +++ b/app/test/support/memory_backend.dart @@ -0,0 +1,278 @@ +import 'package:synapse/src/backend/graph_backend.dart'; +import 'package:synapse/src/state/outline_ops.dart'; + +/// In-memory [GraphBackend] for widget tests. Outline semantics reuse [OutlineOps], which +/// mirror the Rust FFI (the Rust side has its own tests). +class MemoryBackend implements GraphBackend { + MemoryBackend({this.todayDate = '2026-10-21'}); + + final String todayDate; + final pages = {}; + final outlines = >{}; + final aliases = {}; + final calls = []; + int _seq = 0; + + String _id() => 'id-${_seq++}'; + + PageDto createPage(String title, {String? journalDate}) { + final p = PageDto( + id: journalDate != null ? 'j-$journalDate' : _id(), + title: title, + journalDate: journalDate, + createdAt: 0, + updatedAt: 0, + ); + pages[p.id] = p; + outlines[p.id] = []; + return p; + } + + /// Adds blocks `(depth, content)` to a page. + List seed(String pageId, List<(int, String)> rows) { + final l = outlines[pageId]!; + final ids = []; + for (final (d, c) in rows) { + final id = _id(); + l.add(OutlineNode(id: id, depth: d, content: c)); + ids.add(id); + } + OutlineOps.fixParents(l); + return ids; + } + + List _dto(String pageId) { + final l = outlines[pageId]!; + return [ + for (var i = 0; i < l.length; i++) + BlockDto( + id: l[i].id, + parentId: l[i].parentId, + depth: l[i].depth, + content: l[i].content, + collapsed: l[i].collapsed, + hasChildren: OutlineOps.hasChildren(l, i), + ), + ]; + } + + (String, int) _find(String blockId) { + for (final e in outlines.entries) { + final i = e.value.indexWhere((n) => n.id == blockId); + if (i >= 0) return (e.key, i); + } + throw StateError('block $blockId not found'); + } + + PageData _view(PageDto p) => PageData( + page: p, + blocks: _dto(p.id), + aliases: [ + for (final e in aliases.entries) + if (e.value == p.id) e.key, + ], + ); + + PageDto? _byTitle(String title) { + final k = title.trim().toLowerCase(); + for (final p in pages.values) { + if (p.title.toLowerCase() == k) return p; + } + final a = aliases[k]; + return a == null ? null : pages[a]; + } + + @override + String today() => todayDate; + + @override + Future> journals({String? before, required int limit}) async { + if (before == null) await journal(todayDate); + final js = + pages.values + .where( + (p) => + p.journalDate != null && + (before == null || p.journalDate!.compareTo(before) < 0), + ) + .toList() + ..sort((a, b) => b.journalDate!.compareTo(a.journalDate!)); + return js.take(limit).map(_view).toList(); + } + + @override + Future journal(String date) async => + _view(pages['j-$date'] ?? createPage(date, journalDate: date)); + + @override + Future page(String id) async { + final p = pages[id]; + return p == null ? null : _view(p); + } + + @override + Future pageByTitle(String title) async { + final p = _byTitle(title); + return p == null ? null : _view(p); + } + + @override + Future openPage(String title) async => + _view(_byTitle(title) ?? createPage(title)); + + @override + Future> listPages({ + bool includeJournals = false, + required int limit, + int offset = 0, + }) async => pages.values + .where((p) => includeJournals || p.journalDate == null) + .skip(offset) + .take(limit) + .toList(); + + @override + Future renamePage(String id, String newTitle) async { + final p = pages[id]!; + return pages[id] = PageDto( + id: p.id, + title: newTitle, + createdAt: p.createdAt, + updatedAt: p.updatedAt, + ); + } + + @override + Future deletePage(String id) async { + pages.remove(id); + outlines.remove(id); + } + + @override + Future addAlias(String pageId, String alias) async => + aliases[alias.toLowerCase()] = pageId; + + @override + Future removeAlias(String alias) async => + aliases.remove(alias.toLowerCase()); + + int? _index(String pageId, String? id) => + id == null ? null : outlines[pageId]!.indexWhere((n) => n.id == id); + + @override + Future insertBlock( + String pageId, + Place place, + String content, + ) async { + calls.add('insert'); + final n = OutlineNode(id: _id(), depth: 0, content: content); + OutlineOps.insert( + outlines[pageId]!, + n, + place.kind, + _index(pageId, place.anchor), + ); + return BlockDto( + id: n.id, + parentId: n.parentId, + depth: n.depth, + content: content, + collapsed: false, + hasChildren: false, + ); + } + + @override + Future updateBlock(String id, String content) async { + calls.add('update'); + final (p, i) = _find(id); + outlines[p]![i].content = content; + } + + @override + Future setCollapsed(String id, bool collapsed) async { + final (p, i) = _find(id); + outlines[p]![i].collapsed = collapsed; + } + + @override + Future> deleteBlock(String id) async { + final (p, i) = _find(id); + OutlineOps.delete(outlines[p]!, i); + return _dto(p); + } + + @override + Future> moveBlock( + String id, + String pageId, + Place place, + ) async { + final (p, i) = _find(id); + OutlineOps.move(outlines[p]!, i, place.kind, _index(p, place.anchor)); + return _dto(p); + } + + @override + Future> indentBlock(String id) async { + calls.add('indent'); + final (p, i) = _find(id); + OutlineOps.indent(outlines[p]!, i); + return _dto(p); + } + + @override + Future> outdentBlock(String id) async { + calls.add('outdent'); + final (p, i) = _find(id); + OutlineOps.outdent(outlines[p]!, i); + return _dto(p); + } + + @override + Future> mergeBlock(String id, String into) async { + calls.add('merge'); + final (p, i) = _find(id); + OutlineOps.merge(outlines[p]!, i, _index(p, into)!); + return _dto(p); + } + + @override + Future> outline(String pageId) async => _dto(pageId); + + @override + Future> backlinks(String pageId) async => []; + @override + Future> related(String pageId, {int limit = 12}) async => []; + @override + Future recordVisit(String? from, String to) async {} + @override + Future blockRef(String id) async => null; + @override + Future timeline(String from, String to) async => + const TimelineDto(days: [], pages: []); + + @override + Future> searchTitles(String query, {int limit = 20}) async { + final q = query.toLowerCase(); + return pages.values + .where( + (p) => p.journalDate == null && p.title.toLowerCase().contains(q), + ) + .take(limit) + .map((p) => TitleHit(pageId: p.id, title: p.title, isAlias: false)) + .toList(); + } + + @override + Future> searchBlocks(String query, {int limit = 20}) async => + []; + + @override + String? assetPath(String hash) => null; + + @override + Future putAssetFile(String path, {String? mime}) => + throw UnimplementedError(); +} diff --git a/app/windows/.gitignore b/app/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/app/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/app/windows/CMakeLists.txt b/app/windows/CMakeLists.txt new file mode 100644 index 0000000..ca7ebc1 --- /dev/null +++ b/app/windows/CMakeLists.txt @@ -0,0 +1,110 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(synapse LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "synapse") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +# Flutter does not create it when the project path has non-ASCII characters. +file(MAKE_DIRECTORY "${NATIVE_ASSETS_DIR}") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/app/windows/flutter/CMakeLists.txt b/app/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/app/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/app/windows/flutter/generated_plugin_registrant.cc b/app/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..4f78848 --- /dev/null +++ b/app/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/app/windows/flutter/generated_plugin_registrant.h b/app/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/app/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/app/windows/flutter/generated_plugins.cmake b/app/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..d0f47e6 --- /dev/null +++ b/app/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni + synapse_ffi +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/app/windows/runner/CMakeLists.txt b/app/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/app/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/app/windows/runner/Runner.rc b/app/windows/runner/Runner.rc new file mode 100644 index 0000000..4b0c759 --- /dev/null +++ b/app/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "es.zenvairo" "\0" + VALUE "FileDescription", "synapse" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "synapse" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 es.zenvairo. All rights reserved." "\0" + VALUE "OriginalFilename", "synapse.exe" "\0" + VALUE "ProductName", "synapse" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/app/windows/runner/flutter_window.cpp b/app/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/app/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/app/windows/runner/flutter_window.h b/app/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/app/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/app/windows/runner/main.cpp b/app/windows/runner/main.cpp new file mode 100644 index 0000000..495ae6d --- /dev/null +++ b/app/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"synapse", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/app/windows/runner/resource.h b/app/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/app/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/app/windows/runner/resources/app_icon.ico b/app/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/app/windows/runner/resources/app_icon.ico differ diff --git a/app/windows/runner/runner.exe.manifest b/app/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/app/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/app/windows/runner/utils.cpp b/app/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/app/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/app/windows/runner/utils.h b/app/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/app/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/app/windows/runner/win32_window.cpp b/app/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/app/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/app/windows/runner/win32_window.h b/app/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/app/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/crates/synapse-ffi/Cargo.toml b/crates/synapse-ffi/Cargo.toml new file mode 100644 index 0000000..00d64bd --- /dev/null +++ b/crates/synapse-ffi/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "synapse-ffi" +version = "0.1.0" +edition.workspace = true +license.workspace = true +description = "flutter_rust_bridge API over the Synapse core: the only surface the app sees" + +[lib] +crate-type = ["cdylib", "staticlib", "rlib"] + +[dependencies] +anyhow = "1" +chrono.workspace = true +flutter_rust_bridge = "=2.13.0" +synapse-core.workspace = true +uuid.workspace = true + +[dev-dependencies] +tempfile = "3" + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] } diff --git a/crates/synapse-ffi/examples/seed.rs b/crates/synapse-ffi/examples/seed.rs new file mode 100644 index 0000000..82738e7 --- /dev/null +++ b/crates/synapse-ffi/examples/seed.rs @@ -0,0 +1,118 @@ +//! Fills a graph with a few weeks of demo journals and pages, through the same API the app +//! uses. `cargo run -p synapse-ffi --example seed -- /path/to/graph` + +use synapse_ffi::api::dto::{Place, PlaceKind}; +use synapse_ffi::api::graph::SynapseGraph; + +fn main() -> anyhow::Result<()> { + let dir = std::env::args() + .nth(1) + .ok_or_else(|| anyhow::anyhow!("usage: seed "))?; + let g = SynapseGraph::open(dir)?; + let today = chrono::NaiveDate::parse_from_str(&g.today(), "%Y-%m-%d")?; + let day = |back: i64| (today - chrono::Duration::days(back)).to_string(); + let last = |page: &str, content: &str| { + g.insert_block( + page.to_string(), + Place { + kind: PlaceKind::LastChildOf, + anchor: None, + }, + content.to_string(), + ) + }; + let child = |page: &str, parent: &str, content: &str| { + g.insert_block( + page.to_string(), + Place { + kind: PlaceKind::LastChildOf, + anchor: Some(parent.to_string()), + }, + content.to_string(), + ) + }; + + let entries: &[(i64, &[&str])] = &[ + ( + 24, + &[ + "Started reading about [[Spreading Activation]] for the related panel", + "TODO sketch the #timeline view", + ], + ), + ( + 21, + &[ + "Call with Ana about [[Synapse]] sync design", + "#rust ownership notes", + ], + ), + ( + 17, + &[ + "DONE pick fonts: Inter + Noto Serif", + "Idea: [[Hebbian Learning]] for links", + ], + ), + (12, &["Weekly review", "Read [[Zettelkasten]] chapter 3"]), + ( + 8, + &["Drafted [[Outliner Keymap]]", "TODO benchmark tantivy"], + ), + (5, &["[[Synapse]] FFI is green", "Lunch with Marta #people"]), + (2, &["Thinking about [[Spreading Activation]] decay rates"]), + ( + 0, + &[ + "## Today", + "TODO review the **editor** key handling", + "Linked [[Synapse]] and [[Zettelkasten]] ideas", + "Code: `cargo test --workspace`", + ], + ), + ]; + for (back, lines) in entries { + let j = g.journal(day(*back))?; + let pid = j.page.id.clone(); + if !j.blocks.is_empty() { + continue; + } + let mut prev = None; + for l in *lines { + let b = last(&pid, l)?; + prev.get_or_insert(b.id); + } + if *back == 0 { + let first = prev.unwrap(); + child(&pid, &first, "Nested notes stay under their parent")?; + } + } + + let syn = g.open_page("Synapse".into())?; + if syn.blocks.is_empty() { + let id = syn.page.id; + let a = last(&id, "A native, brain-like second brain")?; + child(&id, &a.id, "Rust core + Flutter UI, no webviews")?; + child( + &id, + &a.id, + "Journals chained in time; pages born in journals", + )?; + last( + &id, + "Related: [[Hebbian Learning]], [[Spreading Activation]]", + )?; + last(&id, "DONE ship the outliner")?; + g.add_alias(id, "Second Brain".into())?; + } + let sa = g.open_page("Spreading Activation".into())?; + if sa.blocks.is_empty() { + last( + &sa.page.id, + "Activate a note, propagate through weighted edges with decay", + )?; + last(&sa.page.id, "Used by the **Related** panel in [[Synapse]]")?; + } + println!("seeded {}", g.dir()); + Ok(()) +} diff --git a/crates/synapse-ffi/src/api/dto.rs b/crates/synapse-ffi/src/api/dto.rs new file mode 100644 index 0000000..6044c93 --- /dev/null +++ b/crates/synapse-ffi/src/api/dto.rs @@ -0,0 +1,171 @@ +//! Plain data transferred to the UI. Ids are UUID strings and days are `YYYY-MM-DD`, which +//! keeps the generated Dart side free of extra codecs. + +use synapse_core::{Block, Page, journal_title}; + +/// Page header data. +#[derive(Debug, Clone, PartialEq)] +pub struct PageDto { + pub id: String, + pub title: String, + /// Set for journal pages. + pub journal_date: Option, + /// Journal day the page was born in. + pub origin_journal: Option, + pub created_at: i64, + pub updated_at: i64, +} + +impl From<&Page> for PageDto { + fn from(p: &Page) -> Self { + Self { + id: p.id.to_string(), + title: p.title.clone(), + journal_date: p.journal_date.map(journal_title), + origin_journal: p.origin_journal.map(journal_title), + created_at: p.created_at, + updated_at: p.updated_at, + } + } +} + +/// One row of the outline, in pre-order. +#[derive(Debug, Clone, PartialEq)] +pub struct BlockDto { + pub id: String, + pub parent_id: Option, + pub depth: u32, + pub content: String, + pub collapsed: bool, + pub has_children: bool, +} + +impl BlockDto { + pub(crate) fn new(depth: usize, b: &Block, has_children: bool) -> Self { + Self { + id: b.id.to_string(), + parent_id: b.parent_id.map(|p| p.to_string()), + depth: depth as u32, + content: b.content.clone(), + collapsed: b.collapsed, + has_children, + } + } +} + +/// Everything the page view needs in one call. +#[derive(Debug, Clone, PartialEq)] +pub struct PageData { + pub page: PageDto, + pub blocks: Vec, + pub aliases: Vec, + /// Previous/next existing journal (journal pages only). + pub prev_journal: Option, + pub next_journal: Option, +} + +/// Where a block goes, relative to `anchor`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PlaceKind { + After, + Before, + /// Last child of `anchor`, or last root block when `anchor` is `None`. + LastChildOf, + /// First child of `anchor`, or first root block when `anchor` is `None`. + FirstChildOf, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Place { + pub kind: PlaceKind, + pub anchor: Option, +} + +/// Blocks of one page referencing the queried page. +#[derive(Debug, Clone, PartialEq)] +pub struct BacklinkGroup { + pub page_id: String, + pub page_title: String, + pub is_journal: bool, + pub blocks: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct PageBrief { + pub id: String, + pub title: String, + pub is_journal: bool, +} + +impl From<&Page> for PageBrief { + fn from(p: &Page) -> Self { + Self { + id: p.id.to_string(), + title: p.title.clone(), + is_journal: p.is_journal(), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct RelatedDto { + pub page: PageBrief, + pub score: f32, +} + +/// Target of a `((block ref))`. +#[derive(Debug, Clone, PartialEq)] +pub struct BlockRefDto { + pub id: String, + pub content: String, + pub page_id: String, + pub page_title: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct EditDto { + pub page_id: String, + pub edits: u32, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct TimelineDayDto { + pub date: String, + pub journal_id: Option, + /// Pages born on this day. + pub created: Vec, + /// Pages edited on this day. + pub edited: Vec, +} + +/// Timeline slice plus the titles of every page it mentions. +#[derive(Debug, Clone, PartialEq)] +pub struct TimelineDto { + pub days: Vec, + pub pages: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct AssetDto { + pub hash: String, + pub size: u64, + pub mime: Option, + pub original_name: Option, +} + +/// Quick switcher / `[[` autocomplete hit. +#[derive(Debug, Clone, PartialEq)] +pub struct TitleHit { + pub page_id: String, + /// The matched title or alias. + pub title: String, + pub is_alias: bool, +} + +/// `((` autocomplete hit. +#[derive(Debug, Clone, PartialEq)] +pub struct BlockHit { + pub id: String, + pub content: String, + pub page_title: String, +} diff --git a/crates/synapse-ffi/src/api/graph.rs b/crates/synapse-ffi/src/api/graph.rs new file mode 100644 index 0000000..92499eb --- /dev/null +++ b/crates/synapse-ffi/src/api/graph.rs @@ -0,0 +1,336 @@ +//! The graph handle and read-side queries (pages, journals, links, timeline, assets). + +use super::dto::*; +use anyhow::{Context, Result, anyhow, bail}; +use chrono::NaiveDate; +use flutter_rust_bridge::frb; +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::sync::{Mutex, MutexGuard}; +use synapse_core::{Graph, NewPage, Page, PageId, journal_title}; +use uuid::Uuid; + +/// An open graph. Opaque to Dart; every call locks the graph for its duration, so calls are +/// short and coarse-grained. The app serialises writes on its side to keep their order. +pub struct SynapseGraph { + graph: Mutex, +} + +impl SynapseGraph { + /// Opens (or creates) the graph stored in `dir`. + pub fn open(dir: String) -> Result { + let graph = Graph::open(&dir).with_context(|| format!("opening graph at {dir}"))?; + Ok(SynapseGraph { + graph: Mutex::new(graph), + }) + } + + pub(crate) fn lock(&self) -> MutexGuard<'_, Graph> { + self.graph.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Graph directory. + #[frb(sync)] + pub fn dir(&self) -> String { + self.lock().dir().to_string_lossy().into_owned() + } + + /// Today's date (graph clock) as `YYYY-MM-DD`. + #[frb(sync)] + pub fn today(&self) -> String { + journal_title(self.lock().today()) + } + + // ------------------------------------------------------------- pages + + pub fn page(&self, id: String) -> Result> { + let g = self.lock(); + match g.get_page(parse_id(&id)?)? { + Some(p) => Ok(Some(page_view(&g, &p)?)), + None => Ok(None), + } + } + + /// Page by title or alias, without creating it. + pub fn page_by_title(&self, title: String) -> Result> { + let g = self.lock(); + match g.page_by_title(&title)? { + Some(p) => Ok(Some(page_view(&g, &p)?)), + None => Ok(None), + } + } + + /// Page by title or alias, created if missing (following a `[[link]]`). Date titles open + /// the journal of that day. + pub fn open_page(&self, title: String) -> Result { + let g = self.lock(); + let page = match g.page_by_title(&title)? { + Some(p) => p, + None => match parse_day(&title) { + Some(d) => g.journal(d)?, + None => g.create_page(NewPage::titled(title))?, + }, + }; + page_view(&g, &page) + } + + /// Pages ordered by last update, most recent first. + pub fn list_pages( + &self, + include_journals: bool, + limit: u32, + offset: u32, + ) -> Result> { + let g = self.lock(); + Ok(g.list_pages(include_journals, limit, offset)? + .iter() + .map(PageDto::from) + .collect()) + } + + pub fn rename_page(&self, id: String, new_title: String) -> Result { + let g = self.lock(); + Ok(PageDto::from(&g.rename_page(parse_id(&id)?, &new_title)?)) + } + + pub fn delete_page(&self, id: String) -> Result<()> { + Ok(self.lock().delete_page(parse_id(&id)?)?) + } + + pub fn aliases(&self, page_id: String) -> Result> { + Ok(self.lock().aliases_of(parse_id(&page_id)?)?) + } + + pub fn add_alias(&self, page_id: String, alias: String) -> Result<()> { + let alias = alias.trim(); + if alias.is_empty() { + bail!("empty alias"); + } + Ok(self.lock().set_alias(alias, Some(parse_id(&page_id)?))?) + } + + pub fn remove_alias(&self, alias: String) -> Result<()> { + Ok(self.lock().set_alias(&alias, None)?) + } + + // ---------------------------------------------------------- journals + + /// The journal of `date` (created if missing). + pub fn journal(&self, date: String) -> Result { + let g = self.lock(); + let p = g.journal(parse_date(&date)?)?; + page_view(&g, &p) + } + + /// Journals feed, newest first. With `before = None` it starts at today (creating today's + /// journal); otherwise at the newest journal strictly before `before`. + pub fn journals(&self, before: Option, limit: u32) -> Result> { + let g = self.lock(); + let mut out = Vec::new(); + let mut cursor = match before { + None => { + let today = g.today_journal()?; + let date = today.journal_date; + out.push(page_view(&g, &today)?); + date + } + Some(b) => Some(parse_date(&b)?), + }; + while (out.len() as u32) < limit { + let Some(d) = cursor else { break }; + let Some(prev) = g.journal_neighbors(d)?.prev else { + break; + }; + let page = g.journal(prev)?; + out.push(page_view(&g, &page)?); + cursor = Some(prev); + } + Ok(out) + } + + pub fn journal_neighbors(&self, date: String) -> Result<(Option, Option)> { + let n = self.lock().journal_neighbors(parse_date(&date)?)?; + Ok((n.prev.map(journal_title), n.next.map(journal_title))) + } + + /// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions. + pub fn timeline(&self, from: String, to: String) -> Result { + let g = self.lock(); + let days = g.timeline(parse_date(&from)?, parse_date(&to)?)?; + let mut ids: BTreeSet = BTreeSet::new(); + let days = days + .into_iter() + .map(|d| { + ids.extend(d.created.iter().copied()); + ids.extend(d.edited.iter().map(|(p, _)| *p)); + TimelineDayDto { + date: journal_title(d.date), + journal_id: d.journal.map(|j| j.to_string()), + created: d.created.iter().map(Uuid::to_string).collect(), + edited: d + .edited + .iter() + .map(|(p, n)| EditDto { + page_id: p.to_string(), + edits: *n, + }) + .collect(), + } + }) + .collect(); + let mut pages = Vec::with_capacity(ids.len()); + for id in ids { + if let Some(p) = g.get_page(id)? { + pages.push(PageBrief::from(&p)); + } + } + Ok(TimelineDto { days, pages }) + } + + // ------------------------------------------------------------- links + + /// Linked references grouped by page (most recently edited first). + pub fn backlinks(&self, page_id: String) -> Result> { + let g = self.lock(); + let mut groups: Vec = Vec::new(); + let mut index: HashMap = HashMap::new(); + let mut seen: HashSet = HashSet::new(); + for bl in g.backlinks(parse_id(&page_id)?)? { + if !seen.insert(bl.block.id) { + continue; + } + let i = *index.entry(bl.block.page_id).or_insert_with(|| { + groups.push(BacklinkGroup { + page_id: bl.block.page_id.to_string(), + page_title: bl.page_title.clone(), + is_journal: parse_day(&bl.page_title).is_some(), + blocks: Vec::new(), + }); + groups.len() - 1 + }); + groups[i].blocks.push(BlockDto::new(0, &bl.block, false)); + } + Ok(groups) + } + + /// Notes related to `page_id` by spreading activation. + pub fn related(&self, page_id: String, limit: u32) -> Result> { + let g = self.lock(); + let mut out = Vec::new(); + for (id, score) in g.related(parse_id(&page_id)?, limit as usize)? { + if let Some(p) = g.get_page(id)? { + out.push(RelatedDto { + page: PageBrief::from(&p), + score, + }); + } + } + Ok(out) + } + + /// Records navigation between pages (strengthens their synapse). + pub fn record_visit(&self, from: Option, to: String) -> Result<()> { + let from = from.as_deref().map(parse_id).transpose()?; + Ok(self.lock().record_visit(from, parse_id(&to)?)?) + } + + /// Target of a `((block ref))`. + pub fn block_ref(&self, id: String) -> Result> { + let g = self.lock(); + let Some(b) = g.get_block(parse_id(&id)?)? else { + return Ok(None); + }; + let page_title = g.get_page(b.page_id)?.map(|p| p.title).unwrap_or_default(); + Ok(Some(BlockRefDto { + id: b.id.to_string(), + content: b.content, + page_id: b.page_id.to_string(), + page_title, + })) + } + + // ------------------------------------------------------------ assets + + /// Copies a file into the blob store (streamed). + pub fn put_asset_file(&self, path: String, mime: Option) -> Result { + let a = self + .lock() + .put_asset_file(std::path::Path::new(&path), mime.as_deref())?; + Ok(asset_dto(a)) + } + + /// Stores in-memory bytes (clipboard, Android content URIs). + pub fn put_asset_bytes( + &self, + bytes: Vec, + name: Option, + mime: Option, + ) -> Result { + let a = self + .lock() + .put_asset_reader(&bytes[..], name.as_deref(), mime.as_deref())?; + Ok(asset_dto(a)) + } + + /// Local file path of an asset (for `asset://` images), if present. + #[frb(sync)] + pub fn asset_path(&self, hash: String) -> Option { + if hash.len() != 64 || !hash.bytes().all(|c| c.is_ascii_hexdigit()) { + return None; + } + let g = self.lock(); + g.blobs() + .contains(&hash) + .then(|| g.blobs().path_of(&hash).to_string_lossy().into_owned()) + } +} + +fn asset_dto(a: synapse_core::Asset) -> AssetDto { + AssetDto { + hash: a.hash, + size: a.size, + mime: a.mime, + original_name: a.original_name, + } +} + +pub(crate) fn page_view(g: &Graph, p: &Page) -> Result { + let (prev, next) = match p.journal_date { + Some(d) => { + let n = g.journal_neighbors(d)?; + (n.prev.map(journal_title), n.next.map(journal_title)) + } + None => (None, None), + }; + Ok(PageData { + page: PageDto::from(p), + blocks: outline(g, p.id)?, + aliases: g.aliases_of(p.id)?, + prev_journal: prev, + next_journal: next, + }) +} + +/// The page outline as UI rows. +pub(crate) fn outline(g: &Graph, page: PageId) -> Result> { + let tree = g.page_tree(page)?; + Ok(tree + .iter() + .enumerate() + .map(|(i, (d, b))| { + let has_children = tree.get(i + 1).is_some_and(|(nd, _)| nd > d); + BlockDto::new(*d, b, has_children) + }) + .collect()) +} + +pub(crate) fn parse_id(s: &str) -> Result { + Uuid::parse_str(s).map_err(|e| anyhow!("bad id {s:?}: {e}")) +} + +pub(crate) fn parse_date(s: &str) -> Result { + parse_day(s).ok_or_else(|| anyhow!("bad date {s:?}, expected YYYY-MM-DD")) +} + +fn parse_day(s: &str) -> Option { + NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok() +} diff --git a/crates/synapse-ffi/src/api/mod.rs b/crates/synapse-ffi/src/api/mod.rs new file mode 100644 index 0000000..1f3129a --- /dev/null +++ b/crates/synapse-ffi/src/api/mod.rs @@ -0,0 +1,15 @@ +//! Everything under `api` is scanned by `flutter_rust_bridge_codegen` and exposed to Dart. +//! +//! - `graph`: the opaque [`graph::SynapseGraph`] handle and read-side queries. +//! - `outline`: block editing (insert, update, move, indent/outdent, merge, delete). +//! - `search`: title/block lookup (stopgap until `synapse-search` is wired). +//! +//! Extension points for Phase 2 (one module each, methods on `SynapseGraph` or their own +//! opaque handles): `ai` (synapse-ai), `history` (synapse-history), `caldav` +//! (synapse-caldav) and `sync` (synapse-sync client). Add `pub mod ;` here, implement it +//! on top of the locked `Graph`, and regenerate the bindings. + +pub mod dto; +pub mod graph; +pub mod outline; +pub mod search; diff --git a/crates/synapse-ffi/src/api/outline.rs b/crates/synapse-ffi/src/api/outline.rs new file mode 100644 index 0000000..423ce49 --- /dev/null +++ b/crates/synapse-ffi/src/api/outline.rs @@ -0,0 +1,163 @@ +//! Outliner editing. Structural operations return the page's refreshed outline so the UI can +//! re-sync to the authoritative order after its optimistic update. +//! +//! The core exposes single-block primitives, each in its own transaction; compound edits here +//! (indent, outdent, merge) are sequences of them. See the crate docs for the core helper that +//! would make them atomic. + +use super::dto::*; +use super::graph::{SynapseGraph, outline, parse_id}; +use anyhow::{Result, bail}; +use synapse_core::{Block, BlockId, Graph, PageId, Placement}; + +impl SynapseGraph { + pub fn insert_block(&self, page_id: String, place: Place, content: String) -> Result { + let g = self.lock(); + let page = parse_id(&page_id)?; + let at = placement(&g, page, &place)?; + let b = g.insert_block(page, at, &content)?; + Ok(BlockDto::new(0, &b, false)) + } + + /// Replaces a block's Markdown (the debounced save while typing). + pub fn update_block(&self, id: String, content: String) -> Result<()> { + self.lock().update_block(parse_id(&id)?, &content)?; + Ok(()) + } + + pub fn set_collapsed(&self, id: String, collapsed: bool) -> Result<()> { + Ok(self.lock().set_collapsed(parse_id(&id)?, collapsed)?) + } + + /// Deletes a block and its subtree. + pub fn delete_block(&self, id: String) -> Result> { + let g = self.lock(); + let b = get(&g, parse_id(&id)?)?; + g.delete_block(b.id)?; + outline(&g, b.page_id) + } + + /// Moves a block with its subtree (drag and drop), possibly to another page. + pub fn move_block(&self, id: String, page_id: String, place: Place) -> Result> { + let g = self.lock(); + let page = parse_id(&page_id)?; + let at = placement(&g, page, &place)?; + g.move_block(parse_id(&id)?, page, at)?; + outline(&g, page) + } + + /// Tab: the block becomes the last child of its previous sibling (no-op for a first child). + pub fn indent_block(&self, id: String) -> Result> { + let g = self.lock(); + let b = get(&g, parse_id(&id)?)?; + let sibs = siblings(&g, &b)?; + let i = sibs.iter().position(|s| s.id == b.id).unwrap_or(0); + if i > 0 { + let prev = &sibs[i - 1]; + if prev.collapsed { + g.set_collapsed(prev.id, false)?; + } + g.move_block(b.id, b.page_id, Placement::LastChildOf(Some(prev.id)))?; + } + outline(&g, b.page_id) + } + + /// Shift-Tab: the block moves right after its parent, adopting its following siblings as + /// children so it keeps its visual place (Logseq's default outdenting). + pub fn outdent_block(&self, id: String) -> Result> { + let g = self.lock(); + let b = get(&g, parse_id(&id)?)?; + let Some(parent) = b.parent_id else { + return outline(&g, b.page_id); + }; + let sibs = siblings(&g, &b)?; + let i = sibs.iter().position(|s| s.id == b.id).unwrap_or(0); + g.move_block(b.id, b.page_id, Placement::After(parent))?; + for s in &sibs[i + 1..] { + g.move_block(s.id, b.page_id, Placement::LastChildOf(Some(b.id)))?; + } + if b.collapsed && i + 1 < sibs.len() { + g.set_collapsed(b.id, false)?; + } + outline(&g, b.page_id) + } + + /// Backspace at the start of `id`: its text is appended to `into` (the previous visible + /// block) and the block is deleted. Its children keep their visual place: they take the + /// block's slot when `into` is its parent, otherwise they become last children of `into`. + pub fn merge_block(&self, id: String, into: String) -> Result> { + let g = self.lock(); + let b = get(&g, parse_id(&id)?)?; + let target = get(&g, parse_id(&into)?)?; + if b.id == target.id { + bail!("cannot merge a block into itself"); + } + if !b.content.is_empty() { + g.update_block(target.id, &format!("{}{}", target.content, b.content))?; + } + let children: Vec = g + .page_tree(b.page_id)? + .into_iter() + .filter(|(_, c)| c.parent_id == Some(b.id)) + .map(|(_, c)| c.id) + .collect(); + if !children.is_empty() && target.collapsed && b.parent_id != Some(target.id) { + g.set_collapsed(target.id, false)?; + } + let at = if b.parent_id == Some(target.id) { + Placement::Before(b.id) + } else { + Placement::LastChildOf(Some(target.id)) + }; + for c in children { + g.move_block(c, target.page_id, at)?; + } + g.delete_block(b.id)?; + outline(&g, target.page_id) + } + + /// Current outline of a page. + pub fn outline(&self, page_id: String) -> Result> { + outline(&self.lock(), parse_id(&page_id)?) + } +} + +fn get(g: &Graph, id: BlockId) -> Result { + match g.get_block(id)? { + Some(b) => Ok(b), + None => bail!("block {id} not found"), + } +} + +/// Siblings of `b` (including itself) in order. +fn siblings(g: &Graph, b: &Block) -> Result> { + Ok(g.page_tree(b.page_id)? + .into_iter() + .filter(|(_, s)| s.parent_id == b.parent_id) + .map(|(_, s)| s) + .collect()) +} + +fn placement(g: &Graph, page: PageId, place: &Place) -> Result { + let anchor = place.anchor.as_deref().map(parse_id).transpose()?; + let need = |a: Option| match a { + Some(a) => Ok(a), + None => Err(anyhow::anyhow!("{:?} needs an anchor block", place.kind)), + }; + Ok(match place.kind { + PlaceKind::After => Placement::After(need(anchor)?), + PlaceKind::Before => Placement::Before(need(anchor)?), + PlaceKind::LastChildOf => Placement::LastChildOf(anchor), + PlaceKind::FirstChildOf => { + let first = g + .page_tree(page)? + .into_iter() + .find(|(_, b)| b.parent_id == anchor) + .map(|(_, b)| b.id); + match first { + Some(f) => Placement::Before(f), + None => Placement::LastChildOf(anchor), + } + } + }) +} diff --git a/crates/synapse-ffi/src/api/search.rs b/crates/synapse-ffi/src/api/search.rs new file mode 100644 index 0000000..c3a90a2 --- /dev/null +++ b/crates/synapse-ffi/src/api/search.rs @@ -0,0 +1,94 @@ +//! Search used by the quick switcher and the editor's autocompletes. +//! +//! Extension point: these are simple in-process scans meant to be replaced by +//! `synapse-search` (tantivy full-text + vectors) once it is wired in. Keep the signatures; +//! swap the bodies. + +use super::dto::*; +use super::graph::SynapseGraph; +use anyhow::Result; +use synapse_core::title_key; + +impl SynapseGraph { + /// Page titles and aliases matching `query`: exact, then prefix, then word-prefix, then + /// substring; shorter titles first within a tier. Empty query returns recent pages. + pub fn search_titles(&self, query: String, limit: u32) -> Result> { + let g = self.lock(); + let q = title_key(&query); + if q.is_empty() { + return Ok(g + .list_pages(false, limit, 0)? + .iter() + .map(|p| TitleHit { + page_id: p.id.to_string(), + title: p.title.clone(), + is_alias: false, + }) + .collect()); + } + let mut hits: Vec<(u8, usize, String, synapse_core::PageId)> = g + .all_titles()? + .into_iter() + .filter_map(|(t, id)| { + let k = title_key(&t); + let tier = if k == q { + 0 + } else if k.starts_with(&q) { + 1 + } else if k + .match_indices(&q) + .any(|(i, _)| !k[..i].ends_with(|c: char| c.is_alphanumeric())) + { + 2 + } else if k.contains(&q) { + 3 + } else { + return None; + }; + Some((tier, k.chars().count(), t, id)) + }) + .collect(); + hits.sort_by(|a, b| (a.0, a.1, &a.2).cmp(&(b.0, b.1, &b.2))); + hits.truncate(limit as usize); + let mut out = Vec::with_capacity(hits.len()); + for (_, _, title, id) in hits { + let is_alias = g + .get_page(id)? + .is_some_and(|p| title_key(&p.title) != title_key(&title)); + out.push(TitleHit { + page_id: id.to_string(), + title, + is_alias, + }); + } + Ok(out) + } + + /// Blocks whose text contains `query` (for `((` autocomplete), most recent first. + pub fn search_blocks(&self, query: String, limit: u32) -> Result> { + let q = query.trim(); + if q.is_empty() { + return Ok(Vec::new()); + } + let pattern = format!( + "%{}%", + q.replace('\\', "\\\\") + .replace('%', "\\%") + .replace('_', "\\_") + ); + let g = self.lock(); + // Read-only stopgap over the core tables until synapse-search lands. + let mut st = g.conn().prepare_cached( + "SELECT b.id, b.content, p.title FROM blocks b JOIN pages p ON p.id = b.page_id + WHERE b.content LIKE ?1 ESCAPE '\\' ORDER BY b.updated_at DESC LIMIT ?2", + )?; + let rows = st.query_map((pattern, limit), |r| { + Ok(BlockHit { + id: r.get(0)?, + content: r.get(1)?, + page_title: r.get(2)?, + }) + })?; + Ok(rows.collect::>()?) + } +} diff --git a/crates/synapse-ffi/src/frb_generated.rs b/crates/synapse-ffi/src/frb_generated.rs new file mode 100644 index 0000000..732fe5b --- /dev/null +++ b/crates/synapse-ffi/src/frb_generated.rs @@ -0,0 +1,3367 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +#![allow( + non_camel_case_types, + unused, + non_snake_case, + clippy::needless_return, + clippy::redundant_closure_call, + clippy::redundant_closure, + clippy::useless_conversion, + clippy::unit_arg, + clippy::unused_unit, + clippy::double_parens, + clippy::let_and_return, + clippy::too_many_arguments, + clippy::match_single_binding, + clippy::clone_on_copy, + clippy::let_unit_value, + clippy::deref_addrof, + clippy::explicit_auto_deref, + clippy::borrow_deref_ref, + clippy::uninlined_format_args, + clippy::needless_borrow, + mismatched_lifetime_syntaxes +)] + +// Section: imports + +use crate::api::graph::*; +use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; +use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; +use flutter_rust_bridge::{Handler, IntoIntoDart}; + +// Section: boilerplate + +flutter_rust_bridge::frb_generated_boilerplate!( + default_stream_sink_codec = SseCodec, + default_rust_opaque = RustOpaqueMoi, + default_rust_auto_opaque = RustAutoOpaqueMoi, +); +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.13.0"; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 1980668428; + +// Section: executor + +flutter_rust_bridge::frb_generated_default_handler!(); + +// Section: wire_funcs + +fn wire__crate__api__graph__SynapseGraph_add_alias_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_add_alias", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_alias = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::add_alias( + &*api_that_guard, + api_page_id, + api_alias, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_aliases_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_aliases", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::aliases( + &*api_that_guard, + api_page_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_asset_path_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_asset_path", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_hash = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = Ok::<_, ()>(crate::api::graph::SynapseGraph::asset_path( + &*api_that_guard, + api_hash, + ))?; + std::result::Result::Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_backlinks_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_backlinks", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::backlinks( + &*api_that_guard, + api_page_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_block_ref_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_block_ref", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + crate::api::graph::SynapseGraph::block_ref(&*api_that_guard, api_id)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_delete_block_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_delete_block", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::delete_block( + &*api_that_guard, + api_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_delete_page_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_delete_page", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + crate::api::graph::SynapseGraph::delete_page(&*api_that_guard, api_id)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_dir_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_dir", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + Ok::<_, ()>(crate::api::graph::SynapseGraph::dir(&*api_that_guard))?; + std::result::Result::Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_indent_block_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_indent_block", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::indent_block( + &*api_that_guard, + api_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_insert_block_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_insert_block", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_place = ::sse_decode(&mut deserializer); + let api_content = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::insert_block( + &*api_that_guard, + api_page_id, + api_place, + api_content, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_journal_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_journal", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_date = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + crate::api::graph::SynapseGraph::journal(&*api_that_guard, api_date)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_journal_neighbors_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_journal_neighbors", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_date = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::journal_neighbors( + &*api_that_guard, + api_date, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_journals_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_journals", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_before = >::sse_decode(&mut deserializer); + let api_limit = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::journals( + &*api_that_guard, + api_before, + api_limit, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_list_pages_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_list_pages", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_include_journals = ::sse_decode(&mut deserializer); + let api_limit = ::sse_decode(&mut deserializer); + let api_offset = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::list_pages( + &*api_that_guard, + api_include_journals, + api_limit, + api_offset, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_merge_block_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_merge_block", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + let api_into = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::merge_block( + &*api_that_guard, + api_id, + api_into, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_move_block_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_move_block", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_place = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::move_block( + &*api_that_guard, + api_id, + api_page_id, + api_place, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_open_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_open", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_dir = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let output_ok = crate::api::graph::SynapseGraph::open(api_dir)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_open_page_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_open_page", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_title = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::open_page( + &*api_that_guard, + api_title, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_outdent_block_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_outdent_block", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::outdent_block( + &*api_that_guard, + api_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_outline_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_outline", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::outline( + &*api_that_guard, + api_page_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_page_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_page", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + crate::api::graph::SynapseGraph::page(&*api_that_guard, api_id)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_page_by_title_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_page_by_title", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_title = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::page_by_title( + &*api_that_guard, + api_title, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_put_asset_bytes", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_bytes = >::sse_decode(&mut deserializer); + let api_name = >::sse_decode(&mut deserializer); + let api_mime = >::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::put_asset_bytes( + &*api_that_guard, + api_bytes, + api_name, + api_mime, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_put_asset_file_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_put_asset_file", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_path = ::sse_decode(&mut deserializer); + let api_mime = >::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::put_asset_file( + &*api_that_guard, + api_path, + api_mime, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_record_visit_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_record_visit", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_from = >::sse_decode(&mut deserializer); + let api_to = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::record_visit( + &*api_that_guard, + api_from, + api_to, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_related_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_related", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_limit = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::related( + &*api_that_guard, + api_page_id, + api_limit, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_remove_alias_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_remove_alias", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_alias = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::remove_alias( + &*api_that_guard, + api_alias, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_rename_page_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_rename_page", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + let api_new_title = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::rename_page( + &*api_that_guard, + api_id, + api_new_title, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_search_blocks_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_search_blocks", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_query = ::sse_decode(&mut deserializer); + let api_limit = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::search_blocks( + &*api_that_guard, + api_query, + api_limit, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_search_titles_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_search_titles", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_query = ::sse_decode(&mut deserializer); + let api_limit = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::search_titles( + &*api_that_guard, + api_query, + api_limit, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_set_collapsed_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_set_collapsed", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + let api_collapsed = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::set_collapsed( + &*api_that_guard, + api_id, + api_collapsed, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_timeline_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_timeline", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_from = ::sse_decode(&mut deserializer); + let api_to = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::timeline( + &*api_that_guard, + api_from, + api_to, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_today_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_today", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + Ok::<_, ()>(crate::api::graph::SynapseGraph::today(&*api_that_guard))?; + std::result::Result::Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_update_block_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_update_block", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_id = ::sse_decode(&mut deserializer); + let api_content = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::update_block( + &*api_that_guard, + api_id, + api_content, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} + +// Section: related_funcs + +flutter_rust_bridge::frb_generated_moi_arc_impl_value!( + flutter_rust_bridge::for_generated::RustAutoOpaqueInner +); + +// Section: dart2rust + +impl SseDecode for flutter_rust_bridge::for_generated::anyhow::Error { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = ::sse_decode(deserializer); + return flutter_rust_bridge::for_generated::anyhow::anyhow!("{}", inner); + } +} + +impl SseDecode for SynapseGraph { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = , + >>::sse_decode(deserializer); + return flutter_rust_bridge::for_generated::rust_auto_opaque_decode_owned(inner); + } +} + +impl SseDecode + for RustOpaqueMoi> +{ + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = ::sse_decode(deserializer); + return decode_rust_opaque_moi(inner); + } +} + +impl SseDecode for String { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = >::sse_decode(deserializer); + return String::from_utf8(inner).unwrap(); + } +} + +impl SseDecode for crate::api::dto::AssetDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_hash = ::sse_decode(deserializer); + let mut var_size = ::sse_decode(deserializer); + let mut var_mime = >::sse_decode(deserializer); + let mut var_originalName = >::sse_decode(deserializer); + return crate::api::dto::AssetDto { + hash: var_hash, + size: var_size, + mime: var_mime, + original_name: var_originalName, + }; + } +} + +impl SseDecode for crate::api::dto::BacklinkGroup { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_pageId = ::sse_decode(deserializer); + let mut var_pageTitle = ::sse_decode(deserializer); + let mut var_isJournal = ::sse_decode(deserializer); + let mut var_blocks = >::sse_decode(deserializer); + return crate::api::dto::BacklinkGroup { + page_id: var_pageId, + page_title: var_pageTitle, + is_journal: var_isJournal, + blocks: var_blocks, + }; + } +} + +impl SseDecode for crate::api::dto::BlockDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_id = ::sse_decode(deserializer); + let mut var_parentId = >::sse_decode(deserializer); + let mut var_depth = ::sse_decode(deserializer); + let mut var_content = ::sse_decode(deserializer); + let mut var_collapsed = ::sse_decode(deserializer); + let mut var_hasChildren = ::sse_decode(deserializer); + return crate::api::dto::BlockDto { + id: var_id, + parent_id: var_parentId, + depth: var_depth, + content: var_content, + collapsed: var_collapsed, + has_children: var_hasChildren, + }; + } +} + +impl SseDecode for crate::api::dto::BlockHit { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_id = ::sse_decode(deserializer); + let mut var_content = ::sse_decode(deserializer); + let mut var_pageTitle = ::sse_decode(deserializer); + return crate::api::dto::BlockHit { + id: var_id, + content: var_content, + page_title: var_pageTitle, + }; + } +} + +impl SseDecode for crate::api::dto::BlockRefDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_id = ::sse_decode(deserializer); + let mut var_content = ::sse_decode(deserializer); + let mut var_pageId = ::sse_decode(deserializer); + let mut var_pageTitle = ::sse_decode(deserializer); + return crate::api::dto::BlockRefDto { + id: var_id, + content: var_content, + page_id: var_pageId, + page_title: var_pageTitle, + }; + } +} + +impl SseDecode for bool { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u8().unwrap() != 0 + } +} + +impl SseDecode for crate::api::dto::EditDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_pageId = ::sse_decode(deserializer); + let mut var_edits = ::sse_decode(deserializer); + return crate::api::dto::EditDto { + page_id: var_pageId, + edits: var_edits, + }; + } +} + +impl SseDecode for f32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_f32::().unwrap() + } +} + +impl SseDecode for i32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_i32::().unwrap() + } +} + +impl SseDecode for i64 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_i64::().unwrap() + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for crate::api::dto::PageBrief { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_id = ::sse_decode(deserializer); + let mut var_title = ::sse_decode(deserializer); + let mut var_isJournal = ::sse_decode(deserializer); + return crate::api::dto::PageBrief { + id: var_id, + title: var_title, + is_journal: var_isJournal, + }; + } +} + +impl SseDecode for crate::api::dto::PageData { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_page = ::sse_decode(deserializer); + let mut var_blocks = >::sse_decode(deserializer); + let mut var_aliases = >::sse_decode(deserializer); + let mut var_prevJournal = >::sse_decode(deserializer); + let mut var_nextJournal = >::sse_decode(deserializer); + return crate::api::dto::PageData { + page: var_page, + blocks: var_blocks, + aliases: var_aliases, + prev_journal: var_prevJournal, + next_journal: var_nextJournal, + }; + } +} + +impl SseDecode for crate::api::dto::PageDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_id = ::sse_decode(deserializer); + let mut var_title = ::sse_decode(deserializer); + let mut var_journalDate = >::sse_decode(deserializer); + let mut var_originJournal = >::sse_decode(deserializer); + let mut var_createdAt = ::sse_decode(deserializer); + let mut var_updatedAt = ::sse_decode(deserializer); + return crate::api::dto::PageDto { + id: var_id, + title: var_title, + journal_date: var_journalDate, + origin_journal: var_originJournal, + created_at: var_createdAt, + updated_at: var_updatedAt, + }; + } +} + +impl SseDecode for crate::api::dto::Place { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_kind = ::sse_decode(deserializer); + let mut var_anchor = >::sse_decode(deserializer); + return crate::api::dto::Place { + kind: var_kind, + anchor: var_anchor, + }; + } +} + +impl SseDecode for crate::api::dto::PlaceKind { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = ::sse_decode(deserializer); + return match inner { + 0 => crate::api::dto::PlaceKind::After, + 1 => crate::api::dto::PlaceKind::Before, + 2 => crate::api::dto::PlaceKind::LastChildOf, + 3 => crate::api::dto::PlaceKind::FirstChildOf, + _ => unreachable!("Invalid variant for PlaceKind: {}", inner), + }; + } +} + +impl SseDecode for (Option, Option) { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_field0 = >::sse_decode(deserializer); + let mut var_field1 = >::sse_decode(deserializer); + return (var_field0, var_field1); + } +} + +impl SseDecode for crate::api::dto::RelatedDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_page = ::sse_decode(deserializer); + let mut var_score = ::sse_decode(deserializer); + return crate::api::dto::RelatedDto { + page: var_page, + score: var_score, + }; + } +} + +impl SseDecode for crate::api::dto::TimelineDayDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_date = ::sse_decode(deserializer); + let mut var_journalId = >::sse_decode(deserializer); + let mut var_created = >::sse_decode(deserializer); + let mut var_edited = >::sse_decode(deserializer); + return crate::api::dto::TimelineDayDto { + date: var_date, + journal_id: var_journalId, + created: var_created, + edited: var_edited, + }; + } +} + +impl SseDecode for crate::api::dto::TimelineDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_days = >::sse_decode(deserializer); + let mut var_pages = >::sse_decode(deserializer); + return crate::api::dto::TimelineDto { + days: var_days, + pages: var_pages, + }; + } +} + +impl SseDecode for crate::api::dto::TitleHit { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_pageId = ::sse_decode(deserializer); + let mut var_title = ::sse_decode(deserializer); + let mut var_isAlias = ::sse_decode(deserializer); + return crate::api::dto::TitleHit { + page_id: var_pageId, + title: var_title, + is_alias: var_isAlias, + }; + } +} + +impl SseDecode for u32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u32::().unwrap() + } +} + +impl SseDecode for u64 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u64::().unwrap() + } +} + +impl SseDecode for u8 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u8().unwrap() + } +} + +impl SseDecode for () { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {} +} + +impl SseDecode for usize { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u64::().unwrap() as _ + } +} + +fn pde_ffi_dispatcher_primary_impl( + func_id: i32, + port: flutter_rust_bridge::for_generated::MessagePort, + ptr: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len: i32, + data_len: i32, +) { + // Codec=Pde (Serialization + dispatch), see doc to use other codecs + match func_id { + 1 => { + wire__crate__api__graph__SynapseGraph_add_alias_impl(port, ptr, rust_vec_len, data_len) + } + 2 => wire__crate__api__graph__SynapseGraph_aliases_impl(port, ptr, rust_vec_len, data_len), + 4 => { + wire__crate__api__graph__SynapseGraph_backlinks_impl(port, ptr, rust_vec_len, data_len) + } + 5 => { + wire__crate__api__graph__SynapseGraph_block_ref_impl(port, ptr, rust_vec_len, data_len) + } + 6 => wire__crate__api__graph__SynapseGraph_delete_block_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 7 => wire__crate__api__graph__SynapseGraph_delete_page_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 9 => wire__crate__api__graph__SynapseGraph_indent_block_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 10 => wire__crate__api__graph__SynapseGraph_insert_block_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 11 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len), + 12 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 13 => { + wire__crate__api__graph__SynapseGraph_journals_impl(port, ptr, rust_vec_len, data_len) + } + 14 => { + wire__crate__api__graph__SynapseGraph_list_pages_impl(port, ptr, rust_vec_len, data_len) + } + 15 => wire__crate__api__graph__SynapseGraph_merge_block_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 16 => { + wire__crate__api__graph__SynapseGraph_move_block_impl(port, ptr, rust_vec_len, data_len) + } + 17 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len), + 18 => { + wire__crate__api__graph__SynapseGraph_open_page_impl(port, ptr, rust_vec_len, data_len) + } + 19 => wire__crate__api__graph__SynapseGraph_outdent_block_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 20 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len), + 21 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len), + 22 => wire__crate__api__graph__SynapseGraph_page_by_title_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 23 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 24 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 25 => wire__crate__api__graph__SynapseGraph_record_visit_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 26 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len), + 27 => wire__crate__api__graph__SynapseGraph_remove_alias_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 28 => wire__crate__api__graph__SynapseGraph_rename_page_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 29 => wire__crate__api__graph__SynapseGraph_search_blocks_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 30 => wire__crate__api__graph__SynapseGraph_search_titles_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 31 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 32 => { + wire__crate__api__graph__SynapseGraph_timeline_impl(port, ptr, rust_vec_len, data_len) + } + 34 => wire__crate__api__graph__SynapseGraph_update_block_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + _ => unreachable!(), + } +} + +fn pde_ffi_dispatcher_sync_impl( + func_id: i32, + ptr: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len: i32, + data_len: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + // Codec=Pde (Serialization + dispatch), see doc to use other codecs + match func_id { + 3 => wire__crate__api__graph__SynapseGraph_asset_path_impl(ptr, rust_vec_len, data_len), + 8 => wire__crate__api__graph__SynapseGraph_dir_impl(ptr, rust_vec_len, data_len), + 33 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len), + _ => unreachable!(), + } +} + +// Section: rust2dart + +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for FrbWrapper { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + flutter_rust_bridge::for_generated::rust_auto_opaque_encode::<_, MoiArc<_>>(self.0) + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for FrbWrapper {} + +impl flutter_rust_bridge::IntoIntoDart> for SynapseGraph { + fn into_into_dart(self) -> FrbWrapper { + self.into() + } +} + +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::AssetDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.hash.into_into_dart().into_dart(), + self.size.into_into_dart().into_dart(), + self.mime.into_into_dart().into_dart(), + self.original_name.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::AssetDto {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::AssetDto { + fn into_into_dart(self) -> crate::api::dto::AssetDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::BacklinkGroup { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.page_id.into_into_dart().into_dart(), + self.page_title.into_into_dart().into_dart(), + self.is_journal.into_into_dart().into_dart(), + self.blocks.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::dto::BacklinkGroup +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::BacklinkGroup +{ + fn into_into_dart(self) -> crate::api::dto::BacklinkGroup { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::BlockDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.id.into_into_dart().into_dart(), + self.parent_id.into_into_dart().into_dart(), + self.depth.into_into_dart().into_dart(), + self.content.into_into_dart().into_dart(), + self.collapsed.into_into_dart().into_dart(), + self.has_children.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::BlockDto {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::BlockDto { + fn into_into_dart(self) -> crate::api::dto::BlockDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::BlockHit { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.id.into_into_dart().into_dart(), + self.content.into_into_dart().into_dart(), + self.page_title.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::BlockHit {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::BlockHit { + fn into_into_dart(self) -> crate::api::dto::BlockHit { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::BlockRefDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.id.into_into_dart().into_dart(), + self.content.into_into_dart().into_dart(), + self.page_id.into_into_dart().into_dart(), + self.page_title.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::BlockRefDto {} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::BlockRefDto +{ + fn into_into_dart(self) -> crate::api::dto::BlockRefDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::EditDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.page_id.into_into_dart().into_dart(), + self.edits.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::EditDto {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::EditDto { + fn into_into_dart(self) -> crate::api::dto::EditDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::PageBrief { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.id.into_into_dart().into_dart(), + self.title.into_into_dart().into_dart(), + self.is_journal.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::PageBrief {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::PageBrief { + fn into_into_dart(self) -> crate::api::dto::PageBrief { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::PageData { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.page.into_into_dart().into_dart(), + self.blocks.into_into_dart().into_dart(), + self.aliases.into_into_dart().into_dart(), + self.prev_journal.into_into_dart().into_dart(), + self.next_journal.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::PageData {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::PageData { + fn into_into_dart(self) -> crate::api::dto::PageData { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::PageDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.id.into_into_dart().into_dart(), + self.title.into_into_dart().into_dart(), + self.journal_date.into_into_dart().into_dart(), + self.origin_journal.into_into_dart().into_dart(), + self.created_at.into_into_dart().into_dart(), + self.updated_at.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::PageDto {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::PageDto { + fn into_into_dart(self) -> crate::api::dto::PageDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::Place { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.kind.into_into_dart().into_dart(), + self.anchor.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::Place {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::Place { + fn into_into_dart(self) -> crate::api::dto::Place { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::PlaceKind { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + match self { + Self::After => 0.into_dart(), + Self::Before => 1.into_dart(), + Self::LastChildOf => 2.into_dart(), + Self::FirstChildOf => 3.into_dart(), + _ => unreachable!(), + } + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::PlaceKind {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::PlaceKind { + fn into_into_dart(self) -> crate::api::dto::PlaceKind { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::RelatedDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.page.into_into_dart().into_dart(), + self.score.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::RelatedDto {} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::RelatedDto +{ + fn into_into_dart(self) -> crate::api::dto::RelatedDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::TimelineDayDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.date.into_into_dart().into_dart(), + self.journal_id.into_into_dart().into_dart(), + self.created.into_into_dart().into_dart(), + self.edited.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::dto::TimelineDayDto +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::TimelineDayDto +{ + fn into_into_dart(self) -> crate::api::dto::TimelineDayDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::TimelineDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.days.into_into_dart().into_dart(), + self.pages.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::TimelineDto {} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::TimelineDto +{ + fn into_into_dart(self) -> crate::api::dto::TimelineDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::TitleHit { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.page_id.into_into_dart().into_dart(), + self.title.into_into_dart().into_dart(), + self.is_alias.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::TitleHit {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::TitleHit { + fn into_into_dart(self) -> crate::api::dto::TitleHit { + self + } +} + +impl SseEncode for flutter_rust_bridge::for_generated::anyhow::Error { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(format!("{:?}", self), serializer); + } +} + +impl SseEncode for SynapseGraph { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + >>::sse_encode(flutter_rust_bridge::for_generated::rust_auto_opaque_encode::<_, MoiArc<_>>(self), serializer); + } +} + +impl SseEncode + for RustOpaqueMoi> +{ + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + let (ptr, size) = self.sse_encode_raw(); + ::sse_encode(ptr, serializer); + ::sse_encode(size, serializer); + } +} + +impl SseEncode for String { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + >::sse_encode(self.into_bytes(), serializer); + } +} + +impl SseEncode for crate::api::dto::AssetDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.hash, serializer); + ::sse_encode(self.size, serializer); + >::sse_encode(self.mime, serializer); + >::sse_encode(self.original_name, serializer); + } +} + +impl SseEncode for crate::api::dto::BacklinkGroup { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.page_id, serializer); + ::sse_encode(self.page_title, serializer); + ::sse_encode(self.is_journal, serializer); + >::sse_encode(self.blocks, serializer); + } +} + +impl SseEncode for crate::api::dto::BlockDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.id, serializer); + >::sse_encode(self.parent_id, serializer); + ::sse_encode(self.depth, serializer); + ::sse_encode(self.content, serializer); + ::sse_encode(self.collapsed, serializer); + ::sse_encode(self.has_children, serializer); + } +} + +impl SseEncode for crate::api::dto::BlockHit { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.id, serializer); + ::sse_encode(self.content, serializer); + ::sse_encode(self.page_title, serializer); + } +} + +impl SseEncode for crate::api::dto::BlockRefDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.id, serializer); + ::sse_encode(self.content, serializer); + ::sse_encode(self.page_id, serializer); + ::sse_encode(self.page_title, serializer); + } +} + +impl SseEncode for bool { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u8(self as _).unwrap(); + } +} + +impl SseEncode for crate::api::dto::EditDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.page_id, serializer); + ::sse_encode(self.edits, serializer); + } +} + +impl SseEncode for f32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_f32::(self).unwrap(); + } +} + +impl SseEncode for i32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_i32::(self).unwrap(); + } +} + +impl SseEncode for i64 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_i64::(self).unwrap(); + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for crate::api::dto::PageBrief { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.id, serializer); + ::sse_encode(self.title, serializer); + ::sse_encode(self.is_journal, serializer); + } +} + +impl SseEncode for crate::api::dto::PageData { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.page, serializer); + >::sse_encode(self.blocks, serializer); + >::sse_encode(self.aliases, serializer); + >::sse_encode(self.prev_journal, serializer); + >::sse_encode(self.next_journal, serializer); + } +} + +impl SseEncode for crate::api::dto::PageDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.id, serializer); + ::sse_encode(self.title, serializer); + >::sse_encode(self.journal_date, serializer); + >::sse_encode(self.origin_journal, serializer); + ::sse_encode(self.created_at, serializer); + ::sse_encode(self.updated_at, serializer); + } +} + +impl SseEncode for crate::api::dto::Place { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.kind, serializer); + >::sse_encode(self.anchor, serializer); + } +} + +impl SseEncode for crate::api::dto::PlaceKind { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode( + match self { + crate::api::dto::PlaceKind::After => 0, + crate::api::dto::PlaceKind::Before => 1, + crate::api::dto::PlaceKind::LastChildOf => 2, + crate::api::dto::PlaceKind::FirstChildOf => 3, + _ => { + unimplemented!(""); + } + }, + serializer, + ); + } +} + +impl SseEncode for (Option, Option) { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + >::sse_encode(self.0, serializer); + >::sse_encode(self.1, serializer); + } +} + +impl SseEncode for crate::api::dto::RelatedDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.page, serializer); + ::sse_encode(self.score, serializer); + } +} + +impl SseEncode for crate::api::dto::TimelineDayDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.date, serializer); + >::sse_encode(self.journal_id, serializer); + >::sse_encode(self.created, serializer); + >::sse_encode(self.edited, serializer); + } +} + +impl SseEncode for crate::api::dto::TimelineDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + >::sse_encode(self.days, serializer); + >::sse_encode(self.pages, serializer); + } +} + +impl SseEncode for crate::api::dto::TitleHit { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.page_id, serializer); + ::sse_encode(self.title, serializer); + ::sse_encode(self.is_alias, serializer); + } +} + +impl SseEncode for u32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u32::(self).unwrap(); + } +} + +impl SseEncode for u64 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u64::(self).unwrap(); + } +} + +impl SseEncode for u8 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u8(self).unwrap(); + } +} + +impl SseEncode for () { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {} +} + +impl SseEncode for usize { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer + .cursor + .write_u64::(self as _) + .unwrap(); + } +} + +#[cfg(not(target_family = "wasm"))] +mod io { + // This file is automatically generated, so please do not edit it. + // @generated by `flutter_rust_bridge`@ 2.13.0. + + // Section: imports + + use super::*; + use crate::api::graph::*; + use flutter_rust_bridge::for_generated::byteorder::{ + NativeEndian, ReadBytesExt, WriteBytesExt, + }; + use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; + use flutter_rust_bridge::{Handler, IntoIntoDart}; + + // Section: boilerplate + + flutter_rust_bridge::frb_generated_boilerplate_io!(); + + #[unsafe(no_mangle)] + pub extern "C" fn frbgen_synapse_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ptr: *const std::ffi::c_void, + ) { + MoiArc::>::increment_strong_count(ptr as _); + } + + #[unsafe(no_mangle)] + pub extern "C" fn frbgen_synapse_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ptr: *const std::ffi::c_void, + ) { + MoiArc::>::decrement_strong_count(ptr as _); + } +} +#[cfg(not(target_family = "wasm"))] +pub use io::*; + +/// cbindgen:ignore +#[cfg(target_family = "wasm")] +mod web { + // This file is automatically generated, so please do not edit it. + // @generated by `flutter_rust_bridge`@ 2.13.0. + + // Section: imports + + use super::*; + use crate::api::graph::*; + use flutter_rust_bridge::for_generated::byteorder::{ + NativeEndian, ReadBytesExt, WriteBytesExt, + }; + use flutter_rust_bridge::for_generated::wasm_bindgen; + use flutter_rust_bridge::for_generated::wasm_bindgen::prelude::*; + use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; + use flutter_rust_bridge::{Handler, IntoIntoDart}; + + // Section: boilerplate + + flutter_rust_bridge::frb_generated_boilerplate_web!(); + + #[wasm_bindgen] + pub fn rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ptr: *const std::ffi::c_void, + ) { + MoiArc::>::increment_strong_count(ptr as _); + } + + #[wasm_bindgen] + pub fn rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + ptr: *const std::ffi::c_void, + ) { + MoiArc::>::decrement_strong_count(ptr as _); + } +} +#[cfg(target_family = "wasm")] +pub use web::*; diff --git a/crates/synapse-ffi/src/lib.rs b/crates/synapse-ffi/src/lib.rs new file mode 100644 index 0000000..16e49ad --- /dev/null +++ b/crates/synapse-ffi/src/lib.rs @@ -0,0 +1,7 @@ +//! FFI surface of Synapse for the Flutter app (flutter_rust_bridge v2). The app never touches +//! storage directly: everything goes through [`api`]. Bindings are generated from `api` with +//! `cd app && flutter_rust_bridge_codegen generate`. + +pub mod api; +#[rustfmt::skip] +mod frb_generated; diff --git a/crates/synapse-ffi/tests/api.rs b/crates/synapse-ffi/tests/api.rs new file mode 100644 index 0000000..a27c683 --- /dev/null +++ b/crates/synapse-ffi/tests/api.rs @@ -0,0 +1,187 @@ +use synapse_ffi::api::dto::{BlockDto, Place, PlaceKind}; +use synapse_ffi::api::graph::SynapseGraph; + +fn open() -> (tempfile::TempDir, SynapseGraph) { + let dir = tempfile::tempdir().unwrap(); + let g = SynapseGraph::open(dir.path().to_string_lossy().into_owned()).unwrap(); + (dir, g) +} + +fn place(kind: PlaceKind, anchor: Option<&str>) -> Place { + Place { + kind, + anchor: anchor.map(str::to_string), + } +} + +/// `(depth, content)` rows for compact assertions. +fn shape(rows: &[BlockDto]) -> Vec<(u32, &str)> { + rows.iter().map(|b| (b.depth, b.content.as_str())).collect() +} + +fn page_with(g: &SynapseGraph, title: &str, lines: &[&str]) -> (String, Vec) { + let page = g.open_page(title.into()).unwrap().page.id; + let mut ids = Vec::new(); + for l in lines { + let b = g + .insert_block( + page.clone(), + place(PlaceKind::LastChildOf, None), + (*l).into(), + ) + .unwrap(); + ids.push(b.id); + } + (page, ids) +} + +#[test] +fn indent_and_outdent_keep_visual_order() { + let (_d, g) = open(); + let (_, ids) = page_with(&g, "P", &["a", "b", "c", "d"]); + g.indent_block(ids[1].clone()).unwrap(); + g.indent_block(ids[2].clone()).unwrap(); + let rows = g.indent_block(ids[3].clone()).unwrap(); + assert_eq!(shape(&rows), vec![(0, "a"), (1, "b"), (1, "c"), (1, "d")]); + assert!(rows[0].has_children); + + // Outdenting `c` adopts `d` as its child (Logseq's direct outdenting). + let rows = g.outdent_block(ids[2].clone()).unwrap(); + assert_eq!(shape(&rows), vec![(0, "a"), (1, "b"), (0, "c"), (1, "d")]); + + // A first child cannot be indented; a root block cannot be outdented. + let rows = g.indent_block(ids[1].clone()).unwrap(); + assert_eq!(shape(&rows), vec![(0, "a"), (1, "b"), (0, "c"), (1, "d")]); + let rows = g.outdent_block(ids[0].clone()).unwrap(); + assert_eq!(rows.len(), 4); +} + +#[test] +fn merge_appends_text_and_adopts_children() { + let (_d, g) = open(); + let (page, ids) = page_with(&g, "P", &["hello ", "world", "x"]); + g.indent_block(ids[2].clone()).unwrap(); + let rows = g.merge_block(ids[1].clone(), ids[0].clone()).unwrap(); + assert_eq!(shape(&rows), vec![(0, "hello world"), (1, "x")]); + assert_eq!(g.outline(page).unwrap().len(), 2); +} + +#[test] +fn merging_a_first_child_into_its_parent_keeps_grandchildren_in_place() { + let (_d, g) = open(); + let (_, ids) = page_with(&g, "P", &["p", "c", "gc", "s"]); + g.indent_block(ids[1].clone()).unwrap(); + g.indent_block(ids[2].clone()).unwrap(); + g.indent_block(ids[2].clone()).unwrap(); + g.indent_block(ids[3].clone()).unwrap(); + // p > c > gc, p > s + let rows = g.merge_block(ids[1].clone(), ids[0].clone()).unwrap(); + assert_eq!(shape(&rows), vec![(0, "pc"), (1, "gc"), (1, "s")]); +} + +#[test] +fn insert_first_child_and_move() { + let (_d, g) = open(); + let (page, ids) = page_with(&g, "P", &["a", "b"]); + g.insert_block( + page.clone(), + place(PlaceKind::FirstChildOf, Some(&ids[0])), + "a1".into(), + ) + .unwrap(); + g.insert_block( + page.clone(), + place(PlaceKind::FirstChildOf, Some(&ids[0])), + "a0".into(), + ) + .unwrap(); + let rows = g + .move_block( + ids[1].clone(), + page, + place(PlaceKind::Before, Some(&ids[0])), + ) + .unwrap(); + assert_eq!(shape(&rows), vec![(0, "b"), (0, "a"), (1, "a0"), (1, "a1")]); +} + +#[test] +fn journals_feed_starts_today_and_walks_back() { + let (_d, g) = open(); + for d in ["2024-01-01", "2024-01-03", "2024-02-10"] { + g.journal(d.into()).unwrap(); + } + let feed = g.journals(None, 3).unwrap(); + assert_eq!( + feed[0].page.journal_date.as_deref(), + Some(g.today().as_str()) + ); + assert_eq!(feed[1].page.title, "2024-02-10"); + assert_eq!(feed[2].page.title, "2024-01-03"); + assert_eq!(feed[2].prev_journal.as_deref(), Some("2024-01-01")); + let more = g.journals(Some("2024-01-03".into()), 10).unwrap(); + assert_eq!(more.len(), 1); + assert_eq!(more[0].page.title, "2024-01-01"); +} + +#[test] +fn links_backlinks_search_and_timeline() { + let (_d, g) = open(); + let j = g.journal(g.today()).unwrap(); + let jb = g + .insert_block( + j.page.id.clone(), + place(PlaceKind::LastChildOf, None), + "met [[Rust Lang]] and #ideas".into(), + ) + .unwrap(); + let rust = g.page_by_title("rust lang".into()).unwrap().unwrap(); + assert_eq!( + rust.page.origin_journal.as_deref(), + Some(g.today().as_str()) + ); + + let groups = g.backlinks(rust.page.id.clone()).unwrap(); + assert_eq!(groups.len(), 1); + assert!(groups[0].is_journal); + assert_eq!(groups[0].blocks[0].id, jb.id); + + g.add_alias(rust.page.id.clone(), "Ferris".into()).unwrap(); + let hits = g.search_titles("fer".into(), 10).unwrap(); + assert_eq!(hits[0].page_id, rust.page.id); + assert!(hits[0].is_alias); + let hits = g.search_titles("lang".into(), 10).unwrap(); + assert_eq!(hits[0].title, "Rust Lang"); + + let blocks = g.search_blocks("#ideas".into(), 10).unwrap(); + assert_eq!(blocks.len(), 1); + assert!(g.search_blocks("100%".into(), 10).unwrap().is_empty()); + + let r = g.block_ref(jb.id.clone()).unwrap().unwrap(); + assert_eq!(r.page_title, g.today()); + + let t = g.timeline(g.today(), g.today()).unwrap(); + assert_eq!(t.days.len(), 1); + assert!(t.days[0].created.contains(&rust.page.id)); + assert!(t.pages.iter().any(|p| p.title == "ideas")); + + g.record_visit(Some(j.page.id.clone()), rust.page.id.clone()) + .unwrap(); + let related = g.related(j.page.id, 5).unwrap(); + assert!(related.iter().any(|r| r.page.id == rust.page.id)); +} + +#[test] +fn assets_round_trip() { + let (_d, g) = open(); + let a = g + .put_asset_bytes( + b"png".to_vec(), + Some("x.png".into()), + Some("image/png".into()), + ) + .unwrap(); + let path = g.asset_path(a.hash.clone()).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), b"png"); + assert!(g.asset_path("zz".into()).is_none()); +} diff --git a/docs/README.md b/docs/README.md index 77b56e4..0dc4bf5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,4 +2,5 @@ - [plan.md](plan.md): product scope and roadmap. - [architecture.md](architecture.md): crates, data model, storage and sync design. +- [app.md](app.md): Flutter app and FFI: build/run per platform, editor behaviour. - [server.md](server.md): running and deploying the sync server. diff --git a/docs/app.md b/docs/app.md new file mode 100644 index 0000000..9a40845 --- /dev/null +++ b/docs/app.md @@ -0,0 +1,62 @@ +# App (Flutter) and FFI + +## Layout +- `crates/synapse-ffi`: the only API the app sees. `src/api/` is scanned by + `flutter_rust_bridge` (v2.13): `graph.rs` (opaque `SynapseGraph` handle, reads), `outline.rs` + (block editing), `search.rs` (title/block lookup until `synapse-search` is wired), `dto.rs`. + Extension points for search/AI/history/CalDAV/sync are documented in `src/api/mod.rs`. +- `app/`: Flutter client. `lib/src/rust/` is generated; `rust_builder/` is the cargokit glue + that builds `synapse-ffi` as part of `flutter build`/`run` (paths point at + `../crates/synapse-ffi`). +- `app/lib/src/`: `backend/` (`GraphBackend` interface + FFI implementation), `state/` + (app state, write queue, outline controller and algorithms), `editor/` (block row, editor, + Markdown renderer, autocomplete), `views/` (journals, page, timeline, all pages, quick + switcher, shell), `theme/`. + +## Toolchain +- Flutter stable (3.47+) on `PATH`, Rust stable, `cargo install flutter_rust_bridge_codegen + --version 2.13.0 --locked`. +- Linux desktop: `clang cmake ninja-build gtk3-devel` (Fedora) / `clang cmake ninja-build + libgtk-3-dev` (Debian/Ubuntu). +- Android: Android SDK + NDK (cargokit installs the Rust targets with rustup). +- Windows: Visual Studio 2022 with "Desktop development with C++", Rust MSVC toolchain. + +## Build and run +```bash +cd app +flutter run -d linux # debug, builds the Rust crate via cargokit +flutter build linux --release # build/linux/x64/release/bundle/ +flutter run -d # or: flutter build apk --release +flutter build windows --release # on Windows +``` +The graph lives in the platform app-support dir (`~/.local/share/es.zenvairo.synapse/graph` +on Linux). Override it with `SYNAPSE_GRAPH=/path/to/graph`. + +## After changing the FFI API +```bash +cd app && flutter_rust_bridge_codegen generate +``` +Commit the regenerated `crates/synapse-ffi/src/frb_generated.rs` and `app/lib/src/rust/`. +`frb_generated.rs` is excluded from rustfmt. + +## Checks +- `cargo test -p synapse-ffi` (outline semantics against the real core). +- `cd app && dart analyze && flutter test` (editor key handling runs against an in-memory + backend that reuses the Dart outline algorithms). +- `flutter analyze` crashes when the project path contains non-ASCII characters (its LSP + channel miscounts bytes); `dart analyze` runs the same analysis. + +## Editor +- Blocks render Markdown when idle and become raw-Markdown text fields when focused. +- Keys: Enter split (at start: new block above), Shift+Enter newline, Tab/Shift+Tab + indent/outdent (Logseq's direct outdenting), Backspace at start merges into the previous + block, Delete at end pulls the next one in, ↑/↓/←/→ cross block edges, Alt+Shift+↑/↓ move + among siblings, Ctrl+↑/↓ collapse/expand, Ctrl+Enter cycles TODO/DONE, Esc leaves editing. +- `[[`, `((` auto-pair; `[[`, `#` and `((` open autocomplete (↑/↓, Enter/Tab, Esc). +- Drag a bullet onto a row: upper half = before, lower half = after, lower half to the right + = first child. +- Edits apply locally at once and go to the core through one serial write queue (text saves + are debounced 350 ms); after structural edits the outline is re-read and the core's + structure wins if they ever disagree. +- App shortcuts: Ctrl+K quick switcher, Ctrl+Shift+J journals, Ctrl+Shift+T timeline, + Ctrl+\ sidebar, Alt+←/→ back/forward.