commit 72428dc0759c7e66a494306e09be51412067ae2e Author: Akiba So Date: Sun Jun 21 03:18:00 2026 +0800 Fix bugs across app + server, optimize UI/UX, add Gitea CI Bug fixes (Flutter): - Wrap multi-statement DB writes (insert/update/delete note, deleteDocument, deletePageData, OCR FTS merge, migrations) in transactions to prevent data loss on interruption and a read-modify-write FTS race. - Fix PdfDocument leaks on exception (try/finally dispose) and preserve image aspect ratio when stamping images onto PDF pages. - Guard file-picker against empty selection (was .single -> crash). - Fix eraser ConcurrentModificationError and unmodifiable-list crash on PDF pages; capture page synchronously on save to stop wrong-page data loss. - Fix Riverpod DB-not-ready races, broken pull-to-refresh, settings load race, and search N+1; transform stored annotations on PDF page rotation. - Normalize pen pressure for devices without a pressure range. - PPT: single source of truth for slide strokes so ink displays and exports. UI/UX: - Material 3 typography, theme-aware colors (dark-mode fixes), hover cursors and right-click/visible actions on desktop, keyboard shortcuts (undo/redo/ save/find), toolbar overflow handling, friendlier empty states, semantic OCR status badges, relative timestamps, 1-based page indicators, large-deck PPT navigation, and a scratchpad-scope label in split view. Server (optional backend): - Persist JWT secret (was per-process random), block path traversal in storage, fix CORS '*'+credentials, add OCR job ownership checks, last-writer-wins sync guard, constant-time login, and split out heavy OCR deps so the API/tests run without them. CI: Gitea workflows for format+analyze+test (Linux, system sqlite) and a Windows release build; pristine `flutter analyze`, all Flutter and server tests green. Co-Authored-By: Claude Opus 4.8 (1M context) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..1b78c8e --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,101 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +# Allow builds to find SQLite / Flutter artifacts behind a corporate proxy. +# Configure repo/org secrets HTTP_PROXY / HTTPS_PROXY in Gitea if needed. +env: + FLUTTER_VERSION: "3.41.4" + +jobs: + analyze: + name: Analyze (Flutter) + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.FLUTTER_VERSION }} + channel: stable + cache: true + + - name: Install dependencies + run: flutter pub get + + - name: Verify formatting + run: dart format --output=none --set-exit-if-changed lib test + + - name: Static analysis + run: flutter analyze + + test: + name: Test (Flutter, Linux) + runs-on: ubuntu-latest + needs: analyze + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.FLUTTER_VERSION }} + channel: stable + cache: true + + # The sqlite3 Dart package downloads a precompiled binary from GitHub + # releases when building native assets. On Linux CI we instead link the + # system libsqlite3 to avoid the download (faster + works offline). + # This override is applied only in CI; the committed pubspec.yaml stays + # clean so the Windows build downloads the bundled sqlite3.dll normally. + - name: Install system SQLite + run: sudo apt-get update && sudo apt-get install -y libsqlite3-dev + + - name: Use system SQLite for native assets (CI only) + run: | + cat >> pubspec.yaml <<'EOF' + + hooks: + user_defines: + sqlite3: + source: system + EOF + + - name: Install dependencies + run: flutter pub get + + - name: Run tests + run: flutter test --reporter expanded + + server: + name: Test (Server, optional) + runs-on: ubuntu-latest + # The server is an optional/experimental backend. Keep it from blocking + # the pipeline, but still surface failures. + continue-on-error: true + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + + - name: Install dependencies + working-directory: server + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + + - name: Run tests + working-directory: server + run: pytest -q diff --git a/.gitea/workflows/windows-build.yml b/.gitea/workflows/windows-build.yml new file mode 100644 index 0000000..80d211e --- /dev/null +++ b/.gitea/workflows/windows-build.yml @@ -0,0 +1,57 @@ +name: Windows Build + +on: + push: + branches: [main] + tags: ["v*"] + pull_request: + branches: [main] + workflow_dispatch: + +env: + FLUTTER_VERSION: "3.41.4" + +jobs: + build-windows: + name: Build Windows (x64) + runs-on: windows-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.FLUTTER_VERSION }} + channel: stable + cache: true + + - name: Enable Windows desktop + run: flutter config --enable-windows-desktop + + - name: Install dependencies + run: flutter pub get + + - name: Analyze + run: flutter analyze + + # The sqlite3 native asset downloads a precompiled DLL from GitHub + # releases. If the runner is behind a firewall, set HTTP_PROXY / + # HTTPS_PROXY as repository secrets and they will be honoured here. + - name: Build Windows release + env: + HTTP_PROXY: ${{ secrets.HTTP_PROXY }} + HTTPS_PROXY: ${{ secrets.HTTPS_PROXY }} + run: flutter build windows --release + + - name: Package artifact + run: | + $dir = "build\windows\x64\runner\Release" + Compress-Archive -Path "$dir\*" -DestinationPath "badnote-windows-x64.zip" -Force + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: badnote-windows-x64 + path: badnote-windows-x64.zip + if-no-files-found: error diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..141bbf3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,61 @@ +# 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 + +# OMC orchestration state +.omc/ + +# Local-only sqlite3 override for offline/firewalled test runs +.local-sqlite/ + +# Python server artifacts +server/.venv/ +server/.omc/ +**/__pycache__/ +*.py[cod] +.pytest_cache/ +server/data/ +server/*.db +server/.env diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..89db5de --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# 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: "ff37bef603469fb030f2b72995ab929ccfc227f0" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: android + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: ios + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: linux + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: macos + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: web + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: windows + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/README.md b/README.md new file mode 100644 index 0000000..9c47ce7 --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# BadNote + +Local-first Surface Pen note-taking app with PDF/PPT annotation. + +All notes, documents, search, and OCR run on your device. No server is required to use the app. + +## Features + +- Ink notes with Surface Pen (pressure, stabilizer, undo/redo) +- PDF and PPT import with page-level annotation +- Full-text search over note titles, typed text, and OCR results +- **Local OCR** — handwriting recognition via Windows built-in OCR (Windows desktop) + +## Build (Windows) + +Prerequisites: + +- Flutter SDK (3.10+) +- Visual Studio Build Tools with **Desktop development with C++** +- Developer Mode enabled (for Flutter plugin symlinks) + +```powershell +flutter pub get +flutter build windows --release +``` + +Output: `build\windows\x64\runner\Release\badnote.exe` + +If native asset downloads fail (e.g. sqlite3), set a proxy before building: + +```powershell +$env:HTTP_PROXY="http://127.0.0.1:7890" +$env:HTTPS_PROXY="http://127.0.0.1:7890" +flutter build windows --release +``` + +## Architecture + +``` +lib/ +├── screens/ # UI (notes, PDF/PPT annotator, search, settings) +├── services/ # Local business logic +│ ├── database_service.dart # SQLite + FTS5 +│ ├── ocr_service.dart # Local OCR orchestration +│ ├── stroke_rasterizer.dart # Ink → PNG for OCR +│ └── ocr_engine.dart # Platform OCR bridge +├── providers/ # Riverpod state +└── widgets/ # Ink canvas, toolbars, thumbnails +``` + +OCR flow on save: + +1. Extract typed text from text-tool strokes +2. Rasterize handwriting strokes to PNG +3. Run Windows OCR on the PNG +4. Merge recognized text into the local FTS index for search + +## Optional server + +The `server/` directory contains an experimental FastAPI backend (sync + EasyOCR). It is **not required** for the desktop app and is kept separately for future multi-device sync experiments. See [server/README.md](server/README.md). + +## Development + +```bash +flutter run -d windows +flutter test +``` diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..d7024be --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.badnote.badnote" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.badnote.badnote" + // 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 + 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") + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..aa06c43 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/badnote/badnote/MainActivity.kt b/android/app/src/main/kotlin/com/badnote/badnote/MainActivity.kt new file mode 100644 index 0000000..33fa02a --- /dev/null +++ b/android/app/src/main/kotlin/com/badnote/badnote/MainActivity.kt @@ -0,0 +1,5 @@ +package com.badnote.badnote + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..fbee1d8 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..ca7fe06 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..1dc6cf7 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 13.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..1354592 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,616 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..8c9122e --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Badnote + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + badnote + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..736728a --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'providers/settings_provider.dart'; +import 'screens/home_screen.dart'; +import 'services/database_service.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Ensure DB is ready before the app starts so providers can use it eagerly + await DatabaseService.getInstance(); + + // Initialize SharedPreferences + await SharedPreferences.getInstance(); + + runApp(const ProviderScope(child: BadNoteApp())); +} + +class BadNoteApp extends ConsumerWidget { + const BadNoteApp({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final settings = ref.watch(settingsProvider); + + return MaterialApp( + title: 'BadNote', + themeMode: settings.themeMode, + theme: ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: settings.colorSchemeSeed, + brightness: Brightness.light, + ), + textTheme: GoogleFonts.interTextTheme( + ThemeData(brightness: Brightness.light).textTheme, + ), + useMaterial3: true, + ), + darkTheme: ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: settings.colorSchemeSeed, + brightness: Brightness.dark, + ), + textTheme: GoogleFonts.interTextTheme( + ThemeData(brightness: Brightness.dark).textTheme, + ), + useMaterial3: true, + ), + home: const HomeScreen(), + ); + } +} diff --git a/lib/models/bookmark.dart b/lib/models/bookmark.dart new file mode 100644 index 0000000..c318053 --- /dev/null +++ b/lib/models/bookmark.dart @@ -0,0 +1,19 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'bookmark.freezed.dart'; +part 'bookmark.g.dart'; + +@freezed +abstract class Bookmark with _$Bookmark { + const factory Bookmark({ + required String id, + required String documentId, + required int pageNumber, + @Default('') String label, + @Default(0xFF2196F3) int color, + required DateTime createdAt, + }) = _Bookmark; + + factory Bookmark.fromJson(Map json) => + _$BookmarkFromJson(json); +} diff --git a/lib/models/bookmark.freezed.dart b/lib/models/bookmark.freezed.dart new file mode 100644 index 0000000..47b7a8e --- /dev/null +++ b/lib/models/bookmark.freezed.dart @@ -0,0 +1,290 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'bookmark.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models', +); + +Bookmark _$BookmarkFromJson(Map json) { + return _Bookmark.fromJson(json); +} + +/// @nodoc +mixin _$Bookmark { + String get id => throw _privateConstructorUsedError; + String get documentId => throw _privateConstructorUsedError; + int get pageNumber => throw _privateConstructorUsedError; + String get label => throw _privateConstructorUsedError; + int get color => throw _privateConstructorUsedError; + DateTime get createdAt => throw _privateConstructorUsedError; + + /// Serializes this Bookmark to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of Bookmark + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $BookmarkCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $BookmarkCopyWith<$Res> { + factory $BookmarkCopyWith(Bookmark value, $Res Function(Bookmark) then) = + _$BookmarkCopyWithImpl<$Res, Bookmark>; + @useResult + $Res call({ + String id, + String documentId, + int pageNumber, + String label, + int color, + DateTime createdAt, + }); +} + +/// @nodoc +class _$BookmarkCopyWithImpl<$Res, $Val extends Bookmark> + implements $BookmarkCopyWith<$Res> { + _$BookmarkCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of Bookmark + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? documentId = null, + Object? pageNumber = null, + Object? label = null, + Object? color = null, + Object? createdAt = null, + }) { + return _then( + _value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + documentId: null == documentId + ? _value.documentId + : documentId // ignore: cast_nullable_to_non_nullable + as String, + pageNumber: null == pageNumber + ? _value.pageNumber + : pageNumber // ignore: cast_nullable_to_non_nullable + as int, + label: null == label + ? _value.label + : label // ignore: cast_nullable_to_non_nullable + as String, + color: null == color + ? _value.color + : color // ignore: cast_nullable_to_non_nullable + as int, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + ) + as $Val, + ); + } +} + +/// @nodoc +abstract class _$$BookmarkImplCopyWith<$Res> + implements $BookmarkCopyWith<$Res> { + factory _$$BookmarkImplCopyWith( + _$BookmarkImpl value, + $Res Function(_$BookmarkImpl) then, + ) = __$$BookmarkImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({ + String id, + String documentId, + int pageNumber, + String label, + int color, + DateTime createdAt, + }); +} + +/// @nodoc +class __$$BookmarkImplCopyWithImpl<$Res> + extends _$BookmarkCopyWithImpl<$Res, _$BookmarkImpl> + implements _$$BookmarkImplCopyWith<$Res> { + __$$BookmarkImplCopyWithImpl( + _$BookmarkImpl _value, + $Res Function(_$BookmarkImpl) _then, + ) : super(_value, _then); + + /// Create a copy of Bookmark + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? documentId = null, + Object? pageNumber = null, + Object? label = null, + Object? color = null, + Object? createdAt = null, + }) { + return _then( + _$BookmarkImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + documentId: null == documentId + ? _value.documentId + : documentId // ignore: cast_nullable_to_non_nullable + as String, + pageNumber: null == pageNumber + ? _value.pageNumber + : pageNumber // ignore: cast_nullable_to_non_nullable + as int, + label: null == label + ? _value.label + : label // ignore: cast_nullable_to_non_nullable + as String, + color: null == color + ? _value.color + : color // ignore: cast_nullable_to_non_nullable + as int, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$BookmarkImpl implements _Bookmark { + const _$BookmarkImpl({ + required this.id, + required this.documentId, + required this.pageNumber, + this.label = '', + this.color = 0xFF2196F3, + required this.createdAt, + }); + + factory _$BookmarkImpl.fromJson(Map json) => + _$$BookmarkImplFromJson(json); + + @override + final String id; + @override + final String documentId; + @override + final int pageNumber; + @override + @JsonKey() + final String label; + @override + @JsonKey() + final int color; + @override + final DateTime createdAt; + + @override + String toString() { + return 'Bookmark(id: $id, documentId: $documentId, pageNumber: $pageNumber, label: $label, color: $color, createdAt: $createdAt)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BookmarkImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.documentId, documentId) || + other.documentId == documentId) && + (identical(other.pageNumber, pageNumber) || + other.pageNumber == pageNumber) && + (identical(other.label, label) || other.label == label) && + (identical(other.color, color) || other.color == color) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash( + runtimeType, + id, + documentId, + pageNumber, + label, + color, + createdAt, + ); + + /// Create a copy of Bookmark + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$BookmarkImplCopyWith<_$BookmarkImpl> get copyWith => + __$$BookmarkImplCopyWithImpl<_$BookmarkImpl>(this, _$identity); + + @override + Map toJson() { + return _$$BookmarkImplToJson(this); + } +} + +abstract class _Bookmark implements Bookmark { + const factory _Bookmark({ + required final String id, + required final String documentId, + required final int pageNumber, + final String label, + final int color, + required final DateTime createdAt, + }) = _$BookmarkImpl; + + factory _Bookmark.fromJson(Map json) = + _$BookmarkImpl.fromJson; + + @override + String get id; + @override + String get documentId; + @override + int get pageNumber; + @override + String get label; + @override + int get color; + @override + DateTime get createdAt; + + /// Create a copy of Bookmark + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$BookmarkImplCopyWith<_$BookmarkImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/models/bookmark.g.dart b/lib/models/bookmark.g.dart new file mode 100644 index 0000000..8e822aa --- /dev/null +++ b/lib/models/bookmark.g.dart @@ -0,0 +1,27 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'bookmark.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$BookmarkImpl _$$BookmarkImplFromJson(Map json) => + _$BookmarkImpl( + id: json['id'] as String, + documentId: json['documentId'] as String, + pageNumber: (json['pageNumber'] as num).toInt(), + label: json['label'] as String? ?? '', + color: (json['color'] as num?)?.toInt() ?? 0xFF2196F3, + createdAt: DateTime.parse(json['createdAt'] as String), + ); + +Map _$$BookmarkImplToJson(_$BookmarkImpl instance) => + { + 'id': instance.id, + 'documentId': instance.documentId, + 'pageNumber': instance.pageNumber, + 'label': instance.label, + 'color': instance.color, + 'createdAt': instance.createdAt.toIso8601String(), + }; diff --git a/lib/models/document.dart b/lib/models/document.dart new file mode 100644 index 0000000..c1d3ac0 --- /dev/null +++ b/lib/models/document.dart @@ -0,0 +1,21 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'document.freezed.dart'; +part 'document.g.dart'; + +@freezed +abstract class Document with _$Document { + const factory Document({ + required String id, + required String filename, + required String docType, + required String filePath, + @Default(0) int pageCount, + @Default(0) int rotation, + required DateTime createdAt, + required DateTime updatedAt, + }) = _Document; + + factory Document.fromJson(Map json) => + _$DocumentFromJson(json); +} diff --git a/lib/models/document.freezed.dart b/lib/models/document.freezed.dart new file mode 100644 index 0000000..3df13a6 --- /dev/null +++ b/lib/models/document.freezed.dart @@ -0,0 +1,335 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'document.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models', +); + +Document _$DocumentFromJson(Map json) { + return _Document.fromJson(json); +} + +/// @nodoc +mixin _$Document { + String get id => throw _privateConstructorUsedError; + String get filename => throw _privateConstructorUsedError; + String get docType => throw _privateConstructorUsedError; + String get filePath => throw _privateConstructorUsedError; + int get pageCount => throw _privateConstructorUsedError; + int get rotation => throw _privateConstructorUsedError; + DateTime get createdAt => throw _privateConstructorUsedError; + DateTime get updatedAt => throw _privateConstructorUsedError; + + /// Serializes this Document to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of Document + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $DocumentCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DocumentCopyWith<$Res> { + factory $DocumentCopyWith(Document value, $Res Function(Document) then) = + _$DocumentCopyWithImpl<$Res, Document>; + @useResult + $Res call({ + String id, + String filename, + String docType, + String filePath, + int pageCount, + int rotation, + DateTime createdAt, + DateTime updatedAt, + }); +} + +/// @nodoc +class _$DocumentCopyWithImpl<$Res, $Val extends Document> + implements $DocumentCopyWith<$Res> { + _$DocumentCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of Document + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? filename = null, + Object? docType = null, + Object? filePath = null, + Object? pageCount = null, + Object? rotation = null, + Object? createdAt = null, + Object? updatedAt = null, + }) { + return _then( + _value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + filename: null == filename + ? _value.filename + : filename // ignore: cast_nullable_to_non_nullable + as String, + docType: null == docType + ? _value.docType + : docType // ignore: cast_nullable_to_non_nullable + as String, + filePath: null == filePath + ? _value.filePath + : filePath // ignore: cast_nullable_to_non_nullable + as String, + pageCount: null == pageCount + ? _value.pageCount + : pageCount // ignore: cast_nullable_to_non_nullable + as int, + rotation: null == rotation + ? _value.rotation + : rotation // ignore: cast_nullable_to_non_nullable + as int, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + ) + as $Val, + ); + } +} + +/// @nodoc +abstract class _$$DocumentImplCopyWith<$Res> + implements $DocumentCopyWith<$Res> { + factory _$$DocumentImplCopyWith( + _$DocumentImpl value, + $Res Function(_$DocumentImpl) then, + ) = __$$DocumentImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({ + String id, + String filename, + String docType, + String filePath, + int pageCount, + int rotation, + DateTime createdAt, + DateTime updatedAt, + }); +} + +/// @nodoc +class __$$DocumentImplCopyWithImpl<$Res> + extends _$DocumentCopyWithImpl<$Res, _$DocumentImpl> + implements _$$DocumentImplCopyWith<$Res> { + __$$DocumentImplCopyWithImpl( + _$DocumentImpl _value, + $Res Function(_$DocumentImpl) _then, + ) : super(_value, _then); + + /// Create a copy of Document + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? filename = null, + Object? docType = null, + Object? filePath = null, + Object? pageCount = null, + Object? rotation = null, + Object? createdAt = null, + Object? updatedAt = null, + }) { + return _then( + _$DocumentImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + filename: null == filename + ? _value.filename + : filename // ignore: cast_nullable_to_non_nullable + as String, + docType: null == docType + ? _value.docType + : docType // ignore: cast_nullable_to_non_nullable + as String, + filePath: null == filePath + ? _value.filePath + : filePath // ignore: cast_nullable_to_non_nullable + as String, + pageCount: null == pageCount + ? _value.pageCount + : pageCount // ignore: cast_nullable_to_non_nullable + as int, + rotation: null == rotation + ? _value.rotation + : rotation // ignore: cast_nullable_to_non_nullable + as int, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$DocumentImpl implements _Document { + const _$DocumentImpl({ + required this.id, + required this.filename, + required this.docType, + required this.filePath, + this.pageCount = 0, + this.rotation = 0, + required this.createdAt, + required this.updatedAt, + }); + + factory _$DocumentImpl.fromJson(Map json) => + _$$DocumentImplFromJson(json); + + @override + final String id; + @override + final String filename; + @override + final String docType; + @override + final String filePath; + @override + @JsonKey() + final int pageCount; + @override + @JsonKey() + final int rotation; + @override + final DateTime createdAt; + @override + final DateTime updatedAt; + + @override + String toString() { + return 'Document(id: $id, filename: $filename, docType: $docType, filePath: $filePath, pageCount: $pageCount, rotation: $rotation, createdAt: $createdAt, updatedAt: $updatedAt)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DocumentImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.filename, filename) || + other.filename == filename) && + (identical(other.docType, docType) || other.docType == docType) && + (identical(other.filePath, filePath) || + other.filePath == filePath) && + (identical(other.pageCount, pageCount) || + other.pageCount == pageCount) && + (identical(other.rotation, rotation) || + other.rotation == rotation) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash( + runtimeType, + id, + filename, + docType, + filePath, + pageCount, + rotation, + createdAt, + updatedAt, + ); + + /// Create a copy of Document + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$DocumentImplCopyWith<_$DocumentImpl> get copyWith => + __$$DocumentImplCopyWithImpl<_$DocumentImpl>(this, _$identity); + + @override + Map toJson() { + return _$$DocumentImplToJson(this); + } +} + +abstract class _Document implements Document { + const factory _Document({ + required final String id, + required final String filename, + required final String docType, + required final String filePath, + final int pageCount, + final int rotation, + required final DateTime createdAt, + required final DateTime updatedAt, + }) = _$DocumentImpl; + + factory _Document.fromJson(Map json) = + _$DocumentImpl.fromJson; + + @override + String get id; + @override + String get filename; + @override + String get docType; + @override + String get filePath; + @override + int get pageCount; + @override + int get rotation; + @override + DateTime get createdAt; + @override + DateTime get updatedAt; + + /// Create a copy of Document + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$DocumentImplCopyWith<_$DocumentImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/models/document.g.dart b/lib/models/document.g.dart new file mode 100644 index 0000000..16da537 --- /dev/null +++ b/lib/models/document.g.dart @@ -0,0 +1,31 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'document.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$DocumentImpl _$$DocumentImplFromJson(Map json) => + _$DocumentImpl( + id: json['id'] as String, + filename: json['filename'] as String, + docType: json['docType'] as String, + filePath: json['filePath'] as String, + pageCount: (json['pageCount'] as num?)?.toInt() ?? 0, + rotation: (json['rotation'] as num?)?.toInt() ?? 0, + createdAt: DateTime.parse(json['createdAt'] as String), + updatedAt: DateTime.parse(json['updatedAt'] as String), + ); + +Map _$$DocumentImplToJson(_$DocumentImpl instance) => + { + 'id': instance.id, + 'filename': instance.filename, + 'docType': instance.docType, + 'filePath': instance.filePath, + 'pageCount': instance.pageCount, + 'rotation': instance.rotation, + 'createdAt': instance.createdAt.toIso8601String(), + 'updatedAt': instance.updatedAt.toIso8601String(), + }; diff --git a/lib/models/ink_point.dart b/lib/models/ink_point.dart new file mode 100644 index 0000000..3ff8f64 --- /dev/null +++ b/lib/models/ink_point.dart @@ -0,0 +1,21 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'pointer_device_kind.dart'; + +part 'ink_point.freezed.dart'; +part 'ink_point.g.dart'; + +@freezed +abstract class InkPoint with _$InkPoint { + const factory InkPoint({ + required double x, + required double y, + @Default(0.5) double pressure, + @Default(0.0) double tilt, + required int timestamp, + @Default(InputDeviceKind.unknown) InputDeviceKind pointerDeviceKind, + }) = _InkPoint; + + factory InkPoint.fromJson(Map json) => + _$InkPointFromJson(json); +} diff --git a/lib/models/ink_point.freezed.dart b/lib/models/ink_point.freezed.dart new file mode 100644 index 0000000..2b41287 --- /dev/null +++ b/lib/models/ink_point.freezed.dart @@ -0,0 +1,291 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'ink_point.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models', +); + +InkPoint _$InkPointFromJson(Map json) { + return _InkPoint.fromJson(json); +} + +/// @nodoc +mixin _$InkPoint { + double get x => throw _privateConstructorUsedError; + double get y => throw _privateConstructorUsedError; + double get pressure => throw _privateConstructorUsedError; + double get tilt => throw _privateConstructorUsedError; + int get timestamp => throw _privateConstructorUsedError; + InputDeviceKind get pointerDeviceKind => throw _privateConstructorUsedError; + + /// Serializes this InkPoint to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of InkPoint + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $InkPointCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $InkPointCopyWith<$Res> { + factory $InkPointCopyWith(InkPoint value, $Res Function(InkPoint) then) = + _$InkPointCopyWithImpl<$Res, InkPoint>; + @useResult + $Res call({ + double x, + double y, + double pressure, + double tilt, + int timestamp, + InputDeviceKind pointerDeviceKind, + }); +} + +/// @nodoc +class _$InkPointCopyWithImpl<$Res, $Val extends InkPoint> + implements $InkPointCopyWith<$Res> { + _$InkPointCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of InkPoint + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? x = null, + Object? y = null, + Object? pressure = null, + Object? tilt = null, + Object? timestamp = null, + Object? pointerDeviceKind = null, + }) { + return _then( + _value.copyWith( + x: null == x + ? _value.x + : x // ignore: cast_nullable_to_non_nullable + as double, + y: null == y + ? _value.y + : y // ignore: cast_nullable_to_non_nullable + as double, + pressure: null == pressure + ? _value.pressure + : pressure // ignore: cast_nullable_to_non_nullable + as double, + tilt: null == tilt + ? _value.tilt + : tilt // ignore: cast_nullable_to_non_nullable + as double, + timestamp: null == timestamp + ? _value.timestamp + : timestamp // ignore: cast_nullable_to_non_nullable + as int, + pointerDeviceKind: null == pointerDeviceKind + ? _value.pointerDeviceKind + : pointerDeviceKind // ignore: cast_nullable_to_non_nullable + as InputDeviceKind, + ) + as $Val, + ); + } +} + +/// @nodoc +abstract class _$$InkPointImplCopyWith<$Res> + implements $InkPointCopyWith<$Res> { + factory _$$InkPointImplCopyWith( + _$InkPointImpl value, + $Res Function(_$InkPointImpl) then, + ) = __$$InkPointImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({ + double x, + double y, + double pressure, + double tilt, + int timestamp, + InputDeviceKind pointerDeviceKind, + }); +} + +/// @nodoc +class __$$InkPointImplCopyWithImpl<$Res> + extends _$InkPointCopyWithImpl<$Res, _$InkPointImpl> + implements _$$InkPointImplCopyWith<$Res> { + __$$InkPointImplCopyWithImpl( + _$InkPointImpl _value, + $Res Function(_$InkPointImpl) _then, + ) : super(_value, _then); + + /// Create a copy of InkPoint + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? x = null, + Object? y = null, + Object? pressure = null, + Object? tilt = null, + Object? timestamp = null, + Object? pointerDeviceKind = null, + }) { + return _then( + _$InkPointImpl( + x: null == x + ? _value.x + : x // ignore: cast_nullable_to_non_nullable + as double, + y: null == y + ? _value.y + : y // ignore: cast_nullable_to_non_nullable + as double, + pressure: null == pressure + ? _value.pressure + : pressure // ignore: cast_nullable_to_non_nullable + as double, + tilt: null == tilt + ? _value.tilt + : tilt // ignore: cast_nullable_to_non_nullable + as double, + timestamp: null == timestamp + ? _value.timestamp + : timestamp // ignore: cast_nullable_to_non_nullable + as int, + pointerDeviceKind: null == pointerDeviceKind + ? _value.pointerDeviceKind + : pointerDeviceKind // ignore: cast_nullable_to_non_nullable + as InputDeviceKind, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$InkPointImpl implements _InkPoint { + const _$InkPointImpl({ + required this.x, + required this.y, + this.pressure = 0.5, + this.tilt = 0.0, + required this.timestamp, + this.pointerDeviceKind = InputDeviceKind.unknown, + }); + + factory _$InkPointImpl.fromJson(Map json) => + _$$InkPointImplFromJson(json); + + @override + final double x; + @override + final double y; + @override + @JsonKey() + final double pressure; + @override + @JsonKey() + final double tilt; + @override + final int timestamp; + @override + @JsonKey() + final InputDeviceKind pointerDeviceKind; + + @override + String toString() { + return 'InkPoint(x: $x, y: $y, pressure: $pressure, tilt: $tilt, timestamp: $timestamp, pointerDeviceKind: $pointerDeviceKind)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InkPointImpl && + (identical(other.x, x) || other.x == x) && + (identical(other.y, y) || other.y == y) && + (identical(other.pressure, pressure) || + other.pressure == pressure) && + (identical(other.tilt, tilt) || other.tilt == tilt) && + (identical(other.timestamp, timestamp) || + other.timestamp == timestamp) && + (identical(other.pointerDeviceKind, pointerDeviceKind) || + other.pointerDeviceKind == pointerDeviceKind)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash( + runtimeType, + x, + y, + pressure, + tilt, + timestamp, + pointerDeviceKind, + ); + + /// Create a copy of InkPoint + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$InkPointImplCopyWith<_$InkPointImpl> get copyWith => + __$$InkPointImplCopyWithImpl<_$InkPointImpl>(this, _$identity); + + @override + Map toJson() { + return _$$InkPointImplToJson(this); + } +} + +abstract class _InkPoint implements InkPoint { + const factory _InkPoint({ + required final double x, + required final double y, + final double pressure, + final double tilt, + required final int timestamp, + final InputDeviceKind pointerDeviceKind, + }) = _$InkPointImpl; + + factory _InkPoint.fromJson(Map json) = + _$InkPointImpl.fromJson; + + @override + double get x; + @override + double get y; + @override + double get pressure; + @override + double get tilt; + @override + int get timestamp; + @override + InputDeviceKind get pointerDeviceKind; + + /// Create a copy of InkPoint + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$InkPointImplCopyWith<_$InkPointImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/models/ink_point.g.dart b/lib/models/ink_point.g.dart new file mode 100644 index 0000000..2dc7d24 --- /dev/null +++ b/lib/models/ink_point.g.dart @@ -0,0 +1,42 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'ink_point.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$InkPointImpl _$$InkPointImplFromJson(Map json) => + _$InkPointImpl( + x: (json['x'] as num).toDouble(), + y: (json['y'] as num).toDouble(), + pressure: (json['pressure'] as num?)?.toDouble() ?? 0.5, + tilt: (json['tilt'] as num?)?.toDouble() ?? 0.0, + timestamp: (json['timestamp'] as num).toInt(), + pointerDeviceKind: + $enumDecodeNullable( + _$InputDeviceKindEnumMap, + json['pointerDeviceKind'], + ) ?? + InputDeviceKind.unknown, + ); + +Map _$$InkPointImplToJson( + _$InkPointImpl instance, +) => { + 'x': instance.x, + 'y': instance.y, + 'pressure': instance.pressure, + 'tilt': instance.tilt, + 'timestamp': instance.timestamp, + 'pointerDeviceKind': _$InputDeviceKindEnumMap[instance.pointerDeviceKind]!, +}; + +const _$InputDeviceKindEnumMap = { + InputDeviceKind.touch: 'touch', + InputDeviceKind.mouse: 'mouse', + InputDeviceKind.stylus: 'stylus', + InputDeviceKind.invertedStylus: 'invertedStylus', + InputDeviceKind.trackpad: 'trackpad', + InputDeviceKind.unknown: 'unknown', +}; diff --git a/lib/models/ink_stroke.dart b/lib/models/ink_stroke.dart new file mode 100644 index 0000000..c01cbc8 --- /dev/null +++ b/lib/models/ink_stroke.dart @@ -0,0 +1,25 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'ink_point.dart'; +import 'pen_tool.dart'; + +part 'ink_stroke.freezed.dart'; +part 'ink_stroke.g.dart'; + +@freezed +abstract class InkStroke with _$InkStroke { + const factory InkStroke({ + required String id, + required List points, + @Default(PenTool.pen) PenTool tool, + @Default(0xFF000000) int color, + @Default(2.0) double strokeWidth, + required DateTime createdAt, + @Default(false) bool filled, + String? textContent, + @Default(14.0) double fontSize, + }) = _InkStroke; + + factory InkStroke.fromJson(Map json) => + _$InkStrokeFromJson(json); +} diff --git a/lib/models/ink_stroke.freezed.dart b/lib/models/ink_stroke.freezed.dart new file mode 100644 index 0000000..d0d8e0d --- /dev/null +++ b/lib/models/ink_stroke.freezed.dart @@ -0,0 +1,363 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'ink_stroke.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models', +); + +InkStroke _$InkStrokeFromJson(Map json) { + return _InkStroke.fromJson(json); +} + +/// @nodoc +mixin _$InkStroke { + String get id => throw _privateConstructorUsedError; + List get points => throw _privateConstructorUsedError; + PenTool get tool => throw _privateConstructorUsedError; + int get color => throw _privateConstructorUsedError; + double get strokeWidth => throw _privateConstructorUsedError; + DateTime get createdAt => throw _privateConstructorUsedError; + bool get filled => throw _privateConstructorUsedError; + String? get textContent => throw _privateConstructorUsedError; + double get fontSize => throw _privateConstructorUsedError; + + /// Serializes this InkStroke to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of InkStroke + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $InkStrokeCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $InkStrokeCopyWith<$Res> { + factory $InkStrokeCopyWith(InkStroke value, $Res Function(InkStroke) then) = + _$InkStrokeCopyWithImpl<$Res, InkStroke>; + @useResult + $Res call({ + String id, + List points, + PenTool tool, + int color, + double strokeWidth, + DateTime createdAt, + bool filled, + String? textContent, + double fontSize, + }); +} + +/// @nodoc +class _$InkStrokeCopyWithImpl<$Res, $Val extends InkStroke> + implements $InkStrokeCopyWith<$Res> { + _$InkStrokeCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of InkStroke + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? points = null, + Object? tool = null, + Object? color = null, + Object? strokeWidth = null, + Object? createdAt = null, + Object? filled = null, + Object? textContent = freezed, + Object? fontSize = null, + }) { + return _then( + _value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + points: null == points + ? _value.points + : points // ignore: cast_nullable_to_non_nullable + as List, + tool: null == tool + ? _value.tool + : tool // ignore: cast_nullable_to_non_nullable + as PenTool, + color: null == color + ? _value.color + : color // ignore: cast_nullable_to_non_nullable + as int, + strokeWidth: null == strokeWidth + ? _value.strokeWidth + : strokeWidth // ignore: cast_nullable_to_non_nullable + as double, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + filled: null == filled + ? _value.filled + : filled // ignore: cast_nullable_to_non_nullable + as bool, + textContent: freezed == textContent + ? _value.textContent + : textContent // ignore: cast_nullable_to_non_nullable + as String?, + fontSize: null == fontSize + ? _value.fontSize + : fontSize // ignore: cast_nullable_to_non_nullable + as double, + ) + as $Val, + ); + } +} + +/// @nodoc +abstract class _$$InkStrokeImplCopyWith<$Res> + implements $InkStrokeCopyWith<$Res> { + factory _$$InkStrokeImplCopyWith( + _$InkStrokeImpl value, + $Res Function(_$InkStrokeImpl) then, + ) = __$$InkStrokeImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({ + String id, + List points, + PenTool tool, + int color, + double strokeWidth, + DateTime createdAt, + bool filled, + String? textContent, + double fontSize, + }); +} + +/// @nodoc +class __$$InkStrokeImplCopyWithImpl<$Res> + extends _$InkStrokeCopyWithImpl<$Res, _$InkStrokeImpl> + implements _$$InkStrokeImplCopyWith<$Res> { + __$$InkStrokeImplCopyWithImpl( + _$InkStrokeImpl _value, + $Res Function(_$InkStrokeImpl) _then, + ) : super(_value, _then); + + /// Create a copy of InkStroke + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? points = null, + Object? tool = null, + Object? color = null, + Object? strokeWidth = null, + Object? createdAt = null, + Object? filled = null, + Object? textContent = freezed, + Object? fontSize = null, + }) { + return _then( + _$InkStrokeImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + points: null == points + ? _value._points + : points // ignore: cast_nullable_to_non_nullable + as List, + tool: null == tool + ? _value.tool + : tool // ignore: cast_nullable_to_non_nullable + as PenTool, + color: null == color + ? _value.color + : color // ignore: cast_nullable_to_non_nullable + as int, + strokeWidth: null == strokeWidth + ? _value.strokeWidth + : strokeWidth // ignore: cast_nullable_to_non_nullable + as double, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + filled: null == filled + ? _value.filled + : filled // ignore: cast_nullable_to_non_nullable + as bool, + textContent: freezed == textContent + ? _value.textContent + : textContent // ignore: cast_nullable_to_non_nullable + as String?, + fontSize: null == fontSize + ? _value.fontSize + : fontSize // ignore: cast_nullable_to_non_nullable + as double, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$InkStrokeImpl implements _InkStroke { + const _$InkStrokeImpl({ + required this.id, + required final List points, + this.tool = PenTool.pen, + this.color = 0xFF000000, + this.strokeWidth = 2.0, + required this.createdAt, + this.filled = false, + this.textContent, + this.fontSize = 14.0, + }) : _points = points; + + factory _$InkStrokeImpl.fromJson(Map json) => + _$$InkStrokeImplFromJson(json); + + @override + final String id; + final List _points; + @override + List get points { + if (_points is EqualUnmodifiableListView) return _points; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_points); + } + + @override + @JsonKey() + final PenTool tool; + @override + @JsonKey() + final int color; + @override + @JsonKey() + final double strokeWidth; + @override + final DateTime createdAt; + @override + @JsonKey() + final bool filled; + @override + final String? textContent; + @override + @JsonKey() + final double fontSize; + + @override + String toString() { + return 'InkStroke(id: $id, points: $points, tool: $tool, color: $color, strokeWidth: $strokeWidth, createdAt: $createdAt, filled: $filled, textContent: $textContent, fontSize: $fontSize)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InkStrokeImpl && + (identical(other.id, id) || other.id == id) && + const DeepCollectionEquality().equals(other._points, _points) && + (identical(other.tool, tool) || other.tool == tool) && + (identical(other.color, color) || other.color == color) && + (identical(other.strokeWidth, strokeWidth) || + other.strokeWidth == strokeWidth) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.filled, filled) || other.filled == filled) && + (identical(other.textContent, textContent) || + other.textContent == textContent) && + (identical(other.fontSize, fontSize) || + other.fontSize == fontSize)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash( + runtimeType, + id, + const DeepCollectionEquality().hash(_points), + tool, + color, + strokeWidth, + createdAt, + filled, + textContent, + fontSize, + ); + + /// Create a copy of InkStroke + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$InkStrokeImplCopyWith<_$InkStrokeImpl> get copyWith => + __$$InkStrokeImplCopyWithImpl<_$InkStrokeImpl>(this, _$identity); + + @override + Map toJson() { + return _$$InkStrokeImplToJson(this); + } +} + +abstract class _InkStroke implements InkStroke { + const factory _InkStroke({ + required final String id, + required final List points, + final PenTool tool, + final int color, + final double strokeWidth, + required final DateTime createdAt, + final bool filled, + final String? textContent, + final double fontSize, + }) = _$InkStrokeImpl; + + factory _InkStroke.fromJson(Map json) = + _$InkStrokeImpl.fromJson; + + @override + String get id; + @override + List get points; + @override + PenTool get tool; + @override + int get color; + @override + double get strokeWidth; + @override + DateTime get createdAt; + @override + bool get filled; + @override + String? get textContent; + @override + double get fontSize; + + /// Create a copy of InkStroke + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$InkStrokeImplCopyWith<_$InkStrokeImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/models/ink_stroke.g.dart b/lib/models/ink_stroke.g.dart new file mode 100644 index 0000000..517cc42 --- /dev/null +++ b/lib/models/ink_stroke.g.dart @@ -0,0 +1,47 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'ink_stroke.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$InkStrokeImpl _$$InkStrokeImplFromJson(Map json) => + _$InkStrokeImpl( + id: json['id'] as String, + points: (json['points'] as List) + .map((e) => InkPoint.fromJson(e as Map)) + .toList(), + tool: $enumDecodeNullable(_$PenToolEnumMap, json['tool']) ?? PenTool.pen, + color: (json['color'] as num?)?.toInt() ?? 0xFF000000, + strokeWidth: (json['strokeWidth'] as num?)?.toDouble() ?? 2.0, + createdAt: DateTime.parse(json['createdAt'] as String), + filled: json['filled'] as bool? ?? false, + textContent: json['textContent'] as String?, + fontSize: (json['fontSize'] as num?)?.toDouble() ?? 14.0, + ); + +Map _$$InkStrokeImplToJson(_$InkStrokeImpl instance) => + { + 'id': instance.id, + 'points': instance.points, + 'tool': _$PenToolEnumMap[instance.tool]!, + 'color': instance.color, + 'strokeWidth': instance.strokeWidth, + 'createdAt': instance.createdAt.toIso8601String(), + 'filled': instance.filled, + 'textContent': instance.textContent, + 'fontSize': instance.fontSize, + }; + +const _$PenToolEnumMap = { + PenTool.pen: 'pen', + PenTool.marker: 'marker', + PenTool.eraser: 'eraser', + PenTool.highlighter: 'highlighter', + PenTool.rectangle: 'rectangle', + PenTool.ellipse: 'ellipse', + PenTool.line: 'line', + PenTool.arrow: 'arrow', + PenTool.text: 'text', +}; diff --git a/lib/models/note.dart b/lib/models/note.dart new file mode 100644 index 0000000..ecec8aa --- /dev/null +++ b/lib/models/note.dart @@ -0,0 +1,20 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'ink_stroke.dart'; + +part 'note.freezed.dart'; +part 'note.g.dart'; + +@freezed +abstract class Note with _$Note { + const factory Note({ + required String id, + @Default('Untitled') String title, + @Default([]) List strokes, + required DateTime createdAt, + required DateTime updatedAt, + @Default([]) List tags, + }) = _Note; + + factory Note.fromJson(Map json) => _$NoteFromJson(json); +} diff --git a/lib/models/note.freezed.dart b/lib/models/note.freezed.dart new file mode 100644 index 0000000..85e8339 --- /dev/null +++ b/lib/models/note.freezed.dart @@ -0,0 +1,297 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'note.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models', +); + +Note _$NoteFromJson(Map json) { + return _Note.fromJson(json); +} + +/// @nodoc +mixin _$Note { + String get id => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; + List get strokes => throw _privateConstructorUsedError; + DateTime get createdAt => throw _privateConstructorUsedError; + DateTime get updatedAt => throw _privateConstructorUsedError; + List get tags => throw _privateConstructorUsedError; + + /// Serializes this Note to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of Note + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $NoteCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $NoteCopyWith<$Res> { + factory $NoteCopyWith(Note value, $Res Function(Note) then) = + _$NoteCopyWithImpl<$Res, Note>; + @useResult + $Res call({ + String id, + String title, + List strokes, + DateTime createdAt, + DateTime updatedAt, + List tags, + }); +} + +/// @nodoc +class _$NoteCopyWithImpl<$Res, $Val extends Note> + implements $NoteCopyWith<$Res> { + _$NoteCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of Note + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? title = null, + Object? strokes = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? tags = null, + }) { + return _then( + _value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + strokes: null == strokes + ? _value.strokes + : strokes // ignore: cast_nullable_to_non_nullable + as List, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + tags: null == tags + ? _value.tags + : tags // ignore: cast_nullable_to_non_nullable + as List, + ) + as $Val, + ); + } +} + +/// @nodoc +abstract class _$$NoteImplCopyWith<$Res> implements $NoteCopyWith<$Res> { + factory _$$NoteImplCopyWith( + _$NoteImpl value, + $Res Function(_$NoteImpl) then, + ) = __$$NoteImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({ + String id, + String title, + List strokes, + DateTime createdAt, + DateTime updatedAt, + List tags, + }); +} + +/// @nodoc +class __$$NoteImplCopyWithImpl<$Res> + extends _$NoteCopyWithImpl<$Res, _$NoteImpl> + implements _$$NoteImplCopyWith<$Res> { + __$$NoteImplCopyWithImpl(_$NoteImpl _value, $Res Function(_$NoteImpl) _then) + : super(_value, _then); + + /// Create a copy of Note + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? title = null, + Object? strokes = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? tags = null, + }) { + return _then( + _$NoteImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + strokes: null == strokes + ? _value._strokes + : strokes // ignore: cast_nullable_to_non_nullable + as List, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + tags: null == tags + ? _value._tags + : tags // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$NoteImpl implements _Note { + const _$NoteImpl({ + required this.id, + this.title = 'Untitled', + final List strokes = const [], + required this.createdAt, + required this.updatedAt, + final List tags = const [], + }) : _strokes = strokes, + _tags = tags; + + factory _$NoteImpl.fromJson(Map json) => + _$$NoteImplFromJson(json); + + @override + final String id; + @override + @JsonKey() + final String title; + final List _strokes; + @override + @JsonKey() + List get strokes { + if (_strokes is EqualUnmodifiableListView) return _strokes; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_strokes); + } + + @override + final DateTime createdAt; + @override + final DateTime updatedAt; + final List _tags; + @override + @JsonKey() + List get tags { + if (_tags is EqualUnmodifiableListView) return _tags; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_tags); + } + + @override + String toString() { + return 'Note(id: $id, title: $title, strokes: $strokes, createdAt: $createdAt, updatedAt: $updatedAt, tags: $tags)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NoteImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.title, title) || other.title == title) && + const DeepCollectionEquality().equals(other._strokes, _strokes) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && + const DeepCollectionEquality().equals(other._tags, _tags)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash( + runtimeType, + id, + title, + const DeepCollectionEquality().hash(_strokes), + createdAt, + updatedAt, + const DeepCollectionEquality().hash(_tags), + ); + + /// Create a copy of Note + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$NoteImplCopyWith<_$NoteImpl> get copyWith => + __$$NoteImplCopyWithImpl<_$NoteImpl>(this, _$identity); + + @override + Map toJson() { + return _$$NoteImplToJson(this); + } +} + +abstract class _Note implements Note { + const factory _Note({ + required final String id, + final String title, + final List strokes, + required final DateTime createdAt, + required final DateTime updatedAt, + final List tags, + }) = _$NoteImpl; + + factory _Note.fromJson(Map json) = _$NoteImpl.fromJson; + + @override + String get id; + @override + String get title; + @override + List get strokes; + @override + DateTime get createdAt; + @override + DateTime get updatedAt; + @override + List get tags; + + /// Create a copy of Note + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$NoteImplCopyWith<_$NoteImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/models/note.g.dart b/lib/models/note.g.dart new file mode 100644 index 0000000..25875d1 --- /dev/null +++ b/lib/models/note.g.dart @@ -0,0 +1,32 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'note.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$NoteImpl _$$NoteImplFromJson(Map json) => _$NoteImpl( + id: json['id'] as String, + title: json['title'] as String? ?? 'Untitled', + strokes: + (json['strokes'] as List?) + ?.map((e) => InkStroke.fromJson(e as Map)) + .toList() ?? + const [], + createdAt: DateTime.parse(json['createdAt'] as String), + updatedAt: DateTime.parse(json['updatedAt'] as String), + tags: + (json['tags'] as List?)?.map((e) => e as String).toList() ?? + const [], +); + +Map _$$NoteImplToJson(_$NoteImpl instance) => + { + 'id': instance.id, + 'title': instance.title, + 'strokes': instance.strokes, + 'createdAt': instance.createdAt.toIso8601String(), + 'updatedAt': instance.updatedAt.toIso8601String(), + 'tags': instance.tags, + }; diff --git a/lib/models/pen_tool.dart b/lib/models/pen_tool.dart new file mode 100644 index 0000000..4fa9042 --- /dev/null +++ b/lib/models/pen_tool.dart @@ -0,0 +1,11 @@ +enum PenTool { + pen, + marker, + eraser, + highlighter, + rectangle, + ellipse, + line, + arrow, + text, +} diff --git a/lib/models/pointer_device_kind.dart b/lib/models/pointer_device_kind.dart new file mode 100644 index 0000000..16c259b --- /dev/null +++ b/lib/models/pointer_device_kind.dart @@ -0,0 +1,16 @@ +import 'package:json_annotation/json_annotation.dart'; + +enum InputDeviceKind { + @JsonValue('touch') + touch, + @JsonValue('mouse') + mouse, + @JsonValue('stylus') + stylus, + @JsonValue('invertedStylus') + invertedStylus, + @JsonValue('trackpad') + trackpad, + @JsonValue('unknown') + unknown, +} diff --git a/lib/models/pressure_curve.dart b/lib/models/pressure_curve.dart new file mode 100644 index 0000000..acf38ef --- /dev/null +++ b/lib/models/pressure_curve.dart @@ -0,0 +1,62 @@ +import 'dart:math'; + +/// Predefined pressure curve types. +enum PressureCurveType { linear, soft, hard, custom } + +/// Maps raw pen pressure [0,1] to effective pressure [0,1] using a power curve. +/// +/// - **Linear**: identity (p) +/// - **Soft**: `pow(p, 1.5)` — light touch produces small lines, needs more pressure +/// - **Hard**: `pow(p, 0.5)` — light touch already produces thick lines +/// - **Custom**: `pow(p, exponent)` where exponent is derived from [softness] +class PressureCurve { + final PressureCurveType type; + final double softness; + + const PressureCurve({ + this.type = PressureCurveType.linear, + this.softness = 0.5, + }); + + /// Predefined linear curve (identity). + static const linear = PressureCurve(type: PressureCurveType.linear); + + /// Predefined soft curve — needs more pressure to ramp up. + static const soft = PressureCurve( + type: PressureCurveType.soft, + softness: 0.3, + ); + + /// Predefined hard curve — light touch already produces thick lines. + static const hard = PressureCurve( + type: PressureCurveType.hard, + softness: 0.7, + ); + + /// Maps raw pressure [0,1] to effective pressure [0,1]. + double apply(double rawPressure) { + final p = rawPressure.clamp(0.0, 1.0); + switch (type) { + case PressureCurveType.linear: + return p; + case PressureCurveType.soft: + return pow(p, 1.5).toDouble(); + case PressureCurveType.hard: + return pow(p, 0.5).toDouble(); + case PressureCurveType.custom: + final exponent = softness * 2 + 0.2; + return pow(p, exponent).toDouble(); + } + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is PressureCurve && + runtimeType == other.runtimeType && + type == other.type && + softness == other.softness; + + @override + int get hashCode => type.hashCode ^ softness.hashCode; +} diff --git a/lib/providers/document_provider.dart b/lib/providers/document_provider.dart new file mode 100644 index 0000000..8685253 --- /dev/null +++ b/lib/providers/document_provider.dart @@ -0,0 +1,62 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:uuid/uuid.dart'; + +import '../models/document.dart'; +import '../services/database_service.dart'; +import 'note_provider.dart'; + +const _uuid = Uuid(); + +final documentListProvider = + AsyncNotifierProvider>( + DocumentListNotifier.new, + ); + +class DocumentListNotifier extends AsyncNotifier> { + Future get _db => ref.read(databaseServiceProvider.future); + + @override + Future> build() async { + final db = await _db; + return db.getAllDocuments(); + } + + /// Reloads documents from the database and publishes the result to [state] + /// so the UI rebuilds. Used by pull-to-refresh. + Future loadDocuments() async { + state = const AsyncLoading(); + state = await AsyncValue.guard(() async { + final db = await _db; + return db.getAllDocuments(); + }); + } + + Future addDocument({ + required String filename, + required String docType, + required String filePath, + int pageCount = 0, + }) async { + final db = await _db; + final now = DateTime.now(); + final document = Document( + id: _uuid.v4(), + filename: filename, + docType: docType, + filePath: filePath, + pageCount: pageCount, + createdAt: now, + updatedAt: now, + ); + await db.insertDocument(document); + state = AsyncData([document, ...state.value ?? []]); + return document; + } + + Future removeDocument(String id) async { + final db = await _db; + await db.deleteDocument(id); + final current = state.value ?? []; + state = AsyncData(current.where((d) => d.id != id).toList()); + } +} diff --git a/lib/providers/note_provider.dart b/lib/providers/note_provider.dart new file mode 100644 index 0000000..d9659cc --- /dev/null +++ b/lib/providers/note_provider.dart @@ -0,0 +1,68 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:uuid/uuid.dart'; + +import '../models/note.dart'; +import '../services/database_service.dart'; + +const _uuid = Uuid(); + +final databaseServiceProvider = FutureProvider((ref) async { + return DatabaseService.getInstance(); +}); + +final noteListProvider = AsyncNotifierProvider>( + NoteListNotifier.new, +); + +class NoteListNotifier extends AsyncNotifier> { + Future get _db => ref.read(databaseServiceProvider.future); + + @override + Future> build() async { + final db = await _db; + return db.getAllNotes(); + } + + /// Reloads notes from the database and publishes the result to [state] so + /// the UI rebuilds. Used by pull-to-refresh. + Future loadNotes() async { + state = const AsyncLoading(); + state = await AsyncValue.guard(() async { + final db = await _db; + return db.getAllNotes(); + }); + } + + Future createNote({String title = 'Untitled'}) async { + final db = await _db; + final now = DateTime.now(); + final note = Note( + id: _uuid.v4(), + title: title, + createdAt: now, + updatedAt: now, + ); + await db.insertNote(note); + state = AsyncData([note, ...state.value ?? []]); + return note; + } + + Future updateNote(Note note) async { + final db = await _db; + await db.updateNote(note); + final current = state.value ?? []; + state = AsyncData(current.map((n) => n.id == note.id ? note : n).toList()); + } + + Future deleteNote(String id) async { + final db = await _db; + await db.deleteNote(id); + final current = state.value ?? []; + state = AsyncData(current.where((n) => n.id != id).toList()); + } +} + +final noteProvider = FutureProvider.family((ref, id) async { + final db = await ref.watch(databaseServiceProvider.future); + return db.getNoteById(id); +}); diff --git a/lib/providers/ocr_provider.dart b/lib/providers/ocr_provider.dart new file mode 100644 index 0000000..82888e4 --- /dev/null +++ b/lib/providers/ocr_provider.dart @@ -0,0 +1,43 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../services/ocr_service.dart'; + +enum OcrStatus { none, processing, done, failed } + +final ocrServiceProvider = Provider((ref) => OcrService()); + +/// Tracks local OCR processing status per note ID. +/// +/// This map only ever holds an entry per note that has had OCR triggered in +/// the current session. To keep it from growing without bound over a long +/// session, prune terminal/stale entries via [OcrStatusX] (e.g. remove an +/// entry once its result has been surfaced, or call [OcrStatusX.pruneOcr] +/// after a sweep). Kept as a [StateProvider] so existing call sites that +/// assign `ocrStatusProvider.notifier.state` continue to work. +final ocrStatusProvider = StateProvider>((ref) => {}); + +/// Pruning helpers for [ocrStatusProvider] that keep its backing map bounded. +extension OcrStatusX on Ref { + /// Removes the tracked status for [noteId] (e.g. when its note is deleted + /// or its result has been consumed by the UI). + void clearOcr(String noteId) { + final current = read(ocrStatusProvider); + if (!current.containsKey(noteId)) return; + read(ocrStatusProvider.notifier).state = Map.from( + current, + )..remove(noteId); + } + + /// Drops all completed/failed entries, keeping only in-flight work so the + /// map stays bounded. + void pruneOcr() { + final current = read(ocrStatusProvider); + final next = { + for (final entry in current.entries) + if (entry.value == OcrStatus.processing) entry.key: entry.value, + }; + if (next.length != current.length) { + read(ocrStatusProvider.notifier).state = next; + } + } +} diff --git a/lib/providers/search_provider.dart b/lib/providers/search_provider.dart new file mode 100644 index 0000000..2e3c88a --- /dev/null +++ b/lib/providers/search_provider.dart @@ -0,0 +1,93 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/document.dart'; +import '../models/note.dart'; +import 'note_provider.dart'; + +final searchQueryProvider = StateProvider((ref) => ''); + +/// A search result that can be either a note hit or a document hit. +sealed class SearchResult { + const SearchResult(); +} + +class NoteSearchHit extends SearchResult { + final Note note; + final String snippet; + const NoteSearchHit({required this.note, this.snippet = ''}); +} + +class DocumentSearchHit extends SearchResult { + final String documentId; + final String filename; + final String filePath; + final int pageNumber; + final String snippet; + const DocumentSearchHit({ + required this.documentId, + required this.filename, + required this.filePath, + required this.pageNumber, + this.snippet = '', + }); +} + +final searchResultsProvider = FutureProvider>((ref) async { + final query = ref.watch(searchQueryProvider); + if (query.isEmpty) return []; + + // Obtain the DB through the provider graph so this participates in + // initialization and disposal like every other consumer. + final db = await ref.watch(databaseServiceProvider.future); + + // Run the note and document searches concurrently. + final searches = await Future.wait([ + db.searchNotes(query), + db.searchDocuments(query), + ]); + final noteHits = searches[0] as List; + final docHits = searches[1] as List>; + + final results = []; + + // Add note results. + for (final note in noteHits) { + results.add(NoteSearchHit(note: note, snippet: note.title)); + } + + // Resolve document metadata without an N+1 loop: collect the distinct + // document ids referenced by the hits, look each up exactly once, then + // build the result list from the cached lookups. + final docIds = { + for (final hit in docHits) + if (hit['document_id'] is String) hit['document_id'] as String, + }; + final docEntries = await Future.wait( + docIds.map((id) async => MapEntry(id, await db.getDocument(id))), + ); + final docsById = { + for (final entry in docEntries) + if (entry.value != null) entry.key: entry.value!, + }; + + for (final hit in docHits) { + final documentId = hit['document_id']; + if (documentId is! String) continue; + final doc = docsById[documentId]; + if (doc == null) continue; + + final pageNumber = hit['page_number']; + final content = hit['content']; + results.add( + DocumentSearchHit( + documentId: documentId, + filename: doc.filename, + filePath: doc.filePath, + pageNumber: pageNumber is int ? pageNumber : 0, + snippet: content is String ? content : '', + ), + ); + } + + return results; +}); diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart new file mode 100644 index 0000000..7c6a65c --- /dev/null +++ b/lib/providers/settings_provider.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/pen_tool.dart'; +import '../models/pressure_curve.dart'; +import '../utils/stroke_stabilizer.dart'; + +final settingsProvider = ChangeNotifierProvider( + (ref) => SettingsNotifier(), +); + +/// Persists user settings across sessions using SharedPreferences. +class SettingsNotifier extends ChangeNotifier { + late SharedPreferences _prefs; + + /// Completes once [_load] has assigned [_prefs]. Setters await this before + /// touching [_prefs] to avoid a LateInitializationError when invoked before + /// the fire-and-forget load from the constructor finishes. + late final Future _ready; + + PenTool _defaultTool = PenTool.pen; + Color _defaultColor = Colors.black; + double _defaultStrokeWidth = 2.0; + PressureCurveType _defaultPressureCurve = PressureCurveType.linear; + StabilizationLevel _defaultStabilization = StabilizationLevel.none; + ThemeMode _themeMode = ThemeMode.system; + Color _colorSchemeSeed = Colors.blue; + + SettingsNotifier() { + _ready = _load(); + } + + PenTool get defaultTool => _defaultTool; + Color get defaultColor => _defaultColor; + double get defaultStrokeWidth => _defaultStrokeWidth; + PressureCurveType get defaultPressureCurve => _defaultPressureCurve; + StabilizationLevel get defaultStabilization => _defaultStabilization; + ThemeMode get themeMode => _themeMode; + Color get colorSchemeSeed => _colorSchemeSeed; + + Future setDefaultTool(PenTool tool) async { + _defaultTool = tool; + notifyListeners(); + await _ready; + await _prefs.setString('defaultTool', tool.name); + } + + Future setDefaultColor(Color color) async { + _defaultColor = color; + notifyListeners(); + await _ready; + await _prefs.setInt('defaultColor', color.toARGB32()); + } + + Future setDefaultStrokeWidth(double width) async { + _defaultStrokeWidth = width; + notifyListeners(); + await _ready; + await _prefs.setDouble('defaultStrokeWidth', width); + } + + Future setDefaultPressureCurve(PressureCurveType curve) async { + _defaultPressureCurve = curve; + notifyListeners(); + await _ready; + await _prefs.setString('defaultPressureCurve', curve.name); + } + + Future setDefaultStabilization(StabilizationLevel level) async { + _defaultStabilization = level; + notifyListeners(); + await _ready; + await _prefs.setString('defaultStabilization', level.name); + } + + Future setThemeMode(ThemeMode mode) async { + _themeMode = mode; + notifyListeners(); + await _ready; + await _prefs.setString('themeMode', mode.name); + } + + Future setColorSchemeSeed(Color color) async { + _colorSchemeSeed = color; + notifyListeners(); + await _ready; + await _prefs.setInt('colorSchemeSeed', color.toARGB32()); + } + + Future clearAllData() async { + await _ready; + await _prefs.clear(); + _defaultTool = PenTool.pen; + _defaultColor = Colors.black; + _defaultStrokeWidth = 2.0; + _defaultPressureCurve = PressureCurveType.linear; + _defaultStabilization = StabilizationLevel.none; + _themeMode = ThemeMode.system; + _colorSchemeSeed = Colors.blue; + notifyListeners(); + } + + Future _load() async { + _prefs = await SharedPreferences.getInstance(); + + final toolName = _prefs.getString('defaultTool'); + if (toolName != null) { + _defaultTool = PenTool.values.asNameMap()[toolName] ?? PenTool.pen; + } + + final colorValue = _prefs.getInt('defaultColor'); + if (colorValue != null) { + _defaultColor = Color(colorValue); + } + + _defaultStrokeWidth = + _prefs.getDouble('defaultStrokeWidth') ?? _defaultStrokeWidth; + + final curveName = _prefs.getString('defaultPressureCurve'); + if (curveName != null) { + _defaultPressureCurve = + PressureCurveType.values.asNameMap()[curveName] ?? + PressureCurveType.linear; + } + + final stabName = _prefs.getString('defaultStabilization'); + if (stabName != null) { + _defaultStabilization = + StabilizationLevel.values.asNameMap()[stabName] ?? + StabilizationLevel.none; + } + + final themeName = _prefs.getString('themeMode'); + if (themeName != null) { + _themeMode = ThemeMode.values.asNameMap()[themeName] ?? ThemeMode.system; + } + + final seedValue = _prefs.getInt('colorSchemeSeed'); + if (seedValue != null) { + _colorSchemeSeed = Color(seedValue); + } + + notifyListeners(); + } +} diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart new file mode 100644 index 0000000..62f1645 --- /dev/null +++ b/lib/screens/home_screen.dart @@ -0,0 +1,743 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../models/document.dart'; +import '../models/note.dart'; +import '../providers/document_provider.dart'; +import '../providers/note_provider.dart'; +import '../providers/ocr_provider.dart'; +import '../services/pdf_service.dart'; +import '../services/pptx_service.dart'; +import 'note_editor_screen.dart'; +import 'pdf_annotator_screen.dart'; +import 'ppt_annotator_screen.dart'; +import 'search_screen.dart'; +import 'settings_screen.dart'; +import 'split_view_screen.dart'; + +// [M1] Relative date helper — no new package dependencies. +String _formatDate(DateTime d) { + final now = DateTime.now(); + final diff = now.difference(d); + if (diff.inSeconds < 60) return 'Just now'; + if (diff.inMinutes < 60) return '${diff.inMinutes}m ago'; + if (diff.inHours < 24) return '${diff.inHours}h ago'; + if (diff.inDays == 1 || (diff.inDays == 0 && now.day != d.day)) { + return 'Yesterday'; + } + return '${d.month}/${d.day}/${d.year} ${d.hour}:${d.minute.toString().padLeft(2, '0')}'; +} + +class HomeScreen extends ConsumerWidget { + const HomeScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final notesAsync = ref.watch(noteListProvider); + + return Scaffold( + appBar: AppBar( + title: const Text('BadNote'), + centerTitle: true, + actions: [ + IconButton( + icon: const Icon(Icons.settings), + tooltip: 'Settings', + onPressed: () { + Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => const SettingsScreen())); + }, + ), + IconButton( + icon: const Icon(Icons.picture_as_pdf), + tooltip: 'Import PDF', + onPressed: () => _importPdf(context), + ), + IconButton( + icon: const Icon(Icons.slideshow), + tooltip: 'Import PPT', + onPressed: () => _importPptx(context), + ), + IconButton( + icon: const Icon(Icons.search), + tooltip: 'Search', + onPressed: () { + Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => const SearchScreen())); + }, + ), + ], + ), + floatingActionButton: FloatingActionButton( + onPressed: () => _createAndOpenNote(context, ref), + child: const Icon(Icons.add), + ), + body: notesAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, _) => Center(child: Text('Error: $e')), + data: (notes) { + final documentsAsync = ref.watch(documentListProvider); + final documents = documentsAsync.valueOrNull ?? []; + + if (notes.isEmpty && documents.isEmpty) { + return _buildEmptyState(context, ref); + } + return RefreshIndicator( + onRefresh: () async { + await Future.wait([ + ref.read(noteListProvider.notifier).loadNotes(), + ref.read(documentListProvider.notifier).loadDocuments(), + ]); + }, + child: CustomScrollView( + slivers: [ + // Notes section header always shown when documents exist + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text( + 'Notes', + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ), + ), + if (notes.isNotEmpty) + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) => _NoteTile(note: notes[index]), + childCount: notes.length, + ), + ) + else + // [M2] Per-section empty hint when documents exist but notes don't + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + child: Center( + child: Text( + 'No ink notes yet — tap + to create one', + style: Theme.of(context).textTheme.bodyMedium + ?.copyWith( + color: Theme.of( + context, + ).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + ), + // Documents section header always shown when notes exist + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 4), + child: Text( + 'Recent Documents', + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ), + ), + if (documents.isNotEmpty) + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) => + _DocumentTile(document: documents[index]), + childCount: documents.length, + ), + ) + else + // [M2] Per-section empty hint when notes exist but documents don't + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + child: Center( + child: Text( + 'No documents yet — import a PDF or PPT', + style: Theme.of(context).textTheme.bodyMedium + ?.copyWith( + color: Theme.of( + context, + ).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + ), + const SliverToBoxAdapter(child: SizedBox(height: 80)), + ], + ), + ); + }, + ), + ); + } + + Future _createAndOpenNote(BuildContext context, WidgetRef ref) async { + final note = await ref.read(noteListProvider.notifier).createNote(); + if (context.mounted) { + Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => NoteEditorScreen(note: note))); + } + } + + Future _importPdf(BuildContext context) async { + final pdfService = PdfService(); + final filePath = await pdfService.pickPdfFile(); + if (filePath != null && context.mounted) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => PdfAnnotatorScreen(filePath: filePath), + ), + ); + } + } + + Future _importPptx(BuildContext context) async { + final pptxService = PptxService(); + final filePath = await pptxService.openPptxFile(); + if (filePath == null || !context.mounted) return; + + if (context.mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Processing PPTX...'))); + } + + final slideImages = await pptxService.convertToImages(filePath); + final extractedText = await pptxService.extractText(filePath); + + if (context.mounted) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => PptAnnotatorScreen( + filePath: filePath, + slideImagePaths: slideImages, + extractedText: extractedText.isEmpty ? null : extractedText, + ), + ), + ); + } + } + + Widget _buildEmptyState(BuildContext context, WidgetRef ref) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.edit_note, + size: 80, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(height: 24), + Text( + 'No notes yet', + style: Theme.of( + context, + ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Text( + 'Create your first note', + style: Theme.of(context).textTheme.bodyLarge?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 32), + FilledButton.icon( + onPressed: () => _createAndOpenNote(context, ref), + icon: const Icon(Icons.add), + label: const Text('New Note'), + ), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: () => _importPdf(context), + icon: const Icon(Icons.picture_as_pdf), + label: const Text('Import PDF'), + ), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: () => _importPptx(context), + icon: const Icon(Icons.slideshow), + label: const Text('Import PPT'), + ), + ], + ), + ); + } +} + +class _NoteTile extends ConsumerStatefulWidget { + final Note note; + const _NoteTile({required this.note}); + + @override + ConsumerState<_NoteTile> createState() => _NoteTileState(); +} + +class _NoteTileState extends ConsumerState<_NoteTile> { + bool _hovering = false; + + @override + Widget build(BuildContext context) { + final note = widget.note; + // [M1] Use relative date helper + final dateStr = _formatDate(note.updatedAt); + + final ocrStatusMap = ref.watch(ocrStatusProvider); + final ocrStatus = ocrStatusMap[note.id] ?? OcrStatus.none; + + final subtleColor = Theme.of(context).colorScheme.onSurfaceVariant; + + // [H2] Right-click context menu via GestureDetector + MouseRegion for hover + return GestureDetector( + onSecondaryTapDown: (details) => + _showContextMenu(context, details.globalPosition), + child: MouseRegion( + onEnter: (_) => setState(() => _hovering = true), + onExit: (_) => setState(() => _hovering = false), + child: ListTile( + title: Row( + children: [ + Expanded( + child: Text( + note.title.isEmpty ? 'Untitled' : note.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + _OcrStatusBadge(status: ocrStatus), + ], + ), + subtitle: Padding( + padding: const EdgeInsets.only(top: 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${note.strokes.length} stroke${note.strokes.length == 1 ? '' : 's'} · $dateStr', + style: Theme.of(context).textTheme.bodySmall, + ), + if (note.tags.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Wrap( + spacing: 4, + children: note.tags + .map( + (t) => Chip( + label: Text( + t, + style: const TextStyle(fontSize: 11), + ), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + materialTapTargetSize: + MaterialTapTargetSize.shrinkWrap, + ), + ) + .toList(), + ), + ), + ], + ), + ), + // [H2] Trailing delete button — always visible with subdued color, brighter on hover + trailing: IconButton( + icon: Icon( + Icons.delete_outline, + color: _hovering + ? Theme.of(context).colorScheme.error + : subtleColor.withValues(alpha: 0.4), + ), + tooltip: 'Delete note', + onPressed: () => _confirmDelete(context), + ), + onTap: () { + Navigator.of(context).push( + MaterialPageRoute(builder: (_) => NoteEditorScreen(note: note)), + ); + }, + onLongPress: () => _confirmDelete(context), + ), + ), + ); + } + + void _showContextMenu(BuildContext context, Offset position) async { + final result = await showMenu( + context: context, + position: RelativeRect.fromLTRB( + position.dx, + position.dy, + position.dx + 1, + position.dy + 1, + ), + items: [ + PopupMenuItem( + value: 'open', + child: Row( + children: const [ + Icon(Icons.edit_outlined), + SizedBox(width: 8), + Text('Open'), + ], + ), + ), + PopupMenuItem( + value: 'delete', + child: Row( + children: [ + Icon( + Icons.delete_outline, + color: Theme.of(context).colorScheme.error, + ), + const SizedBox(width: 8), + Text( + 'Delete', + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ], + ), + ), + ], + ); + if (!mounted) return; + if (result == 'open') { + Navigator.of(this.context).push( + MaterialPageRoute(builder: (_) => NoteEditorScreen(note: widget.note)), + ); + } else if (result == 'delete') { + _confirmDelete(this.context); + } + } + + void _confirmDelete(BuildContext context) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Delete note?'), + content: Text( + 'Delete "${widget.note.title.isEmpty ? 'Untitled' : widget.note.title}"?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + ref.read(noteListProvider.notifier).deleteNote(widget.note.id); + Navigator.pop(ctx); + }, + child: const Text('Delete'), + ), + ], + ), + ); + } +} + +class _DocumentTile extends ConsumerStatefulWidget { + final Document document; + const _DocumentTile({required this.document}); + + @override + ConsumerState<_DocumentTile> createState() => _DocumentTileState(); +} + +class _DocumentTileState extends ConsumerState<_DocumentTile> { + bool _hovering = false; + + @override + Widget build(BuildContext context) { + final document = widget.document; + // [M1] Use relative date helper + final dateStr = _formatDate(document.updatedAt); + final isPdf = document.docType == 'pdf'; + + final subtleColor = Theme.of(context).colorScheme.onSurfaceVariant; + + // [H2] Right-click context menu + MouseRegion + trailing action buttons + return GestureDetector( + onSecondaryTapDown: (details) => + _showContextMenu(context, details.globalPosition), + child: MouseRegion( + onEnter: (_) => setState(() => _hovering = true), + onExit: (_) => setState(() => _hovering = false), + child: ListTile( + leading: Icon( + isPdf ? Icons.picture_as_pdf : Icons.slideshow, + color: isPdf ? Colors.red : Colors.orange, + ), + title: Text( + document.filename, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text( + '${document.docType.toUpperCase()} · ${document.pageCount} pages · $dateStr', + style: Theme.of(context).textTheme.bodySmall, + ), + // [H2] Trailing row: split-view (PDF only) + remove + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isPdf) + IconButton( + icon: Icon( + Icons.vertical_split, + color: _hovering + ? Theme.of(context).colorScheme.primary + : subtleColor.withValues(alpha: 0.4), + ), + tooltip: 'Open in Split View', + onPressed: () => _openSplitView(context), + ), + IconButton( + icon: Icon( + Icons.delete_outline, + color: _hovering + ? Theme.of(context).colorScheme.error + : subtleColor.withValues(alpha: 0.4), + ), + tooltip: 'Remove document', + onPressed: () => _confirmDelete(context), + ), + ], + ), + // [L2] Routing bug fix: route by docType + onTap: () => _openDocument(context), + onLongPress: () => _showDocumentMenu(context), + ), + ), + ); + } + + // [L2] Route by docType: pdf → PdfAnnotatorScreen, ppt/pptx → PptAnnotatorScreen + Future _openDocument(BuildContext context) async { + final document = widget.document; + final isPdf = document.docType == 'pdf'; + + if (isPdf) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => PdfAnnotatorScreen(filePath: document.filePath), + ), + ); + } else { + // PPT/PPTX: convert to images then push PptAnnotatorScreen + if (mounted) { + ScaffoldMessenger.of(this.context).showSnackBar( + const SnackBar(content: Text('Processing presentation...')), + ); + } + final pptxService = PptxService(); + final slideImages = await pptxService.convertToImages(document.filePath); + final extractedText = await pptxService.extractText(document.filePath); + if (!mounted) return; + if (slideImages.isEmpty) { + ScaffoldMessenger.of(this.context).showSnackBar( + const SnackBar(content: Text('Could not open presentation.')), + ); + return; + } + Navigator.of(this.context).push( + MaterialPageRoute( + builder: (_) => PptAnnotatorScreen( + filePath: document.filePath, + slideImagePaths: slideImages, + extractedText: extractedText.isEmpty ? null : extractedText, + ), + ), + ); + } + } + + void _openSplitView(BuildContext context) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SplitViewScreen( + filePath: widget.document.filePath, + documentId: widget.document.id, + ), + ), + ); + } + + void _showContextMenu(BuildContext context, Offset position) async { + final isPdf = widget.document.docType == 'pdf'; + final result = await showMenu( + context: context, + position: RelativeRect.fromLTRB( + position.dx, + position.dy, + position.dx + 1, + position.dy + 1, + ), + items: [ + PopupMenuItem( + value: 'open', + child: Row( + children: const [ + Icon(Icons.open_in_new), + SizedBox(width: 8), + Text('Open'), + ], + ), + ), + if (isPdf) + PopupMenuItem( + value: 'split', + child: Row( + children: const [ + Icon(Icons.vertical_split), + SizedBox(width: 8), + Text('Open in Split View'), + ], + ), + ), + PopupMenuItem( + value: 'remove', + child: Row( + children: [ + Icon( + Icons.delete_outline, + color: Theme.of(context).colorScheme.error, + ), + const SizedBox(width: 8), + Text( + 'Remove', + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ], + ), + ), + ], + ); + if (!mounted) return; + if (result == 'open') { + _openDocument(this.context); + } else if (result == 'split') { + _openSplitView(this.context); + } else if (result == 'remove') { + _confirmDelete(this.context); + } + } + + void _showDocumentMenu(BuildContext context) { + final isPdf = widget.document.docType == 'pdf'; + showModalBottomSheet( + context: context, + builder: (ctx) { + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (isPdf) + ListTile( + leading: const Icon(Icons.vertical_split), + title: const Text('Open in Split View'), + subtitle: const Text('PDF reference + scratchpad'), + onTap: () { + Navigator.of(ctx).pop(); + _openSplitView(context); + }, + ), + ListTile( + leading: const Icon(Icons.delete_outline, color: Colors.red), + title: const Text( + 'Remove document', + style: TextStyle(color: Colors.red), + ), + onTap: () { + Navigator.of(ctx).pop(); + _confirmDelete(context); + }, + ), + ], + ), + ); + }, + ); + } + + void _confirmDelete(BuildContext context) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Remove document?'), + content: Text( + 'Remove "${widget.document.filename}" from recent documents?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + ref + .read(documentListProvider.notifier) + .removeDocument(widget.document.id); + Navigator.pop(ctx); + }, + child: const Text('Remove'), + ), + ], + ), + ); + } +} + +// [M3] OCR status badge with semantic theme colors and tooltips +class _OcrStatusBadge extends StatelessWidget { + final OcrStatus status; + const _OcrStatusBadge({required this.status}); + + @override + Widget build(BuildContext context) { + switch (status) { + case OcrStatus.none: + return const SizedBox.shrink(); + case OcrStatus.processing: + return Tooltip( + message: 'Processing OCR…', + child: const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 1.5), + ), + ); + case OcrStatus.done: + return Tooltip( + message: 'OCR complete', + child: Icon( + Icons.check_circle, + size: 16, + color: Theme.of(context).colorScheme.primary, + ), + ); + case OcrStatus.failed: + return Tooltip( + message: 'OCR failed', + child: Icon( + Icons.error_outline, + size: 16, + color: Theme.of(context).colorScheme.error, + ), + ); + } + } +} diff --git a/lib/screens/note_editor_screen.dart b/lib/screens/note_editor_screen.dart new file mode 100644 index 0000000..b838032 --- /dev/null +++ b/lib/screens/note_editor_screen.dart @@ -0,0 +1,303 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart' hide UndoManager; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/ink_stroke.dart'; +import '../models/note.dart'; +import '../models/pen_tool.dart'; +import '../models/pressure_curve.dart'; +import '../providers/note_provider.dart'; +import '../providers/ocr_provider.dart'; +import '../services/undo_manager.dart'; +import '../utils/stroke_stabilizer.dart'; +import '../widgets/annotation_toolbar.dart'; +import '../widgets/ink_canvas.dart'; + +class NoteEditorScreen extends ConsumerStatefulWidget { + final Note? note; + + const NoteEditorScreen({super.key, this.note}); + + @override + ConsumerState createState() => _NoteEditorScreenState(); +} + +class _NoteEditorScreenState extends ConsumerState { + final UndoManager _undoManager = UndoManager(); + PenTool _currentTool = PenTool.pen; + Color _currentColor = Colors.black; + double _currentStrokeWidth = 2.0; + bool _filled = false; + String _title = 'Untitled'; + final TextEditingController _titleController = TextEditingController(); + PressureCurveType _pressureCurveType = PressureCurveType.linear; + StabilizationLevel _stabilizationLevel = StabilizationLevel.none; + final TransformationController _zoomController = TransformationController(); + double _zoomLevel = 1.0; + + bool _isDirty = false; + + Note? get _existingNote => widget.note; + + PressureCurve get _pressureCurve { + switch (_pressureCurveType) { + case PressureCurveType.linear: + return PressureCurve.linear; + case PressureCurveType.soft: + return PressureCurve.soft; + case PressureCurveType.hard: + return PressureCurve.hard; + case PressureCurveType.custom: + return const PressureCurve(type: PressureCurveType.custom); + } + } + + @override + void initState() { + super.initState(); + if (_existingNote != null) { + _title = _existingNote!.title; + for (final stroke in _existingNote!.strokes) { + _undoManager.addStroke(stroke); + } + } + _titleController.text = _title; + } + + @override + void dispose() { + _titleController.dispose(); + _zoomController.dispose(); + super.dispose(); + } + + void _onStrokeComplete(InkStroke stroke) { + setState(() { + _undoManager.addStroke(stroke); + _isDirty = true; + }); + } + + void _onErase(String strokeId, List replacements) { + setState(() { + final original = _undoManager.currentStrokes + .where((s) => s.id == strokeId) + .firstOrNull; + if (original != null) { + _undoManager.removeStroke(original, replacements: replacements); + _isDirty = true; + } + }); + } + + void _undo() { + setState(() { + _undoManager.undo(); + _isDirty = true; + }); + } + + void _redo() { + setState(() { + _undoManager.redo(); + _isDirty = true; + }); + } + + Future _save() async { + final notifier = ref.read(noteListProvider.notifier); + final now = DateTime.now(); + + Note savedNote; + if (_existingNote != null) { + final updated = _existingNote!.copyWith( + title: _title, + strokes: _undoManager.currentStrokes.toList(), + updatedAt: now, + ); + await notifier.updateNote(updated); + savedNote = updated; + } else { + final note = await notifier.createNote(title: _title); + final updated = note.copyWith( + strokes: _undoManager.currentStrokes.toList(), + ); + await notifier.updateNote(updated); + savedNote = updated; + } + + if (!mounted) return; + setState(() { + _isDirty = false; + }); + + _runLocalOcr(savedNote); + } + + /// Run local OCR and index results for search. + void _runLocalOcr(Note note) { + final noteId = note.id; + ref.read(ocrStatusProvider.notifier).state = { + ...ref.read(ocrStatusProvider), + noteId: OcrStatus.processing, + }; + + ref + .read(ocrServiceProvider) + .processNote(note) + .then((_) { + if (!mounted) return; + ref.read(ocrStatusProvider.notifier).state = { + ...ref.read(ocrStatusProvider), + noteId: OcrStatus.done, + }; + }) + .catchError((_) { + if (!mounted) return; + ref.read(ocrStatusProvider.notifier).state = { + ...ref.read(ocrStatusProvider), + noteId: OcrStatus.failed, + }; + }); + } + + void _zoomIn() { + final newLevel = (_zoomLevel + 0.25).clamp(0.5, 5.0); + _applyZoom(newLevel); + } + + void _zoomOut() { + final newLevel = (_zoomLevel - 0.25).clamp(0.5, 5.0); + _applyZoom(newLevel); + } + + void _zoomReset() { + _applyZoom(1.0); + } + + void _applyZoom(double level) { + setState(() => _zoomLevel = level); + _zoomController.value = Matrix4.diagonal3Values(level, level, 1.0); + } + + Future _saveAndNotify() async { + await _save(); + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Saved'))); + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: true, + onPopInvokedWithResult: (didPop, _) { + if (didPop && _isDirty) _save(); + }, + child: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.keyZ, control: true): _undo, + const SingleActivator(LogicalKeyboardKey.keyY, control: true): _redo, + const SingleActivator( + LogicalKeyboardKey.keyZ, + control: true, + shift: true, + ): _redo, + SingleActivator(LogicalKeyboardKey.keyS, control: true): + _saveAndNotify, + }, + child: Focus( + autofocus: true, + child: Scaffold( + appBar: AppBar( + title: SizedBox( + height: 40, + child: TextField( + controller: _titleController, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + ), + decoration: InputDecoration( + border: InputBorder.none, + hintText: 'Note title...', + contentPadding: const EdgeInsets.symmetric(vertical: 8), + suffix: _isDirty + ? const Text( + ' •', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18, + ), + ) + : null, + ), + onChanged: (value) { + _title = value; + setState(() => _isDirty = true); + }, + ), + ), + actions: [ + IconButton( + icon: const Icon(Icons.check), + tooltip: 'Save', + onPressed: _saveAndNotify, + ), + ], + ), + body: Column( + children: [ + AnnotationToolbar( + currentTool: _currentTool, + currentColor: _currentColor, + currentStrokeWidth: _currentStrokeWidth, + filled: _filled, + pressureCurveType: _pressureCurveType, + stabilizationLevel: _stabilizationLevel, + canUndo: _undoManager.canUndo, + canRedo: _undoManager.canRedo, + onToolChanged: (tool) => setState(() => _currentTool = tool), + onColorChanged: (color) => + setState(() => _currentColor = color), + onStrokeWidthChanged: (w) => + setState(() => _currentStrokeWidth = w), + onFilledChanged: (f) => setState(() => _filled = f), + onPressureCurveChanged: (v) => + setState(() => _pressureCurveType = v), + onStabilizationChanged: (v) => + setState(() => _stabilizationLevel = v), + onUndo: _undo, + onRedo: _redo, + onZoomIn: _zoomIn, + onZoomOut: _zoomOut, + onZoomFitWidth: _zoomReset, + zoomLabel: '${(_zoomLevel * 100).round()}%', + ), + Expanded( + child: InteractiveViewer( + transformationController: _zoomController, + minScale: 0.5, + maxScale: 5.0, + child: InkCanvas( + strokes: _undoManager.currentStrokes, + onStrokeComplete: _onStrokeComplete, + onErase: _onErase, + tool: _currentTool, + color: _currentColor, + strokeWidth: _currentStrokeWidth, + pressureCurve: _pressureCurve, + stabilizationLevel: _stabilizationLevel, + filled: _filled, + ), + ), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/screens/pdf_annotator_screen.dart b/lib/screens/pdf_annotator_screen.dart new file mode 100644 index 0000000..38244b0 --- /dev/null +++ b/lib/screens/pdf_annotator_screen.dart @@ -0,0 +1,981 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart' hide UndoManager; +import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart'; +import 'package:uuid/uuid.dart'; + +import '../models/bookmark.dart'; +import '../models/document.dart'; +import '../models/ink_stroke.dart'; +import '../models/pen_tool.dart'; +import '../models/pressure_curve.dart'; +import '../services/camera_service.dart'; +import '../services/database_service.dart'; +import '../services/pdf_service.dart'; +import '../services/thumbnail_service.dart'; +import '../services/undo_manager.dart'; +import '../utils/stroke_stabilizer.dart'; +import '../widgets/annotation_toolbar.dart'; +import '../widgets/ink_canvas.dart'; +import '../widgets/page_thumbnail_sidebar.dart'; +import '../widgets/pdf_annotation_layer.dart'; +import 'pdf_text_search.dart'; +import 'split_view_screen.dart'; + +const _uuid = Uuid(); + +/// Actions available in the AppBar overflow menu. +enum _OverflowAction { pageManagement, cameraInsert, export } + +/// Full-screen PDF viewer with ink annotation overlay. +/// +/// Displays a PDF page-by-page with a transparent [PdfAnnotationLayer] +/// on top for pen/marker/eraser annotations. Annotations are stored +/// per page in normalized [0, 1] coordinates and exported via [PdfService]. +/// Annotations and bookmarks are persisted to the database. +class PdfAnnotatorScreen extends StatefulWidget { + final String filePath; + final int initialPage; + + const PdfAnnotatorScreen({ + super.key, + required this.filePath, + this.initialPage = 0, + }); + + @override + State createState() => _PdfAnnotatorScreenState(); +} + +class _PdfAnnotatorScreenState extends State { + final PdfService _pdfService = PdfService(); + final CameraService _cameraService = CameraService(); + final PdfViewerController _viewerController = PdfViewerController(); + final GlobalKey _scaffoldKey = GlobalKey(); + + int _currentPage = 0; + int _pageCount = 0; + int _pdfMutationVersion = 0; + String _fileName = ''; + PenTool _currentTool = PenTool.pen; + Color _currentColor = Colors.black; + double _currentStrokeWidth = 2.0; + bool _filled = false; + PressureCurveType _pressureCurveType = PressureCurveType.linear; + StabilizationLevel _stabilizationLevel = StabilizationLevel.none; + InteractionMode _interactionMode = InteractionMode.draw; + double _zoomLevel = 1.0; + bool _showThumbnails = false; + + String? _currentDocumentId; + final Map _undoManagers = {}; + final Map> _annotations = {}; + + List _bookmarks = []; + + @override + void initState() { + super.initState(); + _currentPage = widget.initialPage; + _loadPdfInfo(); + } + + Future _loadPdfInfo() async { + final info = await _pdfService.getPdfInfo(widget.filePath); + final count = await _pdfService.getPageCount(widget.filePath); + if (mounted) { + setState(() { + _fileName = info['fileName'] as String; + _pageCount = count; + }); + await _ensureDocumentExists(); + await _loadAllAnnotations(); + await _loadBookmarks(); + } + } + + Future _ensureDocumentExists() async { + final db = await DatabaseService.getInstance(); + final existing = await db.getDocumentByPath(widget.filePath); + if (existing == null) { + final now = DateTime.now(); + final newDoc = Document( + id: _uuid.v4(), + filename: _fileName, + docType: 'pdf', + filePath: widget.filePath, + pageCount: _pageCount, + createdAt: now, + updatedAt: now, + ); + await db.insertDocument(newDoc); + _currentDocumentId = newDoc.id; + } else { + _currentDocumentId = existing.id; + } + } + + Future _loadAllAnnotations() async { + if (_currentDocumentId == null) return; + final db = await DatabaseService.getInstance(); + for (int i = 0; i < _pageCount; i++) { + final json = await db.getAnnotations(_currentDocumentId!, i); + if (json != null && json.isNotEmpty) { + final List list = jsonDecode(json) as List; + _annotations[i] = list + .map((s) => InkStroke.fromJson(s as Map)) + .toList(); + _undoManagers[i] = UndoManager(); + for (final stroke in _annotations[i]!) { + _undoManagers[i]!.addStroke(stroke); + } + } + } + if (mounted) setState(() {}); + } + + void _saveCurrentPageAnnotations({int? page}) async { + if (_currentDocumentId == null) return; + // Capture the page index and serialize its strokes SYNCHRONOUSLY, before + // any await. Otherwise a concurrent navigation could change _currentPage + // while this is suspended, causing the wrong page's data to be saved. + final targetPage = page ?? _currentPage; + final documentId = _currentDocumentId!; + final strokesJson = jsonEncode( + _annotations[targetPage]?.map((s) => s.toJson()).toList() ?? [], + ); + final db = await DatabaseService.getInstance(); + await db.saveAnnotations(documentId, targetPage, strokesJson); + } + + void _onPageChanged(int page) { + // Save the page we are leaving, not the one we are navigating to. + _saveCurrentPageAnnotations(page: _currentPage); + setState(() { + _currentPage = page; + }); + } + + UndoManager _getUndoManager(int page) { + return _undoManagers.putIfAbsent(page, UndoManager.new); + } + + List _getCurrentStrokes() { + return _annotations[_currentPage] ?? []; + } + + void _onStrokeComplete(InkStroke stroke) { + setState(() { + _annotations.putIfAbsent(_currentPage, () => []); + _annotations[_currentPage]!.add(stroke); + _getUndoManager(_currentPage).addStroke(stroke); + }); + _saveCurrentPageAnnotations(); + } + + void _onErase(String strokeId, List replacements) { + setState(() { + final pageStrokes = _annotations[_currentPage]; + if (pageStrokes == null) return; + final original = pageStrokes.where((s) => s.id == strokeId).firstOrNull; + if (original != null) { + _getUndoManager( + _currentPage, + ).removeStroke(original, replacements: replacements); + _annotations[_currentPage] = _getUndoManager( + _currentPage, + ).currentStrokes.toList(); + } + }); + _saveCurrentPageAnnotations(); + } + + void _undo() { + setState(() { + _getUndoManager(_currentPage).undo(); + _annotations[_currentPage] = _getUndoManager( + _currentPage, + ).currentStrokes.toList(); + }); + _saveCurrentPageAnnotations(); + } + + void _redo() { + setState(() { + _getUndoManager(_currentPage).redo(); + _annotations[_currentPage] = _getUndoManager( + _currentPage, + ).currentStrokes.toList(); + }); + _saveCurrentPageAnnotations(); + } + + // -- Bookmarks -- + + bool get _isCurrentPageBookmarked => + _bookmarks.any((b) => b.pageNumber == _currentPage); + + Future _loadBookmarks() async { + if (_currentDocumentId == null) return; + final db = await DatabaseService.getInstance(); + final bookmarks = await db.getBookmarks(_currentDocumentId!); + if (mounted) { + setState(() { + _bookmarks = bookmarks; + }); + } + } + + Future _toggleBookmark() async { + if (_currentDocumentId == null) return; + final db = await DatabaseService.getInstance(); + + if (_isCurrentPageBookmarked) { + final existing = _bookmarks.firstWhere( + (b) => b.pageNumber == _currentPage, + ); + await db.deleteBookmark(existing.id); + setState(() { + _bookmarks.removeWhere((b) => b.id == existing.id); + }); + } else { + final label = await _showBookmarkDialog(); + if (label == null) return; + + final bookmark = Bookmark( + id: _uuid.v4(), + documentId: _currentDocumentId!, + pageNumber: _currentPage, + label: label, + createdAt: DateTime.now(), + ); + await db.insertBookmark(bookmark); + setState(() { + _bookmarks.add(bookmark); + _bookmarks.sort((a, b) => a.pageNumber.compareTo(b.pageNumber)); + }); + } + } + + Future _showBookmarkDialog() async { + final controller = TextEditingController(); + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: const Text('Add Bookmark'), + content: TextField( + controller: controller, + decoration: const InputDecoration( + hintText: 'Label (optional)', + labelText: 'Bookmark label', + ), + autofocus: true, + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(controller.text), + child: const Text('Add'), + ), + ], + ); + }, + ); + } + + Future _deleteBookmark(Bookmark bookmark) async { + final db = await DatabaseService.getInstance(); + await db.deleteBookmark(bookmark.id); + setState(() { + _bookmarks.removeWhere((b) => b.id == bookmark.id); + }); + } + + void _jumpToPage(int page) { + _saveCurrentPageAnnotations(); + _viewerController.jumpToPage(page + 1); + } + + // -- Zoom -- + + void _zoomIn() { + final newLevel = (_zoomLevel + 0.25).clamp(0.5, 5.0); + _viewerController.zoomLevel = newLevel; + setState(() => _zoomLevel = newLevel); + } + + void _zoomOut() { + final newLevel = (_zoomLevel - 0.25).clamp(0.5, 5.0); + _viewerController.zoomLevel = newLevel; + setState(() => _zoomLevel = newLevel); + } + + void _zoomFitWidth() { + _viewerController.zoomLevel = 1.0; + setState(() => _zoomLevel = 1.0); + } + + // -- Search -- + + void _openSearch() { + showDialog( + context: context, + builder: (_) => PdfTextSearchDialog(viewerController: _viewerController), + ); + } + + // -- Export -- + + Future _exportPdf() async { + try { + final outputPath = await _pdfService.exportAnnotatedPdf( + widget.filePath, + _annotations, + ); + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Exported to: $outputPath'))); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Export failed: $e'))); + } + } + } + + // -- Page Management -- + + void _showPageManagementSheet() { + showModalBottomSheet( + context: context, + builder: (context) { + final canDelete = _pageCount > 1; + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.rotate_right), + title: const Text('Rotate Page 90\u00B0'), + subtitle: Text('Page ${_currentPage + 1}'), + onTap: () { + Navigator.of(context).pop(); + _rotateCurrentPage(); + }, + ), + ListTile( + leading: Icon( + Icons.delete_outline, + color: canDelete ? null : Colors.grey, + ), + title: Text( + 'Delete Page', + style: TextStyle(color: canDelete ? null : Colors.grey), + ), + subtitle: Text( + canDelete + ? 'Page ${_currentPage + 1}' + : 'Cannot delete the only page', + ), + enabled: canDelete, + onTap: canDelete + ? () { + Navigator.of(context).pop(); + _deleteCurrentPage(); + } + : null, + ), + ListTile( + leading: const Icon(Icons.note_add_outlined), + title: const Text('Insert Blank Page After Current'), + subtitle: Text('After page ${_currentPage + 1}'), + onTap: () { + Navigator.of(context).pop(); + _insertBlankPageAfterCurrent(); + }, + ), + ], + ), + ); + }, + ); + } + + /// Transform a stroke's normalized [0,1] points to match a 90° clockwise + /// page rotation: a point at (x, y) maps to (1 - y, x). Used to keep + /// existing annotations glued to the page content after the page itself is + /// physically rotated (PDF /Rotate). + InkStroke _rotateStroke90CW(InkStroke stroke) { + return stroke.copyWith( + points: stroke.points + .map((p) => p.copyWith(x: 1.0 - p.y, y: p.x)) + .toList(), + ); + } + + Future _rotateCurrentPage() async { + final rotatedPage = _currentPage; + final success = await _pdfService.rotatePage(widget.filePath, rotatedPage); + if (!success || !mounted) return; + // Invalidate thumbnail for the rotated page. + if (_currentDocumentId != null) { + await ThumbnailService.invalidatePage(_currentDocumentId!, rotatedPage); + } + setState(() { + _pdfMutationVersion++; + // The page is physically rotated 90° CW, so transform existing stored + // annotations the same way to keep them aligned with the page content. + // New strokes drawn afterwards are already captured in the rotated frame. + final existing = _annotations[rotatedPage]; + if (existing != null && existing.isNotEmpty) { + _annotations[rotatedPage] = existing.map(_rotateStroke90CW).toList(); + // Undo history holds pre-rotation coordinates; reset it for this page + // so undo/redo cannot reintroduce misaligned strokes. + _undoManagers.remove(rotatedPage); + } + }); + // Persist the transformed annotations for the rotated page. + _saveCurrentPageAnnotations(page: rotatedPage); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Rotated page ${_currentPage + 1}')), + ); + } + } + + Future _deleteCurrentPage() async { + // Confirm. + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Delete Page'), + content: Text( + 'Delete page ${_currentPage + 1}? This cannot be undone.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Delete', style: TextStyle(color: Colors.red)), + ), + ], + ), + ); + if (confirmed != true) return; + + final success = await _pdfService.deletePage(widget.filePath, _currentPage); + if (!success || !mounted) return; + + if (_currentDocumentId != null) { + final db = await DatabaseService.getInstance(); + // Delete annotation/bookmark/ocr data for the removed page. + await db.deletePageData(_currentDocumentId!, _currentPage); + // Remap higher-indexed data down by 1. + await db.remapAnnotationsAfterDelete(_currentDocumentId!, _currentPage); + await db.remapBookmarksAfterDelete(_currentDocumentId!, _currentPage); + // Update stored page count. + final newCount = _pageCount - 1; + await db.updateDocumentPageCount(_currentDocumentId!, newCount); + // Invalidate all thumbnails (page indices shifted). + await ThumbnailService.invalidateAll(_currentDocumentId!); + } + + // Shift in-memory annotations down. + final newAnnotations = >{}; + for (final entry in _annotations.entries) { + if (entry.key < _currentPage) { + newAnnotations[entry.key] = entry.value; + } else if (entry.key > _currentPage) { + newAnnotations[entry.key - 1] = entry.value; + } + // entry.key == _currentPage is dropped. + } + _annotations + ..clear() + ..addAll(newAnnotations); + + // Shift undo managers. + final newUndoManagers = {}; + for (final entry in _undoManagers.entries) { + if (entry.key < _currentPage) { + newUndoManagers[entry.key] = entry.value; + } else if (entry.key > _currentPage) { + newUndoManagers[entry.key - 1] = entry.value; + } + } + _undoManagers + ..clear() + ..addAll(newUndoManagers); + + // Shift bookmarks in memory. + _bookmarks.removeWhere((b) => b.pageNumber == _currentPage); + for (int i = 0; i < _bookmarks.length; i++) { + if (_bookmarks[i].pageNumber > _currentPage) { + _bookmarks[i] = Bookmark( + id: _bookmarks[i].id, + documentId: _bookmarks[i].documentId, + pageNumber: _bookmarks[i].pageNumber - 1, + label: _bookmarks[i].label, + color: _bookmarks[i].color, + createdAt: _bookmarks[i].createdAt, + ); + } + } + + setState(() { + _pageCount = _pageCount - 1; + if (_currentPage >= _pageCount) { + _currentPage = _pageCount - 1; + } + _pdfMutationVersion++; + }); + + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Page deleted'))); + } + } + + Future _insertBlankPageAfterCurrent() async { + final success = await _pdfService.insertBlankPage( + widget.filePath, + _currentPage, + ); + if (!success || !mounted) return; + + final insertedIndex = _currentPage + 1; + if (_currentDocumentId != null) { + final db = await DatabaseService.getInstance(); + await db.remapAnnotationsAfterInsert(_currentDocumentId!, insertedIndex); + await db.remapBookmarksAfterInsert(_currentDocumentId!, insertedIndex); + final newCount = _pageCount + 1; + await db.updateDocumentPageCount(_currentDocumentId!, newCount); + await ThumbnailService.invalidateAll(_currentDocumentId!); + } + + // Shift in-memory annotations up by 1 for pages >= insertedIndex. + final newAnnotations = >{}; + for (final entry in _annotations.entries) { + if (entry.key < insertedIndex) { + newAnnotations[entry.key] = entry.value; + } else { + newAnnotations[entry.key + 1] = entry.value; + } + } + _annotations + ..clear() + ..addAll(newAnnotations); + + final newUndoManagers = {}; + for (final entry in _undoManagers.entries) { + if (entry.key < insertedIndex) { + newUndoManagers[entry.key] = entry.value; + } else { + newUndoManagers[entry.key + 1] = entry.value; + } + } + _undoManagers + ..clear() + ..addAll(newUndoManagers); + + // Shift bookmarks in memory. + for (int i = 0; i < _bookmarks.length; i++) { + if (_bookmarks[i].pageNumber >= insertedIndex) { + _bookmarks[i] = Bookmark( + id: _bookmarks[i].id, + documentId: _bookmarks[i].documentId, + pageNumber: _bookmarks[i].pageNumber + 1, + label: _bookmarks[i].label, + color: _bookmarks[i].color, + createdAt: _bookmarks[i].createdAt, + ); + } + } + + setState(() { + _pageCount = _pageCount + 1; + _pdfMutationVersion++; + }); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Blank page inserted after page ${_currentPage + 1}'), + ), + ); + } + } + + // -- Camera Insert -- + + Future _showCameraInsertDialog() async { + final source = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('Insert Image'), + children: [ + SimpleDialogOption( + onPressed: () => Navigator.of(context).pop('camera'), + child: const ListTile( + leading: Icon(Icons.camera_alt), + title: Text('Camera'), + ), + ), + SimpleDialogOption( + onPressed: () => Navigator.of(context).pop('gallery'), + child: const ListTile( + leading: Icon(Icons.photo_library), + title: Text('Gallery'), + ), + ), + ], + ), + ); + if (source == null || !mounted) return; + + final String? imagePath; + if (source == 'camera') { + imagePath = await _cameraService.capturePhoto(); + } else { + imagePath = await _cameraService.pickFromGallery(); + } + if (imagePath == null || !mounted) return; + + final result = await _pdfService.insertImageOnPage( + widget.filePath, + _currentPage, + imagePath, + ); + if (result != null && mounted) { + if (_currentDocumentId != null) { + await ThumbnailService.invalidatePage( + _currentDocumentId!, + _currentPage, + ); + } + setState(() { + _pdfMutationVersion++; + }); + // Save current annotations so they overlay the image. + _saveCurrentPageAnnotations(); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Image inserted on page ${_currentPage + 1}')), + ); + } + } else if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Failed to insert image'))); + } + } + + // -- Bookmark drawer -- + + Widget _buildBookmarkDrawer() { + return Drawer( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Text( + 'Bookmarks', + style: Theme.of(context).textTheme.headlineSmall, + ), + ), + Expanded( + child: _bookmarks.isEmpty + ? Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.bookmark_border, + size: 48, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + const SizedBox(height: 12), + const Text( + 'No bookmarks yet', + style: TextStyle(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 4), + const Text( + 'Tap the bookmark icon in the toolbar\nto bookmark the current page.', + textAlign: TextAlign.center, + ), + ], + ), + ) + : ListView.builder( + itemCount: _bookmarks.length, + itemBuilder: (context, index) { + final bookmark = _bookmarks[index]; + return ListTile( + leading: CircleAvatar( + backgroundColor: Color(bookmark.color), + radius: 6, + ), + title: Text( + bookmark.label.isEmpty + ? 'Page ${bookmark.pageNumber + 1}' + : bookmark.label, + ), + subtitle: Text('Page ${bookmark.pageNumber + 1}'), + trailing: IconButton( + icon: const Icon(Icons.delete_outline), + tooltip: 'Delete bookmark', + onPressed: () => _deleteBookmark(bookmark), + ), + onTap: () { + Navigator.of(context).pop(); + _jumpToPage(bookmark.pageNumber); + }, + onLongPress: () => _deleteBookmark(bookmark), + ); + }, + ), + ), + ], + ), + ); + } + + // -- UI -- + + @override + Widget build(BuildContext context) { + final undoManager = _getUndoManager(_currentPage); + return Scaffold( + key: _scaffoldKey, + appBar: AppBar( + title: Text(_fileName, style: const TextStyle(fontSize: 16)), + actions: [ + IconButton( + icon: const Icon(Icons.vertical_split), + tooltip: 'Open in Split View', + onPressed: () { + if (_currentDocumentId == null) return; + _saveCurrentPageAnnotations(); + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SplitViewScreen( + filePath: widget.filePath, + documentId: _currentDocumentId!, + ), + ), + ); + }, + ), + IconButton( + icon: const Icon(Icons.search), + tooltip: 'Search in PDF (Ctrl+F)', + onPressed: _openSearch, + ), + IconButton( + icon: Icon( + _isCurrentPageBookmarked ? Icons.bookmark : Icons.bookmark_border, + ), + tooltip: 'Toggle bookmark', + onPressed: _toggleBookmark, + ), + IconButton( + icon: const Icon(Icons.menu_book), + tooltip: 'Bookmarks', + onPressed: () => _scaffoldKey.currentState?.openEndDrawer(), + ), + IconButton( + icon: Icon( + _showThumbnails + ? Icons.view_sidebar + : Icons.view_sidebar_outlined, + ), + tooltip: 'Toggle page thumbnails', + onPressed: () => setState(() => _showThumbnails = !_showThumbnails), + ), + PopupMenuButton<_OverflowAction>( + icon: const Icon(Icons.more_vert), + tooltip: 'More actions', + onSelected: (action) { + switch (action) { + case _OverflowAction.pageManagement: + _showPageManagementSheet(); + case _OverflowAction.cameraInsert: + _showCameraInsertDialog(); + case _OverflowAction.export: + _exportPdf(); + } + }, + itemBuilder: (context) => const [ + PopupMenuItem( + value: _OverflowAction.pageManagement, + child: ListTile( + leading: Icon(Icons.pages), + title: Text('Page Management'), + contentPadding: EdgeInsets.zero, + ), + ), + PopupMenuItem( + value: _OverflowAction.cameraInsert, + child: ListTile( + leading: Icon(Icons.camera_alt), + title: Text('Insert Image'), + contentPadding: EdgeInsets.zero, + ), + ), + PopupMenuItem( + value: _OverflowAction.export, + child: ListTile( + leading: Icon(Icons.save_alt), + title: Text('Export PDF'), + contentPadding: EdgeInsets.zero, + ), + ), + ], + ), + ], + ), + endDrawer: _buildBookmarkDrawer(), + body: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.keyZ, control: true): _undo, + const SingleActivator(LogicalKeyboardKey.keyY, control: true): _redo, + const SingleActivator( + LogicalKeyboardKey.keyZ, + control: true, + shift: true, + ): _redo, + const SingleActivator(LogicalKeyboardKey.keyF, control: true): + _openSearch, + const SingleActivator(LogicalKeyboardKey.keyS, control: true): + _saveCurrentPageAnnotations, + const SingleActivator(LogicalKeyboardKey.escape): () { + if (_interactionMode != InteractionMode.navigate) { + setState(() => _interactionMode = InteractionMode.navigate); + } + }, + }, + child: Focus( + autofocus: true, + child: Column( + children: [ + AnnotationToolbar( + currentTool: _currentTool, + currentColor: _currentColor, + currentStrokeWidth: _currentStrokeWidth, + filled: _filled, + pressureCurveType: _pressureCurveType, + stabilizationLevel: _stabilizationLevel, + canUndo: undoManager.canUndo, + canRedo: undoManager.canRedo, + onToolChanged: (tool) => setState(() => _currentTool = tool), + onColorChanged: (color) => + setState(() => _currentColor = color), + onStrokeWidthChanged: (w) => + setState(() => _currentStrokeWidth = w), + onFilledChanged: (f) => setState(() => _filled = f), + onPressureCurveChanged: (v) => + setState(() => _pressureCurveType = v), + onStabilizationChanged: (v) => + setState(() => _stabilizationLevel = v), + onUndo: _undo, + onRedo: _redo, + onPreviousPage: _currentPage > 0 + ? () => _viewerController.previousPage() + : null, + onNextPage: _currentPage < _pageCount - 1 + ? () => _viewerController.nextPage() + : null, + pageInfo: '${_currentPage + 1} / $_pageCount', + interactionMode: _interactionMode, + onInteractionModeChanged: (mode) => + setState(() => _interactionMode = mode), + onZoomIn: _zoomIn, + onZoomOut: _zoomOut, + onZoomFitWidth: _zoomFitWidth, + zoomLabel: '${(_zoomLevel * 100).round()}%', + ), + Expanded( + child: Row( + children: [ + if (_showThumbnails && _currentDocumentId != null) + PageThumbnailSidebar( + documentId: _currentDocumentId!, + filePath: widget.filePath, + pageCount: _pageCount, + currentPage: _currentPage, + onPageTap: _jumpToPage, + bookmarkedPages: _bookmarks + .map((b) => b.pageNumber) + .toSet(), + ), + Expanded( + child: Stack( + children: [ + SfPdfViewer.file( + File(widget.filePath), + key: ValueKey('pdf-$_pdfMutationVersion'), + controller: _viewerController, + initialPageNumber: _currentPage + 1, + onPageChanged: (PdfPageChangedDetails details) { + _onPageChanged(details.newPageNumber - 1); + }, + ), + Positioned.fill( + child: _interactionMode == InteractionMode.navigate + ? IgnorePointer( + child: PdfAnnotationLayer( + strokes: _getCurrentStrokes(), + onStrokeComplete: _onStrokeComplete, + onErase: _onErase, + tool: _currentTool, + color: _currentColor, + strokeWidth: _currentStrokeWidth, + filled: _filled, + interactionMode: _interactionMode, + ), + ) + : PdfAnnotationLayer( + strokes: _getCurrentStrokes(), + onStrokeComplete: _onStrokeComplete, + onErase: _onErase, + tool: _currentTool, + color: _currentColor, + strokeWidth: _currentStrokeWidth, + filled: _filled, + interactionMode: _interactionMode, + ), + ), + ], + ), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + @override + void dispose() { + _saveCurrentPageAnnotations(); + _viewerController.dispose(); + super.dispose(); + } +} diff --git a/lib/screens/pdf_text_search.dart b/lib/screens/pdf_text_search.dart new file mode 100644 index 0000000..65d00d9 --- /dev/null +++ b/lib/screens/pdf_text_search.dart @@ -0,0 +1,141 @@ +import 'package:flutter/material.dart'; +import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart'; + +/// A dialog for searching text within a PDF using SfPdfViewer's built-in search. +class PdfTextSearchDialog extends StatefulWidget { + final PdfViewerController viewerController; + + const PdfTextSearchDialog({super.key, required this.viewerController}); + + @override + State createState() => _PdfTextSearchDialogState(); +} + +class _PdfTextSearchDialogState extends State { + final TextEditingController _queryController = TextEditingController(); + PdfTextSearchResult? _searchResult; + String _statusText = ''; + + @override + void dispose() { + _queryController.dispose(); + _searchResult?.clear(); + super.dispose(); + } + + void _search() { + final query = _queryController.text.trim(); + if (query.isEmpty) return; + + final result = widget.viewerController.searchText(query); + setState(() { + _searchResult = result; + _updateStatus(); + }); + } + + void _nextMatch() { + _searchResult?.nextInstance(); + _updateStatus(); + } + + void _previousMatch() { + _searchResult?.previousInstance(); + _updateStatus(); + } + + void _updateStatus() { + final result = _searchResult; + if (result == null || result.totalInstanceCount == 0) { + setState(() => _statusText = 'No matches'); + } else { + setState(() { + _statusText = + '${result.currentInstanceIndex} of ${result.totalInstanceCount} matches'; + }); + } + } + + @override + Widget build(BuildContext context) { + return Dialog( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Expanded( + child: TextField( + controller: _queryController, + autofocus: true, + decoration: const InputDecoration( + hintText: 'Search in PDF...', + prefixIcon: Icon(Icons.search), + isDense: true, + border: OutlineInputBorder(), + ), + onSubmitted: (_) => _search(), + ), + ), + const SizedBox(width: 8), + IconButton( + icon: const Icon(Icons.search), + tooltip: 'Search', + onPressed: _search, + ), + ], + ), + const SizedBox(height: 12), + Row( + children: [ + Text( + _statusText, + style: Theme.of(context).textTheme.bodySmall, + ), + const Spacer(), + IconButton( + icon: const Icon(Icons.keyboard_arrow_up), + tooltip: 'Previous match', + onPressed: + _searchResult != null && + _searchResult!.totalInstanceCount > 0 + ? _previousMatch + : null, + iconSize: 20, + ), + IconButton( + icon: const Icon(Icons.keyboard_arrow_down), + tooltip: 'Next match', + onPressed: + _searchResult != null && + _searchResult!.totalInstanceCount > 0 + ? _nextMatch + : null, + iconSize: 20, + ), + IconButton( + icon: const Icon(Icons.close), + tooltip: 'Clear search', + onPressed: () { + _searchResult?.clear(); + setState(() { + _queryController.clear(); + _searchResult = null; + _statusText = ''; + }); + }, + iconSize: 20, + ), + ], + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/screens/ppt_annotator_screen.dart b/lib/screens/ppt_annotator_screen.dart new file mode 100644 index 0000000..6344be7 --- /dev/null +++ b/lib/screens/ppt_annotator_screen.dart @@ -0,0 +1,528 @@ +import 'dart:io'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; +import 'package:syncfusion_flutter_pdf/pdf.dart'; + +import '../models/ink_stroke.dart'; +import '../models/pen_tool.dart'; +import '../models/pressure_curve.dart'; +import '../services/undo_manager.dart'; +import '../utils/stroke_stabilizer.dart'; +import '../widgets/annotation_toolbar.dart'; +import '../widgets/ink_canvas.dart'; + +/// Per-slide annotation state. The [UndoManager] is the single source of +/// truth for a slide's strokes; [strokes] reflects its current contents so +/// the live canvas and the PDF export always render what was actually drawn. +class _SlideAnnotations { + final UndoManager undoManager = UndoManager(); + List get strokes => undoManager.currentStrokes; +} + +/// Screen that displays PPTX slides with an ink annotation overlay. +/// +/// Each slide is shown as an image in a [PageView]. A transparent [InkCanvas] +/// sits on top of each slide so the user can annotate freely. Annotations are +/// stored per-slide and can be exported as a PDF. +class PptAnnotatorScreen extends StatefulWidget { + final String filePath; + final List slideImagePaths; + final String? extractedText; + + const PptAnnotatorScreen({ + super.key, + required this.filePath, + required this.slideImagePaths, + this.extractedText, + }); + + @override + State createState() => _PptAnnotatorScreenState(); +} + +class _PptAnnotatorScreenState extends State { + late final PageController _pageController; + late final Map _annotations; + int _currentPage = 0; + bool _isDrawing = false; + bool _showTextPanel = false; + // Set to true once the unsaved-annotations warning SnackBar has been shown. + bool _hasShownUnsavedWarning = false; + + // Toolbar state + PenTool _currentTool = PenTool.pen; + Color _currentColor = Colors.black; + double _currentStrokeWidth = 2.0; + bool _filled = false; + PressureCurveType _pressureCurveType = PressureCurveType.linear; + StabilizationLevel _stabilizationLevel = StabilizationLevel.none; + + // Derived + late final String _fileName; + late final int _slideCount; + late final String _extractedText; + + PressureCurve get _pressureCurve { + switch (_pressureCurveType) { + case PressureCurveType.linear: + return PressureCurve.linear; + case PressureCurveType.soft: + return PressureCurve.soft; + case PressureCurveType.hard: + return PressureCurve.hard; + case PressureCurveType.custom: + return const PressureCurve(type: PressureCurveType.custom); + } + } + + UndoManager get _currentUndoManager => + _annotations.putIfAbsent(_currentPage, _SlideAnnotations.new).undoManager; + + @override + void initState() { + super.initState(); + _fileName = p.basename(widget.filePath); + _slideCount = widget.slideImagePaths.length; + _extractedText = widget.extractedText ?? ''; + + _pageController = PageController(); + _annotations = {}; + for (var i = 0; i < _slideCount; i++) { + _annotations[i] = _SlideAnnotations(); + } + } + + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + + // -- Drawing callbacks -- + + void _onStrokeComplete(InkStroke stroke) { + setState(() { + _currentUndoManager.addStroke(stroke); + }); + // Warn once per session that PPT annotations are not auto-saved. + if (!_hasShownUnsavedWarning) { + _hasShownUnsavedWarning = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text( + "PPT ink isn't saved automatically — use Export to PDF to keep your annotations.", + ), + duration: Duration(seconds: 5), + ), + ); + }); + } + } + + void _onErase(String strokeId, List replacements) { + setState(() { + final original = _currentUndoManager.currentStrokes + .where((s) => s.id == strokeId) + .firstOrNull; + if (original != null) { + _currentUndoManager.removeStroke(original, replacements: replacements); + } + }); + } + + // -- Export -- + + Future _exportPdf() async { + if (!mounted) return; + + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Exporting PDF...'))); + + try { + final bytes = await _buildPdfBytes(); + if (!mounted) return; + + final dir = await _getExportDir(); + final baseName = p.basenameWithoutExtension(_fileName); + final outPath = p.join(dir.path, '${baseName}_annotated.pdf'); + await File(outPath).writeAsBytes(bytes); + + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('PDF saved: $outPath'))); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Export failed: $e'))); + } + } + + Future _getExportDir() async { + try { + final home = Platform.environment['HOME']; + if (home != null) { + final dir = Directory(p.join(home, 'Documents', 'BadNote')); + if (!await dir.exists()) { + await dir.create(recursive: true); + } + return dir; + } + } catch (_) {} + return Directory.current; + } + + Future _buildPdfBytes() async { + final doc = PdfDocument(); + doc.pageSettings.margins.all = 0; + + for (var i = 0; i < _slideCount; i++) { + final page = doc.pages.add(); + final pageSize = page.getClientSize(); + + // Draw slide image + final imgPath = widget.slideImagePaths[i]; + try { + final imgBytes = await File(imgPath).readAsBytes(); + final bitmap = PdfBitmap(imgBytes); + + final imgW = bitmap.width.toDouble(); + final imgH = bitmap.height.toDouble(); + final scale = min(pageSize.width / imgW, pageSize.height / imgH); + final drawW = imgW * scale; + final drawH = imgH * scale; + final offX = (pageSize.width - drawW) / 2; + final offY = (pageSize.height - drawH) / 2; + final imgRect = Rect.fromLTWH(offX, offY, drawW, drawH); + + page.graphics.drawImage(bitmap, imgRect); + + // Draw ink strokes + final annots = _annotations[i]; + if (annots != null && annots.strokes.isNotEmpty) { + // KNOWN LIMITATION: strokes are captured in the live viewer's + // full-fill pixel space (the InkCanvas is Positioned.fill over the + // whole slide area, while the slide image is BoxFit.contain inside + // it). The scale below is derived from the PDF page layout, not the + // live widget size, so exported ink can be misaligned/scaled wrong. + // A correct fix normalizes strokes to [0,1] of the *rendered image + // rect* at capture time (mirroring PdfAnnotationLayer) and maps that + // to the PDF draw rect here. Requires on-device visual verification. + final imgAspect = imgW / imgH; + final pageAspect = pageSize.width / pageSize.height; + double widgetW, widgetH; + if (imgAspect > pageAspect) { + widgetW = pageSize.width; + widgetH = pageSize.width / imgAspect; + } else { + widgetH = pageSize.height; + widgetW = pageSize.height * imgAspect; + } + final scaleX = drawW / widgetW; + final scaleY = drawH / widgetH; + + for (final stroke in annots.strokes) { + if (stroke.tool == PenTool.eraser) continue; + if (stroke.points.length < 2) continue; + + final r = (stroke.color >> 16) & 0xFF; + final g = (stroke.color >> 8) & 0xFF; + final b = stroke.color & 0xFF; + final pdfColor = PdfColor(r, g, b); + + final path = PdfPath(); + path.startFigure(); + for (var j = 0; j < stroke.points.length - 1; j++) { + final pt1 = stroke.points[j]; + final pt2 = stroke.points[j + 1]; + path.addLine( + Offset(offX + pt1.x * scaleX, offY + pt1.y * scaleY), + Offset(offX + pt2.x * scaleX, offY + pt2.y * scaleY), + ); + } + + page.graphics.drawPath( + path, + pen: PdfPen(pdfColor, width: stroke.strokeWidth), + ); + } + } + } catch (_) { + page.graphics.drawRectangle( + brush: PdfSolidBrush(PdfColor(230, 230, 230)), + bounds: Rect.fromLTWH(0, 0, pageSize.width, pageSize.height), + ); + } + } + + final bytes = await doc.save(); + doc.dispose(); + return Uint8List.fromList(bytes); + } + + // -- UI -- + + @override + Widget build(BuildContext context) { + // No slides to annotate: show an empty state and skip the toolbar, which + // would otherwise dereference a non-existent slide's annotation state. + if (_slideCount == 0) { + return Scaffold( + appBar: AppBar( + title: Text(_fileName, style: const TextStyle(fontSize: 16)), + ), + body: const Center(child: Text('No slides to display')), + ); + } + + return Scaffold( + appBar: AppBar( + title: Text(_fileName, style: const TextStyle(fontSize: 16)), + actions: [ + if (_extractedText.isNotEmpty) + IconButton( + icon: Icon( + _showTextPanel + ? Icons.text_snippet + : Icons.text_snippet_outlined, + ), + tooltip: 'Toggle extracted text', + onPressed: () => setState(() => _showTextPanel = !_showTextPanel), + ), + IconButton( + icon: const Icon(Icons.picture_as_pdf), + tooltip: 'Export as PDF', + onPressed: _exportPdf, + ), + ], + ), + body: Column( + children: [ + AnnotationToolbar( + currentTool: _currentTool, + currentColor: _currentColor, + currentStrokeWidth: _currentStrokeWidth, + filled: _filled, + pressureCurveType: _pressureCurveType, + stabilizationLevel: _stabilizationLevel, + canUndo: _currentUndoManager.canUndo, + canRedo: _currentUndoManager.canRedo, + onToolChanged: (tool) => setState(() => _currentTool = tool), + onColorChanged: (color) => setState(() => _currentColor = color), + onStrokeWidthChanged: (w) => + setState(() => _currentStrokeWidth = w), + onFilledChanged: (f) => setState(() => _filled = f), + onPressureCurveChanged: (v) => + setState(() => _pressureCurveType = v), + onStabilizationChanged: (v) => + setState(() => _stabilizationLevel = v), + onUndo: _undo, + onRedo: _redo, + ), + Expanded( + child: Row( + children: [ + Expanded(child: _buildSlideViewer()), + if (_showTextPanel) _buildTextPanel(), + ], + ), + ), + _buildPageIndicator(), + ], + ), + ); + } + + Widget _buildSlideViewer() { + if (_slideCount == 0) { + return const Center(child: Text('No slides to display')); + } + + return Listener( + onPointerDown: (_) => setState(() => _isDrawing = true), + onPointerUp: (_) => setState(() => _isDrawing = false), + child: PageView.builder( + controller: _pageController, + physics: _isDrawing ? const NeverScrollableScrollPhysics() : null, + itemCount: _slideCount, + onPageChanged: (page) => setState(() => _currentPage = page), + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.all(8), + child: Stack( + children: [ + // Slide image (background) + Positioned.fill( + child: Image.file( + File(widget.slideImagePaths[index]), + fit: BoxFit.contain, + errorBuilder: (context, error, stackTrace) => Container( + color: Colors.grey.shade200, + child: Center( + child: Text( + 'Slide ${index + 1}', + style: TextStyle( + fontSize: 24, + color: Colors.grey.shade500, + ), + ), + ), + ), + ), + ), + // Ink annotation overlay (foreground) + Positioned.fill( + child: InkCanvas( + strokes: _annotations[index]?.strokes ?? [], + onStrokeComplete: _onStrokeComplete, + onErase: _onErase, + tool: _currentTool, + color: _currentColor, + strokeWidth: _currentStrokeWidth, + pressureCurve: _pressureCurve, + stabilizationLevel: _stabilizationLevel, + filled: _filled, + ), + ), + ], + ), + ); + }, + ), + ); + } + + Widget _buildPageIndicator() { + if (_slideCount == 0) return const SizedBox.shrink(); + + return Container( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + color: Theme.of(context).colorScheme.surface, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + // Previous button — always present for both modes. + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage > 0 + ? () => _pageController.previousPage( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ) + : null, + ), + // Dot row for small decks; compact text counter for large decks. + if (_slideCount <= 12) + ...List.generate(_slideCount, (i) { + final isActive = i == _currentPage; + return GestureDetector( + onTap: () => _pageController.animateToPage( + i, + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ), + child: Container( + width: isActive ? 12 : 8, + height: isActive ? 12 : 8, + margin: const EdgeInsets.symmetric(horizontal: 4), + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isActive + ? Theme.of(context).colorScheme.primary + : Colors.grey.shade400, + ), + ), + ); + }) + else + Text( + '${_currentPage + 1} / $_slideCount', + style: TextStyle(fontSize: 13, color: Colors.grey.shade600), + ), + // Next button — always present for both modes. + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage < _slideCount - 1 + ? () => _pageController.nextPage( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ) + : null, + ), + const Spacer(), + // Slide counter is always shown at the trailing end for dot mode; + // the compact text above already serves this role for large decks. + if (_slideCount <= 12) + Text( + '${_currentPage + 1} / $_slideCount', + style: TextStyle(fontSize: 13, color: Colors.grey.shade600), + ), + ], + ), + ); + } + + Widget _buildTextPanel() { + return SizedBox( + width: 280, + child: Card( + margin: const EdgeInsets.all(8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: const BorderRadius.vertical( + top: Radius.circular(12), + ), + ), + child: Row( + children: [ + const Icon(Icons.text_fields, size: 18), + const SizedBox(width: 8), + Text( + 'Extracted Text', + style: Theme.of(context).textTheme.titleSmall, + ), + const Spacer(), + IconButton( + icon: const Icon(Icons.close, size: 18), + onPressed: () => setState(() => _showTextPanel = false), + ), + ], + ), + ), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.all(12), + child: SelectableText( + _extractedText, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ), + ], + ), + ), + ); + } + + // -- Dialogs -- + + void _undo() { + setState(() => _currentUndoManager.undo()); + } + + void _redo() { + setState(() => _currentUndoManager.redo()); + } +} diff --git a/lib/screens/search_screen.dart b/lib/screens/search_screen.dart new file mode 100644 index 0000000..ca6d094 --- /dev/null +++ b/lib/screens/search_screen.dart @@ -0,0 +1,286 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/note.dart'; +import '../providers/search_provider.dart'; +import 'note_editor_screen.dart'; +import 'pdf_annotator_screen.dart'; + +class SearchScreen extends ConsumerStatefulWidget { + const SearchScreen({super.key}); + + @override + ConsumerState createState() => _SearchScreenState(); +} + +class _SearchScreenState extends ConsumerState { + final TextEditingController _controller = TextEditingController(); + Timer? _debounce; + + @override + void initState() { + super.initState(); + _controller.addListener(() => setState(() {})); + } + + @override + void dispose() { + _debounce?.cancel(); + _controller.dispose(); + super.dispose(); + } + + void _onQueryChanged(String value) { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 300), () { + ref.read(searchQueryProvider.notifier).state = value.trim(); + }); + } + + @override + Widget build(BuildContext context) { + final results = ref.watch(searchResultsProvider); + + return Scaffold( + appBar: AppBar( + title: TextField( + controller: _controller, + autofocus: true, + decoration: const InputDecoration( + hintText: 'Search notes and documents...', + border: InputBorder.none, + hintStyle: TextStyle(color: Colors.grey), + ), + onChanged: _onQueryChanged, + onSubmitted: (value) { + _debounce?.cancel(); + ref.read(searchQueryProvider.notifier).state = value.trim(); + }, + ), + actions: [ + if (_controller.text.isNotEmpty) + IconButton( + icon: const Icon(Icons.clear), + onPressed: () { + _controller.clear(); + ref.read(searchQueryProvider.notifier).state = ''; + }, + ), + ], + ), + body: results.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, _) => Center(child: Text('Search error: $e')), + data: (hits) { + final query = ref.watch(searchQueryProvider); + if (query.isEmpty) { + return const Center( + child: Text( + 'Type to search your notes and documents', + style: TextStyle(color: Colors.grey), + ), + ); + } + if (hits.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.search_off, + size: 64, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + const SizedBox(height: 16), + Text( + 'No results for "$query"', + style: Theme.of(context).textTheme.bodyLarge?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ); + } + + final noteHits = hits.whereType().toList(); + final docHits = hits.whereType().toList(); + + return ListView( + children: [ + if (noteHits.isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text( + 'Notes', + style: Theme.of(context).textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.primary, + ), + ), + ), + ...noteHits.map( + (hit) => _NoteSearchResultTile(note: hit.note, query: query), + ), + ], + if (docHits.isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 4), + child: Text( + 'Documents', + style: Theme.of(context).textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.primary, + ), + ), + ), + ...docHits.map( + (hit) => _DocumentSearchResultTile( + documentId: hit.documentId, + filename: hit.filename, + filePath: hit.filePath, + pageNumber: hit.pageNumber, + snippet: hit.snippet, + query: query, + ), + ), + ], + ], + ); + }, + ), + ); + } +} + +class _NoteSearchResultTile extends StatelessWidget { + final Note note; + final String query; + + const _NoteSearchResultTile({required this.note, required this.query}); + + @override + Widget build(BuildContext context) { + final d = note.updatedAt; + final dateStr = + '${d.month}/${d.day}/${d.year} ${d.hour}:${d.minute.toString().padLeft(2, '0')}'; + + return ListTile( + leading: const Icon(Icons.edit_note), + title: _HighlightedText(text: note.title, query: query), + subtitle: Text( + '${note.strokes.length} stroke${note.strokes.length == 1 ? '' : 's'} · $dateStr', + style: Theme.of(context).textTheme.bodySmall, + ), + onTap: () { + Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => NoteEditorScreen(note: note))); + }, + ); + } +} + +class _DocumentSearchResultTile extends StatelessWidget { + final String documentId; + final String filename; + final String filePath; + final int pageNumber; + final String snippet; + final String query; + + const _DocumentSearchResultTile({ + required this.documentId, + required this.filename, + required this.filePath, + required this.pageNumber, + required this.snippet, + required this.query, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + leading: const Icon(Icons.picture_as_pdf, color: Colors.red), + title: _HighlightedText(text: filename, query: query), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Page ${pageNumber + 1}', + style: Theme.of(context).textTheme.bodySmall, + ), + if (snippet.isNotEmpty) + _HighlightedText(text: snippet, query: query, maxLines: 2), + ], + ), + onTap: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => + PdfAnnotatorScreen(filePath: filePath, initialPage: pageNumber), + ), + ); + }, + ); + } +} + +/// Highlights matching portions of [text] that match [query]. +class _HighlightedText extends StatelessWidget { + final String text; + final String query; + final int maxLines; + + const _HighlightedText({ + required this.text, + required this.query, + this.maxLines = 1, + }); + + @override + Widget build(BuildContext context) { + if (query.isEmpty || text.isEmpty) { + return Text(text, maxLines: maxLines, overflow: TextOverflow.ellipsis); + } + + final lowerText = text.toLowerCase(); + final lowerQuery = query.toLowerCase(); + final spans = []; + int start = 0; + + while (true) { + final index = lowerText.indexOf(lowerQuery, start); + if (index < 0) { + if (start < text.length) { + spans.add(TextSpan(text: text.substring(start))); + } + break; + } + if (index > start) { + spans.add(TextSpan(text: text.substring(start, index))); + } + spans.add( + TextSpan( + text: text.substring(index, index + query.length), + style: TextStyle( + fontWeight: FontWeight.bold, + backgroundColor: Theme.of(context).colorScheme.primaryContainer, + ), + ), + ); + start = index + query.length; + } + + return RichText( + maxLines: maxLines, + overflow: TextOverflow.ellipsis, + text: TextSpan( + style: DefaultTextStyle.of(context).style, + children: spans, + ), + ); + } +} diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart new file mode 100644 index 0000000..f89f20a --- /dev/null +++ b/lib/screens/settings_screen.dart @@ -0,0 +1,344 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_colorpicker/flutter_colorpicker.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/pen_tool.dart'; +import '../models/pressure_curve.dart'; +import '../providers/settings_provider.dart'; +import '../utils/stroke_stabilizer.dart'; + +/// Material 3 settings screen for BadNote. +class SettingsScreen extends ConsumerWidget { + const SettingsScreen({super.key}); + + void _showColorPicker( + BuildContext context, + Color current, + ValueChanged onPicked, + ) { + Color pickerColor = current; + showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: const Text('Pick a color'), + content: SingleChildScrollView( + child: ColorPicker( + pickerColor: pickerColor, + onColorChanged: (color) => pickerColor = color, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + onPicked(pickerColor); + Navigator.of(context).pop(); + }, + child: const Text('OK'), + ), + ], + ); + }, + ); + } + + void _confirmClearData(BuildContext context, WidgetRef ref) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Clear all local settings?'), + content: const Text( + 'This will reset pen defaults and appearance settings. ' + 'Notes and documents are not affected.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + ref.read(settingsProvider).clearAllData(); + Navigator.pop(ctx); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Settings reset to defaults')), + ); + }, + child: const Text('Clear'), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final settings = ref.watch(settingsProvider); + final colorScheme = Theme.of(context).colorScheme; + + return Scaffold( + appBar: AppBar(title: const Text('Settings')), + body: ListView( + children: [ + _SectionHeader(title: 'Defaults', icon: Icons.tune), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Default Tool', + style: TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 4), + DropdownButtonFormField( + initialValue: settings.defaultTool, + decoration: const InputDecoration( + border: OutlineInputBorder(), + isDense: true, + ), + items: PenTool.values.map((tool) { + return DropdownMenuItem( + value: tool, + child: Text(tool.name), + ); + }).toList(), + onChanged: (tool) { + if (tool != null) settings.setDefaultTool(tool); + }, + ), + const SizedBox(height: 16), + const Text( + 'Default Color', + style: TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 4), + Row( + children: [ + MouseRegion( + cursor: SystemMouseCursors.click, + child: InkWell( + borderRadius: BorderRadius.circular(8), + onTap: () => _showColorPicker( + context, + settings.defaultColor, + settings.setDefaultColor, + ), + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: settings.defaultColor, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: colorScheme.outline), + ), + ), + ), + ), + const SizedBox(width: 12), + Text( + '#${settings.defaultColor.toARGB32().toRadixString(16).padLeft(8, '0').toUpperCase()}', + style: const TextStyle(fontFamily: 'monospace'), + ), + ], + ), + const SizedBox(height: 16), + const Text( + 'Default Stroke Width', + style: TextStyle(fontWeight: FontWeight.w500), + ), + Slider( + value: settings.defaultStrokeWidth, + min: 1.0, + max: 20.0, + divisions: 19, + label: settings.defaultStrokeWidth.toStringAsFixed(1), + onChanged: settings.setDefaultStrokeWidth, + ), + const SizedBox(height: 16), + const Text( + 'Pressure Curve', + style: TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 4), + DropdownButtonFormField( + initialValue: settings.defaultPressureCurve, + decoration: const InputDecoration( + border: OutlineInputBorder(), + isDense: true, + ), + items: PressureCurveType.values.map((curve) { + return DropdownMenuItem( + value: curve, + child: Text(curve.name), + ); + }).toList(), + onChanged: (curve) { + if (curve != null) { + settings.setDefaultPressureCurve(curve); + } + }, + ), + const SizedBox(height: 16), + const Text( + 'Stabilization', + style: TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 4), + DropdownButtonFormField( + initialValue: settings.defaultStabilization, + decoration: const InputDecoration( + border: OutlineInputBorder(), + isDense: true, + ), + items: StabilizationLevel.values.map((level) { + return DropdownMenuItem( + value: level, + child: Text(level.name), + ); + }).toList(), + onChanged: (level) { + if (level != null) settings.setDefaultStabilization(level); + }, + ), + ], + ), + ), + const Divider(), + _SectionHeader(title: 'Appearance', icon: Icons.palette), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Theme Mode', + style: TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 4), + SegmentedButton( + segments: const [ + ButtonSegment( + value: ThemeMode.system, + label: Text('System'), + icon: Icon(Icons.brightness_auto), + ), + ButtonSegment( + value: ThemeMode.light, + label: Text('Light'), + icon: Icon(Icons.light_mode), + ), + ButtonSegment( + value: ThemeMode.dark, + label: Text('Dark'), + icon: Icon(Icons.dark_mode), + ), + ], + selected: {settings.themeMode}, + onSelectionChanged: (modes) { + settings.setThemeMode(modes.first); + }, + ), + const SizedBox(height: 16), + const Text( + 'Color Scheme Seed', + style: TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 4), + Row( + children: [ + MouseRegion( + cursor: SystemMouseCursors.click, + child: InkWell( + borderRadius: BorderRadius.circular(8), + onTap: () => _showColorPicker( + context, + settings.colorSchemeSeed, + settings.setColorSchemeSeed, + ), + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: settings.colorSchemeSeed, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: colorScheme.outline), + ), + ), + ), + ), + const SizedBox(width: 12), + const Text('Seed color for Material 3 theme'), + ], + ), + ], + ), + ), + const Divider(), + _SectionHeader(title: 'About', icon: Icons.info), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'BadNote v0.1.0', + style: TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 4), + Text( + 'Local-first Surface Pen note-taking with PDF/PPT annotation. ' + 'OCR and search run entirely on your device.', + style: TextStyle( + fontSize: 13, + color: colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 16), + OutlinedButton.icon( + onPressed: () => _confirmClearData(context, ref), + icon: const Icon(Icons.delete_forever, color: Colors.red), + label: const Text( + 'Clear All Local Settings', + style: TextStyle(color: Colors.red), + ), + ), + ], + ), + ), + const SizedBox(height: 32), + ], + ), + ); + } +} + +class _SectionHeader extends StatelessWidget { + final String title; + final IconData icon; + + const _SectionHeader({required this.title, required this.icon}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 4), + child: Row( + children: [ + Icon(icon, size: 20, color: Theme.of(context).colorScheme.primary), + const SizedBox(width: 8), + Text( + title, + style: Theme.of( + context, + ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), + ), + ], + ), + ); + } +} diff --git a/lib/screens/split_view_screen.dart b/lib/screens/split_view_screen.dart new file mode 100644 index 0000000..2cfe018 --- /dev/null +++ b/lib/screens/split_view_screen.dart @@ -0,0 +1,469 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart'; + +import '../models/ink_stroke.dart'; +import '../models/pen_tool.dart'; +import '../models/pressure_curve.dart'; +import '../services/database_service.dart'; +import '../services/undo_manager.dart'; +import '../utils/stroke_stabilizer.dart'; +import '../widgets/annotation_toolbar.dart'; +import '../widgets/ink_canvas.dart'; + +/// Split-view derivation mode: left pane = reference PDF, right pane = infinite +/// scratchpad for formula derivation. Scratchpad strokes are persisted per +/// document via [DatabaseService.saveScratchpad] / [DatabaseService.loadScratchpad]. +class SplitViewScreen extends StatefulWidget { + final String filePath; + final String documentId; + + const SplitViewScreen({ + super.key, + required this.filePath, + required this.documentId, + }); + + @override + State createState() => _SplitViewState(); +} + +class _SplitViewState extends State { + // -- PDF (left pane) -- + final PdfViewerController _pdfController = PdfViewerController(); + int _currentPage = 0; + int _pageCount = 0; + String _fileName = ''; + + // -- Split divider -- + double _leftPaneFraction = 0.5; + bool _isDraggingDivider = false; + + // -- Scratchpad (right pane) -- + final UndoManager _undoManager = UndoManager(); + List _strokes = []; + double _canvasWidth = 4000; + double _canvasHeight = 4000; + + // -- Tool state -- + PenTool _currentTool = PenTool.pen; + Color _currentColor = Colors.black; + double _currentStrokeWidth = 2.0; + bool _filled = false; + PressureCurveType _pressureCurveType = PressureCurveType.linear; + StabilizationLevel _stabilizationLevel = StabilizationLevel.none; + + // -- Auto-save debounce -- + Timer? _saveTimer; + bool _dirty = false; + + // -- Page link markers (optional feature) -- + final List<_PageLink> _pageLinks = []; + + static const double _edgeThreshold = 200.0; + static const double _expandAmount = 1000.0; + + @override + void initState() { + super.initState(); + _loadScratchpad(); + } + + @override + void dispose() { + _saveTimer?.cancel(); + _saveImmediate(); + _pdfController.dispose(); + super.dispose(); + } + + // -- Persistence -- + + Future _loadScratchpad() async { + final db = await DatabaseService.getInstance(); + final strokes = await db.loadScratchpad(widget.documentId); + if (mounted) { + setState(() { + _strokes = strokes; + for (final s in strokes) { + _undoManager.addStroke(s); + } + }); + } + } + + void _scheduleSave() { + _dirty = true; + _saveTimer?.cancel(); + _saveTimer = Timer(const Duration(seconds: 3), _saveImmediate); + } + + Future _saveImmediate() async { + if (!_dirty) return; + _dirty = false; + final db = await DatabaseService.getInstance(); + final json = jsonEncode(_strokes.map((s) => s.toJson()).toList()); + await db.saveScratchpad(widget.documentId, json); + } + + // -- Scratchpad stroke callbacks -- + + void _onStrokeComplete(InkStroke stroke) { + setState(() { + _strokes.add(stroke); + _undoManager.addStroke(stroke); + _checkCanvasExpansion(stroke); + }); + _scheduleSave(); + } + + void _onErase(String strokeId, List replacements) { + setState(() { + final original = _strokes.where((s) => s.id == strokeId).firstOrNull; + if (original != null) { + _undoManager.removeStroke(original, replacements: replacements); + _strokes = List.from(_undoManager.currentStrokes); + } + }); + _scheduleSave(); + } + + void _undo() { + setState(() { + _undoManager.undo(); + _strokes = List.from(_undoManager.currentStrokes); + }); + _scheduleSave(); + } + + void _redo() { + setState(() { + _undoManager.redo(); + _strokes = List.from(_undoManager.currentStrokes); + }); + _scheduleSave(); + } + + // -- Auto-expand canvas -- + + void _checkCanvasExpansion(InkStroke stroke) { + double maxRight = 0; + double maxBottom = 0; + for (final p in stroke.points) { + if (p.x > maxRight) maxRight = p.x; + if (p.y > maxBottom) maxBottom = p.y; + } + bool expanded = false; + if (maxRight > _canvasWidth - _edgeThreshold) { + _canvasWidth += _expandAmount; + expanded = true; + } + if (maxBottom > _canvasHeight - _edgeThreshold) { + _canvasHeight += _expandAmount; + expanded = true; + } + if (expanded) setState(() {}); + } + + // -- Divider drag -- + + void _onDividerDragStart(DragStartDetails details) { + setState(() => _isDraggingDivider = true); + } + + void _onDividerDragUpdate( + DragUpdateDetails details, + BoxConstraints constraints, + ) { + final renderWidth = constraints.maxWidth; + if (renderWidth <= 0) return; + final delta = details.delta.dx / renderWidth; + setState(() { + _leftPaneFraction = (_leftPaneFraction + delta).clamp(0.2, 0.8); + }); + } + + void _onDividerDragEnd(DragEndDetails details) { + setState(() => _isDraggingDivider = false); + } + + // -- PDF page navigation -- + + void _prevPage() { + if (_currentPage > 0) { + _pdfController.previousPage(); + } + } + + void _nextPage() { + if (_currentPage < _pageCount - 1) { + _pdfController.nextPage(); + } + } + + // -- Page link creation (long-press on left pane) -- + + void _onPdfLongPress(int pageNumber) { + // Place a page link marker at the current scratchpad viewport center. + // We approximate the viewport center as (0, 0) since InteractiveViewer + // manages its own transform — the user can reposition by panning. + setState(() { + _pageLinks.add( + _PageLink( + pageNumber: pageNumber, + position: const Offset(100, 100), // default top-left area + ), + ); + }); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Page link marker added for page $pageNumber')), + ); + } + + void _onPageLinkTap(_PageLink link) { + _pdfController.jumpToPage(link.pageNumber); + setState(() { + _currentPage = link.pageNumber - 1; + }); + } + + void _deletePageLink(_PageLink link) { + setState(() { + _pageLinks.remove(link); + }); + } + + // -- Build -- + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text( + _fileName.isEmpty ? 'Split View' : _fileName, + style: const TextStyle(fontSize: 16), + ), + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + _saveImmediate(); + Navigator.of(context).pop(); + }, + ), + actions: [ + // Left pane page navigation + IconButton( + icon: const Icon(Icons.navigate_before), + tooltip: 'Previous page (PDF)', + onPressed: _currentPage > 0 ? _prevPage : null, + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Center( + child: Text( + '${_currentPage + 1} / $_pageCount', + style: const TextStyle(fontSize: 13), + ), + ), + ), + IconButton( + icon: const Icon(Icons.navigate_next), + tooltip: 'Next page (PDF)', + onPressed: _currentPage < _pageCount - 1 ? _nextPage : null, + ), + const SizedBox(width: 8), + // Canvas info + Tooltip( + message: + 'Scratchpad size: ${_canvasWidth.round()} x ${_canvasHeight.round()}', + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Center( + child: Text( + '${_canvasWidth.round()}x${_canvasHeight.round()}', + style: const TextStyle(fontSize: 11, color: Colors.grey), + ), + ), + ), + ), + ], + ), + body: Column( + children: [ + // Label clarifying that the toolbar controls the scratchpad pane. + Padding( + padding: const EdgeInsets.only(left: 12, top: 4), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + 'Scratchpad tools', + style: Theme.of(context).textTheme.labelSmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + // Toolbar (applies to scratchpad only) + AnnotationToolbar( + currentTool: _currentTool, + currentColor: _currentColor, + currentStrokeWidth: _currentStrokeWidth, + filled: _filled, + pressureCurveType: _pressureCurveType, + stabilizationLevel: _stabilizationLevel, + canUndo: _undoManager.canUndo, + canRedo: _undoManager.canRedo, + onToolChanged: (tool) => setState(() => _currentTool = tool), + onColorChanged: (color) => setState(() => _currentColor = color), + onStrokeWidthChanged: (w) => + setState(() => _currentStrokeWidth = w), + onFilledChanged: (f) => setState(() => _filled = f), + onPressureCurveChanged: (v) => + setState(() => _pressureCurveType = v), + onStabilizationChanged: (v) => + setState(() => _stabilizationLevel = v), + onUndo: _undo, + onRedo: _redo, + ), + // Split view body + Expanded( + child: LayoutBuilder( + builder: (context, constraints) { + final totalWidth = constraints.maxWidth; + final leftWidth = totalWidth * _leftPaneFraction; + final rightWidth = + totalWidth - leftWidth - 12; // 12px divider hit area + + return Row( + children: [ + // Left pane: PDF reference (read-only) + SizedBox(width: leftWidth, child: _buildPdfPane()), + // Draggable divider: 12px hit area, 4px visual strip. + GestureDetector( + onHorizontalDragStart: _onDividerDragStart, + onHorizontalDragUpdate: (d) => + _onDividerDragUpdate(d, constraints), + onHorizontalDragEnd: _onDividerDragEnd, + child: MouseRegion( + cursor: SystemMouseCursors.resizeColumn, + child: SizedBox( + width: 12, + child: Center( + child: Container( + width: 4, + color: _isDraggingDivider + ? Theme.of(context).colorScheme.primary + : Theme.of(context).dividerColor, + ), + ), + ), + ), + ), + // Right pane: Infinite scratchpad + SizedBox(width: rightWidth, child: _buildScratchpadPane()), + ], + ); + }, + ), + ), + ], + ), + ); + } + + Widget _buildPdfPane() { + return Stack( + children: [ + GestureDetector( + onLongPress: () { + // Long-press on PDF to create page link marker + _onPdfLongPress(_currentPage + 1); + }, + child: SfPdfViewer.file( + File(widget.filePath), + controller: _pdfController, + canShowScrollHead: true, + canShowScrollStatus: true, + onPageChanged: (PdfPageChangedDetails details) { + setState(() { + _currentPage = details.newPageNumber - 1; + }); + }, + onDocumentLoaded: (PdfDocumentLoadedDetails details) { + setState(() { + _pageCount = details.document.pages.count; + _fileName = widget.filePath.split(Platform.pathSeparator).last; + }); + }, + ), + ), + // Page link markers overlay (on PDF pane, showing linked pages) + if (_pageLinks.isNotEmpty) + Positioned(bottom: 8, left: 8, child: _buildPageLinkChips()), + ], + ); + } + + Widget _buildPageLinkChips() { + return Wrap( + spacing: 4, + runSpacing: 4, + children: _pageLinks.map((link) { + return GestureDetector( + onTap: () => _onPageLinkTap(link), + onLongPress: () => _deletePageLink(link), + child: Chip( + avatar: const Icon(Icons.link, size: 14, color: Colors.white), + label: Text( + 'p${link.pageNumber}', + style: const TextStyle(fontSize: 11, color: Colors.white), + ), + backgroundColor: Colors.blue.shade600, + padding: EdgeInsets.zero, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + visualDensity: VisualDensity.compact, + ), + ); + }).toList(), + ); + } + + Widget _buildScratchpadPane() { + return Container( + color: Theme.of(context).scaffoldBackgroundColor, + child: InteractiveViewer( + constrained: false, + minScale: 0.25, + maxScale: 8.0, + boundaryMargin: const EdgeInsets.all(double.infinity), + child: SizedBox( + width: _canvasWidth, + height: _canvasHeight, + child: InkCanvas( + strokes: _strokes, + onStrokeComplete: _onStrokeComplete, + onErase: _onErase, + tool: _currentTool, + color: _currentColor, + strokeWidth: _currentStrokeWidth, + pressureCurve: PressureCurve(type: _pressureCurveType), + stabilizationLevel: _stabilizationLevel, + filled: _filled, + interactionMode: InteractionMode.draw, + ), + ), + ), + ); + } +} + +/// A marker linking a scratchpad position to a specific PDF page. +class _PageLink { + final int pageNumber; + final Offset position; + + const _PageLink({required this.pageNumber, required this.position}); +} diff --git a/lib/services/camera_service.dart b/lib/services/camera_service.dart new file mode 100644 index 0000000..6f26cdf --- /dev/null +++ b/lib/services/camera_service.dart @@ -0,0 +1,20 @@ +import 'package:image_picker/image_picker.dart'; + +/// Thin wrapper around image_picker for camera capture and gallery selection. +class CameraService { + final ImagePicker _picker = ImagePicker(); + + /// Capture a photo using the device camera. + /// Returns the file path, or null if the user cancelled. + Future capturePhoto() async { + final XFile? image = await _picker.pickImage(source: ImageSource.camera); + return image?.path; + } + + /// Pick an image from the device gallery. + /// Returns the file path, or null if the user cancelled. + Future pickFromGallery() async { + final XFile? image = await _picker.pickImage(source: ImageSource.gallery); + return image?.path; + } +} diff --git a/lib/services/database_service.dart b/lib/services/database_service.dart new file mode 100644 index 0000000..cd43624 --- /dev/null +++ b/lib/services/database_service.dart @@ -0,0 +1,841 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:uuid/uuid.dart'; + +import '../models/bookmark.dart'; +import '../models/document.dart' as doc; +import '../models/ink_point.dart'; +import '../models/ink_stroke.dart'; +import '../models/note.dart'; +import '../models/pen_tool.dart'; +import '../models/pointer_device_kind.dart'; + +class DatabaseService { + static DatabaseService? _instance; + late Database _database; + + DatabaseService._(); + + static Future getInstance() async { + if (_instance != null) return _instance!; + final service = DatabaseService._(); + await service._initialize(); + _instance = service; + return service; + } + + Database get database => _database; + + Future _initialize() async { + if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + } + + final dir = await getApplicationDocumentsDirectory(); + final dbPath = p.join(dir.path, 'badnote.db'); + + _database = await openDatabase( + dbPath, + version: 5, + onCreate: _onCreate, + onUpgrade: _onUpgrade, + ); + } + + Future _onCreate(Database db, int version) async { + // Core tables (original v1) + await db.execute(''' + CREATE TABLE notes ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + tags TEXT NOT NULL DEFAULT '[]' + ) + '''); + + await db.execute(''' + CREATE TABLE strokes ( + id TEXT PRIMARY KEY, + note_id TEXT NOT NULL, + tool TEXT NOT NULL, + color INTEGER NOT NULL, + stroke_width REAL NOT NULL, + created_at TEXT NOT NULL, + points TEXT NOT NULL, + FOREIGN KEY (note_id) REFERENCES notes(id) ON DELETE CASCADE + ) + '''); + + await db.execute('CREATE INDEX idx_strokes_note_id ON strokes(note_id)'); + + await _createFtsTable(db); + + // Documents & annotations (originally v2, now part of fresh install) + await db.execute(''' + CREATE TABLE documents ( + id TEXT PRIMARY KEY, + filename TEXT NOT NULL, + doc_type TEXT NOT NULL, + file_path TEXT NOT NULL, + page_count INTEGER NOT NULL DEFAULT 0, + rotation INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ) + '''); + + await db.execute(''' + CREATE TABLE annotations ( + id TEXT PRIMARY KEY, + uuid TEXT NOT NULL, + document_id TEXT NOT NULL, + page_number INTEGER NOT NULL, + annotation_json TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE + ) + '''); + + await db.execute( + 'CREATE INDEX idx_annotations_doc_page ON annotations(document_id, page_number)', + ); + + await db.execute(''' + CREATE TABLE bookmarks ( + id TEXT PRIMARY KEY, + document_id TEXT NOT NULL, + page_number INTEGER NOT NULL, + label TEXT NOT NULL DEFAULT '', + color INTEGER NOT NULL DEFAULT 4283215696, + created_at TEXT NOT NULL, + FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE + ) + '''); + + await db.execute( + 'CREATE INDEX idx_bookmarks_doc ON bookmarks(document_id)', + ); + + await db.execute(''' + CREATE TABLE ocr_results ( + id TEXT PRIMARY KEY, + document_id TEXT NOT NULL, + page_number INTEGER NOT NULL, + ocr_text TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE + ) + '''); + + // Document FTS (v3) + await db.execute(''' + CREATE VIRTUAL TABLE document_fts USING fts5( + document_id, page_number, content, tokenize='porter unicode61' + ) + '''); + + // Scratchpads (v5) + await db.execute(''' + CREATE TABLE scratchpads ( + id TEXT PRIMARY KEY, + document_id TEXT UNIQUE NOT NULL, + strokes_json TEXT NOT NULL DEFAULT '[]', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE + ) + '''); + + await db.execute( + 'CREATE INDEX idx_scratchpads_doc ON scratchpads(document_id)', + ); + } + + Future _onUpgrade(Database db, int oldVersion, int newVersion) async { + if (oldVersion < 3) await _migrateV2toV3(db); + if (oldVersion < 4) {} // v3->v4: version boundary (no-op schema) + if (oldVersion < 5) await _migrateV4toV5(db); + } + + Future _migrateV2toV3(Database db) async { + // Wrap the whole migration in a transaction: a failure mid-migration + // (after DROP TABLE annotations) would otherwise destroy data. + await db.transaction((txn) async { + // Add uuid column to annotations + await txn.execute('ALTER TABLE annotations ADD COLUMN uuid TEXT'); + + // Generate UUIDs for existing rows + await txn.rawUpdate( + "UPDATE annotations SET uuid = hex(randomblob(16)) WHERE uuid IS NULL", + ); + + // Recreate annotations table with UUID primary key + await txn.execute(''' + CREATE TABLE annotations_new ( + id TEXT PRIMARY KEY, + uuid TEXT NOT NULL, + document_id TEXT NOT NULL, + page_number INTEGER NOT NULL, + annotation_json TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE + ) + '''); + + await txn.rawInsert(''' + INSERT INTO annotations_new (id, uuid, document_id, page_number, annotation_json, created_at, updated_at) + SELECT id, uuid, document_id, page_number, annotation_json, created_at, updated_at FROM annotations + '''); + + await txn.execute('DROP TABLE annotations'); + await txn.execute('ALTER TABLE annotations_new RENAME TO annotations'); + await txn.execute( + 'CREATE INDEX idx_annotations_doc_page ON annotations(document_id, page_number)', + ); + + // Create document FTS table + await txn.execute(''' + CREATE VIRTUAL TABLE document_fts USING fts5( + document_id, page_number, content, tokenize='porter unicode61' + ) + '''); + + // Add rotation column to documents + await txn.execute( + 'ALTER TABLE documents ADD COLUMN rotation INTEGER NOT NULL DEFAULT 0', + ); + }); + } + + Future _migrateV4toV5(Database db) async { + // Wrap in a transaction so a partial failure does not leave the schema + // in an inconsistent state. + await db.transaction((txn) async { + // Create scratchpads table + await txn.execute(''' + CREATE TABLE scratchpads ( + id TEXT PRIMARY KEY, + document_id TEXT UNIQUE NOT NULL, + strokes_json TEXT NOT NULL DEFAULT '[]', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE + ) + '''); + + await txn.execute( + 'CREATE INDEX idx_scratchpads_doc ON scratchpads(document_id)', + ); + }); + } + + // ── Notes CRUD ────────────────────────────────────────────────────── + + Future> getAllNotes() async { + final noteRows = await _database.query('notes', orderBy: 'updated_at DESC'); + final notes = []; + for (final row in noteRows) { + notes.add(await _noteFromRow(row)); + } + return notes; + } + + Future getNoteById(String id) async { + final rows = await _database.query( + 'notes', + where: 'id = ?', + whereArgs: [id], + ); + if (rows.isEmpty) return null; + return _noteFromRow(rows.first); + } + + Future insertNote(Note note) async { + // Atomic: the note row, its strokes, and the FTS index must all commit + // together or not at all. + await _database.transaction((txn) async { + await txn.insert('notes', { + 'id': note.id, + 'title': note.title, + 'created_at': note.createdAt.toIso8601String(), + 'updated_at': note.updatedAt.toIso8601String(), + 'tags': jsonEncode(note.tags), + }); + + for (final stroke in note.strokes) { + await _insertStroke(txn, note.id, stroke); + } + + await _extractAndIndexNoteContent(txn, note); + }); + } + + Future updateNote(Note note) async { + // Atomic: this deletes all strokes then re-inserts them and rebuilds the + // FTS entry. An interruption mid-way would permanently lose strokes, so + // the whole sequence must run inside one transaction. + await _database.transaction((txn) async { + await txn.update( + 'notes', + { + 'title': note.title, + 'updated_at': note.updatedAt.toIso8601String(), + 'tags': jsonEncode(note.tags), + }, + where: 'id = ?', + whereArgs: [note.id], + ); + + // Replace all strokes for this note + await txn.delete('strokes', where: 'note_id = ?', whereArgs: [note.id]); + for (final stroke in note.strokes) { + await _insertStroke(txn, note.id, stroke); + } + + await removeFromFts(txn, note.id); + await _extractAndIndexNoteContent(txn, note); + }); + } + + Future deleteNote(String id) async { + await _database.transaction((txn) async { + await txn.delete('strokes', where: 'note_id = ?', whereArgs: [id]); + await txn.delete('notes', where: 'id = ?', whereArgs: [id]); + await removeFromFts(txn, id); + }); + } + + // ── Strokes ───────────────────────────────────────────────────────── + + Future _insertStroke( + DatabaseExecutor db, + String noteId, + InkStroke stroke, + ) async { + await db.insert('strokes', { + 'id': stroke.id, + 'note_id': noteId, + 'tool': stroke.tool.name, + 'color': stroke.color, + 'stroke_width': stroke.strokeWidth, + 'created_at': stroke.createdAt.toIso8601String(), + 'points': jsonEncode(stroke.points.map(_pointToJson).toList()), + }); + } + + Future> _getStrokesForNote(String noteId) async { + final rows = await _database.query( + 'strokes', + where: 'note_id = ?', + whereArgs: [noteId], + orderBy: 'created_at ASC', + ); + return rows.map(_strokeFromRow).toList(); + } + + // ── Serialization helpers ─────────────────────────────────────────── + + Map _pointToJson(InkPoint p) => { + 'x': p.x, + 'y': p.y, + 'pressure': p.pressure, + 'tilt': p.tilt, + 'timestamp': p.timestamp, + 'pointerDeviceKind': p.pointerDeviceKind.name, + }; + + InkPoint _pointFromJson(Map json) => InkPoint( + x: (json['x'] as num).toDouble(), + y: (json['y'] as num).toDouble(), + pressure: (json['pressure'] as num?)?.toDouble() ?? 0.5, + tilt: (json['tilt'] as num?)?.toDouble() ?? 0.0, + timestamp: json['timestamp'] as int, + pointerDeviceKind: _parseDeviceKind(json['pointerDeviceKind'] as String?), + ); + + InputDeviceKind _parseDeviceKind(String? value) { + if (value == null) return InputDeviceKind.unknown; + return InputDeviceKind.values.asNameMap()[value] ?? InputDeviceKind.unknown; + } + + InkStroke _strokeFromRow(Map row) { + final pointsJson = jsonDecode(row['points'] as String) as List; + return InkStroke( + id: row['id'] as String, + points: pointsJson + .map((p) => _pointFromJson(p as Map)) + .toList(), + tool: _parsePenTool(row['tool'] as String), + color: row['color'] as int, + strokeWidth: (row['stroke_width'] as num).toDouble(), + createdAt: DateTime.parse(row['created_at'] as String), + ); + } + + PenTool _parsePenTool(String value) { + return PenTool.values.asNameMap()[value] ?? PenTool.pen; + } + + Future _noteFromRow(Map row) async { + final tagsJson = jsonDecode(row['tags'] as String) as List; + final strokes = await _getStrokesForNote(row['id'] as String); + return Note( + id: row['id'] as String, + title: row['title'] as String, + strokes: strokes, + createdAt: DateTime.parse(row['created_at'] as String), + updatedAt: DateTime.parse(row['updated_at'] as String), + tags: tagsJson.cast(), + ); + } + + // ── Full-Text Search (FTS5) ──────────────────────────────────────── + + Future _createFtsTable(Database db) async { + await db.execute(''' + CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5( + note_id, title, content, tokenize='porter unicode61' + ) + '''); + } + + /// Index a note's text content for full-text search. + /// [content] should include any typed text, OCR text, etc. + Future indexNoteContent( + DatabaseExecutor db, + String noteId, + String title, + String content, + ) async { + await db.insert('notes_fts', { + 'note_id': noteId, + 'title': title, + 'content': content, + }); + } + + /// Extract text content from a note's strokes and index it for FTS. + /// Concatenates the title with any textContent from strokes. + Future _extractAndIndexNoteContent( + DatabaseExecutor db, + Note note, + ) async { + final textParts = [note.title]; + for (final stroke in note.strokes) { + if (stroke.textContent != null && stroke.textContent!.isNotEmpty) { + textParts.add(stroke.textContent!); + } + } + final content = textParts.join(' '); + await indexNoteContent(db, note.id, note.title, content); + } + + /// Append OCR text to an existing note's FTS entry. + /// Reads current content, merges with new OCR text, and re-indexes. + Future appendOcrToFts(String noteId, String ocrText) async { + if (ocrText.trim().isEmpty) return; + + // Read-modify-write must be atomic: querying the current content, removing + // the old entry, and re-inserting the merged content all run inside one + // transaction so a concurrent writer cannot cause a lost update. + await _database.transaction((txn) async { + // Read current FTS content + final rows = await txn.query( + 'notes_fts', + where: 'note_id = ?', + whereArgs: [noteId], + ); + + String existingContent = ''; + String existingTitle = ''; + if (rows.isNotEmpty) { + existingTitle = rows.first['title'] as String? ?? ''; + existingContent = rows.first['content'] as String? ?? ''; + } + + // Merge: append OCR text to existing content + final mergedContent = existingContent.isEmpty + ? ocrText + : '$existingContent $ocrText'; + + // Remove old entry and re-insert with merged content + await removeFromFts(txn, noteId); + await indexNoteContent(txn, noteId, existingTitle, mergedContent); + }); + } + + /// Full-text search across indexed notes. + Future> searchNotes(String query) async { + if (query.trim().isEmpty) return []; + + // Sanitize query for FTS5: escape special chars and add prefix matching + final sanitized = query.replaceAll('"', '').replaceAll("'", '').trim(); + if (sanitized.isEmpty) return []; + + final ftsQuery = sanitized + .split(RegExp(r'\s+')) + .map((w) => '"$w"*') + .join(' '); + + final rows = await _database.rawQuery( + 'SELECT note_id FROM notes_fts WHERE notes_fts MATCH ? ORDER BY rank', + [ftsQuery], + ); + + final notes = []; + for (final row in rows) { + final noteId = row['note_id'] as String; + final note = await getNoteById(noteId); + if (note != null) { + notes.add(note); + } + } + return notes; + } + + /// Remove a note from the FTS index. + Future removeFromFts(DatabaseExecutor db, String noteId) async { + await db.delete('notes_fts', where: 'note_id = ?', whereArgs: [noteId]); + } + + // ── Document FTS ──────────────────────────────────────────────────── + + /// Index a page's text content for document full-text search. + Future indexDocumentContent( + String documentId, + int pageNumber, + String content, + ) async { + // Remove existing entry for this page first + await _database.delete( + 'document_fts', + where: 'document_id = ? AND page_number = ?', + whereArgs: [documentId, pageNumber], + ); + await _database.insert('document_fts', { + 'document_id': documentId, + 'page_number': pageNumber.toString(), + 'content': content, + }); + } + + /// Remove a page from the document FTS index. + Future removeDocumentFromFts( + DatabaseExecutor db, + String documentId, + int pageNumber, + ) async { + await db.delete( + 'document_fts', + where: 'document_id = ? AND page_number = ?', + whereArgs: [documentId, pageNumber], + ); + } + + /// Full-text search across indexed document pages. + Future>> searchDocuments(String query) async { + if (query.trim().isEmpty) return []; + + final sanitized = query.replaceAll('"', '').replaceAll("'", '').trim(); + if (sanitized.isEmpty) return []; + + final ftsQuery = sanitized + .split(RegExp(r'\s+')) + .map((w) => '"$w"*') + .join(' '); + + final rows = await _database.rawQuery( + 'SELECT document_id, page_number, content FROM document_fts WHERE document_fts MATCH ? ORDER BY rank', + [ftsQuery], + ); + + return rows + .map( + (row) => { + 'document_id': row['document_id'] as String, + 'page_number': int.parse(row['page_number'] as String), + 'content': row['content'] as String, + }, + ) + .toList(); + } + + // ── Documents CRUD ───────────────────────────────────────────────── + + Future insertDocument(doc.Document document) async { + await _database.insert('documents', { + 'id': document.id, + 'filename': document.filename, + 'doc_type': document.docType, + 'file_path': document.filePath, + 'page_count': document.pageCount, + 'rotation': document.rotation, + 'created_at': document.createdAt.toIso8601String(), + 'updated_at': document.updatedAt.toIso8601String(), + }); + } + + Future getDocument(String id) async { + final rows = await _database.query( + 'documents', + where: 'id = ?', + whereArgs: [id], + ); + if (rows.isEmpty) return null; + return _documentFromRow(rows.first); + } + + Future getDocumentByPath(String filePath) async { + final rows = await _database.query( + 'documents', + where: 'file_path = ?', + whereArgs: [filePath], + ); + if (rows.isEmpty) return null; + return _documentFromRow(rows.first); + } + + Future> getAllDocuments() async { + final rows = await _database.query('documents', orderBy: 'updated_at DESC'); + return rows.map(_documentFromRow).toList(); + } + + Future deleteDocument(String id) async { + await _database.transaction((txn) async { + await txn.delete( + 'annotations', + where: 'document_id = ?', + whereArgs: [id], + ); + await txn.delete('bookmarks', where: 'document_id = ?', whereArgs: [id]); + await txn.delete( + 'ocr_results', + where: 'document_id = ?', + whereArgs: [id], + ); + await txn.delete( + 'scratchpads', + where: 'document_id = ?', + whereArgs: [id], + ); + await txn.delete('documents', where: 'id = ?', whereArgs: [id]); + }); + } + + doc.Document _documentFromRow(Map row) { + return doc.Document( + id: row['id'] as String, + filename: row['filename'] as String, + docType: row['doc_type'] as String, + filePath: row['file_path'] as String, + pageCount: row['page_count'] as int, + rotation: (row['rotation'] as int?) ?? 0, + createdAt: DateTime.parse(row['created_at'] as String), + updatedAt: DateTime.parse(row['updated_at'] as String), + ); + } + + // ── Annotations CRUD ─────────────────────────────────────────────── + + Future saveAnnotations( + String documentId, + int pageNumber, + String annotationJson, + ) async { + await _database.delete( + 'annotations', + where: 'document_id = ? AND page_number = ?', + whereArgs: [documentId, pageNumber], + ); + await _database.insert('annotations', { + 'id': const Uuid().v4(), + 'uuid': const Uuid().v4(), + 'document_id': documentId, + 'page_number': pageNumber, + 'annotation_json': annotationJson, + 'created_at': DateTime.now().toIso8601String(), + 'updated_at': DateTime.now().toIso8601String(), + }); + } + + Future getAnnotations(String documentId, int pageNumber) async { + final rows = await _database.query( + 'annotations', + where: 'document_id = ? AND page_number = ?', + whereArgs: [documentId, pageNumber], + ); + if (rows.isEmpty) return null; + return rows.first['annotation_json'] as String; + } + + Future deleteDocumentAnnotations(String documentId) async { + await _database.delete( + 'annotations', + where: 'document_id = ?', + whereArgs: [documentId], + ); + } + + // ── Annotation/Bookmark Remapping ────────────────────────────────── + + /// After deleting a page at [deletedIndex], shift all annotations + /// with page_number > deletedIndex down by 1. + Future remapAnnotationsAfterDelete( + String documentId, + int deletedIndex, + ) async { + await _database.rawUpdate( + 'UPDATE annotations SET page_number = page_number - 1 WHERE document_id = ? AND page_number > ?', + [documentId, deletedIndex], + ); + } + + /// After inserting a page at [insertedIndex], shift all annotations + /// with page_number >= insertedIndex up by 1. + Future remapAnnotationsAfterInsert( + String documentId, + int insertedIndex, + ) async { + await _database.rawUpdate( + 'UPDATE annotations SET page_number = page_number + 1 WHERE document_id = ? AND page_number >= ?', + [documentId, insertedIndex], + ); + } + + /// After deleting a page at [deletedIndex], shift all bookmarks + /// with page_number > deletedIndex down by 1. + Future remapBookmarksAfterDelete( + String documentId, + int deletedIndex, + ) async { + await _database.rawUpdate( + 'UPDATE bookmarks SET page_number = page_number - 1 WHERE document_id = ? AND page_number > ?', + [documentId, deletedIndex], + ); + } + + /// After inserting a page at [insertedIndex], shift all bookmarks + /// with page_number >= insertedIndex up by 1. + Future remapBookmarksAfterInsert( + String documentId, + int insertedIndex, + ) async { + await _database.rawUpdate( + 'UPDATE bookmarks SET page_number = page_number + 1 WHERE document_id = ? AND page_number >= ?', + [documentId, insertedIndex], + ); + } + + /// Delete all annotations, bookmarks, and OCR data for a specific page. + Future deletePageData(String documentId, int pageNumber) async { + await _database.transaction((txn) async { + await txn.delete( + 'annotations', + where: 'document_id = ? AND page_number = ?', + whereArgs: [documentId, pageNumber], + ); + await txn.delete( + 'bookmarks', + where: 'document_id = ? AND page_number = ?', + whereArgs: [documentId, pageNumber], + ); + await txn.delete( + 'ocr_results', + where: 'document_id = ? AND page_number = ?', + whereArgs: [documentId, pageNumber], + ); + await removeDocumentFromFts(txn, documentId, pageNumber); + }); + } + + /// Update the stored page count for a document. + Future updateDocumentPageCount( + String documentId, + int newPageCount, + ) async { + await _database.update( + 'documents', + { + 'page_count': newPageCount, + 'updated_at': DateTime.now().toIso8601String(), + }, + where: 'id = ?', + whereArgs: [documentId], + ); + } + + // ── Bookmarks CRUD ───────────────────────────────────────────────── + + Future insertBookmark(Bookmark bookmark) async { + await _database.insert('bookmarks', { + 'id': bookmark.id, + 'document_id': bookmark.documentId, + 'page_number': bookmark.pageNumber, + 'label': bookmark.label, + 'color': bookmark.color, + 'created_at': bookmark.createdAt.toIso8601String(), + }); + } + + Future> getBookmarks(String documentId) async { + final rows = await _database.query( + 'bookmarks', + where: 'document_id = ?', + whereArgs: [documentId], + orderBy: 'page_number ASC', + ); + return rows.map(_bookmarkFromRow).toList(); + } + + Future deleteBookmark(String id) async { + await _database.delete('bookmarks', where: 'id = ?', whereArgs: [id]); + } + + Bookmark _bookmarkFromRow(Map row) { + return Bookmark( + id: row['id'] as String, + documentId: row['document_id'] as String, + pageNumber: row['page_number'] as int, + label: row['label'] as String, + color: row['color'] as int, + createdAt: DateTime.parse(row['created_at'] as String), + ); + } + + // ── Scratchpad CRUD ──────────────────────────────────────────────── + + /// Save scratchpad strokes for a document (upsert). + Future saveScratchpad(String documentId, String strokesJson) async { + final now = DateTime.now().toIso8601String(); + await _database.rawInsert( + '''INSERT INTO scratchpads (id, document_id, strokes_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(document_id) DO UPDATE SET strokes_json = excluded.strokes_json, updated_at = excluded.updated_at''', + [const Uuid().v4(), documentId, strokesJson, now, now], + ); + } + + /// Load scratchpad strokes for a document. + Future> loadScratchpad(String documentId) async { + final rows = await _database.query( + 'scratchpads', + where: 'document_id = ?', + whereArgs: [documentId], + ); + if (rows.isEmpty) return []; + final json = rows.first['strokes_json'] as String; + if (json.isEmpty || json == '[]') return []; + final List list = jsonDecode(json) as List; + return list + .map((s) => InkStroke.fromJson(s as Map)) + .toList(); + } +} diff --git a/lib/services/ocr_engine.dart b/lib/services/ocr_engine.dart new file mode 100644 index 0000000..3b19884 --- /dev/null +++ b/lib/services/ocr_engine.dart @@ -0,0 +1,21 @@ +import 'dart:io'; + +import 'package:flutter/services.dart'; + +/// Platform OCR backend. Uses Windows built-in OCR on desktop Windows. +class OcrEngine { + static const _channel = MethodChannel('badnote/ocr'); + + /// Recognize text from a PNG image. Returns null when unavailable or empty. + static Future recognizeImage(Uint8List pngBytes) async { + if (!Platform.isWindows) return null; + try { + final result = await _channel.invokeMethod('recognize', pngBytes); + final text = result?.trim(); + if (text == null || text.isEmpty) return null; + return text; + } catch (_) { + return null; + } + } +} diff --git a/lib/services/ocr_service.dart b/lib/services/ocr_service.dart new file mode 100644 index 0000000..b3bd4f0 --- /dev/null +++ b/lib/services/ocr_service.dart @@ -0,0 +1,46 @@ +import '../models/note.dart'; +import '../models/pen_tool.dart'; +import 'database_service.dart'; +import 'ocr_engine.dart'; +import 'stroke_rasterizer.dart'; + +/// Runs OCR locally: typed text from strokes + handwriting via platform OCR. +class OcrService { + /// Extract searchable text from [note] and merge into the local FTS index. + Future processNote(Note note) async { + final parts = []; + + for (final stroke in note.strokes) { + if (stroke.tool == PenTool.text && + stroke.textContent != null && + stroke.textContent!.trim().isNotEmpty) { + parts.add(stroke.textContent!.trim()); + } + } + + final handwritingStrokes = note.strokes + .where( + (s) => + s.tool != PenTool.eraser && + s.tool != PenTool.text && + s.points.isNotEmpty, + ) + .toList(); + + if (handwritingStrokes.isNotEmpty) { + final png = await StrokeRasterizer.render(handwritingStrokes); + if (png != null) { + final recognized = await OcrEngine.recognizeImage(png); + if (recognized != null && recognized.isNotEmpty) { + parts.add(recognized); + } + } + } + + final combined = parts.join(' ').trim(); + if (combined.isEmpty) return; + + final db = await DatabaseService.getInstance(); + await db.appendOcrToFts(note.id, combined); + } +} diff --git a/lib/services/pdf_service.dart b/lib/services/pdf_service.dart new file mode 100644 index 0000000..c9e58f3 --- /dev/null +++ b/lib/services/pdf_service.dart @@ -0,0 +1,245 @@ +import 'dart:io'; +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:file_picker/file_picker.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:syncfusion_flutter_pdf/pdf.dart'; + +import '../models/ink_stroke.dart'; + +/// Service for PDF operations: file picking, info extraction, and annotation export. +class PdfService { + /// Pick a PDF file path using the cross-platform file_picker. + Future pickPdfFile() async { + final result = await FilePicker.platform.pickFiles( + type: FileType.custom, + allowedExtensions: ['pdf'], + ); + final files = result?.files; + if (files == null || files.isEmpty) return null; + return files.first.path; + } + + /// Get the page count of the PDF at [filePath]. + Future getPageCount(String filePath) async { + final bytes = await File(filePath).readAsBytes(); + final document = PdfDocument(inputBytes: bytes); + try { + return document.pages.count; + } finally { + document.dispose(); + } + } + + /// Get basic info about a PDF file: fileName and fileSize. + Future> getPdfInfo(String filePath) async { + final file = File(filePath); + final fileSize = await file.length(); + return {'fileName': p.basename(filePath), 'fileSize': fileSize}; + } + + /// Export an annotated PDF by drawing ink strokes onto each page. + /// + /// [annotations] maps page index (0-based) to lists of [InkStroke]. + /// Stroke coordinates are normalized to [0, 1] relative to the annotation + /// overlay size used during capture, and are scaled to actual PDF page + /// dimensions during export. + /// + /// Returns the path to the exported annotated PDF. + Future exportAnnotatedPdf( + String filePath, + Map> annotations, + ) async { + final bytes = await File(filePath).readAsBytes(); + final document = PdfDocument(inputBytes: bytes); + try { + for (final entry in annotations.entries) { + final pageIndex = entry.key; + final strokes = entry.value; + if (strokes.isEmpty) continue; + if (pageIndex >= document.pages.count) continue; + + final page = document.pages[pageIndex]; + _renderStrokes(page, strokes); + } + + final outputDir = await getTemporaryDirectory(); + final baseName = p.basenameWithoutExtension(filePath); + final outputPath = p.join(outputDir.path, '${baseName}_annotated.pdf'); + final savedBytes = await document.save(); + await File(outputPath).writeAsBytes(savedBytes, flush: true); + + return outputPath; + } finally { + document.dispose(); + } + } + + /// Delete a page at [pageIndex]. Returns true on success. + Future deletePage(String filePath, int pageIndex) async { + try { + final bytes = await File(filePath).readAsBytes(); + final document = PdfDocument(inputBytes: bytes); + try { + if (pageIndex < 0 || pageIndex >= document.pages.count) { + return false; + } + document.pages.removeAt(pageIndex); + final outputBytes = await document.save(); + await File(filePath).writeAsBytes(outputBytes, flush: true); + return true; + } finally { + document.dispose(); + } + } catch (_) { + return false; + } + } + + /// Insert a blank A4 page (595 x 842 pt) after [afterIndex]. + /// Returns true on success. + Future insertBlankPage(String filePath, int afterIndex) async { + try { + final bytes = await File(filePath).readAsBytes(); + final document = PdfDocument(inputBytes: bytes); + final insertAt = (afterIndex + 1).clamp(0, document.pages.count); + document.pages.insert(insertAt); + final outputBytes = await document.save(); + document.dispose(); + await File(filePath).writeAsBytes(outputBytes, flush: true); + return true; + } catch (_) { + return false; + } + } + + /// Rotate page at [pageIndex] 90 degrees clockwise. + /// Returns true on success. + Future rotatePage(String filePath, int pageIndex) async { + try { + final bytes = await File(filePath).readAsBytes(); + final document = PdfDocument(inputBytes: bytes); + try { + if (pageIndex < 0 || pageIndex >= document.pages.count) { + return false; + } + final page = document.pages[pageIndex]; + final current = page.rotation; + // Cycle through: 0 -> 90 -> 180 -> 270 -> 0 + switch (current) { + case PdfPageRotateAngle.rotateAngle0: + page.rotation = PdfPageRotateAngle.rotateAngle90; + case PdfPageRotateAngle.rotateAngle90: + page.rotation = PdfPageRotateAngle.rotateAngle180; + case PdfPageRotateAngle.rotateAngle180: + page.rotation = PdfPageRotateAngle.rotateAngle270; + case PdfPageRotateAngle.rotateAngle270: + page.rotation = PdfPageRotateAngle.rotateAngle0; + } + final outputBytes = await document.save(); + await File(filePath).writeAsBytes(outputBytes, flush: true); + return true; + } finally { + document.dispose(); + } + } catch (_) { + return false; + } + } + + /// Draw an image from [imagePath] onto the page at [pageIndex], + /// fitted to the page dimensions while preserving aspect ratio. + /// Returns the [pdfPath] on success, null on failure. + Future insertImageOnPage( + String pdfPath, + int pageIndex, + String imagePath, + ) async { + try { + final pdfBytes = await File(pdfPath).readAsBytes(); + final document = PdfDocument(inputBytes: pdfBytes); + try { + if (pageIndex < 0 || pageIndex >= document.pages.count) { + return null; + } + final page = document.pages[pageIndex]; + final imageBytes = await File(imagePath).readAsBytes(); + final pdfImage = PdfBitmap(imageBytes); + final pageSize = page.getClientSize(); + + // Fit the image to the page while preserving its aspect ratio + // (letterboxed and centered), rather than stretching it to fill. + final imageWidth = pdfImage.width.toDouble(); + final imageHeight = pdfImage.height.toDouble(); + final scale = (imageWidth <= 0 || imageHeight <= 0) + ? 1.0 + : math.min( + pageSize.width / imageWidth, + pageSize.height / imageHeight, + ); + final drawWidth = imageWidth * scale; + final drawHeight = imageHeight * scale; + final left = (pageSize.width - drawWidth) / 2; + final top = (pageSize.height - drawHeight) / 2; + + page.graphics.drawImage( + pdfImage, + Rect.fromLTWH(left, top, drawWidth, drawHeight), + ); + final outputBytes = await document.save(); + await File(pdfPath).writeAsBytes(outputBytes, flush: true); + return pdfPath; + } finally { + document.dispose(); + } + } catch (_) { + return null; + } + } + + /// Renders [strokes] onto a PDF [page] using normalized [0, 1] coordinates + /// scaled to the actual page dimensions. + void _renderStrokes(PdfPage page, List strokes) { + final graphics = page.graphics; + final pageSize = page.getClientSize(); + + for (final stroke in strokes) { + if (stroke.points.isEmpty) continue; + + final color = stroke.color; + final r = (color >> 16) & 0xFF; + final g = (color >> 8) & 0xFF; + final b = color & 0xFF; + final a = (color >> 24) & 0xFF; + + final pen = PdfPen(PdfColor(r, g, b, a)); + pen.width = stroke.strokeWidth.clamp(1.0, 8.0); + + if (stroke.points.length == 1) { + // Single point — draw a dot + final pt = stroke.points.first; + graphics.drawEllipse( + Rect.fromCenter( + center: Offset(pt.x * pageSize.width, pt.y * pageSize.height), + width: stroke.strokeWidth, + height: stroke.strokeWidth, + ), + pen: pen, + ); + } else { + // Draw line segments between consecutive points + for (int i = 0; i < stroke.points.length - 1; i++) { + final p1 = stroke.points[i]; + final p2 = stroke.points[i + 1]; + graphics.drawLine( + pen, + Offset(p1.x * pageSize.width, p1.y * pageSize.height), + Offset(p2.x * pageSize.width, p2.y * pageSize.height), + ); + } + } + } + } +} diff --git a/lib/services/pen_input_service.dart b/lib/services/pen_input_service.dart new file mode 100644 index 0000000..4d45ea6 --- /dev/null +++ b/lib/services/pen_input_service.dart @@ -0,0 +1,62 @@ +import 'dart:async'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../models/ink_point.dart'; +import '../models/pen_tool.dart'; +import '../models/pointer_device_kind.dart'; + +class PenInputService { + final StreamController _pointController = + StreamController.broadcast(); + + Stream get pointStream => _pointController.stream; + + PenTool currentTool = PenTool.pen; + Color currentColor = Colors.black; + double currentStrokeWidth = 2.0; + + void addPoint(InkPoint point) { + _pointController.add(point); + } + + InputDeviceKind mapFlutterKind(PointerDeviceKind kind) { + switch (kind) { + case PointerDeviceKind.touch: + return InputDeviceKind.touch; + case PointerDeviceKind.mouse: + return InputDeviceKind.mouse; + case PointerDeviceKind.stylus: + return InputDeviceKind.stylus; + case PointerDeviceKind.invertedStylus: + return InputDeviceKind.invertedStylus; + case PointerDeviceKind.trackpad: + return InputDeviceKind.trackpad; + case PointerDeviceKind.unknown: + return InputDeviceKind.unknown; + } + } + + InkPoint fromPointerEvent(PointerEvent event) { + // Devices without real pressure support (mouse, basic touch) report a + // degenerate range where pressureMin == pressureMax, which can yield a + // pressure of 0.0 and produce zero-width strokes. In that case fall back + // to a neutral mid-pressure value so strokes remain visible. + final pressure = event.pressureMin == event.pressureMax + ? 0.5 + : event.pressure; + return InkPoint( + x: event.localPosition.dx, + y: event.localPosition.dy, + pressure: pressure, + tilt: event is PointerMoveEvent ? event.tilt : 0.0, + timestamp: event.timeStamp.inMicroseconds, + pointerDeviceKind: mapFlutterKind(event.kind), + ); + } + + void dispose() { + _pointController.close(); + } +} diff --git a/lib/services/pptx_service.dart b/lib/services/pptx_service.dart new file mode 100644 index 0000000..9a3a4cf --- /dev/null +++ b/lib/services/pptx_service.dart @@ -0,0 +1,293 @@ +import 'dart:io'; + +import 'package:file_picker/file_picker.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:uuid/uuid.dart'; + +/// Service for processing PPTX files: text extraction, image conversion, file picking. +/// +/// PPTX files are ZIP archives containing XML. We extract text from +/// `ppt/slides/slide*.xml` `` elements and convert slides to images +/// using LibreOffice (headless) or generate placeholder images as fallback. +class PptxService { + static const _uuid = Uuid(); + + /// Extract all text content from a PPTX file. + /// + /// PPTX is a ZIP archive. Slide text lives in `ppt/slides/slide*.xml` + /// inside `` (ASCII text) elements within `` (run) or + /// `` (paragraph) nodes. + Future extractText(String pptxPath) async { + final tmpDir = await _makeTmpDir('pptx_text'); + + try { + // Unzip the PPTX + final unzipResult = await Process.run('unzip', [ + '-o', + '-q', + pptxPath, + '-d', + tmpDir.path, + ]); + + if (unzipResult.exitCode != 0) { + return ''; + } + + // Find all slide XML files + final slidesDir = Directory(p.join(tmpDir.path, 'ppt', 'slides')); + if (!await slidesDir.exists()) return ''; + + final slideFiles = await slidesDir + .list() + .where((f) => f.path.contains(RegExp(r'slide\d+\.xml$'))) + .toList(); + + // Sort by slide number + slideFiles.sort((a, b) { + final aNum = _extractSlideNumber(a.path); + final bNum = _extractSlideNumber(b.path); + return aNum.compareTo(bNum); + }); + + final buffer = StringBuffer(); + for (final slideFile in slideFiles) { + final xml = await File(slideFile.path).readAsString(); + final slideText = _extractTextFromXml(xml); + if (slideText.isNotEmpty) { + final num = _extractSlideNumber(slideFile.path); + buffer.writeln('--- Slide $num ---'); + buffer.writeln(slideText); + buffer.writeln(); + } + } + + return buffer.toString().trim(); + } catch (_) { + return ''; + } finally { + // Cleanup + try { + await tmpDir.delete(recursive: true); + } catch (_) {} + } + } + + /// Convert PPTX slides to a list of image file paths. + /// + /// Attempts LibreOffice headless conversion first. Falls back to + /// generating placeholder slide images (colored rectangles with slide numbers). + Future> convertToImages(String pptxPath) async { + // Try LibreOffice first + final loImages = await _convertViaLibreOffice(pptxPath); + if (loImages.isNotEmpty) return loImages; + + // Fallback: generate placeholder images + return _generatePlaceholderImages(pptxPath); + } + + /// Open a file picker dialog and return the selected PPTX path, or null. + /// + /// Uses the cross-platform file_picker package. + Future openPptxFile() async { + final result = await FilePicker.platform.pickFiles( + type: FileType.custom, + allowedExtensions: ['pptx', 'ppt'], + ); + final files = result?.files; + if (files == null || files.isEmpty) return null; + return files.first.path; + } + + // --------------------------------------------------------------------------- + // Implementation helpers + // --------------------------------------------------------------------------- + + /// Extract text from PPTX slide XML by finding `` content. + String _extractTextFromXml(String xml) { + final lines = []; + // Match ... — handles both text and text + final regex = RegExp(r']*>(.*?)', dotAll: true); + for (final match in regex.allMatches(xml)) { + final text = match.group(1) ?? ''; + if (text.trim().isNotEmpty) { + lines.add(text.trim()); + } + } + return lines.join('\n'); + } + + int _extractSlideNumber(String path) { + final match = RegExp(r'slide(\d+)\.xml$').firstMatch(path); + if (match != null) return int.parse(match.group(1)!); + return 0; + } + + /// Try converting via LibreOffice headless. + Future> _convertViaLibreOffice(String pptxPath) async { + try { + // Check if LibreOffice is available + final which = await Process.run('which', ['libreoffice']); + if (which.exitCode != 0) return []; + + final outDir = await _makeTmpDir('pptx_images'); + + final result = await Process.run('libreoffice', [ + '--headless', + '--convert-to', + 'png', + '--outdir', + outDir.path, + pptxPath, + ]); + + if (result.exitCode != 0) return []; + + // Collect generated PNGs, sorted by name + final pngs = await outDir + .list() + .where((f) => f.path.endsWith('.png')) + .map((f) => f.path) + .toList(); + + pngs.sort(); + + // Move to a persistent temp location so outDir can be cleaned up + final persistDir = await _makeTmpDir('pptx_slides'); + final persistentPaths = []; + for (var i = 0; i < pngs.length; i++) { + final src = File(pngs[i]); + final dst = p.join(persistDir.path, 'slide_${i + 1}.png'); + await src.copy(dst); + persistentPaths.add(dst); + } + + // Clean up the LibreOffice output dir + try { + await outDir.delete(recursive: true); + } catch (_) {} + + return persistentPaths; + } catch (_) { + return []; + } + } + + /// Generate placeholder slide images when LibreOffice is not available. + /// + /// Uses ImageMagick `convert` to create PNG files with slide numbers. + /// If ImageMagick is not available, writes minimal 1x1 white PNGs as + /// last-resort placeholders. + Future> _generatePlaceholderImages(String pptxPath) async { + // Count slides by unzipping and counting slide XML files + final slideCount = await _countSlides(pptxPath); + if (slideCount == 0) return []; + + final outDir = await _makeTmpDir('pptx_placeholders'); + final paths = []; + + // Try ImageMagick + final hasConvert = await _hasCommand('convert'); + + for (var i = 1; i <= slideCount; i++) { + final path = p.join(outDir.path, 'slide_$i.png'); + if (hasConvert) { + await _generateWithImageMagick(path, i, slideCount); + } else { + await _writeMinimalPng(path); + } + paths.add(path); + } + + return paths; + } + + Future _countSlides(String pptxPath) async { + final tmpDir = await _makeTmpDir('pptx_count'); + try { + await Process.run('unzip', ['-o', '-q', pptxPath, '-d', tmpDir.path]); + final slidesDir = Directory(p.join(tmpDir.path, 'ppt', 'slides')); + if (!await slidesDir.exists()) return 0; + final count = await slidesDir + .list() + .where((f) => f.path.contains(RegExp(r'slide\d+\.xml$'))) + .length; + return count; + } catch (_) { + return 0; + } finally { + try { + await tmpDir.delete(recursive: true); + } catch (_) {} + } + } + + Future _hasCommand(String cmd) async { + try { + final result = await Process.run('which', [cmd]); + return result.exitCode == 0; + } catch (_) { + return false; + } + } + + Future _generateWithImageMagick( + String outPath, + int slideNum, + int total, + ) async { + // Light pastel background with slide number + final hue = ((slideNum - 1) * 137) % 360; // golden-angle spacing + await Process.run('convert', [ + '-size', + '1920x1080', + 'xc:hsl($hue, 60%, 92%)', + '-gravity', + 'center', + '-pointsize', + '120', + '-fill', + 'hsl($hue, 30%, 40%)', + '-annotate', + '+0+0', + 'Slide $slideNum / $total', + outPath, + ]); + } + + /// Write a minimal valid 1x1 white PNG as an absolute last resort. + /// This is a hand-crafted PNG (IHDR + single white pixel IDAT + IEND). + Future _writeMinimalPng(String path) async { + // Minimal valid 1x1 white PNG + const pngBytes = [ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature + // IHDR chunk + 0x00, 0x00, 0x00, 0x0D, // length = 13 + 0x49, 0x48, 0x44, 0x52, // "IHDR" + 0x00, 0x00, 0x00, 0x01, // width = 1 + 0x00, 0x00, 0x00, 0x01, // height = 1 + 0x08, 0x02, // bit depth = 8, color type = 2 (RGB) + 0x00, 0x00, 0x00, // compression, filter, interlace + 0x90, 0x77, 0x53, 0xDE, // CRC + // IDAT chunk + 0x00, 0x00, 0x00, 0x0C, // length = 12 + 0x49, 0x44, 0x41, 0x54, // "IDAT" + 0x08, 0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, + 0x01, 0x01, 0x01, 0x00, // compressed data + 0x18, 0xDD, 0x8D, 0xB4, // CRC + // IEND chunk + 0x00, 0x00, 0x00, 0x00, // length = 0 + 0x49, 0x45, 0x4E, 0x44, // "IEND" + 0xAE, 0x42, 0x60, 0x82, // CRC + ]; + await File(path).writeAsBytes(pngBytes); + } + + Future _makeTmpDir(String prefix) async { + final base = await getTemporaryDirectory(); + final dir = Directory(p.join(base.path, '${prefix}_${_uuid.v4()}')); + await dir.create(recursive: true); + return dir; + } +} diff --git a/lib/services/stroke_rasterizer.dart b/lib/services/stroke_rasterizer.dart new file mode 100644 index 0000000..6d6d94f --- /dev/null +++ b/lib/services/stroke_rasterizer.dart @@ -0,0 +1,302 @@ +import 'dart:math'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:perfect_freehand/perfect_freehand.dart' as pf; + +import '../models/ink_point.dart'; +import '../models/ink_stroke.dart'; +import '../models/pen_tool.dart'; +import '../models/pressure_curve.dart'; + +/// Renders ink strokes to a PNG byte array for local OCR. +class StrokeRasterizer { + static const _padding = 24.0; + static const _defaultPressureCurve = PressureCurve.linear; + + /// Render [strokes] onto a white canvas and return PNG bytes, or null if empty. + static Future render(List strokes) async { + final drawable = strokes + .where((s) => s.tool != PenTool.eraser && s.points.isNotEmpty) + .toList(); + if (drawable.isEmpty) return null; + + final bounds = _computeBounds(drawable); + if (bounds == null) return null; + + final width = (bounds.width + _padding * 2).ceil().clamp(1, 4096); + final height = (bounds.height + _padding * 2).ceil().clamp(1, 4096); + final offset = Offset(_padding - bounds.left, _padding - bounds.top); + + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + canvas.drawRect( + Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()), + Paint()..color = Colors.white, + ); + + for (final stroke in drawable) { + _drawStroke(canvas, stroke, offset); + } + + final picture = recorder.endRecording(); + final image = await picture.toImage(width, height); + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + return byteData?.buffer.asUint8List(); + } + + static Rect? _computeBounds(List strokes) { + double? minX, minY, maxX, maxY; + for (final stroke in strokes) { + for (final p in stroke.points) { + minX = minX == null ? p.x : min(minX, p.x); + minY = minY == null ? p.y : min(minY, p.y); + maxX = maxX == null ? p.x : max(maxX, p.x); + maxY = maxY == null ? p.y : max(maxY, p.y); + } + } + if (minX == null || minY == null || maxX == null || maxY == null) { + return null; + } + return Rect.fromLTRB(minX, minY, maxX, maxY); + } + + static List _offsetPoints(List points, Offset offset) { + return points + .map( + (p) => InkPoint( + x: p.x + offset.dx, + y: p.y + offset.dy, + pressure: p.pressure, + timestamp: p.timestamp, + ), + ) + .toList(); + } + + static void _drawStroke(Canvas canvas, InkStroke stroke, Offset offset) { + final points = _offsetPoints(stroke.points, offset); + final color = Color(stroke.color); + final tool = stroke.tool; + + switch (tool) { + case PenTool.pen: + case PenTool.marker: + case PenTool.highlighter: + _drawFreehand(canvas, points, tool, color, stroke.strokeWidth); + break; + case PenTool.rectangle: + if (points.length >= 2) { + _drawRect(canvas, points, color, stroke.strokeWidth, stroke.filled); + } else { + _drawFreehand(canvas, points, tool, color, stroke.strokeWidth); + } + break; + case PenTool.ellipse: + if (points.length >= 2) { + _drawOval(canvas, points, color, stroke.strokeWidth, stroke.filled); + } else { + _drawFreehand(canvas, points, tool, color, stroke.strokeWidth); + } + break; + case PenTool.line: + if (points.length >= 2) { + _drawLine(canvas, points, color, stroke.strokeWidth); + } else { + _drawFreehand(canvas, points, tool, color, stroke.strokeWidth); + } + break; + case PenTool.arrow: + if (points.length >= 2) { + _drawArrow(canvas, points, color, stroke.strokeWidth); + } else { + _drawFreehand(canvas, points, tool, color, stroke.strokeWidth); + } + break; + case PenTool.text: + if (stroke.textContent != null && stroke.textContent!.isNotEmpty) { + _drawText( + canvas, + points, + stroke.textContent!, + stroke.fontSize, + color, + ); + } + break; + case PenTool.eraser: + break; + } + } + + static void _drawFreehand( + Canvas canvas, + List points, + PenTool tool, + Color color, + double strokeWidth, + ) { + final pfPoints = points + .map( + (p) => pf.Point( + p.x, + p.y, + _defaultPressureCurve.apply(p.pressure).clamp(0.0, 1.0), + ), + ) + .toList(); + + final thinning = (tool == PenTool.marker || tool == PenTool.highlighter) + ? 0.0 + : 0.7; + + final outline = pf.getStroke( + pfPoints, + size: strokeWidth, + thinning: thinning, + smoothing: 0.5, + streamline: 0.5, + simulatePressure: tool != PenTool.marker && tool != PenTool.highlighter, + isComplete: true, + ); + if (outline.isEmpty) return; + + final path = Path()..moveTo(outline[0].x, outline[0].y); + for (var i = 1; i < outline.length; i++) { + path.lineTo(outline[i].x, outline[i].y); + } + path.close(); + + canvas.drawPath( + path, + Paint() + ..color = color + ..style = PaintingStyle.fill + ..isAntiAlias = true, + ); + } + + static void _drawRect( + Canvas canvas, + List points, + Color color, + double strokeWidth, + bool filled, + ) { + final rect = Rect.fromPoints( + Offset(points[0].x, points[0].y), + Offset(points[1].x, points[1].y), + ); + canvas.drawRect( + rect, + Paint() + ..color = color + ..strokeWidth = strokeWidth + ..style = filled ? PaintingStyle.fill : PaintingStyle.stroke + ..isAntiAlias = true, + ); + } + + static void _drawOval( + Canvas canvas, + List points, + Color color, + double strokeWidth, + bool filled, + ) { + final rect = Rect.fromPoints( + Offset(points[0].x, points[0].y), + Offset(points[1].x, points[1].y), + ); + canvas.drawOval( + rect, + Paint() + ..color = color + ..strokeWidth = strokeWidth + ..style = filled ? PaintingStyle.fill : PaintingStyle.stroke + ..isAntiAlias = true, + ); + } + + static void _drawLine( + Canvas canvas, + List points, + Color color, + double strokeWidth, + ) { + canvas.drawLine( + Offset(points[0].x, points[0].y), + Offset(points[1].x, points[1].y), + Paint() + ..color = color + ..strokeWidth = strokeWidth + ..strokeCap = StrokeCap.round + ..isAntiAlias = true, + ); + } + + static void _drawArrow( + Canvas canvas, + List points, + Color color, + double strokeWidth, + ) { + final start = Offset(points[0].x, points[0].y); + final end = Offset(points[1].x, points[1].y); + canvas.drawLine( + start, + end, + Paint() + ..color = color + ..strokeWidth = strokeWidth + ..strokeCap = StrokeCap.round + ..isAntiAlias = true, + ); + + final angle = atan2(end.dy - start.dy, end.dx - start.dx); + const headLength = 12.0; + const headAngle = pi / 6; + final p1 = + end + + Offset( + -headLength * cos(angle - headAngle), + -headLength * sin(angle - headAngle), + ); + final p2 = + end + + Offset( + -headLength * cos(angle + headAngle), + -headLength * sin(angle + headAngle), + ); + final head = Path() + ..moveTo(end.dx, end.dy) + ..lineTo(p1.dx, p1.dy) + ..lineTo(p2.dx, p2.dy) + ..close(); + canvas.drawPath( + head, + Paint() + ..color = color + ..style = PaintingStyle.fill, + ); + } + + static void _drawText( + Canvas canvas, + List points, + String text, + double fontSize, + Color color, + ) { + if (points.isEmpty) return; + final painter = TextPainter( + text: TextSpan( + text: text, + style: TextStyle(color: color, fontSize: fontSize), + ), + textDirection: TextDirection.ltr, + )..layout(); + painter.paint(canvas, Offset(points[0].x, points[0].y)); + } +} diff --git a/lib/services/thumbnail_service.dart b/lib/services/thumbnail_service.dart new file mode 100644 index 0000000..5ef4f25 --- /dev/null +++ b/lib/services/thumbnail_service.dart @@ -0,0 +1,130 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:syncfusion_pdfviewer_platform_interface/pdfviewer_platform_interface.dart'; + +/// Service for generating, caching, and retrieving page thumbnails. +class ThumbnailService { + static Future _thumbnailFile(String documentId, int pageIndex) async { + final appDir = await getApplicationDocumentsDirectory(); + final dir = Directory('${appDir.path}/thumbnails/$documentId'); + if (!await dir.exists()) await dir.create(recursive: true); + return File('${dir.path}/$pageIndex.png'); + } + + static Future _rgbaToPng( + Uint8List rgba, + int width, + int height, + ) async { + final completer = Completer(); + ui.decodeImageFromPixels( + rgba, + width, + height, + ui.PixelFormat.bgra8888, + completer.complete, + rowBytes: width * 4, + ); + final image = await completer.future; + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + return byteData?.buffer.asUint8List(); + } + + /// Render a single PDF page to PNG bytes at [maxWidth] pixel width. + /// Returns null on failure. + static Future generate( + String filePath, + int pageIndex, { + int maxWidth = 160, + }) async { + // Stable, low-collision renderer handle key for this file. Plain + // `filePath.hashCode` can collide between different paths; combining it + // with the path length and basename (no extra deps beyond `path`) + // drastically reduces the chance two distinct files share a handle. + final documentId = + 'thumb-${filePath.hashCode}-${filePath.length}-${p.basename(filePath)}'; + try { + final bytes = await File(filePath).readAsBytes(); + final pageCountStr = await PdfViewerPlatform.instance + .initializePdfRenderer(bytes, documentId); + if (pageCountStr == null) return null; + + final pageCount = int.tryParse(pageCountStr); + if (pageCount == null || pageIndex < 0 || pageIndex >= pageCount) { + await PdfViewerPlatform.instance.closeDocument(documentId); + return null; + } + + final pagesHeight = await PdfViewerPlatform.instance.getPagesHeight( + documentId, + ); + final pagesWidth = await PdfViewerPlatform.instance.getPagesWidth( + documentId, + ); + if (pagesHeight == null || pagesWidth == null) { + await PdfViewerPlatform.instance.closeDocument(documentId); + return null; + } + + final pageHeight = pagesHeight[pageIndex] as double; + final pageWidth = pagesWidth[pageIndex] as double; + final thumbnailHeight = (maxWidth * pageHeight / pageWidth).round(); + + final rgba = await PdfViewerPlatform.instance.getPage( + pageIndex + 1, + maxWidth, + thumbnailHeight, + documentId, + ); + await PdfViewerPlatform.instance.closeDocument(documentId); + + if (rgba == null) return null; + return _rgbaToPng(rgba, maxWidth, thumbnailHeight); + } catch (_) { + try { + await PdfViewerPlatform.instance.closeDocument(documentId); + } catch (_) {} + return null; + } + } + + /// Persist thumbnail bytes to disk and return the file. + static Future cacheThumbnail( + String documentId, + int pageIndex, + Uint8List data, + ) async { + final file = await _thumbnailFile(documentId, pageIndex); + await file.writeAsBytes(data); + return file; + } + + /// Whether a cached thumbnail exists on disk. + static Future hasCached(String documentId, int pageIndex) async { + return (await _thumbnailFile(documentId, pageIndex)).exists(); + } + + /// Return the cached file if it exists, otherwise null. + static Future getCached(String documentId, int pageIndex) async { + final file = await _thumbnailFile(documentId, pageIndex); + return (await file.exists()) ? file : null; + } + + /// Delete all cached thumbnails for [documentId]. + static Future invalidateAll(String documentId) async { + final appDir = await getApplicationDocumentsDirectory(); + final dir = Directory('${appDir.path}/thumbnails/$documentId'); + if (await dir.exists()) await dir.delete(recursive: true); + } + + /// Invalidate a single page thumbnail. + static Future invalidatePage(String documentId, int pageIndex) async { + final file = await _thumbnailFile(documentId, pageIndex); + if (await file.exists()) await file.delete(); + } +} diff --git a/lib/services/undo_manager.dart b/lib/services/undo_manager.dart new file mode 100644 index 0000000..e7e4c87 --- /dev/null +++ b/lib/services/undo_manager.dart @@ -0,0 +1,102 @@ +import '../models/ink_stroke.dart'; + +/// Manages undo/redo state for ink strokes. +/// +/// Each action records a stroke that was added or removed. +/// [undo] returns the inverse of the last action (remove if add, add if remove). +/// [redo] re-applies the undone action. +class UndoManager { + final List<_UndoAction> _undoStack = []; + final List<_UndoAction> _redoStack = []; + final List _strokes = []; + + /// The current list of strokes (read-only view). + List get currentStrokes => List.unmodifiable(_strokes); + + bool get canUndo => _undoStack.isNotEmpty; + bool get canRedo => _redoStack.isNotEmpty; + + /// Records that a new stroke was added to the canvas. + void addStroke(InkStroke stroke) { + _strokes.add(stroke); + _undoStack.add(_UndoAction(type: _ActionType.add, stroke: stroke)); + _redoStack.clear(); + } + + /// Records that a stroke was removed from the canvas. + /// Also handles partial-eraser replacements: removes [stroke] and adds + /// [replacements] (which may be empty if fully erased, or 1-2 sub-strokes). + void removeStroke( + InkStroke stroke, { + List replacements = const [], + }) { + _strokes.removeWhere((s) => s.id == stroke.id); + _strokes.addAll(replacements); + _undoStack.add( + _UndoAction( + type: _ActionType.remove, + stroke: stroke, + replacements: replacements, + ), + ); + _redoStack.clear(); + } + + /// Undoes the last action. Returns the stroke that was affected and needs + /// to be reversed on the canvas, or `null` if nothing to undo. + /// + /// For add actions: the stroke should be removed from the canvas. + /// For remove actions: the stroke (and its replacements) should be restored. + InkStroke? undo() { + if (_undoStack.isEmpty) return null; + + final action = _undoStack.removeLast(); + _redoStack.add(action); + + switch (action.type) { + case _ActionType.add: + _strokes.removeWhere((s) => s.id == action.stroke.id); + return action.stroke; + case _ActionType.remove: + // Remove the replacements that were added during the original remove + for (final r in action.replacements) { + _strokes.removeWhere((s) => s.id == r.id); + } + _strokes.add(action.stroke); + return action.stroke; + } + } + + /// Redoes the last undone action. Returns the stroke that was affected, or + /// `null` if nothing to redo. + InkStroke? redo() { + if (_redoStack.isEmpty) return null; + + final action = _redoStack.removeLast(); + _undoStack.add(action); + + switch (action.type) { + case _ActionType.add: + _strokes.add(action.stroke); + return action.stroke; + case _ActionType.remove: + _strokes.removeWhere((s) => s.id == action.stroke.id); + _strokes.addAll(action.replacements); + return action.stroke; + } + } +} + +enum _ActionType { add, remove } + +class _UndoAction { + final _ActionType type; + final InkStroke stroke; + final List replacements; + + _UndoAction({ + required this.type, + required this.stroke, + this.replacements = const [], + }); +} diff --git a/lib/utils/stroke_stabilizer.dart b/lib/utils/stroke_stabilizer.dart new file mode 100644 index 0000000..461a310 --- /dev/null +++ b/lib/utils/stroke_stabilizer.dart @@ -0,0 +1,70 @@ +import '../models/ink_point.dart'; + +/// Stabilization level for hand-drawn strokes. +enum StabilizationLevel { none, light, medium, heavy } + +/// Smooths pen input using an Exponential Moving Average (EMA) filter. +/// +/// - **none**: no smoothing (passthrough) +/// - **light**: alpha = 0.6 (subtle smoothing) +/// - **medium**: alpha = 0.4 (moderate smoothing) +/// - **heavy**: alpha = 0.25 (strong smoothing, removes most tremor) +/// +/// The formula applied to each coordinate independently: +/// x_smoothed = alpha * x_raw + (1 - alpha) * x_prev +class StrokeStabilizer { + final StabilizationLevel level; + + double? _prevX; + double? _prevY; + + StrokeStabilizer({this.level = StabilizationLevel.none}); + + double get _alpha { + switch (level) { + case StabilizationLevel.none: + return 1.0; + case StabilizationLevel.light: + return 0.6; + case StabilizationLevel.medium: + return 0.4; + case StabilizationLevel.heavy: + return 0.25; + } + } + + /// Filters a raw point through the EMA, returning a smoothed point. + /// Returns the raw point unchanged if level is [StabilizationLevel.none]. + InkPoint filter(InkPoint rawPoint) { + if (level == StabilizationLevel.none) return rawPoint; + + final alpha = _alpha; + + if (_prevX == null || _prevY == null) { + _prevX = rawPoint.x; + _prevY = rawPoint.y; + return rawPoint; + } + + final smoothedX = alpha * rawPoint.x + (1 - alpha) * _prevX!; + final smoothedY = alpha * rawPoint.y + (1 - alpha) * _prevY!; + + _prevX = smoothedX; + _prevY = smoothedY; + + return InkPoint( + x: smoothedX, + y: smoothedY, + pressure: rawPoint.pressure, + tilt: rawPoint.tilt, + timestamp: rawPoint.timestamp, + pointerDeviceKind: rawPoint.pointerDeviceKind, + ); + } + + /// Resets the filter state. Call when starting a new stroke. + void reset() { + _prevX = null; + _prevY = null; + } +} diff --git a/lib/widgets/annotation_toolbar.dart b/lib/widgets/annotation_toolbar.dart new file mode 100644 index 0000000..9cd0fad --- /dev/null +++ b/lib/widgets/annotation_toolbar.dart @@ -0,0 +1,433 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_colorpicker/flutter_colorpicker.dart'; + +import '../models/pen_tool.dart'; +import '../models/pressure_curve.dart'; +import '../utils/stroke_stabilizer.dart'; +import '../widgets/ink_canvas.dart'; +import 'color_preset_bar.dart'; + +/// Shared annotation toolbar used by note editor, PDF annotator, and PPT annotator. +class AnnotationToolbar extends StatelessWidget { + final PenTool currentTool; + final Color currentColor; + final double currentStrokeWidth; + final bool filled; + final PressureCurveType pressureCurveType; + final StabilizationLevel stabilizationLevel; + final bool canUndo; + final bool canRedo; + final ValueChanged onToolChanged; + final ValueChanged onColorChanged; + final ValueChanged onStrokeWidthChanged; + final ValueChanged onFilledChanged; + final ValueChanged onPressureCurveChanged; + final ValueChanged onStabilizationChanged; + final VoidCallback? onUndo; + final VoidCallback? onRedo; + final VoidCallback? onPreviousPage; + final VoidCallback? onNextPage; + final String? pageInfo; + final InteractionMode interactionMode; + final ValueChanged? onInteractionModeChanged; + final double? zoomLevel; + final VoidCallback? onZoomIn; + final VoidCallback? onZoomOut; + final VoidCallback? onZoomFitWidth; + final String? zoomLabel; + + const AnnotationToolbar({ + super.key, + required this.currentTool, + required this.currentColor, + required this.currentStrokeWidth, + this.filled = false, + required this.pressureCurveType, + required this.stabilizationLevel, + required this.canUndo, + required this.canRedo, + required this.onToolChanged, + required this.onColorChanged, + required this.onStrokeWidthChanged, + required this.onFilledChanged, + required this.onPressureCurveChanged, + required this.onStabilizationChanged, + this.onUndo, + this.onRedo, + this.onPreviousPage, + this.onNextPage, + this.pageInfo, + this.interactionMode = InteractionMode.draw, + this.onInteractionModeChanged, + this.zoomLevel, + this.onZoomIn, + this.onZoomOut, + this.onZoomFitWidth, + this.zoomLabel, + }); + + static const _toolDefinitions = [ + _ToolDef(PenTool.pen, Icons.edit, 'Pen'), + _ToolDef(PenTool.marker, Icons.highlight, 'Marker'), + _ToolDef(PenTool.highlighter, Icons.border_color, 'Highlighter'), + _ToolDef(PenTool.eraser, Icons.auto_fix_normal, 'Eraser'), + _ToolDef(PenTool.rectangle, Icons.rectangle_outlined, 'Rectangle'), + _ToolDef(PenTool.ellipse, Icons.circle_outlined, 'Ellipse'), + _ToolDef(PenTool.line, Icons.horizontal_rule, 'Line'), + _ToolDef(PenTool.arrow, Icons.arrow_right_alt, 'Arrow'), + _ToolDef(PenTool.text, Icons.text_fields, 'Text'), + ]; + + bool get _isShapeTool { + return currentTool == PenTool.rectangle || currentTool == PenTool.ellipse; + } + + void _showColorPicker(BuildContext context) { + showDialog( + context: context, + builder: (context) { + Color pickerColor = currentColor; + return AlertDialog( + title: const Text('Pick a color'), + content: SingleChildScrollView( + child: ColorPicker( + pickerColor: pickerColor, + onColorChanged: (color) => pickerColor = color, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + onColorChanged(pickerColor); + Navigator.of(context).pop(); + }, + child: const Text('OK'), + ), + ], + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.1), + blurRadius: 4, + offset: const Offset(0, 2), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Row 1: Mode toggle + Tools + color presets + stroke width + undo/redo + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + // Pen/Navigate mode toggle + if (onInteractionModeChanged != null) ...[ + Tooltip( + message: interactionMode == InteractionMode.draw + ? 'Drawing mode' + : 'Navigate mode', + child: GestureDetector( + onTap: () { + final newMode = interactionMode == InteractionMode.draw + ? InteractionMode.navigate + : InteractionMode.draw; + onInteractionModeChanged!(newMode); + }, + child: Container( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: interactionMode == InteractionMode.draw + ? Theme.of(context).colorScheme.primaryContainer + : Theme.of(context).colorScheme.tertiaryContainer, + borderRadius: BorderRadius.circular(8), + ), + child: Icon( + interactionMode == InteractionMode.draw + ? Icons.edit + : Icons.pan_tool, + size: 20, + color: interactionMode == InteractionMode.draw + ? Theme.of(context).colorScheme.onPrimaryContainer + : Theme.of( + context, + ).colorScheme.onTertiaryContainer, + ), + ), + ), + ), + const SizedBox(width: 6), + ], + for (final def in _toolDefinitions) ...[ + _ToolButton( + icon: def.icon, + label: def.label, + isSelected: currentTool == def.tool, + onPressed: () => onToolChanged(def.tool), + ), + const SizedBox(width: 4), + ], + // Filled toggle for shape tools + if (_isShapeTool) ...[ + const SizedBox(width: 4), + Tooltip( + message: filled ? 'Filled' : 'Outline', + child: GestureDetector( + onTap: () => onFilledChanged(!filled), + child: Container( + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: filled + ? Theme.of(context).colorScheme.primaryContainer + : Colors.transparent, + borderRadius: BorderRadius.circular(4), + border: Border.all( + color: filled + ? Theme.of(context).colorScheme.primary + : Colors.grey.shade400, + ), + ), + child: Icon( + filled ? Icons.square : Icons.square_outlined, + size: 16, + color: filled + ? Theme.of(context).colorScheme.onPrimaryContainer + : Colors.grey.shade600, + ), + ), + ), + ), + ], + const SizedBox(width: 8), + ColorPresetBar( + selectedColor: currentColor, + onColorSelected: onColorChanged, + onOpenFullPicker: () => _showColorPicker(context), + ), + const SizedBox(width: 8), + SizedBox( + width: 120, + child: Slider( + value: currentStrokeWidth, + min: 1.0, + max: 20.0, + divisions: 19, + label: currentStrokeWidth.toStringAsFixed(1), + onChanged: onStrokeWidthChanged, + ), + ), + IconButton( + icon: const Icon(Icons.undo), + tooltip: 'Undo', + iconSize: 20, + padding: const EdgeInsets.all(4), + onPressed: canUndo ? onUndo : null, + ), + IconButton( + icon: const Icon(Icons.redo), + tooltip: 'Redo', + iconSize: 20, + padding: const EdgeInsets.all(4), + onPressed: canRedo ? onRedo : null, + ), + // Page navigation (optional, for PDF/PPT) + if (onPreviousPage != null) ...[ + IconButton( + icon: const Icon(Icons.navigate_before), + tooltip: 'Previous page', + iconSize: 20, + padding: const EdgeInsets.all(4), + onPressed: onPreviousPage, + ), + if (pageInfo != null) + Text(pageInfo!, style: const TextStyle(fontSize: 12)), + IconButton( + icon: const Icon(Icons.navigate_next), + tooltip: 'Next page', + iconSize: 20, + padding: const EdgeInsets.all(4), + onPressed: onNextPage, + ), + ], + // Zoom controls (optional) + if (onZoomIn != null) ...[ + const SizedBox(width: 4), + IconButton( + icon: const Icon(Icons.zoom_out), + tooltip: 'Zoom out', + iconSize: 20, + padding: const EdgeInsets.all(4), + onPressed: onZoomOut, + ), + if (zoomLabel != null) + Text(zoomLabel!, style: const TextStyle(fontSize: 11)), + IconButton( + icon: const Icon(Icons.zoom_in), + tooltip: 'Zoom in', + iconSize: 20, + padding: const EdgeInsets.all(4), + onPressed: onZoomIn, + ), + if (onZoomFitWidth != null) + IconButton( + icon: const Icon(Icons.fit_screen), + tooltip: 'Fit to width', + iconSize: 20, + padding: const EdgeInsets.all(4), + onPressed: onZoomFitWidth, + ), + ], + ], + ), + ), + // Row 2: Pressure curve + stabilization selectors + Row( + children: [ + const Icon(Icons.touch_app, size: 14, color: Colors.grey), + const SizedBox(width: 4), + const Text( + 'Pressure:', + style: TextStyle(fontSize: 11, color: Colors.grey), + ), + const SizedBox(width: 4), + _buildSegmentedButton( + context: context, + options: const { + PressureCurveType.linear: 'Lin', + PressureCurveType.soft: 'Soft', + PressureCurveType.hard: 'Hard', + }, + selected: pressureCurveType, + onChanged: onPressureCurveChanged, + ), + const SizedBox(width: 16), + const Icon(Icons.gesture, size: 14, color: Colors.grey), + const SizedBox(width: 4), + const Text( + 'Smooth:', + style: TextStyle(fontSize: 11, color: Colors.grey), + ), + const SizedBox(width: 4), + _buildSegmentedButton( + context: context, + options: const { + StabilizationLevel.none: 'Off', + StabilizationLevel.light: 'Low', + StabilizationLevel.medium: 'Med', + StabilizationLevel.heavy: 'High', + }, + selected: stabilizationLevel, + onChanged: onStabilizationChanged, + ), + ], + ), + ], + ), + ); + } + + Widget _buildSegmentedButton({ + required BuildContext context, + required Map options, + required T selected, + required ValueChanged onChanged, + }) { + return Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(6), + border: Border.all(color: Theme.of(context).colorScheme.outline), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: options.entries.map((entry) { + final isSelected = entry.key == selected; + return GestureDetector( + onTap: () => onChanged(entry.key), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: isSelected + ? Theme.of(context).colorScheme.primaryContainer + : Colors.transparent, + borderRadius: BorderRadius.circular(5), + ), + child: Text( + entry.value, + style: TextStyle( + fontSize: 11, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, + color: isSelected + ? Theme.of(context).colorScheme.onPrimaryContainer + : Theme.of(context).colorScheme.onSurface, + ), + ), + ), + ); + }).toList(), + ), + ); + } +} + +class _ToolDef { + final PenTool tool; + final IconData icon; + final String label; + + const _ToolDef(this.tool, this.icon, this.label); +} + +class _ToolButton extends StatelessWidget { + final IconData icon; + final String label; + final bool isSelected; + final VoidCallback onPressed; + + const _ToolButton({ + required this.icon, + required this.label, + required this.isSelected, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + return Tooltip( + message: label, + child: Material( + color: isSelected + ? Theme.of(context).colorScheme.primaryContainer + : Colors.transparent, + borderRadius: BorderRadius.circular(8), + child: InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.all(6), + child: Icon( + icon, + size: 20, + color: isSelected + ? Theme.of(context).colorScheme.onPrimaryContainer + : Theme.of(context).colorScheme.onSurface, + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/color_preset_bar.dart b/lib/widgets/color_preset_bar.dart new file mode 100644 index 0000000..3133c2b --- /dev/null +++ b/lib/widgets/color_preset_bar.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; + +/// A row of preset color circles with a palette icon to open the full picker. +class ColorPresetBar extends StatelessWidget { + final Color selectedColor; + final ValueChanged onColorSelected; + final VoidCallback onOpenFullPicker; + + const ColorPresetBar({ + super.key, + required this.selectedColor, + required this.onColorSelected, + required this.onOpenFullPicker, + }); + + static const List presetColors = [ + Colors.black, + Color(0xFFE53935), // red + Color(0xFF1E88E5), // blue + Color(0xFF43A047), // green + Color(0xFFFB8C00), // orange + Color(0xFF8E24AA), // purple + Color(0xFF6D4C41), // brown + Colors.white, + ]; + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (final color in presetColors) ...[ + MouseRegion( + cursor: SystemMouseCursors.click, + child: InkWell( + onTap: () => onColorSelected(color), + borderRadius: BorderRadius.circular(11), + child: Container( + width: 22, + height: 22, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: selectedColor == color + ? Theme.of(context).colorScheme.primary + : Colors.grey.shade400, + width: selectedColor == color ? 2.5 : 1.5, + ), + ), + ), + ), + ), + const SizedBox(width: 4), + ], + MouseRegion( + cursor: SystemMouseCursors.click, + child: InkWell( + onTap: onOpenFullPicker, + borderRadius: BorderRadius.circular(11), + child: Container( + width: 22, + height: 22, + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: Colors.grey.shade400, width: 1.5), + ), + child: const Icon(Icons.palette, size: 14, color: Colors.grey), + ), + ), + ), + ], + ); + } +} diff --git a/lib/widgets/ink_canvas.dart b/lib/widgets/ink_canvas.dart new file mode 100644 index 0000000..caa2e8a --- /dev/null +++ b/lib/widgets/ink_canvas.dart @@ -0,0 +1,709 @@ +import 'dart:math'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:perfect_freehand/perfect_freehand.dart' as pf; +import 'package:uuid/uuid.dart'; + +import '../models/ink_point.dart'; +import '../models/ink_stroke.dart'; +import '../models/pen_tool.dart'; +import '../models/pointer_device_kind.dart'; +import '../models/pressure_curve.dart'; +import '../utils/stroke_stabilizer.dart'; + +/// Controls whether the canvas accepts drawing input or passes events through. +enum InteractionMode { draw, navigate } + +class InkCanvas extends StatefulWidget { + final List strokes; + final void Function(InkStroke stroke)? onStrokeComplete; + final void Function(String strokeId, List replacements)? onErase; + final PenTool tool; + final Color color; + final double strokeWidth; + final PressureCurve pressureCurve; + final StabilizationLevel stabilizationLevel; + final bool filled; + final InteractionMode interactionMode; + final Rect? viewportBounds; + + const InkCanvas({ + super.key, + required this.strokes, + this.onStrokeComplete, + this.onErase, + this.tool = PenTool.pen, + this.color = Colors.black, + this.strokeWidth = 2.0, + this.pressureCurve = PressureCurve.linear, + this.stabilizationLevel = StabilizationLevel.none, + this.filled = false, + this.interactionMode = InteractionMode.draw, + this.viewportBounds, + }); + + @override + State createState() => _InkCanvasState(); +} + +class _InkCanvasState extends State { + final List _currentPoints = []; + bool _isDrawing = false; + PenTool? _activeTool; + StrokeStabilizer? _stabilizer; + + /// Start point for shape tools. + InkPoint? _shapeStart; + + /// Whether the active tool is a shape tool (needs only 2 points). + bool get _isShapeTool { + final t = _activeTool ?? widget.tool; + return t == PenTool.rectangle || + t == PenTool.ellipse || + t == PenTool.line || + t == PenTool.arrow; + } + + /// Whether the active tool is the text tool. + bool get _isTextTool { + return (_activeTool ?? widget.tool) == PenTool.text; + } + + @override + void initState() { + super.initState(); + _stabilizer = StrokeStabilizer(level: widget.stabilizationLevel); + } + + @override + void didUpdateWidget(InkCanvas oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.stabilizationLevel != widget.stabilizationLevel) { + _stabilizer = StrokeStabilizer(level: widget.stabilizationLevel); + } + } + + InputDeviceKind _mapKind(PointerDeviceKind kind) { + switch (kind) { + case PointerDeviceKind.touch: + return InputDeviceKind.touch; + case PointerDeviceKind.mouse: + return InputDeviceKind.mouse; + case PointerDeviceKind.stylus: + return InputDeviceKind.stylus; + case PointerDeviceKind.invertedStylus: + return InputDeviceKind.invertedStylus; + case PointerDeviceKind.trackpad: + return InputDeviceKind.trackpad; + case PointerDeviceKind.unknown: + return InputDeviceKind.unknown; + } + } + + InkPoint _makePoint(PointerEvent event) { + return InkPoint( + x: event.localPosition.dx, + y: event.localPosition.dy, + pressure: event.pressure, + tilt: event is PointerMoveEvent ? event.tilt : 0.0, + timestamp: event.timeStamp.inMicroseconds, + pointerDeviceKind: _mapKind(event.kind), + ); + } + + void _handlePointerDown(PointerDownEvent event) { + if (event.kind == PointerDeviceKind.trackpad) return; + + // In navigate mode, no drawing at all — pass all events through. + if (widget.interactionMode == InteractionMode.navigate) return; + + // In draw mode: stylus and mouse draw, touch passes through for scrolling. + if (event.kind == PointerDeviceKind.touch) return; + + _isDrawing = true; + _activeTool = widget.tool; + + if (event.kind == PointerDeviceKind.invertedStylus) { + _activeTool = PenTool.eraser; + } + + final point = _makePoint(event); + + if (_activeTool == PenTool.eraser) { + _eraseAt(point); + } else if (_isTextTool) { + // Text tool: record position, handled on pointer up + _shapeStart = point; + } else if (_isShapeTool) { + // Shape tool: record start point + _shapeStart = point; + _stabilizer?.reset(); + setState(() { + _currentPoints.clear(); + _currentPoints.add(point); + }); + } else { + // Freehand tools (pen, marker, highlighter) + _stabilizer?.reset(); + final smoothed = _stabilizer?.filter(point) ?? point; + setState(() { + _currentPoints.clear(); + _currentPoints.add(smoothed); + }); + } + } + + void _handlePointerMove(PointerMoveEvent event) { + if (!_isDrawing) return; + + final point = _makePoint(event); + + if (_activeTool == PenTool.eraser) { + _eraseAt(point); + } else if (_isTextTool) { + // No preview for text tool + return; + } else if (_isShapeTool) { + // Shape preview: keep only start + current + setState(() { + if (_currentPoints.length >= 2) { + _currentPoints[1] = point; + } else { + _currentPoints.add(point); + } + }); + } else { + // Freehand + final smoothed = _stabilizer?.filter(point) ?? point; + setState(() { + _currentPoints.add(smoothed); + }); + } + } + + void _handlePointerUp(PointerUpEvent event) { + if (!_isDrawing) return; + _isDrawing = false; + + final activeTool = _activeTool ?? widget.tool; + + if (activeTool == PenTool.eraser) { + // Nothing to finalize + } else if (_isTextTool) { + if (_shapeStart != null) { + _showTextDialog(_shapeStart!); + } + } else if (_isShapeTool) { + // Shape: finalize with start + end points + if (_currentPoints.length >= 2) { + final stroke = InkStroke( + id: _generateId(), + points: List.from(_currentPoints), + tool: activeTool, + color: _getColorForTool(activeTool).toARGB32(), + strokeWidth: widget.strokeWidth, + createdAt: DateTime.now(), + filled: widget.filled, + ); + widget.onStrokeComplete?.call(stroke); + } + } else if (_currentPoints.isNotEmpty) { + // Freehand + final stroke = InkStroke( + id: _generateId(), + points: List.from(_currentPoints), + tool: activeTool, + color: _getColorForTool(activeTool).toARGB32(), + strokeWidth: activeTool == PenTool.highlighter + ? widget.strokeWidth * 3 + : widget.strokeWidth, + createdAt: DateTime.now(), + ); + widget.onStrokeComplete?.call(stroke); + } + + setState(() { + _currentPoints.clear(); + _shapeStart = null; + }); + } + + void _showTextDialog(InkPoint position) { + final controller = TextEditingController(); + showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: const Text('Add Text'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(hintText: 'Enter text...'), + maxLines: null, + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + final text = controller.text.trim(); + if (text.isNotEmpty) { + final stroke = InkStroke( + id: _generateId(), + points: [position], + tool: PenTool.text, + color: widget.color.toARGB32(), + strokeWidth: widget.strokeWidth, + createdAt: DateTime.now(), + textContent: text, + fontSize: widget.strokeWidth * 7, + ); + widget.onStrokeComplete?.call(stroke); + } + Navigator.of(context).pop(); + }, + child: const Text('OK'), + ), + ], + ); + }, + ); + } + + void _eraseAt(InkPoint point) { + final eraserRadius = widget.strokeWidth * 3; + + // Collect all (strokeId, replacements) pairs before invoking any callback, + // to avoid ConcurrentModificationError when the parent's onErase triggers + // a setState that mutates widget.strokes mid-iteration. + final toErase = <(String, List)>[]; + + for (final stroke in widget.strokes) { + if (stroke.tool == PenTool.eraser) continue; + + final erasedIndices = {}; + for (int i = 0; i < stroke.points.length; i++) { + final p = stroke.points[i]; + final dx = p.x - point.x; + final dy = p.y - point.y; + if (dx * dx + dy * dy < eraserRadius * eraserRadius) { + erasedIndices.add(i); + } + } + + if (erasedIndices.isEmpty) continue; + + toErase.add((stroke.id, _splitStroke(stroke, erasedIndices))); + } + + for (final (strokeId, replacements) in toErase) { + widget.onErase?.call(strokeId, replacements); + } + } + + List _splitStroke(InkStroke stroke, Set erasedIndices) { + final segments = >[]; + List currentSegment = []; + + for (int i = 0; i < stroke.points.length; i++) { + if (erasedIndices.contains(i)) { + if (currentSegment.isNotEmpty) { + segments.add(currentSegment); + currentSegment = []; + } + } else { + currentSegment.add(stroke.points[i]); + } + } + + if (currentSegment.isNotEmpty) { + segments.add(currentSegment); + } + + final replacements = []; + for (final segment in segments) { + if (segment.length >= 2) { + replacements.add( + InkStroke( + id: _generateId(), + points: segment, + tool: stroke.tool, + color: stroke.color, + strokeWidth: stroke.strokeWidth, + createdAt: stroke.createdAt, + filled: stroke.filled, + textContent: stroke.textContent, + fontSize: stroke.fontSize, + ), + ); + } + } + + return replacements; + } + + Color _getColorForTool(PenTool tool) { + switch (tool) { + case PenTool.marker: + return widget.color.withAlpha(77); + case PenTool.highlighter: + return const Color(0x80FFFF00); + case PenTool.pen: + case PenTool.eraser: + case PenTool.rectangle: + case PenTool.ellipse: + case PenTool.line: + case PenTool.arrow: + case PenTool.text: + return widget.color; + } + } + + String _generateId() { + return const Uuid().v4(); + } + + @override + Widget build(BuildContext context) { + return Listener( + onPointerDown: _handlePointerDown, + onPointerMove: _handlePointerMove, + onPointerUp: _handlePointerUp, + child: CustomPaint( + painter: _InkPainter( + strokes: widget.strokes, + currentPoints: _currentPoints, + currentTool: _activeTool ?? widget.tool, + currentColor: _getColorForTool(_activeTool ?? widget.tool), + currentStrokeWidth: + (_activeTool ?? widget.tool) == PenTool.highlighter + ? widget.strokeWidth * 3 + : widget.strokeWidth, + pressureCurve: widget.pressureCurve, + filled: widget.filled, + viewportBounds: widget.viewportBounds, + ), + size: Size.infinite, + ), + ); + } +} + +class _InkPainter extends CustomPainter { + final List strokes; + final List currentPoints; + final PenTool currentTool; + final Color currentColor; + final double currentStrokeWidth; + final PressureCurve pressureCurve; + final bool filled; + final Rect? viewportBounds; + + _InkPainter({ + required this.strokes, + required this.currentPoints, + required this.currentTool, + required this.currentColor, + required this.currentStrokeWidth, + required this.pressureCurve, + required this.filled, + this.viewportBounds, + }); + + bool _strokeInViewport(InkStroke stroke, Rect viewport) { + if (stroke.points.isEmpty) return false; + double minX = double.infinity, minY = double.infinity; + double maxX = double.negativeInfinity, maxY = double.negativeInfinity; + for (final p in stroke.points) { + if (p.x < minX) minX = p.x; + if (p.y < minY) minY = p.y; + if (p.x > maxX) maxX = p.x; + if (p.y > maxY) maxY = p.y; + } + return viewport.overlaps(Rect.fromLTRB(minX, minY, maxX, maxY)); + } + + @override + void paint(Canvas canvas, Size size) { + for (final stroke in strokes) { + if (stroke.tool == PenTool.eraser) continue; + if (viewportBounds != null && + !_strokeInViewport(stroke, viewportBounds!)) { + continue; + } + _drawStroke( + canvas, + stroke.points, + stroke.tool, + Color(stroke.color), + stroke.strokeWidth, + true, + stroke.filled, + stroke.textContent, + stroke.fontSize, + ); + } + + if (currentPoints.isNotEmpty && currentTool != PenTool.eraser) { + _drawStroke( + canvas, + currentPoints, + currentTool, + currentColor, + currentStrokeWidth, + false, + filled, + null, + 14.0, + ); + } + } + + void _drawStroke( + Canvas canvas, + List points, + PenTool tool, + Color color, + double strokeWidth, + bool isComplete, + bool strokeFilled, + String? textContent, + double fontSize, + ) { + if (points.isEmpty) return; + + switch (tool) { + case PenTool.pen: + case PenTool.marker: + case PenTool.highlighter: + case PenTool.eraser: + _drawFreehand(canvas, points, tool, color, strokeWidth, isComplete); + break; + case PenTool.rectangle: + if (points.length < 2) { + _drawFreehand(canvas, points, tool, color, strokeWidth, isComplete); + } else { + _drawRect(canvas, points, color, strokeWidth, strokeFilled); + } + break; + case PenTool.ellipse: + if (points.length < 2) { + _drawFreehand(canvas, points, tool, color, strokeWidth, isComplete); + } else { + _drawOval(canvas, points, color, strokeWidth, strokeFilled); + } + break; + case PenTool.line: + if (points.length < 2) { + _drawFreehand(canvas, points, tool, color, strokeWidth, isComplete); + } else { + _drawLine(canvas, points, color, strokeWidth); + } + break; + case PenTool.arrow: + if (points.length < 2) { + _drawFreehand(canvas, points, tool, color, strokeWidth, isComplete); + } else { + _drawArrow(canvas, points, color, strokeWidth); + } + break; + case PenTool.text: + if (textContent != null && textContent.isNotEmpty) { + _drawText(canvas, points, textContent, fontSize, color); + } + break; + } + } + + void _drawFreehand( + Canvas canvas, + List points, + PenTool tool, + Color color, + double strokeWidth, + bool isComplete, + ) { + final pfPoints = points + .map( + (p) => pf.Point( + p.x, + p.y, + pressureCurve.apply(p.pressure).clamp(0.0, 1.0), + ), + ) + .toList(); + + final thinning = (tool == PenTool.marker || tool == PenTool.highlighter) + ? 0.0 + : 0.7; + + final outlinePoints = pf.getStroke( + pfPoints, + size: strokeWidth, + thinning: thinning, + smoothing: 0.5, + streamline: 0.5, + taperStart: 0.0, + taperEnd: 0.0, + capStart: true, + capEnd: true, + simulatePressure: tool != PenTool.marker && tool != PenTool.highlighter, + isComplete: isComplete, + ); + + if (outlinePoints.isEmpty) return; + + final path = Path(); + path.moveTo(outlinePoints[0].x, outlinePoints[0].y); + + for (int i = 1; i < outlinePoints.length; i++) { + path.lineTo(outlinePoints[i].x, outlinePoints[i].y); + } + path.close(); + + final paint = Paint() + ..color = color + ..style = PaintingStyle.fill + ..isAntiAlias = true; + + canvas.drawPath(path, paint); + } + + void _drawRect( + Canvas canvas, + List points, + Color color, + double strokeWidth, + bool strokeFilled, + ) { + final rect = Rect.fromPoints( + Offset(points[0].x, points[0].y), + Offset(points[1].x, points[1].y), + ); + + final paint = Paint() + ..color = color + ..strokeWidth = strokeWidth + ..isAntiAlias = true + ..style = strokeFilled ? PaintingStyle.fill : PaintingStyle.stroke; + + canvas.drawRect(rect, paint); + } + + void _drawOval( + Canvas canvas, + List points, + Color color, + double strokeWidth, + bool strokeFilled, + ) { + final rect = Rect.fromPoints( + Offset(points[0].x, points[0].y), + Offset(points[1].x, points[1].y), + ); + + final paint = Paint() + ..color = color + ..strokeWidth = strokeWidth + ..isAntiAlias = true + ..style = strokeFilled ? PaintingStyle.fill : PaintingStyle.stroke; + + canvas.drawOval(rect, paint); + } + + void _drawLine( + Canvas canvas, + List points, + Color color, + double strokeWidth, + ) { + final paint = Paint() + ..color = color + ..strokeWidth = strokeWidth + ..isAntiAlias = true + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; + + canvas.drawLine( + Offset(points[0].x, points[0].y), + Offset(points[1].x, points[1].y), + paint, + ); + } + + void _drawArrow( + Canvas canvas, + List points, + Color color, + double strokeWidth, + ) { + final p1 = Offset(points[0].x, points[0].y); + final p2 = Offset(points[1].x, points[1].y); + + final paint = Paint() + ..color = color + ..strokeWidth = strokeWidth + ..isAntiAlias = true + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; + + // Main line + canvas.drawLine(p1, p2, paint); + + // Arrowhead + final dx = p2.dx - p1.dx; + final dy = p2.dy - p1.dy; + final angle = atan2(dy, dx); + final arrowLength = strokeWidth * 5; + const arrowAngle = pi / 6; // 30 degrees + + final arrowP1 = Offset( + p2.dx - arrowLength * cos(angle - arrowAngle), + p2.dy - arrowLength * sin(angle - arrowAngle), + ); + final arrowP2 = Offset( + p2.dx - arrowLength * cos(angle + arrowAngle), + p2.dy - arrowLength * sin(angle + arrowAngle), + ); + + canvas.drawLine(p2, arrowP1, paint); + canvas.drawLine(p2, arrowP2, paint); + } + + void _drawText( + Canvas canvas, + List points, + String text, + double fontSize, + Color color, + ) { + final textPainter = TextPainter( + text: TextSpan( + text: text, + style: TextStyle(color: color, fontSize: fontSize), + ), + textDirection: TextDirection.ltr, + ); + textPainter.layout(); + textPainter.paint(canvas, Offset(points[0].x, points[0].y)); + } + + @override + bool shouldRepaint(covariant _InkPainter oldDelegate) { + if (strokes.length != oldDelegate.strokes.length) return true; + if (currentPoints.length != oldDelegate.currentPoints.length) return true; + for (int i = 0; i < strokes.length; i++) { + final a = strokes[i], b = oldDelegate.strokes[i]; + if (a.id != b.id || + a.color != b.color || + a.strokeWidth != b.strokeWidth || + a.tool != b.tool) { + return true; + } + } + return currentTool != oldDelegate.currentTool; + } +} diff --git a/lib/widgets/page_thumbnail_sidebar.dart b/lib/widgets/page_thumbnail_sidebar.dart new file mode 100644 index 0000000..0d886a6 --- /dev/null +++ b/lib/widgets/page_thumbnail_sidebar.dart @@ -0,0 +1,206 @@ +import 'package:flutter/material.dart'; + +import '../services/thumbnail_service.dart'; + +/// Vertical sidebar showing page thumbnails for quick navigation. +/// +/// Thumbnails are lazily generated and cached on disk. The current page is +/// highlighted with a blue border, and bookmarked pages show a colored dot. +class PageThumbnailSidebar extends StatefulWidget { + final String documentId; + final String filePath; + final int pageCount; + final int currentPage; + final ValueChanged onPageTap; + final Set bookmarkedPages; + + const PageThumbnailSidebar({ + super.key, + required this.documentId, + required this.filePath, + required this.pageCount, + required this.currentPage, + required this.onPageTap, + this.bookmarkedPages = const {}, + }); + + @override + State createState() => _PageThumbnailSidebarState(); +} + +class _PageThumbnailSidebarState extends State { + /// Cached thumbnail image data keyed by page index. + final Map _cache = {}; + + /// Pages currently being generated (to avoid duplicate work). + final Set _loading = {}; + + /// Pages that permanently failed thumbnail generation (null result or throw). + /// Skipped on subsequent rebuilds to avoid a retry storm. + final Set _failed = {}; + + @override + void didUpdateWidget(PageThumbnailSidebar oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.documentId != widget.documentId) { + _cache.clear(); + _loading.clear(); + _failed.clear(); + } + } + + Future _loadThumbnail(int pageIndex) async { + if (_cache.containsKey(pageIndex) || + _loading.contains(pageIndex) || + _failed.contains(pageIndex)) { + return; + } + _loading.add(pageIndex); + + try { + // Check disk cache first. + final cached = await ThumbnailService.getCached( + widget.documentId, + pageIndex, + ); + if (cached != null && mounted) { + setState(() { + _cache[pageIndex] = FileImage(cached); + }); + _loading.remove(pageIndex); + return; + } + + // Generate from the PDF. + final bytes = await ThumbnailService.generate( + widget.filePath, + pageIndex, + maxWidth: 160, + ); + if (bytes != null) { + await ThumbnailService.cacheThumbnail( + widget.documentId, + pageIndex, + bytes, + ); + if (mounted) { + setState(() { + _cache[pageIndex] = MemoryImage(bytes); + }); + } + } else { + // Null result means generation failed permanently for this page. + _failed.add(pageIndex); + } + } catch (_) { + // Any exception is treated as a permanent failure to avoid retry storms. + _failed.add(pageIndex); + } finally { + _loading.remove(pageIndex); + } + } + + @override + Widget build(BuildContext context) { + return Container( + width: 120, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + border: Border( + right: BorderSide(color: Theme.of(context).dividerColor, width: 1), + ), + ), + child: ListView.builder( + padding: const EdgeInsets.symmetric(vertical: 8), + itemCount: widget.pageCount, + itemBuilder: (context, index) { + _loadThumbnail(index); + final isCurrentPage = index == widget.currentPage; + final isBookmarked = widget.bookmarkedPages.contains(index); + + return GestureDetector( + onTap: () => widget.onPageTap(index), + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + border: Border.all( + color: isCurrentPage + ? Theme.of(context).colorScheme.primary + : Colors.grey.shade400, + width: isCurrentPage ? 2.5 : 1.0, + ), + borderRadius: BorderRadius.circular(4), + ), + child: Stack( + children: [ + // Thumbnail image or placeholder. + AspectRatio( + aspectRatio: 8.5 / 11, // US Letter-ish ratio + child: ClipRRect( + borderRadius: BorderRadius.circular(3), + child: _cache.containsKey(index) + ? Image(image: _cache[index]!, fit: BoxFit.cover) + : Container( + color: Theme.of( + context, + ).colorScheme.surfaceContainerLow, + child: Center( + child: Text( + '${index + 1}', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Theme.of( + context, + ).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + ), + ), + // Page number overlay. + Positioned( + bottom: 2, + right: 2, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 4, + vertical: 1, + ), + decoration: BoxDecoration( + color: Colors.black54, + borderRadius: BorderRadius.circular(3), + ), + child: Text( + '${index + 1}', + style: const TextStyle( + color: Colors.white, + fontSize: 10, + ), + ), + ), + ), + // Bookmark indicator. + if (isBookmarked) + Positioned( + top: 2, + left: 2, + child: Container( + width: 8, + height: 8, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, + shape: BoxShape.circle, + ), + ), + ), + ], + ), + ), + ); + }, + ), + ); + } +} diff --git a/lib/widgets/pdf_annotation_layer.dart b/lib/widgets/pdf_annotation_layer.dart new file mode 100644 index 0000000..3159a2c --- /dev/null +++ b/lib/widgets/pdf_annotation_layer.dart @@ -0,0 +1,162 @@ +import 'package:flutter/material.dart'; + +import '../models/ink_point.dart'; +import '../models/ink_stroke.dart'; +import '../models/pen_tool.dart'; +import '../widgets/ink_canvas.dart'; + +/// Transparent overlay widget positioned on top of the PDF viewer. +/// +/// Reuses the existing [InkCanvas] widget for ink rendering. +/// Coordinates are normalized to [0, 1] relative to the overlay size, +/// enabling correct mapping to PDF page coordinates during export. +class PdfAnnotationLayer extends StatefulWidget { + final List strokes; + final void Function(InkStroke stroke)? onStrokeComplete; + final void Function(String strokeId, List replacements)? onErase; + final PenTool tool; + final Color color; + final double strokeWidth; + final bool filled; + final InteractionMode interactionMode; + final int rotation; + + const PdfAnnotationLayer({ + super.key, + required this.strokes, + this.onStrokeComplete, + this.onErase, + this.tool = PenTool.pen, + this.color = Colors.black, + this.strokeWidth = 2.0, + this.filled = false, + this.interactionMode = InteractionMode.draw, + this.rotation = 0, + }); + + @override + State createState() => _PdfAnnotationLayerState(); +} + +class _PdfAnnotationLayerState extends State { + Size _canvasSize = Size.zero; + + /// Applies inverse rotation to normalized coordinates for rendering. + /// Converts from stored (possibly rotated) coords back to display coords. + Offset _inverseRotate(double nx, double ny, int rotation) { + switch (rotation % 360) { + case 90: + return Offset(1.0 - ny, nx); + case 180: + return Offset(1.0 - nx, 1.0 - ny); + case 270: + return Offset(ny, 1.0 - nx); + default: + return Offset(nx, ny); + } + } + + /// Applies forward rotation to normalized coordinates before storage. + /// Converts from display coords to the canonical rotated representation. + Offset _forwardRotate(double nx, double ny, int rotation) { + switch (rotation % 360) { + case 90: + return Offset(ny, 1.0 - nx); + case 180: + return Offset(1.0 - nx, 1.0 - ny); + case 270: + return Offset(1.0 - ny, nx); + default: + return Offset(nx, ny); + } + } + + /// Scales a stroke's points from normalized [0, 1] coordinates to + /// the current canvas pixel coordinates for rendering. + /// Applies inverse rotation before scaling so strokes render correctly + /// on a rotated page. + List get _scaledStrokes { + if (_canvasSize == Size.zero) return widget.strokes; + return widget.strokes.map((stroke) { + return InkStroke( + id: stroke.id, + points: stroke.points.map((pt) { + final rotated = _inverseRotate(pt.x, pt.y, widget.rotation); + return InkPoint( + x: rotated.dx * _canvasSize.width, + y: rotated.dy * _canvasSize.height, + pressure: pt.pressure, + tilt: pt.tilt, + timestamp: pt.timestamp, + pointerDeviceKind: pt.pointerDeviceKind, + ); + }).toList(), + tool: stroke.tool, + color: stroke.color, + strokeWidth: stroke.strokeWidth, + createdAt: stroke.createdAt, + filled: stroke.filled, + textContent: stroke.textContent, + fontSize: stroke.fontSize, + ); + }).toList(); + } + + /// Normalizes a stroke's points from canvas pixel coordinates to + /// [0, 1] relative to the overlay size. + /// Applies forward rotation before storage so the canonical representation + /// accounts for the current page rotation. + InkStroke _normalizeStroke(InkStroke stroke) { + if (_canvasSize == Size.zero) return stroke; + return InkStroke( + id: stroke.id, + points: stroke.points.map((pt) { + final nx = pt.x / _canvasSize.width; + final ny = pt.y / _canvasSize.height; + final rotated = _forwardRotate(nx, ny, widget.rotation); + return InkPoint( + x: rotated.dx, + y: rotated.dy, + pressure: pt.pressure, + tilt: pt.tilt, + timestamp: pt.timestamp, + pointerDeviceKind: pt.pointerDeviceKind, + ); + }).toList(), + tool: stroke.tool, + color: stroke.color, + strokeWidth: stroke.strokeWidth, + createdAt: stroke.createdAt, + filled: stroke.filled, + textContent: stroke.textContent, + fontSize: stroke.fontSize, + ); + } + + void _onStrokeComplete(InkStroke stroke) { + widget.onStrokeComplete?.call(_normalizeStroke(stroke)); + } + + void _onErase(String strokeId, List replacements) { + widget.onErase?.call(strokeId, replacements.map(_normalizeStroke).toList()); + } + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) { + _canvasSize = Size(constraints.maxWidth, constraints.maxHeight); + return InkCanvas( + strokes: _scaledStrokes, + onStrokeComplete: _onStrokeComplete, + onErase: _onErase, + tool: widget.tool, + color: widget.color, + strokeWidth: widget.strokeWidth, + filled: widget.filled, + interactionMode: widget.interactionMode, + ); + }, + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..9b9766b --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# 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 "badnote") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.badnote.badnote") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..7299b5c --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,19 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..886932b --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..a50b131 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "badnote"); + 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, "badnote"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..48b3875 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,24 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import device_info_plus +import file_picker +import file_selector_macos +import shared_preferences_foundation +import sqflite_darwin +import syncfusion_pdfviewer_macos +import url_launcher_macos + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) + FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin")) + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) + SyncfusionFlutterPdfViewerPlugin.register(with: registry.registrar(forPlugin: "SyncfusionFlutterPdfViewerPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..0772e64 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* badnote.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "badnote.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* badnote.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* badnote.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/badnote.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/badnote"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/badnote.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/badnote"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/badnote.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/badnote"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..2dfbe9e --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..a293a89 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = badnote + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.badnote.badnote + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.badnote. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..6e7bcb4 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,1266 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f + url: "https://pub.dev" + source: hosted + version: "85.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: f4ad0fea5f102201015c9aae9d93bc02f75dd9491529a8c21f88d17a8523d44c + url: "https://pub.dev" + source: hosted + version: "7.6.0" + analyzer_plugin: + dependency: transitive + description: + name: analyzer_plugin + sha256: a5ab7590c27b779f3d4de67f31c4109dbe13dd7339f86461a6f2a8ab2594d8ce + url: "https://pub.dev" + source: hosted + version: "0.13.4" + 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: + dependency: transitive + description: + name: build + sha256: "51dc711996cbf609b90cbe5b335bbce83143875a9d58e4b5c6d3c4f684d3dda7" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + build_config: + dependency: transitive + description: + name: build_config + sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + build_daemon: + dependency: transitive + description: + name: build_daemon + sha256: bf05f6e12cfea92d3c09308d7bcdab1906cd8a179b023269eed00c071004b957 + url: "https://pub.dev" + source: hosted + version: "4.1.1" + build_resolvers: + dependency: transitive + description: + name: build_resolvers + sha256: ee4257b3f20c0c90e72ed2b57ad637f694ccba48839a821e87db762548c22a62 + url: "https://pub.dev" + source: hosted + version: "2.5.4" + build_runner: + dependency: "direct dev" + description: + name: build_runner + sha256: "382a4d649addbfb7ba71a3631df0ec6a45d5ab9b098638144faf27f02778eb53" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + build_runner_core: + dependency: transitive + description: + name: build_runner_core + sha256: "85fbbb1036d576d966332a3f5ce83f2ce66a40bea1a94ad2d5fc29a19a0d3792" + url: "https://pub.dev" + source: hosted + version: "9.1.2" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.dev" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + sha256: "34e4067d30ce212937df995f03b69992eea683539ceeac7f679a1f1eba055b56" + url: "https://pub.dev" + source: hosted + version: "8.12.6" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "67cf6d84013f9c601e42a6f8a6b74c4c0d9dc1a1619d775f2b28b732d3551b85" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + code_builder: + dependency: transitive + description: + name: code_builder + sha256: "6a6cab2ba4680d6423f34a9b972a4c9a94ebe1b62ecec4e1a1f2cba91fd1319d" + url: "https://pub.dev" + source: hosted + version: "4.11.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + custom_lint_core: + dependency: transitive + description: + name: custom_lint_core + sha256: "31110af3dde9d29fb10828ca33f1dce24d2798477b167675543ce3d208dee8be" + url: "https://pub.dev" + source: hosted + version: "0.7.5" + custom_lint_visitor: + dependency: transitive + description: + name: custom_lint_visitor + sha256: "4a86a0d8415a91fbb8298d6ef03e9034dc8e323a599ddc4120a0e36c433983a2" + url: "https://pub.dev" + source: hosted + version: "1.0.0+7.7.0" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: "8a0e5fba27e8ee025d2ffb4ee820b4e6e2cf5e4246a6b1a477eb66866947e0bb" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + device_info_plus: + dependency: transitive + description: + name: device_info_plus + sha256: "98f28b42168cc509abc92f88518882fd58061ea372d7999aecc424345c7bff6a" + url: "https://pub.dev" + source: hosted + version: "11.5.0" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f + url: "https://pub.dev" + source: hosted + version: "7.0.3" + 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" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: ab13ae8ef5580a411c458d6207b6774a6c237d77ac37011b13994879f68a8810 + url: "https://pub.dev" + source: hosted + version: "8.3.7" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + url: "https://pub.dev" + source: hosted + version: "0.9.4" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + url: "https://pub.dev" + source: hosted + version: "0.9.5" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + url: "https://pub.dev" + source: hosted + version: "0.9.3+5" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_colorpicker: + dependency: "direct main" + description: + name: flutter_colorpicker + sha256: "969de5f6f9e2a570ac660fb7b501551451ea2a1ab9e2097e89475f60e07816ea" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" + url: "https://pub.dev" + source: hosted + version: "2.0.34" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "9532ee6db4a943a1ed8383072a2e3eeda041db5657cdf6d2acecf3c21ecbe7e1" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + 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" + freezed: + dependency: "direct dev" + description: + name: freezed + sha256: "59a584c24b3acdc5250bb856d0d3e9c0b798ed14a4af1ddb7dc1c7b41df91c9c" + url: "https://pub.dev" + source: hosted + version: "2.5.8" + freezed_annotation: + dependency: "direct main" + description: + name: freezed_annotation + sha256: c2e2d632dd9b8a2b7751117abcfc2b4888ecfe181bd9fca7170d9ef02e595fe2 + url: "https://pub.dev" + source: hosted + version: "2.4.4" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + google_fonts: + dependency: "direct main" + description: + name: google_fonts + sha256: ba03d03bcaa2f6cb7bd920e3b5027181db75ab524f8891c8bc3aa603885b8055 + url: "https://pub.dev" + source: hosted + version: "6.3.3" + graphs: + dependency: transitive + description: + name: graphs + sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + hooks: + dependency: transitive + description: + name: hooks + sha256: a41af4e8fc687cd6d33de9751eb936c8c0204ebe2bcb6c15ecf707504bf47f31 + url: "https://pub.dev" + source: hosted + version: "2.0.0" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: d5b3e1774af29c9ab00103afb0d4614070f924d2e0057ac867ec98800114793f + url: "https://pub.dev" + source: hosted + version: "0.8.13+17" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: b9c4a438a9ff4f60808c9cf0039b93a42bb6c2211ef6ebb647394b2b3fa84588 + url: "https://pub.dev" + source: hosted + version: "0.8.13+6" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + intl: + dependency: transitive + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + jni: + dependency: transitive + description: + name: jni + sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f + url: "https://pub.dev" + source: hosted + version: "1.0.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + js: + dependency: transitive + description: + name: js + sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + url: "https://pub.dev" + source: hosted + version: "0.7.2" + json_annotation: + dependency: "direct main" + description: + name: json_annotation + sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" + url: "https://pub.dev" + source: hosted + version: "4.9.0" + json_serializable: + dependency: "direct dev" + description: + name: json_serializable + sha256: c50ef5fc083d5b5e12eef489503ba3bf5ccc899e487d691584699b4bdefeea8c + url: "https://pub.dev" + source: hosted + version: "6.9.5" + 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: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: f59351d28f49520cd3a74eb1f41c5f19ae15e53c65a3231d14af672e46510a96 + url: "https://pub.dev" + source: hosted + version: "0.19.1" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "6cb691c686fa2838c6deb34980d426145c2a5d537491cb83d463c33cdbc726ed" + url: "https://pub.dev" + source: hosted + version: "9.4.1" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + path: + dependency: "direct main" + 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: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + 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: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + perfect_freehand: + dependency: "direct main" + description: + name: perfect_freehand + sha256: "77bfdd5efb223d120de5cc18c5d6e0b36a835e920521cfe67e281960bad44c9b" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + url: "https://pub.dev" + source: hosted + version: "1.5.2" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + riverpod_analyzer_utils: + dependency: transitive + description: + name: riverpod_analyzer_utils + sha256: "837a6dc33f490706c7f4632c516bcd10804ee4d9ccc8046124ca56388715fdf3" + url: "https://pub.dev" + source: hosted + version: "0.5.9" + riverpod_annotation: + dependency: "direct main" + description: + name: riverpod_annotation + sha256: e14b0bf45b71326654e2705d462f21b958f987087be850afd60578fcd502d1b8 + url: "https://pub.dev" + source: hosted + version: "2.6.1" + riverpod_generator: + dependency: "direct dev" + description: + name: riverpod_generator + sha256: "120d3310f687f43e7011bb213b90a436f1bbc300f0e4b251a72c39bccb017a4f" + url: "https://pub.dev" + source: hosted + version: "2.6.4" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.dev" + source: hosted + version: "2.5.5" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + url: "https://pub.dev" + source: hosted + version: "2.4.23" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + source_helper: + dependency: transitive + description: + name: source_helper + sha256: a447acb083d3a5ef17f983dd36201aeea33fedadb3228fa831f2f0c92f0f3aca + url: "https://pub.dev" + source: hosted + version: "1.3.7" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + sqflite: + dependency: "direct main" + description: + name: sqflite + sha256: "564cfed0746fe53140c23b70b308e045c3b31f17778f2f326ccb7d804ea0250a" + url: "https://pub.dev" + source: hosted + version: "2.4.2+1" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: "881e28efdcc9950fd8e9bb42713dcf1103e62a2e7168f23c9338d82db13dec40" + url: "https://pub.dev" + source: hosted + version: "2.4.2+3" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: "1581ffbf7a0e333b380d6a30737d78516b826cb35beb7fb0bf8a3ea0c678b465" + url: "https://pub.dev" + source: hosted + version: "2.5.8" + sqflite_common_ffi: + dependency: "direct main" + description: + name: sqflite_common_ffi + sha256: cd0c7f7de39a08f2d54ef144d9058c46eca8461879aaa648025643455c1e5a20 + url: "https://pub.dev" + source: hosted + version: "2.4.0+3" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: "279832e5cde3fe99e8571879498c9211f3ca6391b0d818df4e17d9fff5c6ccb3" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + sqlite3: + dependency: transitive + description: + name: sqlite3 + sha256: "9488c7d2cdb1091c91cacf7e207cff81b28bff8e366f042bad3afe7d34afe189" + url: "https://pub.dev" + source: hosted + version: "3.3.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + url: "https://pub.dev" + source: hosted + version: "2.1.1" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + syncfusion_flutter_core: + dependency: transitive + description: + name: syncfusion_flutter_core + sha256: f1d2b52697543e13bdefdc62d15868124a265987577f53224a7dbe176c8448f0 + url: "https://pub.dev" + source: hosted + version: "28.2.12" + syncfusion_flutter_pdf: + dependency: "direct main" + description: + name: syncfusion_flutter_pdf + sha256: f5e02ac4264bc69eeffa3ec54c9c0ad6e8a9f9161b105451b4a83dd1a317eaf9 + url: "https://pub.dev" + source: hosted + version: "28.2.12" + syncfusion_flutter_pdfviewer: + dependency: "direct main" + description: + name: syncfusion_flutter_pdfviewer + sha256: "95e678444ff9571c4d33b8443037cdcc9e34faf1c53af7724043266b2d2df5df" + url: "https://pub.dev" + source: hosted + version: "28.2.12" + syncfusion_flutter_signaturepad: + dependency: transitive + description: + name: syncfusion_flutter_signaturepad + sha256: "30de4c9f77d1b75850697262bf9ce30b46a8d4401cec91dae95c4ee4e589d857" + url: "https://pub.dev" + source: hosted + version: "28.2.12" + syncfusion_pdfviewer_macos: + dependency: transitive + description: + name: syncfusion_pdfviewer_macos + sha256: c76af8dc3e8df38be3f5d7a78f4bae5ff9f5d73706da997d8428e087af418102 + url: "https://pub.dev" + source: hosted + version: "28.2.12" + syncfusion_pdfviewer_platform_interface: + dependency: "direct main" + description: + name: syncfusion_pdfviewer_platform_interface + sha256: a9c102d1edd68fbe449e37021f5b82a8e32339023112807a828fb4e585e077cc + url: "https://pub.dev" + source: hosted + version: "28.2.12" + syncfusion_pdfviewer_web: + dependency: transitive + description: + name: syncfusion_pdfviewer_web + sha256: "6f2bf5c385e003e8f7312c445240c8648045400de9d7050df9d9a4b191c02568" + url: "https://pub.dev" + source: hosted + version: "28.2.12" + syncfusion_pdfviewer_windows: + dependency: transitive + description: + name: syncfusion_pdfviewer_windows + sha256: cf638a7d64bdd4120a8e27d944cb966a05a409ee3d0c24fa63e83341a535d6fb + url: "https://pub.dev" + source: hosted + version: "28.2.12" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0 + url: "https://pub.dev" + source: hosted + version: "3.4.0" + 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: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + url: "https://pub.dev" + source: hosted + version: "0.7.7" + timing: + dependency: transitive + description: + name: timing + sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: transitive + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c" + url: "https://pub.dev" + source: hosted + version: "6.3.30" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0" + url: "https://pub.dev" + source: hosted + version: "6.4.1" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + 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: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + uuid: + dependency: "direct main" + description: + name: uuid + sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + url: "https://pub.dev" + source: hosted + version: "4.5.3" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.10.8 <4.0.0" + flutter: ">=3.38.4" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..ffc33d3 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,63 @@ +name: badnote +description: "BadNote - Local-first Surface Pen note-taking with PDF/PPT annotation" +publish_to: 'none' +version: 0.1.0+1 + +environment: + sdk: ^3.10.8 + +dependencies: + flutter: + sdk: flutter + cupertino_icons: ^1.0.8 + + # Pen & Ink Rendering + perfect_freehand: ^1.0.0 + + # PDF + syncfusion_flutter_pdfviewer: ^28.2.7 + syncfusion_flutter_pdf: ^28.2.7 + # Used directly by ThumbnailService to render PDF pages off-screen. + syncfusion_pdfviewer_platform_interface: ^28.2.7 + + # State Management + flutter_riverpod: ^2.6.1 + riverpod_annotation: ^2.6.1 + + # Local Storage + sqflite: ^2.4.2 + sqflite_common_ffi: ^2.3.4+4 + path_provider: ^2.1.5 + path: ^1.9.1 + + # Data Classes + freezed_annotation: ^2.4.4 + json_annotation: ^4.9.0 + uuid: ^4.5.1 + + # UI Utilities + google_fonts: ^6.2.1 + flutter_colorpicker: ^1.1.0 + + # Settings persistence + shared_preferences: ^2.3.0 + + # Cross-platform file picker + file_picker: ^8.0.0 + + # Camera / image picker + image_picker: ^1.1.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + + # Code Generation + build_runner: ^2.4.14 + riverpod_generator: ^2.6.3 + freezed: ^2.5.8 + json_serializable: ^6.9.4 + +flutter: + uses-material-design: true diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..c658478 --- /dev/null +++ b/server/README.md @@ -0,0 +1,52 @@ +# BadNote Server (Optional) + +This directory contains an **optional** Python/FastAPI backend. The BadNote desktop app does **not** depend on it. + +The Flutter client is local-first: + +- Notes and documents are stored in SQLite on device +- OCR runs locally via Windows built-in OCR +- Full-text search uses on-device FTS5 + +## Why this exists + +This server was an early experiment for: + +- Multi-device note sync (push/pull) +- Server-side OCR with EasyOCR +- JWT authentication + +These features are **not wired into the current client**. The client previously had incomplete sync/OCR scaffolding that has been removed in favor of local processing. + +## Running (if you want to experiment) + +```bash +cd server +python -m venv .venv +source .venv/bin/activate # Windows: .venv\Scripts\activate +pip install -r requirements.txt +uvicorn badnote_server.main:app --host 0.0.0.0 --port 8080 +``` + +API docs: http://localhost:8080/docs + +The OCR worker has heavy extra dependencies (EasyOCR + torch). Install them only +if you want to run it: + +```bash +pip install -r requirements-ocr.txt +python -m badnote_server.ocr.worker +``` + +### Security notes + +- Set `BADNOTE_JWT_SECRET` in production. If unset, a secret is generated once + and persisted to `/.jwt_secret` so tokens survive restarts. +- Restrict origins with `BADNOTE_CORS_ORIGINS` (comma-separated). The default is + permissive (`*`, without credentials) for local development. + +## Status + +- Kept for reference and future optional sync work +- Not part of the primary development path +- No guarantee of API compatibility with future client versions diff --git a/server/badnote_server/__init__.py b/server/badnote_server/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/badnote_server/auth.py b/server/badnote_server/auth.py new file mode 100644 index 0000000..5baf45c --- /dev/null +++ b/server/badnote_server/auth.py @@ -0,0 +1,73 @@ +"""JWT authentication utilities for BadNote.""" + +from datetime import datetime, timedelta, timezone +from uuid import uuid4 + +from fastapi import Depends, HTTPException, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from jose import JWTError, jwt +from passlib.context import CryptContext + +from .config import settings + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") +bearer_scheme = HTTPBearer() + + +def hash_password(password: str) -> str: + """Hash a plaintext password with bcrypt.""" + return pwd_context.hash(password) + + +def verify_password(password: str, password_hash: str) -> bool: + """Verify a password against its hash.""" + return pwd_context.verify(password, password_hash) + + +# A precomputed hash used to spend roughly the same time verifying a password +# for a non-existent user as for an existing one, so login response timing does +# not leak whether a username exists. +_DUMMY_HASH = pwd_context.hash("badnote-dummy-password") + + +def dummy_verify() -> None: + """Run a throwaway bcrypt verification to equalise login timing.""" + pwd_context.verify("badnote-dummy-password", _DUMMY_HASH) + + +def create_access_token(user_id: str) -> str: + """Create a JWT access token for the given user_id.""" + expire = datetime.now(timezone.utc) + timedelta(hours=settings.jwt_expiry_hours) + payload = { + "sub": user_id, + "exp": expire, + "iat": datetime.now(timezone.utc), + "jti": str(uuid4()), + } + return jwt.encode(payload, settings.jwt_secret, algorithm="HS256") + + +def decode_access_token(token: str) -> dict: + """Decode and validate a JWT token. Returns the payload dict.""" + try: + payload = jwt.decode(token, settings.jwt_secret, algorithms=["HS256"]) + return payload + except JWTError as exc: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired token", + ) from exc + + +async def get_current_user( + credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme), +) -> str: + """FastAPI dependency: extract user_id from Bearer token.""" + payload = decode_access_token(credentials.credentials) + user_id: str | None = payload.get("sub") + if user_id is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token missing subject", + ) + return user_id diff --git a/server/badnote_server/config.py b/server/badnote_server/config.py new file mode 100644 index 0000000..ae69529 --- /dev/null +++ b/server/badnote_server/config.py @@ -0,0 +1,73 @@ +"""BadNote server configuration via environment variables.""" + +import os +import secrets +import warnings + + +def _resolve_jwt_secret() -> str: + """Resolve the JWT signing secret. + + Priority: + 1. ``BADNOTE_JWT_SECRET`` environment variable (recommended for prod). + 2. A persisted secret file (so the secret survives restarts and is shared + across worker processes). + 3. A freshly generated secret, persisted to that file. + + A per-process random secret (the previous behaviour) invalidated every + token on restart and gave each worker a different secret in multi-worker + deployments, so tokens were rejected at random. We persist instead. + """ + env_secret = os.environ.get("BADNOTE_JWT_SECRET") + if env_secret: + return env_secret + + db_path = os.environ.get("BADNOTE_DB_PATH", "./data/badnote_server.db") + default_secret_file = os.path.join(os.path.dirname(db_path) or ".", ".jwt_secret") + secret_path = os.environ.get("BADNOTE_JWT_SECRET_FILE", default_secret_file) + + try: + if os.path.exists(secret_path): + with open(secret_path, "r", encoding="utf-8") as f: + existing = f.read().strip() + if existing: + return existing + + secret = secrets.token_urlsafe(48) + os.makedirs(os.path.dirname(secret_path) or ".", exist_ok=True) + # Restrictive permissions: only the owner may read the secret. + fd = os.open(secret_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(secret) + return secret + except OSError: + warnings.warn( + "Could not persist a JWT secret; using an ephemeral one. " + "Set BADNOTE_JWT_SECRET to keep tokens valid across restarts.", + RuntimeWarning, + ) + return secrets.token_urlsafe(48) + + +def _resolve_cors_origins() -> list[str]: + """Parse the allowed CORS origins from ``BADNOTE_CORS_ORIGINS``. + + Comma-separated list of origins. Empty by default; the app falls back to a + permissive ``*`` (without credentials) when none are configured. + """ + raw = os.environ.get("BADNOTE_CORS_ORIGINS", "") + return [o.strip() for o in raw.split(",") if o.strip()] + + +class Settings: + host: str = os.environ.get("BADNOTE_HOST", "0.0.0.0") + port: int = int(os.environ.get("BADNOTE_PORT", "8080")) + db_path: str = os.environ.get("BADNOTE_DB_PATH", "./data/badnote_server.db") + storage_path: str = os.environ.get("BADNOTE_STORAGE_PATH", "./data/storage") + queue_path: str = os.environ.get("BADNOTE_QUEUE_PATH", "./data/queue") + jwt_secret: str = _resolve_jwt_secret() + jwt_expiry_hours: int = int(os.environ.get("BADNOTE_JWT_EXPIRY_HOURS", "720")) + cors_origins: list[str] = _resolve_cors_origins() + + +settings = Settings() diff --git a/server/badnote_server/database.py b/server/badnote_server/database.py new file mode 100644 index 0000000..da06a93 --- /dev/null +++ b/server/badnote_server/database.py @@ -0,0 +1,90 @@ +"""Async SQLite database layer for BadNote.""" + +import aiosqlite +from .config import settings + +_db: aiosqlite.Connection | None = None + + +async def get_db() -> aiosqlite.Connection: + """Return the global database connection.""" + global _db + if _db is None: + _db = await aiosqlite.connect(settings.db_path) + _db.row_factory = aiosqlite.Row + await _db.execute("PRAGMA journal_mode=WAL") + await _db.execute("PRAGMA foreign_keys=ON") + return _db + + +async def close_db() -> None: + """Close the global database connection.""" + global _db + if _db is not None: + await _db.close() + _db = None + + +async def init_db() -> None: + """Create all tables if they do not exist.""" + db = await get_db() + await db.executescript(""" + CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + username TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS notes ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id), + title TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + tags TEXT NOT NULL DEFAULT '[]', + strokes_json TEXT NOT NULL DEFAULT '[]' + ); + + CREATE TABLE IF NOT EXISTS documents ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id), + filename TEXT NOT NULL, + doc_type TEXT NOT NULL, + file_path TEXT NOT NULL, + page_count INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS annotations ( + id TEXT PRIMARY KEY, + document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE, + page_number INTEGER NOT NULL, + annotation_json TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS bookmarks ( + id TEXT PRIMARY KEY, + document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE, + page_number INTEGER NOT NULL, + label TEXT NOT NULL DEFAULT '', + color INTEGER NOT NULL DEFAULT 4283215696, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS ocr_jobs ( + id TEXT PRIMARY KEY, + note_id TEXT, + document_id TEXT, + page_number INTEGER, + status TEXT NOT NULL DEFAULT 'pending', + result_text TEXT, + error_message TEXT, + created_at TEXT NOT NULL, + completed_at TEXT + ); + """) + await db.commit() diff --git a/server/badnote_server/main.py b/server/badnote_server/main.py new file mode 100644 index 0000000..958ad65 --- /dev/null +++ b/server/badnote_server/main.py @@ -0,0 +1,55 @@ +"""BadNote FastAPI server — main application.""" + +import os +from contextlib import asynccontextmanager + +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from .config import settings +from .database import close_db, init_db +from .routers.auth_router import router as auth_router +from .routers.notes_router import router as notes_router +from .routers.documents_router import router as documents_router +from .routers.ocr_router import router as ocr_router +from .routers.sync_router import router as sync_router + + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Startup: create directories and init DB. Shutdown: close DB.""" + os.makedirs(settings.storage_path, exist_ok=True) + for subdir in ("pending", "processing", "done", "failed"): + os.makedirs(os.path.join(settings.queue_path, subdir), exist_ok=True) + await init_db() + yield + await close_db() + + +app = FastAPI(title="BadNote Server", version="1.0.0", lifespan=lifespan) + +# Authentication is Bearer-token based, so cookies/credentials are not needed. +# `allow_origins=["*"]` together with `allow_credentials=True` is an invalid and +# insecure combination, so we keep credentials disabled. Set BADNOTE_CORS_ORIGINS +# (comma-separated) to lock the API down to specific front-end origins. +_cors_origins = settings.cors_origins or ["*"] + +app.add_middleware( + CORSMiddleware, + allow_origins=_cors_origins, + allow_credentials=False, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(auth_router, prefix="/api/auth", tags=["auth"]) +app.include_router(notes_router, prefix="/api/notes", tags=["notes"]) +app.include_router(documents_router, prefix="/api/documents", tags=["documents"]) +app.include_router(ocr_router, prefix="/api/ocr", tags=["ocr"]) +app.include_router(sync_router, prefix="/api/sync", tags=["sync"]) + + +@app.get("/api/ping") +async def ping() -> dict: + """Health check endpoint.""" + return {"status": "ok"} diff --git a/server/badnote_server/models.py b/server/badnote_server/models.py new file mode 100644 index 0000000..a6ca6a1 --- /dev/null +++ b/server/badnote_server/models.py @@ -0,0 +1,136 @@ +"""Pydantic request/response models for BadNote.""" + +from pydantic import BaseModel, Field + + +# ── Auth ──────────────────────────────────────────────────────────────────── + +class UserCreate(BaseModel): + username: str = Field(..., min_length=1, max_length=64) + password: str = Field(..., min_length=4, max_length=128) + + +class UserLogin(BaseModel): + username: str + password: str + + +class TokenResponse(BaseModel): + token: str + user_id: str + + +# ── Notes ─────────────────────────────────────────────────────────────────── + +class NoteCreate(BaseModel): + id: str + title: str = "" + tags: list[str] = Field(default_factory=list) + strokes_json: str = "[]" + + +class NoteUpdate(BaseModel): + title: str | None = None + tags: list[str] | None = None + strokes_json: str | None = None + + +class NoteResponse(BaseModel): + id: str + user_id: str + title: str + created_at: str + updated_at: str + tags: list[str] + strokes_json: str + + +# ── Documents ─────────────────────────────────────────────────────────────── + +class DocumentResponse(BaseModel): + id: str + user_id: str + filename: str + doc_type: str + page_count: int + created_at: str + updated_at: str + + +class AnnotationUpdate(BaseModel): + annotation_json: list[dict] = Field(default_factory=list) + + +class AnnotationResponse(BaseModel): + id: str + document_id: str + page_number: int + annotation_json: list[dict] + created_at: str + updated_at: str + + +class BookmarkCreate(BaseModel): + page_number: int + label: str = "" + color: int = 4283215696 + + +class BookmarkResponse(BaseModel): + id: str + document_id: str + page_number: int + label: str + color: int + created_at: str + + +# ── OCR ───────────────────────────────────────────────────────────────────── + +class OcrJobRequest(BaseModel): + note_id: str | None = None + document_id: str | None = None + page_number: int | None = None + + +class OcrJobStatus(BaseModel): + id: str + status: str + result_text: str | None = None + error_message: str | None = None + created_at: str + completed_at: str | None = None + + +class OcrResult(BaseModel): + id: str + note_id: str | None + document_id: str | None + page_number: int | None + status: str + result_text: str | None + error_message: str | None + created_at: str + completed_at: str | None + + +# ── Sync ──────────────────────────────────────────────────────────────────── + +class SyncNote(BaseModel): + id: str + title: str = "" + tags: list[str] = Field(default_factory=list) + strokes_json: str = "[]" + updated_at: str + + +class SyncPushRequest(BaseModel): + notes: list[SyncNote] + + +class SyncPullRequest(BaseModel): + since: str + + +class SyncResponse(BaseModel): + synced_count: int diff --git a/server/badnote_server/ocr/__init__.py b/server/badnote_server/ocr/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/badnote_server/ocr/engine.py b/server/badnote_server/ocr/engine.py new file mode 100644 index 0000000..ec1e19b --- /dev/null +++ b/server/badnote_server/ocr/engine.py @@ -0,0 +1,78 @@ +"""OCR engine for BadNote using EasyOCR. + +Lightweight handwriting-capable OCR using EasyOCR with CPU-only inference. +Suitable for Zen2 APU 25W / 16GB RAM (~200MB memory once loaded). +""" + +import asyncio +import logging + +logger = logging.getLogger(__name__) + +# NOTE: `easyocr` (and its torch dependency) is heavy and optional. It is +# imported lazily inside the engine so that importing the FastAPI app — and +# running its test suite — does not require the OCR dependencies. Install them +# with `pip install -r requirements-ocr.txt` when running the OCR worker. + + +class OcrEngine: + """EasyOCR-based text recognition engine. + + Lazy-loads the reader on first use to avoid startup overhead. + Supports Chinese (simplified) + English. Runs on CPU only. + """ + + def __init__(self): + self._reader = None + + def _ensure_reader(self): + """Lazy-initialize the EasyOCR reader.""" + if self._reader is None: + import easyocr # imported lazily; see module docstring note + + logger.info("Loading EasyOCR reader (ch_sim + en, CPU)...") + self._reader = easyocr.Reader(['ch_sim', 'en'], gpu=False) + logger.info("EasyOCR reader loaded") + + async def recognize(self, image_bytes: bytes) -> str: + """Recognize text from image bytes. + + Args: + image_bytes: Raw image file bytes (PNG, JPEG, etc.) + + Returns: + Recognized text as a single string, or empty string on failure. + """ + if not image_bytes: + return "" + + loop = asyncio.get_event_loop() + + try: + self._ensure_reader() + results = await loop.run_in_executor( + None, self._reader.readtext, image_bytes + ) + # results is a list of (bbox, text, confidence) tuples + text_parts = [text for _, text, _ in results if text.strip()] + return ' '.join(text_parts) + except Exception as exc: + logger.error("OCR recognition failed: %s", exc) + return "" + + async def recognize_file(self, image_path: str) -> str: + """Recognize text from an image file path. + + Args: + image_path: Path to the image file on disk. + + Returns: + Recognized text as a single string, or empty string on failure. + """ + try: + with open(image_path, 'rb') as f: + image_bytes = f.read() + return await self.recognize(image_bytes) + except Exception as exc: + logger.error("Failed to read image file %s: %s", image_path, exc) + return "" diff --git a/server/badnote_server/ocr/queue.py b/server/badnote_server/ocr/queue.py new file mode 100644 index 0000000..1313c94 --- /dev/null +++ b/server/badnote_server/ocr/queue.py @@ -0,0 +1,136 @@ +"""File-based OCR job queue for BadNote.""" + +import json +import os +import shutil +from datetime import datetime, timezone +from uuid import uuid4 + +from ..config import settings + + +def _queue_dir(subdir: str) -> str: + path = os.path.join(settings.queue_path, subdir) + os.makedirs(path, exist_ok=True) + return path + + +def _job_path(job_id: str, subdir: str) -> str: + return os.path.join(_queue_dir(subdir), f"{job_id}.json") + + +def _read_job(path: str) -> dict | None: + try: + with open(path, "r") as f: + return json.load(f) + except (FileNotFoundError, json.JSONDecodeError): + return None + + +def _write_job(path: str, data: dict) -> None: + with open(path, "w") as f: + json.dump(data, f, indent=2) + + +def enqueue(job_data: dict) -> str: + """Add a job to the pending queue. Returns job_id.""" + job_id = job_data.get("id", str(uuid4())) + job_data["id"] = job_id + job_data["status"] = "pending" + job_data["created_at"] = datetime.now(timezone.utc).isoformat() + _write_job(_job_path(job_id, "pending"), job_data) + return job_id + + +def dequeue() -> dict | None: + """Move the first pending job to processing. Returns job dict or None.""" + pending_dir = _queue_dir("pending") + try: + files = sorted(os.listdir(pending_dir)) + except FileNotFoundError: + return None + for fname in files: + if not fname.endswith(".json"): + continue + src = os.path.join(pending_dir, fname) + job = _read_job(src) + if job is None: + continue + job["status"] = "processing" + dst = _job_path(job["id"], "processing") + shutil.move(src, dst) + return job + return None + + +def complete(job_id: str, result: str) -> None: + """Mark a job as done with result text.""" + src = _job_path(job_id, "processing") + job = _read_job(src) + if job is None: + return + job["status"] = "done" + job["result_text"] = result + job["completed_at"] = datetime.now(timezone.utc).isoformat() + dst = _job_path(job_id, "done") + if os.path.exists(src): + os.remove(src) + _write_job(dst, job) + + +def fail(job_id: str, error: str) -> None: + """Mark a job as failed with error message.""" + src = _job_path(job_id, "processing") + job = _read_job(src) + if job is None: + return + job["status"] = "failed" + job["error_message"] = error + job["completed_at"] = datetime.now(timezone.utc).isoformat() + dst = _job_path(job_id, "failed") + if os.path.exists(src): + os.remove(src) + _write_job(dst, job) + + +def get_status(job_id: str) -> dict | None: + """Check all directories for a job and return its data.""" + for subdir in ("pending", "processing", "done", "failed"): + job = _read_job(_job_path(job_id, subdir)) + if job is not None: + return job + return None + + +def get_jobs_for_note(note_id: str) -> list[dict]: + """Return all completed OCR jobs for a given note_id.""" + results = [] + for subdir in ("done", "pending", "processing", "failed"): + dir_path = _queue_dir(subdir) + try: + for fname in os.listdir(dir_path): + if not fname.endswith(".json"): + continue + job = _read_job(os.path.join(dir_path, fname)) + if job and job.get("note_id") == note_id: + results.append(job) + except FileNotFoundError: + pass + return results + + +def get_jobs_for_document(document_id: str) -> list[dict]: + """Return all OCR jobs for a given document_id.""" + results = [] + for subdir in ("done", "pending", "processing", "failed"): + dir_path = _queue_dir(subdir) + try: + for fname in os.listdir(dir_path): + if not fname.endswith(".json"): + continue + job = _read_job(os.path.join(dir_path, fname)) + if job and job.get("document_id") == document_id: + results.append(job) + except FileNotFoundError: + pass + return results diff --git a/server/badnote_server/ocr/worker.py b/server/badnote_server/ocr/worker.py new file mode 100644 index 0000000..27ff551 --- /dev/null +++ b/server/badnote_server/ocr/worker.py @@ -0,0 +1,69 @@ +"""Background OCR worker for BadNote. + +Polls the file-based queue and processes jobs using the OcrEngine. +""" + +import asyncio +import logging +import os + +from ..config import settings +from .engine import OcrEngine +from . import queue as job_queue + +logger = logging.getLogger(__name__) + + +async def run_worker(poll_interval: int = 5) -> None: + """Poll the queue and process OCR jobs. + + Loads images from the job's image_path and runs them through EasyOCR. + """ + # Ensure queue dirs exist + for subdir in ("pending", "processing", "done", "failed"): + os.makedirs(os.path.join(settings.queue_path, subdir), exist_ok=True) + + engine = OcrEngine() + logger.info("OCR worker started (poll_interval=%ds)", poll_interval) + + while True: + job = job_queue.dequeue() + if job is not None: + job_id = job["id"] + logger.info("Processing OCR job %s", job_id) + try: + # Read image from the path specified in the job + image_path = job.get("image_path", "") + if image_path and os.path.exists(image_path): + result = await engine.recognize_file(image_path) + else: + # Fall back to image_bytes if provided inline + image_bytes = job.get("image_bytes", b"") + if isinstance(image_bytes, str): + import base64 + image_bytes = base64.b64decode(image_bytes) + result = await engine.recognize(image_bytes) + + job_queue.complete(job_id, result) + logger.info("OCR job %s completed: %d chars", job_id, len(result)) + except Exception as exc: + logger.error("OCR job %s failed: %s", job_id, exc) + job_queue.fail(job_id, str(exc)) + else: + await asyncio.sleep(poll_interval) + + +def main() -> None: + """Entry point for `python -m badnote_server.ocr.worker`.""" + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", + ) + try: + asyncio.run(run_worker()) + except KeyboardInterrupt: + logger.info("OCR worker stopped") + + +if __name__ == "__main__": + main() diff --git a/server/badnote_server/routers/__init__.py b/server/badnote_server/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/badnote_server/routers/auth_router.py b/server/badnote_server/routers/auth_router.py new file mode 100644 index 0000000..81e714f --- /dev/null +++ b/server/badnote_server/routers/auth_router.py @@ -0,0 +1,78 @@ +"""Auth router for BadNote.""" + +from datetime import datetime, timezone +from uuid import uuid4 + +from fastapi import APIRouter, Depends, HTTPException, status + +from ..auth import ( + create_access_token, + dummy_verify, + get_current_user, + hash_password, + verify_password, +) +from ..database import get_db +from ..models import TokenResponse, UserCreate, UserLogin + +router = APIRouter() + + +@router.post("/register", response_model=TokenResponse, status_code=status.HTTP_201_CREATED) +async def register(body: UserCreate) -> TokenResponse: + """Register a new user.""" + db = await get_db() + existing = await db.execute( + "SELECT id FROM users WHERE username = ?", (body.username,) + ) + if await existing.fetchone() is not None: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Username already taken", + ) + + user_id = str(uuid4()) + now = datetime.now(timezone.utc).isoformat() + await db.execute( + "INSERT INTO users (id, username, password_hash, created_at) VALUES (?, ?, ?, ?)", + (user_id, body.username, hash_password(body.password), now), + ) + await db.commit() + + token = create_access_token(user_id) + return TokenResponse(token=token, user_id=user_id) + + +@router.post("/login", response_model=TokenResponse) +async def login(body: UserLogin) -> TokenResponse: + """Authenticate and return a token.""" + db = await get_db() + row = await ( + await db.execute( + "SELECT id, password_hash FROM users WHERE username = ?", (body.username,) + ) + ).fetchone() + + if row is None: + # Spend comparable time hashing so timing does not reveal whether the + # username exists. + dummy_verify() + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid username or password", + ) + if not verify_password(body.password, row["password_hash"]): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid username or password", + ) + + token = create_access_token(row["id"]) + return TokenResponse(token=token, user_id=row["id"]) + + +@router.post("/refresh", response_model=TokenResponse) +async def refresh(user_id: str = Depends(get_current_user)) -> TokenResponse: + """Refresh an existing valid token.""" + token = create_access_token(user_id) + return TokenResponse(token=token, user_id=user_id) diff --git a/server/badnote_server/routers/documents_router.py b/server/badnote_server/routers/documents_router.py new file mode 100644 index 0000000..1c76cb4 --- /dev/null +++ b/server/badnote_server/routers/documents_router.py @@ -0,0 +1,310 @@ +"""Documents router for BadNote — upload, download, annotations, bookmarks.""" + +import json +from datetime import datetime, timezone +from uuid import uuid4 + +from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, status +from fastapi.responses import FileResponse + +from ..auth import get_current_user +from ..database import get_db +from ..models import ( + AnnotationResponse, + AnnotationUpdate, + BookmarkCreate, + BookmarkResponse, + DocumentResponse, +) +from ..storage import delete_document, get_document_path, save_document + +router = APIRouter() + + +def _row_to_doc(row) -> DocumentResponse: + return DocumentResponse( + id=row["id"], + user_id=row["user_id"], + filename=row["filename"], + doc_type=row["doc_type"], + page_count=row["page_count"], + created_at=row["created_at"], + updated_at=row["updated_at"], + ) + + +# ── Documents ─────────────────────────────────────────────────────────────── + + +@router.post("/upload", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED) +async def upload_document( + file: UploadFile = File(...), + doc_type: str = Form("pdf"), + page_count: int = Form(0), + user_id: str = Depends(get_current_user), +) -> DocumentResponse: + """Upload a document file.""" + doc_id = str(uuid4()) + now = datetime.now(timezone.utc).isoformat() + filename = file.filename or "document" + file_bytes = await file.read() + file_path = save_document(file_bytes, doc_id, filename) + + db = await get_db() + await db.execute( + """INSERT INTO documents (id, user_id, filename, doc_type, file_path, page_count, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + (doc_id, user_id, filename, doc_type, file_path, page_count, now, now), + ) + await db.commit() + + cursor = await db.execute("SELECT * FROM documents WHERE id = ?", (doc_id,)) + row = await cursor.fetchone() + return _row_to_doc(row) + + +@router.get("", response_model=list[DocumentResponse]) +async def list_documents( + user_id: str = Depends(get_current_user), +) -> list[DocumentResponse]: + """List all documents for the current user.""" + db = await get_db() + cursor = await db.execute( + "SELECT * FROM documents WHERE user_id = ? ORDER BY created_at DESC", + (user_id,), + ) + rows = await cursor.fetchall() + return [_row_to_doc(r) for r in rows] + + +@router.get("/{doc_id}", response_model=DocumentResponse) +async def get_document( + doc_id: str, + user_id: str = Depends(get_current_user), +) -> DocumentResponse: + """Get document metadata.""" + db = await get_db() + cursor = await db.execute( + "SELECT * FROM documents WHERE id = ? AND user_id = ?", (doc_id, user_id) + ) + row = await cursor.fetchone() + if row is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") + return _row_to_doc(row) + + +@router.get("/{doc_id}/file") +async def download_document( + doc_id: str, + user_id: str = Depends(get_current_user), +) -> FileResponse: + """Stream document file download.""" + db = await get_db() + cursor = await db.execute( + "SELECT * FROM documents WHERE id = ? AND user_id = ?", (doc_id, user_id) + ) + row = await cursor.fetchone() + if row is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") + + file_path = row["file_path"] + return FileResponse(path=file_path, filename=row["filename"], media_type="application/octet-stream") + + +@router.delete("/{doc_id}", status_code=status.HTTP_200_OK) +async def delete_document_endpoint( + doc_id: str, + user_id: str = Depends(get_current_user), +) -> dict: + """Delete document, its file, annotations, and bookmarks.""" + db = await get_db() + cursor = await db.execute( + "SELECT id FROM documents WHERE id = ? AND user_id = ?", (doc_id, user_id) + ) + if await cursor.fetchone() is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") + + delete_document(doc_id) + await db.execute("DELETE FROM documents WHERE id = ?", (doc_id,)) + await db.commit() + return {"deleted": doc_id} + + +# ── Annotations ───────────────────────────────────────────────────────────── + + +@router.get("/{doc_id}/annotations", response_model=list[AnnotationResponse]) +async def list_annotations( + doc_id: str, + user_id: str = Depends(get_current_user), +) -> list[AnnotationResponse]: + """Get all annotations for a document.""" + db = await get_db() + # Verify document ownership + cursor = await db.execute( + "SELECT id FROM documents WHERE id = ? AND user_id = ?", (doc_id, user_id) + ) + if await cursor.fetchone() is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") + + cursor = await db.execute( + "SELECT * FROM annotations WHERE document_id = ? ORDER BY page_number", + (doc_id,), + ) + rows = await cursor.fetchall() + return [ + AnnotationResponse( + id=r["id"], + document_id=r["document_id"], + page_number=r["page_number"], + annotation_json=json.loads(r["annotation_json"]), + created_at=r["created_at"], + updated_at=r["updated_at"], + ) + for r in rows + ] + + +@router.put("/{doc_id}/annotations/{page}", response_model=AnnotationResponse, status_code=status.HTTP_200_OK) +async def update_annotation( + doc_id: str, + page: int, + body: AnnotationUpdate, + user_id: str = Depends(get_current_user), +) -> AnnotationResponse: + """Create or replace annotations for a page.""" + db = await get_db() + cursor = await db.execute( + "SELECT id FROM documents WHERE id = ? AND user_id = ?", (doc_id, user_id) + ) + if await cursor.fetchone() is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") + + now = datetime.now(timezone.utc).isoformat() + annotation_json = json.dumps(body.annotation_json) + + # Check if annotation for this page already exists + cursor = await db.execute( + "SELECT id FROM annotations WHERE document_id = ? AND page_number = ?", + (doc_id, page), + ) + existing = await cursor.fetchone() + + if existing: + ann_id = existing["id"] + await db.execute( + "UPDATE annotations SET annotation_json = ?, updated_at = ? WHERE id = ?", + (annotation_json, now, ann_id), + ) + else: + ann_id = str(uuid4()) + await db.execute( + """INSERT INTO annotations (id, document_id, page_number, annotation_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?)""", + (ann_id, doc_id, page, annotation_json, now, now), + ) + await db.commit() + + cursor = await db.execute("SELECT * FROM annotations WHERE id = ?", (ann_id,)) + row = await cursor.fetchone() + return AnnotationResponse( + id=row["id"], + document_id=row["document_id"], + page_number=row["page_number"], + annotation_json=json.loads(row["annotation_json"]), + created_at=row["created_at"], + updated_at=row["updated_at"], + ) + + +# ── Bookmarks ─────────────────────────────────────────────────────────────── + + +@router.get("/{doc_id}/bookmarks", response_model=list[BookmarkResponse]) +async def list_bookmarks( + doc_id: str, + user_id: str = Depends(get_current_user), +) -> list[BookmarkResponse]: + """Get all bookmarks for a document.""" + db = await get_db() + cursor = await db.execute( + "SELECT id FROM documents WHERE id = ? AND user_id = ?", (doc_id, user_id) + ) + if await cursor.fetchone() is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") + + cursor = await db.execute( + "SELECT * FROM bookmarks WHERE document_id = ? ORDER BY page_number", + (doc_id,), + ) + rows = await cursor.fetchall() + return [ + BookmarkResponse( + id=r["id"], + document_id=r["document_id"], + page_number=r["page_number"], + label=r["label"], + color=r["color"], + created_at=r["created_at"], + ) + for r in rows + ] + + +@router.post("/{doc_id}/bookmarks", response_model=BookmarkResponse, status_code=status.HTTP_201_CREATED) +async def create_bookmark( + doc_id: str, + body: BookmarkCreate, + user_id: str = Depends(get_current_user), +) -> BookmarkResponse: + """Add a bookmark to a document.""" + db = await get_db() + cursor = await db.execute( + "SELECT id FROM documents WHERE id = ? AND user_id = ?", (doc_id, user_id) + ) + if await cursor.fetchone() is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") + + bookmark_id = str(uuid4()) + now = datetime.now(timezone.utc).isoformat() + await db.execute( + """INSERT INTO bookmarks (id, document_id, page_number, label, color, created_at) + VALUES (?, ?, ?, ?, ?, ?)""", + (bookmark_id, doc_id, body.page_number, body.label, body.color, now), + ) + await db.commit() + + return BookmarkResponse( + id=bookmark_id, + document_id=doc_id, + page_number=body.page_number, + label=body.label, + color=body.color, + created_at=now, + ) + + +@router.delete("/{doc_id}/bookmarks/{bookmark_id}", status_code=status.HTTP_200_OK) +async def delete_bookmark( + doc_id: str, + bookmark_id: str, + user_id: str = Depends(get_current_user), +) -> dict: + """Delete a bookmark.""" + db = await get_db() + cursor = await db.execute( + "SELECT id FROM documents WHERE id = ? AND user_id = ?", (doc_id, user_id) + ) + if await cursor.fetchone() is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") + + cursor = await db.execute( + "SELECT id FROM bookmarks WHERE id = ? AND document_id = ?", + (bookmark_id, doc_id), + ) + if await cursor.fetchone() is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Bookmark not found") + + await db.execute("DELETE FROM bookmarks WHERE id = ?", (bookmark_id,)) + await db.commit() + return {"deleted": bookmark_id} diff --git a/server/badnote_server/routers/notes_router.py b/server/badnote_server/routers/notes_router.py new file mode 100644 index 0000000..1af8d00 --- /dev/null +++ b/server/badnote_server/routers/notes_router.py @@ -0,0 +1,117 @@ +"""Notes CRUD router for BadNote.""" + +import json +from datetime import datetime, timezone +from uuid import uuid4 + +from fastapi import APIRouter, Depends, HTTPException, Query, status + +from ..auth import get_current_user +from ..database import get_db +from ..models import NoteCreate, NoteResponse, NoteUpdate + +router = APIRouter() + + +def _row_to_note(row) -> NoteResponse: + return NoteResponse( + id=row["id"], + user_id=row["user_id"], + title=row["title"], + created_at=row["created_at"], + updated_at=row["updated_at"], + tags=json.loads(row["tags"]), + strokes_json=row["strokes_json"], + ) + + +@router.get("", response_model=list[NoteResponse]) +async def list_notes( + since: str | None = Query(None, description="ISO8601 timestamp filter"), + user_id: str = Depends(get_current_user), +) -> list[NoteResponse]: + """List notes, optionally filtered by updated_at > since.""" + db = await get_db() + if since: + cursor = await db.execute( + "SELECT * FROM notes WHERE user_id = ? AND updated_at > ? ORDER BY updated_at", + (user_id, since), + ) + else: + cursor = await db.execute( + "SELECT * FROM notes WHERE user_id = ? ORDER BY updated_at", + (user_id,), + ) + rows = await cursor.fetchall() + return [_row_to_note(r) for r in rows] + + +@router.get("/{note_id}", response_model=NoteResponse) +async def get_note( + note_id: str, + user_id: str = Depends(get_current_user), +) -> NoteResponse: + """Get a single note by ID.""" + db = await get_db() + cursor = await db.execute( + "SELECT * FROM notes WHERE id = ? AND user_id = ?", (note_id, user_id) + ) + row = await cursor.fetchone() + if row is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Note not found") + return _row_to_note(row) + + +@router.post("", response_model=NoteResponse, status_code=status.HTTP_201_CREATED) +async def upsert_note( + body: NoteCreate, + user_id: str = Depends(get_current_user), +) -> NoteResponse: + """Create or update a note (upsert by id).""" + db = await get_db() + now = datetime.now(timezone.utc).isoformat() + tags_json = json.dumps(body.tags) + + existing = await ( + await db.execute( + "SELECT id FROM notes WHERE id = ? AND user_id = ?", (body.id, user_id) + ) + ).fetchone() + + if existing: + await db.execute( + """UPDATE notes SET title = ?, tags = ?, strokes_json = ?, updated_at = ? + WHERE id = ? AND user_id = ?""", + (body.title, tags_json, body.strokes_json, now, body.id, user_id), + ) + else: + await db.execute( + """INSERT INTO notes (id, user_id, title, created_at, updated_at, tags, strokes_json) + VALUES (?, ?, ?, ?, ?, ?, ?)""", + (body.id, user_id, body.title, now, now, tags_json, body.strokes_json), + ) + await db.commit() + + cursor = await db.execute( + "SELECT * FROM notes WHERE id = ? AND user_id = ?", (body.id, user_id) + ) + row = await cursor.fetchone() + return _row_to_note(row) + + +@router.delete("/{note_id}", status_code=status.HTTP_200_OK) +async def delete_note( + note_id: str, + user_id: str = Depends(get_current_user), +) -> dict: + """Delete a note.""" + db = await get_db() + cursor = await db.execute( + "SELECT id FROM notes WHERE id = ? AND user_id = ?", (note_id, user_id) + ) + if await cursor.fetchone() is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Note not found") + + await db.execute("DELETE FROM notes WHERE id = ? AND user_id = ?", (note_id, user_id)) + await db.commit() + return {"deleted": note_id} diff --git a/server/badnote_server/routers/ocr_router.py b/server/badnote_server/routers/ocr_router.py new file mode 100644 index 0000000..72b0365 --- /dev/null +++ b/server/badnote_server/routers/ocr_router.py @@ -0,0 +1,99 @@ +"""OCR router for BadNote.""" + +from fastapi import APIRouter, Depends, HTTPException, status + +from ..auth import get_current_user +from ..database import get_db +from ..models import OcrJobRequest, OcrJobStatus, OcrResult +from ..ocr import queue as job_queue + +router = APIRouter() + + +@router.post("/process", status_code=status.HTTP_201_CREATED) +async def submit_ocr_job( + body: OcrJobRequest, + user_id: str = Depends(get_current_user), +) -> dict: + """Enqueue an OCR job.""" + job_data: dict = { + "user_id": user_id, + "note_id": body.note_id, + "document_id": body.document_id, + "page_number": body.page_number, + } + job_id = job_queue.enqueue(job_data) + return {"job_id": job_id} + + +@router.get("/status/{job_id}", response_model=OcrJobStatus) +async def get_job_status( + job_id: str, + user_id: str = Depends(get_current_user), +) -> OcrJobStatus: + """Get OCR job status and result.""" + job = job_queue.get_status(job_id) + # Treat jobs owned by another user as not found to avoid leaking their data. + if job is None or job.get("user_id") != user_id: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Job not found") + + return OcrJobStatus( + id=job["id"], + status=job["status"], + result_text=job.get("result_text"), + error_message=job.get("error_message"), + created_at=job["created_at"], + completed_at=job.get("completed_at"), + ) + + +@router.get("/results/{note_id}", response_model=list[OcrResult]) +async def get_ocr_results( + note_id: str, + user_id: str = Depends(get_current_user), +) -> list[OcrResult]: + """Get all OCR results for a note.""" + jobs = [ + j for j in job_queue.get_jobs_for_note(note_id) if j.get("user_id") == user_id + ] + return [ + OcrResult( + id=j["id"], + note_id=j.get("note_id"), + document_id=j.get("document_id"), + page_number=j.get("page_number"), + status=j["status"], + result_text=j.get("result_text"), + error_message=j.get("error_message"), + created_at=j["created_at"], + completed_at=j.get("completed_at"), + ) + for j in jobs + ] + + +@router.get("/results/document/{document_id}", response_model=list[OcrResult]) +async def get_document_ocr_results( + document_id: str, + user_id: str = Depends(get_current_user), +) -> list[OcrResult]: + """Get all OCR results for a document.""" + jobs = [ + j + for j in job_queue.get_jobs_for_document(document_id) + if j.get("user_id") == user_id + ] + return [ + OcrResult( + id=j["id"], + note_id=j.get("note_id"), + document_id=j.get("document_id"), + page_number=j.get("page_number"), + status=j["status"], + result_text=j.get("result_text"), + error_message=j.get("error_message"), + created_at=j["created_at"], + completed_at=j.get("completed_at"), + ) + for j in jobs + ] diff --git a/server/badnote_server/routers/sync_router.py b/server/badnote_server/routers/sync_router.py new file mode 100644 index 0000000..6d46a4d --- /dev/null +++ b/server/badnote_server/routers/sync_router.py @@ -0,0 +1,90 @@ +"""Sync router for BadNote — push/pull notes.""" + +import json +from datetime import datetime, timezone +from uuid import uuid4 + +from fastapi import APIRouter, Depends, status + +from ..auth import get_current_user +from ..database import get_db +from ..models import NoteResponse, SyncPullRequest, SyncPushRequest, SyncResponse + +router = APIRouter() + + +@router.post("/push", response_model=SyncResponse, status_code=status.HTTP_200_OK) +async def sync_push( + body: SyncPushRequest, + user_id: str = Depends(get_current_user), +) -> SyncResponse: + """Upsert notes from client.""" + db = await get_db() + synced = 0 + + for note in body.notes: + now = datetime.now(timezone.utc).isoformat() + tags_json = json.dumps(note.tags) + + existing = await ( + await db.execute( + "SELECT id FROM notes WHERE id = ? AND user_id = ?", (note.id, user_id) + ) + ).fetchone() + + if existing: + # Last-writer-wins by timestamp: only apply the client's version if + # it is newer than what the server already has, so a stale client + # cannot overwrite a more recent note (data loss). + await db.execute( + """UPDATE notes SET title = ?, tags = ?, strokes_json = ?, updated_at = ? + WHERE id = ? AND user_id = ? AND updated_at < ?""", + ( + note.title, + tags_json, + note.strokes_json, + note.updated_at, + note.id, + user_id, + note.updated_at, + ), + ) + else: + await db.execute( + """INSERT INTO notes (id, user_id, title, created_at, updated_at, tags, strokes_json) + VALUES (?, ?, ?, ?, ?, ?, ?)""", + (note.id, user_id, note.title, now, note.updated_at, tags_json, note.strokes_json), + ) + synced += 1 + + await db.commit() + return SyncResponse(synced_count=synced) + + +@router.post("/pull", status_code=status.HTTP_200_OK) +async def sync_pull( + body: SyncPullRequest, + user_id: str = Depends(get_current_user), +) -> dict: + """Pull notes updated since a timestamp.""" + db = await get_db() + cursor = await db.execute( + """SELECT * FROM notes WHERE user_id = ? AND updated_at > ? ORDER BY updated_at""", + (user_id, body.since), + ) + rows = await cursor.fetchall() + + notes = [ + NoteResponse( + id=r["id"], + user_id=r["user_id"], + title=r["title"], + created_at=r["created_at"], + updated_at=r["updated_at"], + tags=json.loads(r["tags"]), + strokes_json=r["strokes_json"], + ).model_dump() + for r in rows + ] + + return {"notes": notes} diff --git a/server/badnote_server/storage.py b/server/badnote_server/storage.py new file mode 100644 index 0000000..852a050 --- /dev/null +++ b/server/badnote_server/storage.py @@ -0,0 +1,56 @@ +"""File-system document storage for BadNote.""" + +import os +import shutil + +from .config import settings + + +def _safe_filename(filename: str) -> str: + """Reduce a client-supplied filename to a safe basename. + + Prevents path traversal (e.g. ``../../etc/passwd``) by stripping any + directory components and parent references before the name is joined onto + the storage path. + """ + name = os.path.basename(filename or "") + name = name.replace("\\", "").replace("/", "").strip() + if not name or name in (".", ".."): + name = "document" + return name + + +def _resolve_within(base: str, *parts: str) -> str: + """Join ``parts`` onto ``base`` and ensure the result stays inside ``base``.""" + base_abs = os.path.abspath(base) + target = os.path.abspath(os.path.join(base_abs, *parts)) + if os.path.commonpath([base_abs, target]) != base_abs: + raise ValueError("Resolved path escapes the storage directory") + return target + + +def save_document(file_bytes: bytes, doc_id: str, filename: str) -> str: + """Save uploaded file bytes to storage. Returns the stored file path.""" + safe_doc_id = _safe_filename(doc_id) + safe_name = _safe_filename(filename) + doc_dir = _resolve_within(settings.storage_path, safe_doc_id) + os.makedirs(doc_dir, exist_ok=True) + file_path = _resolve_within(doc_dir, safe_name) + with open(file_path, "wb") as f: + f.write(file_bytes) + return file_path + + +def get_document_path(doc_id: str, filename: str) -> str: + """Return the full path to a stored document file.""" + safe_doc_id = _safe_filename(doc_id) + safe_name = _safe_filename(filename) + return _resolve_within(settings.storage_path, safe_doc_id, safe_name) + + +def delete_document(doc_id: str) -> None: + """Remove a document's directory and all its contents.""" + safe_doc_id = _safe_filename(doc_id) + doc_dir = _resolve_within(settings.storage_path, safe_doc_id) + if os.path.isdir(doc_dir): + shutil.rmtree(doc_dir) diff --git a/server/requirements-ocr.txt b/server/requirements-ocr.txt new file mode 100644 index 0000000..e77219e --- /dev/null +++ b/server/requirements-ocr.txt @@ -0,0 +1,8 @@ +# Optional OCR worker dependencies. Heavy (pulls in torch). Only required to +# run `python -m badnote_server.ocr.worker`. The API server and tests do not +# need these. +-r requirements.txt + +easyocr>=1.7.0 +opencv-python-headless>=4.10.0 +Pillow>=10.0.0 diff --git a/server/requirements.txt b/server/requirements.txt new file mode 100644 index 0000000..f209383 --- /dev/null +++ b/server/requirements.txt @@ -0,0 +1,17 @@ +fastapi>=0.115.0 +uvicorn[standard]>=0.34.0 +pydantic>=2.10.0 +python-jose[cryptography]>=3.3.0 +passlib[bcrypt]>=1.7.4 +aiosqlite>=0.21.0 +python-multipart>=0.0.20 +aiofiles>=24.0.0 +httpx>=0.28.0 + +# Testing +pytest>=8.0.0 +pytest-asyncio>=0.25.0 + +# OCR dependencies (easyocr, opencv, torch) are heavy and optional. They are +# only needed to run the background OCR worker, not the API server or its tests. +# Install them with: pip install -r requirements-ocr.txt diff --git a/server/scripts/run.sh b/server/scripts/run.sh new file mode 100755 index 0000000..2a96d57 --- /dev/null +++ b/server/scripts/run.sh @@ -0,0 +1,4 @@ +#!/bin/bash +cd "$(dirname "$0")/.." +source .venv/bin/activate 2>/dev/null || { echo "Run setup.sh first"; exit 1; } +uvicorn badnote_server.main:app --host 0.0.0.0 --port 8080 --workers 1 diff --git a/server/scripts/setup.sh b/server/scripts/setup.sh new file mode 100755 index 0000000..5037fff --- /dev/null +++ b/server/scripts/setup.sh @@ -0,0 +1,10 @@ +#!/bin/bash +set -e +cd "$(dirname "$0")/.." +python3 -m venv .venv +source .venv/bin/activate +pip install -r requirements.txt +mkdir -p data/storage data/queue/pending data/queue/processing data/queue/done data/queue/failed +echo "BadNote server setup complete." +echo "Run: source .venv/bin/activate && uvicorn badnote_server.main:app --reload" +echo "To run the OCR worker, also install OCR deps: pip install -r requirements-ocr.txt" diff --git a/server/scripts/worker.sh b/server/scripts/worker.sh new file mode 100755 index 0000000..f1199f1 --- /dev/null +++ b/server/scripts/worker.sh @@ -0,0 +1,4 @@ +#!/bin/bash +cd "$(dirname "$0")/.." +source .venv/bin/activate 2>/dev/null || { echo "Run setup.sh first"; exit 1; } +nice -n 10 python -m badnote_server.ocr.worker diff --git a/server/tests/__init__.py b/server/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/tests/conftest.py b/server/tests/conftest.py new file mode 100644 index 0000000..0ddb46a --- /dev/null +++ b/server/tests/conftest.py @@ -0,0 +1,43 @@ +"""Shared test fixtures for BadNote tests.""" + +import os +import shutil +import sys +import tempfile + +import pytest +import pytest_asyncio +from httpx import ASGITransport, AsyncClient + +# Ensure the server package is importable +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) + +os.environ["BADNOTE_STORAGE_PATH"] = "/tmp/badnote_test_storage" +os.environ["BADNOTE_QUEUE_PATH"] = "/tmp/badnote_test_queue" +os.environ["BADNOTE_JWT_SECRET"] = "test-secret-key-for-testing-only" + +from badnote_server.config import settings # noqa: E402 +from badnote_server.main import app # noqa: E402 +from badnote_server.database import get_db, close_db, init_db # noqa: E402 + + +@pytest_asyncio.fixture(autouse=True) +async def setup_db(tmp_path): + """Fresh DB and clean queue for each test.""" + db_path = str(tmp_path / "test.db") + settings.db_path = db_path + # Clean the queue directory before each test + queue_path = settings.queue_path + if os.path.exists(queue_path): + shutil.rmtree(queue_path) + await init_db() + yield + await close_db() + + +@pytest_asyncio.fixture +async def client(): + """Async test client for the FastAPI app.""" + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as ac: + yield ac diff --git a/server/tests/helpers.py b/server/tests/helpers.py new file mode 100644 index 0000000..6b9b30a --- /dev/null +++ b/server/tests/helpers.py @@ -0,0 +1,18 @@ +"""Shared test helpers for BadNote tests.""" + +from httpx import AsyncClient + + +async def register_and_login(client: AsyncClient) -> tuple[str, str]: + """Helper: register a user and return (token, user_id).""" + resp = await client.post( + "/api/auth/register", + json={"username": "testuser", "password": "testpass123"}, + ) + data = resp.json() + return data["token"], data["user_id"] + + +def auth_header(token: str) -> dict: + """Return Authorization header dict.""" + return {"Authorization": f"Bearer {token}"} diff --git a/server/tests/test_auth.py b/server/tests/test_auth.py new file mode 100644 index 0000000..637fd91 --- /dev/null +++ b/server/tests/test_auth.py @@ -0,0 +1,82 @@ +"""Tests for auth endpoints.""" + +import sys, os +sys.path.insert(0, os.path.dirname(__file__)) + +import pytest +import pytest_asyncio +from httpx import AsyncClient +from helpers import auth_header, register_and_login + + +@pytest.mark.asyncio +async def test_register(client: AsyncClient): + resp = await client.post( + "/api/auth/register", + json={"username": "newuser", "password": "password123"}, + ) + assert resp.status_code == 201 + data = resp.json() + assert "token" in data + assert "user_id" in data + + +@pytest.mark.asyncio +async def test_register_duplicate(client: AsyncClient): + await client.post( + "/api/auth/register", + json={"username": "dupuser", "password": "password123"}, + ) + resp = await client.post( + "/api/auth/register", + json={"username": "dupuser", "password": "password123"}, + ) + assert resp.status_code == 409 + + +@pytest.mark.asyncio +async def test_login(client: AsyncClient): + await client.post( + "/api/auth/register", + json={"username": "loginuser", "password": "mypassword"}, + ) + resp = await client.post( + "/api/auth/login", + json={"username": "loginuser", "password": "mypassword"}, + ) + assert resp.status_code == 200 + data = resp.json() + assert "token" in data + assert "user_id" in data + + +@pytest.mark.asyncio +async def test_login_wrong_password(client: AsyncClient): + await client.post( + "/api/auth/register", + json={"username": "wrongpw", "password": "correct"}, + ) + resp = await client.post( + "/api/auth/login", + json={"username": "wrongpw", "password": "incorrect"}, + ) + assert resp.status_code == 401 + + +@pytest.mark.asyncio +async def test_refresh(client: AsyncClient): + token, user_id = await register_and_login(client) + resp = await client.post( + "/api/auth/refresh", + headers=auth_header(token), + ) + assert resp.status_code == 200 + data = resp.json() + assert "token" in data + assert data["user_id"] == user_id + + +@pytest.mark.asyncio +async def test_refresh_no_token(client: AsyncClient): + resp = await client.post("/api/auth/refresh") + assert resp.status_code in (401, 403) diff --git a/server/tests/test_notes.py b/server/tests/test_notes.py new file mode 100644 index 0000000..57c603f --- /dev/null +++ b/server/tests/test_notes.py @@ -0,0 +1,146 @@ +"""Tests for notes CRUD and sync endpoints.""" + +import sys, os +sys.path.insert(0, os.path.dirname(__file__)) + +import pytest +import pytest_asyncio +from httpx import AsyncClient +from helpers import auth_header, register_and_login + + +@pytest.mark.asyncio +async def test_create_note(client: AsyncClient): + token, _ = await register_and_login(client) + resp = await client.post( + "/api/notes", + json={ + "id": "note-001", + "title": "Test Note", + "tags": ["tag1", "tag2"], + "strokes_json": "[{\"x\":1,\"y\":2}]", + }, + headers=auth_header(token), + ) + assert resp.status_code == 201 + data = resp.json() + assert data["id"] == "note-001" + assert data["title"] == "Test Note" + assert data["tags"] == ["tag1", "tag2"] + + +@pytest.mark.asyncio +async def test_get_note(client: AsyncClient): + token, _ = await register_and_login(client) + await client.post( + "/api/notes", + json={"id": "note-002", "title": "Fetch Me", "tags": [], "strokes_json": "[]"}, + headers=auth_header(token), + ) + resp = await client.get("/api/notes/note-002", headers=auth_header(token)) + assert resp.status_code == 200 + assert resp.json()["title"] == "Fetch Me" + + +@pytest.mark.asyncio +async def test_get_note_not_found(client: AsyncClient): + token, _ = await register_and_login(client) + resp = await client.get("/api/notes/nonexistent", headers=auth_header(token)) + assert resp.status_code == 404 + + +@pytest.mark.asyncio +async def test_update_note(client: AsyncClient): + token, _ = await register_and_login(client) + await client.post( + "/api/notes", + json={"id": "note-003", "title": "Original", "tags": [], "strokes_json": "[]"}, + headers=auth_header(token), + ) + resp = await client.post( + "/api/notes", + json={"id": "note-003", "title": "Updated", "tags": ["new"], "strokes_json": "[1]"}, + headers=auth_header(token), + ) + assert resp.status_code == 201 + assert resp.json()["title"] == "Updated" + assert resp.json()["tags"] == ["new"] + + +@pytest.mark.asyncio +async def test_delete_note(client: AsyncClient): + token, _ = await register_and_login(client) + await client.post( + "/api/notes", + json={"id": "note-004", "title": "Delete Me", "tags": [], "strokes_json": "[]"}, + headers=auth_header(token), + ) + resp = await client.delete("/api/notes/note-004", headers=auth_header(token)) + assert resp.status_code == 200 + resp = await client.get("/api/notes/note-004", headers=auth_header(token)) + assert resp.status_code == 404 + + +@pytest.mark.asyncio +async def test_list_notes_with_since(client: AsyncClient): + token, _ = await register_and_login(client) + await client.post( + "/api/notes", + json={"id": "note-005", "title": "Old", "tags": [], "strokes_json": "[]"}, + headers=auth_header(token), + ) + resp = await client.get("/api/notes", headers=auth_header(token)) + assert resp.status_code == 200 + assert len(resp.json()) >= 1 + + resp = await client.get( + "/api/notes?since=2099-01-01T00:00:00+00:00", + headers=auth_header(token), + ) + assert resp.status_code == 200 + assert len(resp.json()) == 0 + + +@pytest.mark.asyncio +async def test_notes_require_auth(client: AsyncClient): + resp = await client.get("/api/notes") + assert resp.status_code in (401, 403) + + +# ── Sync ──────────────────────────────────────────────────────────────────── + + +@pytest.mark.asyncio +async def test_sync_push(client: AsyncClient): + token, _ = await register_and_login(client) + resp = await client.post( + "/api/sync/push", + json={ + "notes": [ + {"id": "sync-1", "title": "Synced", "tags": [], "strokes_json": "[]", "updated_at": "2024-01-01T00:00:00+00:00"}, + {"id": "sync-2", "title": "Also", "tags": ["t"], "strokes_json": "[]", "updated_at": "2024-01-02T00:00:00+00:00"}, + ] + }, + headers=auth_header(token), + ) + assert resp.status_code == 200 + assert resp.json()["synced_count"] == 2 + + +@pytest.mark.asyncio +async def test_sync_pull(client: AsyncClient): + token, _ = await register_and_login(client) + await client.post( + "/api/sync/push", + json={"notes": [{"id": "pull-1", "title": "Pull Me", "tags": [], "strokes_json": "[]", "updated_at": "2024-06-01T00:00:00+00:00"}]}, + headers=auth_header(token), + ) + resp = await client.post( + "/api/sync/pull", + json={"since": "2024-01-01T00:00:00+00:00"}, + headers=auth_header(token), + ) + assert resp.status_code == 200 + notes = resp.json()["notes"] + assert len(notes) >= 1 + assert any(n["id"] == "pull-1" for n in notes) diff --git a/server/tests/test_ocr.py b/server/tests/test_ocr.py new file mode 100644 index 0000000..b225ec0 --- /dev/null +++ b/server/tests/test_ocr.py @@ -0,0 +1,82 @@ +"""Tests for OCR endpoints.""" + +import sys, os +sys.path.insert(0, os.path.dirname(__file__)) + +import pytest +import pytest_asyncio +from httpx import AsyncClient +from helpers import auth_header, register_and_login + + +@pytest.mark.asyncio +async def test_submit_ocr_job(client: AsyncClient): + token, _ = await register_and_login(client) + resp = await client.post( + "/api/ocr/process", + json={"note_id": "note-ocr-1", "document_id": None, "page_number": None}, + headers=auth_header(token), + ) + assert resp.status_code == 201 + data = resp.json() + assert "job_id" in data + + +@pytest.mark.asyncio +async def test_get_job_status(client: AsyncClient): + token, _ = await register_and_login(client) + resp = await client.post( + "/api/ocr/process", + json={"note_id": "note-ocr-2", "document_id": None, "page_number": None}, + headers=auth_header(token), + ) + job_id = resp.json()["job_id"] + + resp = await client.get(f"/api/ocr/status/{job_id}", headers=auth_header(token)) + assert resp.status_code == 200 + data = resp.json() + assert data["id"] == job_id + assert data["status"] == "pending" + + +@pytest.mark.asyncio +async def test_get_job_status_not_found(client: AsyncClient): + token, _ = await register_and_login(client) + resp = await client.get("/api/ocr/status/nonexistent", headers=auth_header(token)) + assert resp.status_code == 404 + + +@pytest.mark.asyncio +async def test_get_ocr_results_empty(client: AsyncClient): + token, _ = await register_and_login(client) + resp = await client.get("/api/ocr/results/note-no-jobs", headers=auth_header(token)) + assert resp.status_code == 200 + assert resp.json() == [] + + +@pytest.mark.asyncio +async def test_get_ocr_results_with_jobs(client: AsyncClient): + token, _ = await register_and_login(client) + await client.post( + "/api/ocr/process", + json={"note_id": "note-ocr-3", "document_id": None, "page_number": None}, + headers=auth_header(token), + ) + await client.post( + "/api/ocr/process", + json={"note_id": "note-ocr-3", "document_id": None, "page_number": None}, + headers=auth_header(token), + ) + + resp = await client.get("/api/ocr/results/note-ocr-3", headers=auth_header(token)) + assert resp.status_code == 200 + assert len(resp.json()) == 2 + + +@pytest.mark.asyncio +async def test_ocr_requires_auth(client: AsyncClient): + resp = await client.post( + "/api/ocr/process", + json={"note_id": "x", "document_id": None, "page_number": None}, + ) + assert resp.status_code in (401, 403) diff --git a/test/undo_manager_test.dart b/test/undo_manager_test.dart new file mode 100644 index 0000000..dc353c6 --- /dev/null +++ b/test/undo_manager_test.dart @@ -0,0 +1,79 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:badnote/models/ink_point.dart'; +import 'package:badnote/models/ink_stroke.dart'; +import 'package:badnote/models/pen_tool.dart'; +import 'package:badnote/services/undo_manager.dart'; + +InkStroke _stroke(String id) => InkStroke( + id: id, + points: const [ + InkPoint(x: 0, y: 0, pressure: 0.5, tilt: 0, timestamp: 0), + InkPoint(x: 1, y: 1, pressure: 0.5, tilt: 0, timestamp: 1), + ], + tool: PenTool.pen, + createdAt: DateTime(2024, 1, 1), +); + +void main() { + group('UndoManager', () { + test('starts empty with no undo/redo available', () { + final m = UndoManager(); + expect(m.currentStrokes, isEmpty); + expect(m.canUndo, isFalse); + expect(m.canRedo, isFalse); + }); + + test('addStroke then undo/redo round-trips the stroke', () { + final m = UndoManager(); + final s = _stroke('a'); + + m.addStroke(s); + expect(m.currentStrokes.map((e) => e.id), ['a']); + expect(m.canUndo, isTrue); + + m.undo(); + expect(m.currentStrokes, isEmpty); + expect(m.canRedo, isTrue); + + m.redo(); + expect(m.currentStrokes.map((e) => e.id), ['a']); + }); + + test('a new stroke clears the redo stack', () { + final m = UndoManager(); + m.addStroke(_stroke('a')); + m.undo(); + expect(m.canRedo, isTrue); + + m.addStroke(_stroke('b')); + expect(m.canRedo, isFalse); + expect(m.currentStrokes.map((e) => e.id), ['b']); + }); + + test('removeStroke with replacements (partial erase) is reversible', () { + final m = UndoManager(); + m.addStroke(_stroke('whole')); + + m.removeStroke( + _stroke('whole'), + replacements: [_stroke('part1'), _stroke('part2')], + ); + expect(m.currentStrokes.map((e) => e.id), ['part1', 'part2']); + + // Undo restores the original and drops the replacements. + m.undo(); + expect(m.currentStrokes.map((e) => e.id), ['whole']); + + // Redo re-applies the erase. + m.redo(); + expect(m.currentStrokes.map((e) => e.id), ['part1', 'part2']); + }); + + test('currentStrokes is an unmodifiable view', () { + final m = UndoManager(); + m.addStroke(_stroke('a')); + expect(() => m.currentStrokes.add(_stroke('b')), throwsUnsupportedError); + }); + }); +} diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..dc3c96d --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,27 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:badnote/screens/home_screen.dart'; + +void main() { + testWidgets('Home screen renders its app bar title', ( + WidgetTester tester, + ) async { + // The note list is backed by the on-device database, which is not + // available in the widget-test environment; the body therefore shows a + // loading/error state. The app-bar chrome renders regardless, so we assert + // on that. The home screen must be wrapped in a ProviderScope, which the + // app's real entrypoint (main.dart) provides. + SharedPreferences.setMockInitialValues({}); + + await tester.pumpWidget( + const ProviderScope(child: MaterialApp(home: HomeScreen())), + ); + await tester.pump(); + + expect(find.text('BadNote'), findsOneWidget); + expect(find.byTooltip('Search'), findsOneWidget); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..dba9df7 --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + badnote + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..d3b78ec --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "badnote", + "short_name": "badnote", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..02abe40 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(badnote 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 "badnote") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..779f0ee --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,20 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); + SyncfusionPdfviewerWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("SyncfusionPdfviewerWindowsPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e6e95f --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,27 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_windows + syncfusion_pdfviewer_windows + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..727ff1e --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,42 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "ocr_channel.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib" "windowsapp.lib") +target_compile_options(${BINARY_NAME} PRIVATE /await) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..a3ab879 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.badnote" "\0" + VALUE "FileDescription", "badnote" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "badnote" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.badnote. All rights reserved." "\0" + VALUE "OriginalFilename", "badnote.exe" "\0" + VALUE "ProductName", "badnote" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..795370a --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,73 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" +#include "ocr_channel.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + RegisterOcrChannel(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..4accad6 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"badnote", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/ocr_channel.cpp b/windows/runner/ocr_channel.cpp new file mode 100644 index 0000000..1e7b2a5 --- /dev/null +++ b/windows/runner/ocr_channel.cpp @@ -0,0 +1,103 @@ +#include "ocr_channel.h" + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +std::vector ExtractBytes(const flutter::EncodableValue& value) { + if (const auto* bytes = std::get_if>(&value)) { + return *bytes; + } + if (const auto* list = std::get_if(&value)) { + std::vector out; + out.reserve(list->size()); + for (const auto& item : *list) { + if (const auto* i = std::get_if(&item)) { + out.push_back(static_cast(*i)); + } + } + return out; + } + return {}; +} + +std::string RecognizePng(const std::vector& bytes) { + if (bytes.empty()) { + return {}; + } + + using namespace winrt; + using namespace Windows::Storage::Streams; + using namespace Windows::Graphics::Imaging; + using namespace Windows::Media::Ocr; + + InMemoryRandomAccessStream stream; + { + DataWriter writer{stream}; + writer.WriteBytes(bytes); + writer.StoreAsync().get(); + writer.DetachStream(); + } + stream.Seek(0); + + BitmapDecoder decoder = BitmapDecoder::CreateAsync(stream).get(); + SoftwareBitmap bitmap = decoder.GetSoftwareBitmapAsync().get(); + + OcrEngine engine = OcrEngine::TryCreateFromUserProfileLanguages(); + if (!engine) { + return {}; + } + + OcrResult result = engine.RecognizeAsync(bitmap).get(); + return winrt::to_string(result.Text()); +} + +std::unique_ptr> g_ocr_channel; + +} // namespace + +void RegisterOcrChannel(flutter::FlutterEngine* engine) { + winrt::init_apartment(); + + g_ocr_channel = + std::make_unique>( + engine->messenger(), "badnote/ocr", + &flutter::StandardMethodCodec::GetInstance()); + + g_ocr_channel->SetMethodCallHandler( + [](const flutter::MethodCall& call, + std::unique_ptr> + result) { + if (call.method_name() != "recognize") { + result->NotImplemented(); + return; + } + + if (!call.arguments()) { + result->Error("invalid_args", "Expected PNG byte data"); + return; + } + + try { + const auto png_bytes = ExtractBytes(*call.arguments()); + const auto text = RecognizePng(png_bytes); + result->Success(flutter::EncodableValue(text)); + } catch (const winrt::hresult_error& error) { + result->Error("ocr_failed", winrt::to_string(error.message())); + } catch (...) { + result->Error("ocr_failed", "Unknown OCR error"); + } + }); +} diff --git a/windows/runner/ocr_channel.h b/windows/runner/ocr_channel.h new file mode 100644 index 0000000..6eaed47 --- /dev/null +++ b/windows/runner/ocr_channel.h @@ -0,0 +1,10 @@ +#ifndef RUNNER_OCR_CHANNEL_H_ +#define RUNNER_OCR_CHANNEL_H_ + +namespace flutter { +class FlutterEngine; +} + +void RegisterOcrChannel(flutter::FlutterEngine* engine); + +#endif // RUNNER_OCR_CHANNEL_H_ diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_