mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
feat(app): Flutter outliner with journals, page view and timeline
Logseq-like outliner (render/edit Markdown per block, Enter/Tab/Shift-Tab, backspace merge, arrow navigation, drag to reorder, collapse, [[ # (( autocomplete, TODO/DONE), journals feed with prev/next links, page view with linked references and related panel, virtualised CustomPainter timeline, Ctrl+K quick switcher, sidebar with recents, light/dark theme with bundled Inter, Noto Serif and Source Code Pro. Edits are optimistic and serialised to the core through one write queue. Cargokit builds synapse-ffi; its build tool is patched to use the library name (synapse_ffi) of hyphenated crates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c3d6636606
commit
df42d4010f
135 files changed
+17689
No files matched your search
@@ -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/
|
||||
@@ -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'
|
||||
@@ -0,0 +1,9 @@
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
analyzer:
|
||||
exclude:
|
||||
- build/**
|
||||
- android/**
|
||||
- windows/**
|
||||
- linux/**
|
||||
- rust_builder/cargokit/**
|
||||
@@ -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
|
||||
@@ -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 = "../.."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- The INTERNET permission is required for development. Specifically,
|
||||
the Flutter tool needs it to communicate with the running application
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
</manifest>
|
||||
@@ -0,0 +1,45 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application
|
||||
android:label="synapse"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/ic_launcher">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/LaunchTheme"
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
|
||||
android:hardwareAccelerated="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<!-- Specifies an Android theme to apply to this Activity as soon as
|
||||
the Android process has started. This theme is visible to the user
|
||||
while the Flutter UI initializes. After that, this theme continues
|
||||
to determine the Window background behind the Flutter UI. -->
|
||||
<meta-data
|
||||
android:name="io.flutter.embedding.android.NormalTheme"
|
||||
android:resource="@style/NormalTheme"
|
||||
/>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<!-- Don't delete the meta-data below.
|
||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||
<meta-data
|
||||
android:name="flutterEmbedding"
|
||||
android:value="2" />
|
||||
</application>
|
||||
<!-- Required to query activities that can process text, see:
|
||||
https://developer.android.com/training/package-visibility and
|
||||
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
|
||||
|
||||
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.PROCESS_TEXT"/>
|
||||
<data android:mimeType="text/plain"/>
|
||||
</intent>
|
||||
</queries>
|
||||
</manifest>
|
||||
@@ -0,0 +1,5 @@
|
||||
package es.zenvairo.synapse
|
||||
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
|
||||
class MainActivity : FlutterActivity()
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="?android:colorBackground" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
<bitmap
|
||||
android:gravity="center"
|
||||
android:src="@mipmap/launch_image" />
|
||||
</item> -->
|
||||
</layer-list>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="@android:color/white" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
<bitmap
|
||||
android:gravity="center"
|
||||
android:src="@mipmap/launch_image" />
|
||||
</item> -->
|
||||
</layer-list>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 544 B |
Binary file not shown.
|
After Width: | Height: | Size: 442 B |
Binary file not shown.
|
After Width: | Height: | Size: 721 B |
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<!-- Show a splash screen on the activity. Automatically removed when
|
||||
the Flutter engine draws its first frame -->
|
||||
<item name="android:windowBackground">@drawable/launch_background</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
Flutter UI initializes, as well as behind your Flutter UI while its
|
||||
running.
|
||||
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">?android:colorBackground</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<!-- Show a splash screen on the activity. Automatically removed when
|
||||
the Flutter engine draws its first frame -->
|
||||
<item name="android:windowBackground">@drawable/launch_background</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
Flutter UI initializes, as well as behind your Flutter UI while its
|
||||
running.
|
||||
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">?android:colorBackground</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- The INTERNET permission is required for development. Specifically,
|
||||
the Flutter tool needs it to communicate with the running application
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
</manifest>
|
||||
@@ -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<Delete>("clean") {
|
||||
delete(rootProject.layout.buildDirectory)
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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")
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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.
|
||||
Binary file not shown.
Binary file not shown.
@@ -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.
|
||||
Binary file not shown.
@@ -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.
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
rust_input: crate::api
|
||||
rust_root: ../crates/synapse-ffi/
|
||||
dart_output: lib/src/rust
|
||||
@@ -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<void> 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));
|
||||
}
|
||||
@@ -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<SynapseApp> createState() => _SynapseAppState();
|
||||
}
|
||||
|
||||
class _SynapseAppState extends State<SynapseApp> {
|
||||
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(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<List<PageData>> journals({String? before, required int limit});
|
||||
Future<PageData> journal(String date);
|
||||
Future<PageData?> page(String id);
|
||||
Future<PageData?> pageByTitle(String title);
|
||||
|
||||
/// Page by title or alias, created if missing.
|
||||
Future<PageData> openPage(String title);
|
||||
Future<List<PageDto>> listPages({
|
||||
bool includeJournals = false,
|
||||
required int limit,
|
||||
int offset = 0,
|
||||
});
|
||||
Future<PageDto> renamePage(String id, String newTitle);
|
||||
Future<void> deletePage(String id);
|
||||
Future<void> addAlias(String pageId, String alias);
|
||||
Future<void> removeAlias(String alias);
|
||||
|
||||
Future<BlockDto> insertBlock(String pageId, Place place, String content);
|
||||
Future<void> updateBlock(String id, String content);
|
||||
Future<void> setCollapsed(String id, bool collapsed);
|
||||
Future<List<BlockDto>> deleteBlock(String id);
|
||||
Future<List<BlockDto>> moveBlock(String id, String pageId, Place place);
|
||||
Future<List<BlockDto>> indentBlock(String id);
|
||||
Future<List<BlockDto>> outdentBlock(String id);
|
||||
Future<List<BlockDto>> mergeBlock(String id, String into);
|
||||
Future<List<BlockDto>> outline(String pageId);
|
||||
|
||||
Future<List<BacklinkGroup>> backlinks(String pageId);
|
||||
Future<List<RelatedDto>> related(String pageId, {int limit = 12});
|
||||
Future<void> recordVisit(String? from, String to);
|
||||
Future<BlockRefDto?> blockRef(String id);
|
||||
Future<TimelineDto> timeline(String from, String to);
|
||||
|
||||
Future<List<TitleHit>> searchTitles(String query, {int limit = 20});
|
||||
Future<List<BlockHit>> searchBlocks(String query, {int limit = 20});
|
||||
|
||||
/// Local path of an `asset://<hash>` blob, if present.
|
||||
String? assetPath(String hash);
|
||||
Future<AssetDto> putAssetFile(String path, {String? mime});
|
||||
}
|
||||
|
||||
class FfiGraphBackend implements GraphBackend {
|
||||
FfiGraphBackend(this._g);
|
||||
|
||||
final SynapseGraph _g;
|
||||
|
||||
static Future<FfiGraphBackend> open(String dir) async =>
|
||||
FfiGraphBackend(await SynapseGraph.open(dir: dir));
|
||||
|
||||
@override
|
||||
String today() => _g.today();
|
||||
|
||||
@override
|
||||
Future<List<PageData>> journals({String? before, required int limit}) =>
|
||||
_g.journals(before: before, limit: limit);
|
||||
@override
|
||||
Future<PageData> journal(String date) => _g.journal(date: date);
|
||||
@override
|
||||
Future<PageData?> page(String id) => _g.page(id: id);
|
||||
@override
|
||||
Future<PageData?> pageByTitle(String title) => _g.pageByTitle(title: title);
|
||||
@override
|
||||
Future<PageData> openPage(String title) => _g.openPage(title: title);
|
||||
@override
|
||||
Future<List<PageDto>> listPages({
|
||||
bool includeJournals = false,
|
||||
required int limit,
|
||||
int offset = 0,
|
||||
}) => _g.listPages(
|
||||
includeJournals: includeJournals,
|
||||
limit: limit,
|
||||
offset: offset,
|
||||
);
|
||||
@override
|
||||
Future<PageDto> renamePage(String id, String newTitle) =>
|
||||
_g.renamePage(id: id, newTitle: newTitle);
|
||||
@override
|
||||
Future<void> deletePage(String id) => _g.deletePage(id: id);
|
||||
@override
|
||||
Future<void> addAlias(String pageId, String alias) =>
|
||||
_g.addAlias(pageId: pageId, alias: alias);
|
||||
@override
|
||||
Future<void> removeAlias(String alias) => _g.removeAlias(alias: alias);
|
||||
|
||||
@override
|
||||
Future<BlockDto> insertBlock(String pageId, Place place, String content) =>
|
||||
_g.insertBlock(pageId: pageId, place: place, content: content);
|
||||
@override
|
||||
Future<void> updateBlock(String id, String content) =>
|
||||
_g.updateBlock(id: id, content: content);
|
||||
@override
|
||||
Future<void> setCollapsed(String id, bool collapsed) =>
|
||||
_g.setCollapsed(id: id, collapsed: collapsed);
|
||||
@override
|
||||
Future<List<BlockDto>> deleteBlock(String id) => _g.deleteBlock(id: id);
|
||||
@override
|
||||
Future<List<BlockDto>> moveBlock(String id, String pageId, Place place) =>
|
||||
_g.moveBlock(id: id, pageId: pageId, place: place);
|
||||
@override
|
||||
Future<List<BlockDto>> indentBlock(String id) => _g.indentBlock(id: id);
|
||||
@override
|
||||
Future<List<BlockDto>> outdentBlock(String id) => _g.outdentBlock(id: id);
|
||||
@override
|
||||
Future<List<BlockDto>> mergeBlock(String id, String into) =>
|
||||
_g.mergeBlock(id: id, into: into);
|
||||
@override
|
||||
Future<List<BlockDto>> outline(String pageId) => _g.outline(pageId: pageId);
|
||||
|
||||
@override
|
||||
Future<List<BacklinkGroup>> backlinks(String pageId) =>
|
||||
_g.backlinks(pageId: pageId);
|
||||
@override
|
||||
Future<List<RelatedDto>> related(String pageId, {int limit = 12}) =>
|
||||
_g.related(pageId: pageId, limit: limit);
|
||||
@override
|
||||
Future<void> recordVisit(String? from, String to) =>
|
||||
_g.recordVisit(from: from, to: to);
|
||||
@override
|
||||
Future<BlockRefDto?> blockRef(String id) => _g.blockRef(id: id);
|
||||
@override
|
||||
Future<TimelineDto> timeline(String from, String to) =>
|
||||
_g.timeline(from: from, to: to);
|
||||
|
||||
@override
|
||||
Future<List<TitleHit>> searchTitles(String query, {int limit = 20}) =>
|
||||
_g.searchTitles(query: query, limit: limit);
|
||||
@override
|
||||
Future<List<BlockHit>> searchBlocks(String query, {int limit = 20}) =>
|
||||
_g.searchBlocks(query: query, limit: limit);
|
||||
|
||||
@override
|
||||
String? assetPath(String hash) => _g.assetPath(hash: hash);
|
||||
@override
|
||||
Future<AssetDto> putAssetFile(String path, {String? mime}) =>
|
||||
_g.putAssetFile(path: path, mime: mime);
|
||||
}
|
||||
@@ -0,0 +1,875 @@
|
||||
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<BlockRow> createState() => _BlockRowState();
|
||||
}
|
||||
|
||||
class _BlockRowState extends State<BlockRow> {
|
||||
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<BlockDrag>(
|
||||
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<BlockDrag>(
|
||||
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 {
|
||||
d = 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<BlockView> createState() => _BlockViewState();
|
||||
}
|
||||
|
||||
class _BlockViewState extends State<BlockView> {
|
||||
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<BlockEditor> createState() => _BlockEditorState();
|
||||
}
|
||||
|
||||
class _BlockEditorState extends State<BlockEditor> {
|
||||
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<CompletionItem> _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<List<CompletionItem>> 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,
|
||||
_text.selection.baseOffset,
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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<CompletionItem> 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),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
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` with the caret at `caret`.
|
||||
TextEditingValue applyCompletion(
|
||||
String text,
|
||||
int caret,
|
||||
CompletionQuery q,
|
||||
CompletionItem item,
|
||||
) {
|
||||
final head = text.substring(0, q.start);
|
||||
var tail = text.substring(caret);
|
||||
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),
|
||||
);
|
||||
}
|
||||
@@ -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<SourceRun> runs;
|
||||
final List<GestureRecognizer> 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 = <InlineSpan>[];
|
||||
final _runs = <SourceRun>[];
|
||||
final _recognizers = <GestureRecognizer>[];
|
||||
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;
|
||||
}
|
||||
}
|
||||
// 
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 = <Object, int>{
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<BlockDto> 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<BlockDto> blocks;
|
||||
final List<String> 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<String> created;
|
||||
|
||||
/// Pages edited on this day.
|
||||
final List<EditDto> 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<TimelineDayDto> days;
|
||||
final List<PageBrief> 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;
|
||||
}
|
||||
@@ -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<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>>
|
||||
abstract class SynapseGraph implements RustOpaqueInterface {
|
||||
Future<void> addAlias({required String pageId, required String alias});
|
||||
|
||||
Future<List<String>> aliases({required String pageId});
|
||||
|
||||
/// Local file path of an asset (for `asset://<hash>` images), if present.
|
||||
String? assetPath({required String hash});
|
||||
|
||||
/// Linked references grouped by page (most recently edited first).
|
||||
Future<List<BacklinkGroup>> backlinks({required String pageId});
|
||||
|
||||
/// Target of a `((block ref))`.
|
||||
Future<BlockRefDto?> blockRef({required String id});
|
||||
|
||||
/// Deletes a block and its subtree.
|
||||
Future<List<BlockDto>> deleteBlock({required String id});
|
||||
|
||||
Future<void> 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<List<BlockDto>> indentBlock({required String id});
|
||||
|
||||
Future<BlockDto> insertBlock({
|
||||
required String pageId,
|
||||
required Place place,
|
||||
required String content,
|
||||
});
|
||||
|
||||
/// The journal of `date` (created if missing).
|
||||
Future<PageData> 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<List<PageData>> journals({String? before, required int limit});
|
||||
|
||||
/// Pages ordered by last update, most recent first.
|
||||
Future<List<PageDto>> 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<List<BlockDto>> mergeBlock({required String id, required String into});
|
||||
|
||||
/// Moves a block with its subtree (drag and drop), possibly to another page.
|
||||
Future<List<BlockDto>> moveBlock({
|
||||
required String id,
|
||||
required String pageId,
|
||||
required Place place,
|
||||
});
|
||||
|
||||
/// Opens (or creates) the graph stored in `dir`.
|
||||
static Future<SynapseGraph> 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<PageData> 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<List<BlockDto>> outdentBlock({required String id});
|
||||
|
||||
/// Current outline of a page.
|
||||
Future<List<BlockDto>> outline({required String pageId});
|
||||
|
||||
Future<PageData?> page({required String id});
|
||||
|
||||
/// Page by title or alias, without creating it.
|
||||
Future<PageData?> pageByTitle({required String title});
|
||||
|
||||
/// Stores in-memory bytes (clipboard, Android content URIs).
|
||||
Future<AssetDto> putAssetBytes({
|
||||
required List<int> bytes,
|
||||
String? name,
|
||||
String? mime,
|
||||
});
|
||||
|
||||
/// Copies a file into the blob store (streamed).
|
||||
Future<AssetDto> putAssetFile({required String path, String? mime});
|
||||
|
||||
/// Records navigation between pages (strengthens their synapse).
|
||||
Future<void> recordVisit({String? from, required String to});
|
||||
|
||||
/// Notes related to `page_id` by spreading activation.
|
||||
Future<List<RelatedDto>> related({
|
||||
required String pageId,
|
||||
required int limit,
|
||||
});
|
||||
|
||||
Future<void> removeAlias({required String alias});
|
||||
|
||||
Future<PageDto> renamePage({required String id, required String newTitle});
|
||||
|
||||
/// Blocks whose text contains `query` (for `((` autocomplete), most recent first.
|
||||
Future<List<BlockHit>> 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<List<TitleHit>> searchTitles({
|
||||
required String query,
|
||||
required int limit,
|
||||
});
|
||||
|
||||
Future<void> setCollapsed({required String id, required bool collapsed});
|
||||
|
||||
/// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions.
|
||||
Future<TimelineDto> 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<void> updateBlock({required String id, required String content});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<RustLibWire> {
|
||||
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<String> dco_decode_list_String(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<BacklinkGroup> dco_decode_list_backlink_group(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<BlockDto> dco_decode_list_block_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<BlockHit> dco_decode_list_block_hit(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<EditDto> dco_decode_list_edit_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<PageData> dco_decode_list_page_data(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<PageDto> dco_decode_list_page_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<int> dco_decode_list_prim_u_8_loose(dynamic raw);
|
||||
|
||||
@protected
|
||||
Uint8List dco_decode_list_prim_u_8_strict(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<RelatedDto> dco_decode_list_related_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<TimelineDayDto> dco_decode_list_timeline_day_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<TitleHit> 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<String> sse_decode_list_String(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<BacklinkGroup> sse_decode_list_backlink_group(
|
||||
SseDeserializer deserializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
List<BlockDto> sse_decode_list_block_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<BlockHit> sse_decode_list_block_hit(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<EditDto> sse_decode_list_edit_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<PageData> sse_decode_list_page_data(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<PageDto> sse_decode_list_page_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<int> sse_decode_list_prim_u_8_loose(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<RelatedDto> sse_decode_list_related_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<TimelineDayDto> sse_decode_list_timeline_day_dto(
|
||||
SseDeserializer deserializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
List<TitleHit> 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<String> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_backlink_group(
|
||||
List<BacklinkGroup> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_block_dto(List<BlockDto> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_block_hit(List<BlockHit> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_edit_dto(List<EditDto> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_page_brief(
|
||||
List<PageBrief> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_page_data(List<PageData> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_page_dto(List<PageDto> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_prim_u_8_loose(List<int> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_prim_u_8_strict(
|
||||
Uint8List self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_related_dto(
|
||||
List<RelatedDto> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_timeline_day_dto(
|
||||
List<TimelineDayDto> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_title_hit(List<TitleHit> 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<T> Function<T extends ffi.NativeType>(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<ffi.Void> 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<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Void>)>>(
|
||||
'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 Function(ffi.Pointer<ffi.Void>)>();
|
||||
|
||||
void
|
||||
rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
|
||||
ffi.Pointer<ffi.Void> 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<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Void>)>>(
|
||||
'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<void Function(ffi.Pointer<ffi.Void>)>();
|
||||
}
|
||||
@@ -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<RustLibWire> {
|
||||
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<String> dco_decode_list_String(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<BacklinkGroup> dco_decode_list_backlink_group(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<BlockDto> dco_decode_list_block_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<BlockHit> dco_decode_list_block_hit(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<EditDto> dco_decode_list_edit_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<PageData> dco_decode_list_page_data(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<PageDto> dco_decode_list_page_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<int> dco_decode_list_prim_u_8_loose(dynamic raw);
|
||||
|
||||
@protected
|
||||
Uint8List dco_decode_list_prim_u_8_strict(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<RelatedDto> dco_decode_list_related_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<TimelineDayDto> dco_decode_list_timeline_day_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<TitleHit> 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<String> sse_decode_list_String(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<BacklinkGroup> sse_decode_list_backlink_group(
|
||||
SseDeserializer deserializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
List<BlockDto> sse_decode_list_block_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<BlockHit> sse_decode_list_block_hit(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<EditDto> sse_decode_list_edit_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<PageData> sse_decode_list_page_data(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<PageDto> sse_decode_list_page_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<int> sse_decode_list_prim_u_8_loose(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<RelatedDto> sse_decode_list_related_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<TimelineDayDto> sse_decode_list_timeline_day_dto(
|
||||
SseDeserializer deserializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
List<TitleHit> 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<String> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_backlink_group(
|
||||
List<BacklinkGroup> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_block_dto(List<BlockDto> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_block_hit(List<BlockHit> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_edit_dto(List<EditDto> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_page_brief(
|
||||
List<PageBrief> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_page_data(List<PageData> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_page_dto(List<PageDto> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_prim_u_8_loose(List<int> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_prim_u_8_strict(
|
||||
Uint8List self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_related_dto(
|
||||
List<RelatedDto> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_timeline_day_dto(
|
||||
List<TimelineDayDto> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_title_hit(List<TitleHit> 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,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
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})
|
||||
: queue = queue ?? WriteQueue(onError: _logError),
|
||||
refs = BlockRefCache(backend);
|
||||
|
||||
final GraphBackend backend;
|
||||
final WriteQueue queue;
|
||||
final BlockRefCache refs;
|
||||
|
||||
AppRoute _route = const JournalsRoute();
|
||||
final _back = <AppRoute>[];
|
||||
final _forward = <AppRoute>[];
|
||||
ThemeMode themeMode = ThemeMode.system;
|
||||
final List<PageBrief> recent = [];
|
||||
|
||||
/// Last page shown (for synapse reinforcement on navigation).
|
||||
String? _lastPageId;
|
||||
|
||||
/// Bumped when an error makes views reload from the core.
|
||||
int generation = 0;
|
||||
|
||||
AppRoute get route => _route;
|
||||
bool get canGoBack => _back.isNotEmpty;
|
||||
bool get canGoForward => _forward.isNotEmpty;
|
||||
|
||||
static void _logError(Object e, StackTrace st) {
|
||||
debugPrint('graph write failed: $e\n$st');
|
||||
}
|
||||
|
||||
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<void> 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 = <String, BlockRefDto?>{};
|
||||
final _loading = <String>{};
|
||||
|
||||
/// 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<AppState> {
|
||||
const AppScope({super.key, required AppState state, required super.child})
|
||||
: super(notifier: state);
|
||||
|
||||
static AppState of(BuildContext context) =>
|
||||
context.dependOnInheritedWidgetOfExactType<AppScope>()!.notifier!;
|
||||
|
||||
/// Access without subscribing to changes.
|
||||
static AppState read(BuildContext context) =>
|
||||
context.getInheritedWidgetOfExactType<AppScope>()!.notifier!;
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
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<BlockDto> 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<OutlineNode> nodes;
|
||||
|
||||
/// Block being edited, if any.
|
||||
String? focusedId;
|
||||
|
||||
/// Caret requested for the focused block; consumed by the row once applied.
|
||||
int? pendingCaret;
|
||||
|
||||
final _timers = <OutlineNode, Timer>{};
|
||||
Timer? _reconcile;
|
||||
int _structuralEdits = 0;
|
||||
static int _tmpSeq = 0;
|
||||
bool _disposed = false;
|
||||
|
||||
// ------------------------------------------------------------- queries
|
||||
|
||||
List<int> 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();
|
||||
});
|
||||
}
|
||||
|
||||
void _refocus(OutlineNode n, int? caret) {
|
||||
if (focusedId == n.id) {
|
||||
pendingCaret = caret;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _structural(Future<List<BlockDto>> Function() op) {
|
||||
_structuralEdits++;
|
||||
final seen = _structuralEdits;
|
||||
_enqueue(() async {
|
||||
await op();
|
||||
});
|
||||
_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<void> Function() task) {
|
||||
queue.run(task).ignore();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
flushAll();
|
||||
_reconcile?.cancel();
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -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<OutlineNode> l, int i) {
|
||||
var j = i + 1;
|
||||
while (j < l.length && l[j].depth > l[i].depth) {
|
||||
j++;
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
static bool hasChildren(List<OutlineNode> l, int i) =>
|
||||
i + 1 < l.length && l[i + 1].depth > l[i].depth;
|
||||
|
||||
static int? prevSibling(List<OutlineNode> 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<OutlineNode> l, int i) {
|
||||
final j = subtreeEnd(l, i);
|
||||
return j < l.length && l[j].depth == l[i].depth ? j : null;
|
||||
}
|
||||
|
||||
static int? parent(List<OutlineNode> 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<int> visible(List<OutlineNode> l) {
|
||||
final out = <int>[];
|
||||
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<OutlineNode> l) {
|
||||
final stack = <OutlineNode>[];
|
||||
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<OutlineNode> 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<OutlineNode> 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<OutlineNode> 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<OutlineNode> 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<OutlineNode> 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<OutlineNode> 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<OutlineNode> 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<OutlineNode> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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.
|
||||
final void Function(Object error, StackTrace stack)? onError;
|
||||
|
||||
final _tasks = Queue<Future<void> Function()>();
|
||||
bool _running = false;
|
||||
Completer<void>? _idle;
|
||||
|
||||
bool get isIdle => !_running && _tasks.isEmpty;
|
||||
|
||||
/// Completes when every queued task has run.
|
||||
Future<void> get idle {
|
||||
if (isIdle) return Future.value();
|
||||
return (_idle ??= Completer<void>()).future;
|
||||
}
|
||||
|
||||
Future<T> run<T>(Future<T> Function() task) {
|
||||
final done = Completer<T>();
|
||||
_tasks.add(() async {
|
||||
try {
|
||||
done.complete(await task());
|
||||
} catch (e, st) {
|
||||
onError?.call(e, st);
|
||||
done.completeError(e, st);
|
||||
}
|
||||
});
|
||||
_pump();
|
||||
return done.future;
|
||||
}
|
||||
|
||||
Future<void> _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;
|
||||
}
|
||||
@@ -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<SynapseColors> {
|
||||
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<SynapseColors>()!;
|
||||
}
|
||||
|
||||
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)),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -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<AllPagesView> createState() => _AllPagesViewState();
|
||||
}
|
||||
|
||||
class _AllPagesViewState extends State<AllPagesView> {
|
||||
final _pages = <PageDto>[];
|
||||
bool _loading = false;
|
||||
bool _done = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_more();
|
||||
}
|
||||
|
||||
Future<void> _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<ScrollNotification>(
|
||||
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),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
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<JournalsView> createState() => _JournalsViewState();
|
||||
}
|
||||
|
||||
class _Day {
|
||||
_Day(this.view, this.controller);
|
||||
final PageData view;
|
||||
final OutlineController controller;
|
||||
}
|
||||
|
||||
class _JournalsViewState extends State<JournalsView> {
|
||||
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<void> _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;
|
||||
final views = await app.backend.journals(before: before, limit: _batch);
|
||||
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<ScrollNotification>(
|
||||
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),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
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<PageScreen> createState() => _PageScreenState();
|
||||
}
|
||||
|
||||
class _PageScreenState extends State<PageScreen> {
|
||||
PageData? _view;
|
||||
OutlineController? _outline;
|
||||
List<BacklinkGroup>? _backlinks;
|
||||
List<RelatedDto>? _related;
|
||||
Object? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_outline?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
final app = AppScope.read(context);
|
||||
try {
|
||||
final t = widget.target;
|
||||
PageData? v;
|
||||
if (t.id != null) {
|
||||
v = await app.backend.page(t.id!);
|
||||
} else {
|
||||
v = await app.backend.openPage(t.title!);
|
||||
}
|
||||
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<BacklinkGroup>;
|
||||
_related = results[1] as List<RelatedDto>;
|
||||
});
|
||||
} 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<void> _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);
|
||||
} 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<String> initial;
|
||||
|
||||
@override
|
||||
State<_Aliases> createState() => _AliasesState();
|
||||
}
|
||||
|
||||
class _AliasesState extends State<_Aliases> {
|
||||
late final List<String> _aliases = List.of(widget.initial);
|
||||
bool _adding = false;
|
||||
final _text = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_text.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _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<void> _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<BacklinkGroup>? 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<int>(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<RelatedDto>? 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),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<void> showQuickSwitcher(BuildContext context) => showDialog<void>(
|
||||
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<QuickSwitcher> createState() => _QuickSwitcherState();
|
||||
}
|
||||
|
||||
class _QuickSwitcherState extends State<QuickSwitcher> {
|
||||
final _text = TextEditingController();
|
||||
List<TitleHit> _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<void> _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),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
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<Shell> createState() => _ShellState();
|
||||
}
|
||||
|
||||
class _ShellState extends State<Shell> {
|
||||
bool _sidebar = true;
|
||||
final _scaffold = GlobalKey<ScaffoldState>();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final app = AppScope.of(context);
|
||||
final colors = context.colors;
|
||||
final route = app.route;
|
||||
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),
|
||||
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;
|
||||
}
|
||||
@@ -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 = <int>{};
|
||||
final days = <int, TimelineDayDto>{};
|
||||
final titles = <String, PageBrief>{};
|
||||
|
||||
/// Where each page hangs: (day index, row).
|
||||
final born = <String, (int, int)>{};
|
||||
|
||||
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<void> _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<TimelineView> createState() => _TimelineViewState();
|
||||
}
|
||||
|
||||
class _TimelineViewState extends State<TimelineView> {
|
||||
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'),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<TextLink> createState() => _TextLinkState();
|
||||
}
|
||||
|
||||
class _TextLinkState extends State<TextLink> {
|
||||
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<StaticBlock> createState() => _StaticBlockState();
|
||||
}
|
||||
|
||||
class _StaticBlockState extends State<StaticBlock> {
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
flutter/ephemeral
|
||||
@@ -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 "$<$<NOT:$<CONFIG:Debug>>:-O3>")
|
||||
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>: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()
|
||||
@@ -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}
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
//
|
||||
// Generated file. Do not edit.
|
||||
//
|
||||
|
||||
// clang-format off
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <url_launcher_linux/url_launcher_plugin.h>
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//
|
||||
// Generated file. Do not edit.
|
||||
//
|
||||
|
||||
// clang-format off
|
||||
|
||||
#ifndef GENERATED_PLUGIN_REGISTRANT_
|
||||
#define GENERATED_PLUGIN_REGISTRANT_
|
||||
|
||||
#include <flutter_linux/flutter_linux.h>
|
||||
|
||||
// Registers Flutter plugins.
|
||||
void fl_register_plugins(FlPluginRegistry* registry);
|
||||
|
||||
#endif // GENERATED_PLUGIN_REGISTRANT_
|
||||
@@ -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 $<TARGET_FILE:${plugin}_plugin>)
|
||||
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)
|
||||
@@ -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}")
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
#include "my_application.h"
|
||||
|
||||
#include <flutter_linux/flutter_linux.h>
|
||||
#ifdef GDK_WINDOWING_X11
|
||||
#include <gdk/gdkx.h>
|
||||
#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));
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef FLUTTER_MY_APPLICATION_H_
|
||||
#define FLUTTER_MY_APPLICATION_H_
|
||||
|
||||
#include <gtk/gtk.h>
|
||||
|
||||
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_
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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/
|
||||
@@ -0,0 +1 @@
|
||||
Please ignore this folder, which is just glue to build Rust with Flutter.
|
||||
@@ -0,0 +1,9 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/workspace.xml
|
||||
/.idea/libraries
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.cxx
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = 'synapse_ffi'
|
||||
@@ -0,0 +1,3 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.flutter_rust_bridge.synapse_ffi">
|
||||
</manifest>
|
||||
@@ -0,0 +1,4 @@
|
||||
target
|
||||
.dart_tool
|
||||
*.iml
|
||||
!pubspec.lock
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
Executable
+58
@@ -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"
|
||||
@@ -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/`.
|
||||
@@ -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
|
||||
@@ -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<String> arguments) {
|
||||
build_tool.runMain(arguments);
|
||||
}
|
||||
@@ -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<void> runMain(List<String> args) async {
|
||||
return build_tool.runMain(args);
|
||||
}
|
||||
@@ -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<String> 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<Map<String, String>> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<Map<Target, List<Artifact>>> getArtifacts(List<Target> 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 = <String>{
|
||||
...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<Map<Target, List<Artifact>>> _getPrecompiledArtifacts(
|
||||
List<Target> 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 = <Target, List<Artifact>>{};
|
||||
|
||||
for (final target in targets) {
|
||||
final requiredArtifacts = getArtifactNames(
|
||||
target: target,
|
||||
libraryName: environment.crateInfo.libName,
|
||||
remote: true,
|
||||
);
|
||||
final artifactsForTarget = <Artifact>[];
|
||||
|
||||
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<Response> _get(Uri url, {Map<String, String>? 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<void> _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<String> 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}");
|
||||
}
|
||||
}
|
||||
@@ -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<void> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<void> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<void> 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<String> 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');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<void> runBuildCommand(CargokitUserOptions options);
|
||||
|
||||
@override
|
||||
Future<void> 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<void> 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<void> 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<void> 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<void> 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<String>;
|
||||
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<void> run() async {
|
||||
final manifestDir = argResults!['manifest-dir'] as String;
|
||||
final verifyBinaries = VerifyBinaries(
|
||||
manifestDir: manifestDir,
|
||||
);
|
||||
await verifyBinaries.run();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> runMain(List<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<Map<String, String>> _buildEnvironment() async {
|
||||
if (target.ohos != null) {
|
||||
return _buildOhosEnv();
|
||||
}
|
||||
if (target.android != null) {
|
||||
return _buildAndroidEnv();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Future<Map<String, String>> _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<String, String> _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'),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<File> files) {
|
||||
final output = AccumulatorSink<Digest>();
|
||||
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<File> files) {
|
||||
final output = AccumulatorSink<Digest>();
|
||||
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<File> getFiles() {
|
||||
final src = Directory(path.join(manifestDir, 'src'));
|
||||
final files = src
|
||||
.listSync(recursive: true, followLinks: false)
|
||||
.whereType<File>()
|
||||
.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;
|
||||
}
|
||||
@@ -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<String> 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<String> 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];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<String> 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<String> 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<YamlNode> 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<dynamic, YamlNode> 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<dynamic, YamlNode> 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<BuildConfiguration, CargoBuildOptions> 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 = <BuildConfiguration, CargoBuildOptions>{};
|
||||
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;
|
||||
}
|
||||
@@ -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<Target> 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<void> 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 = <CreateReleaseAsset>[];
|
||||
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<Release> _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;
|
||||
}
|
||||
}
|
||||
@@ -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<String> targets;
|
||||
}
|
||||
|
||||
class Rustup {
|
||||
List<String>? 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<String>? _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<String> _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;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user