commit 9bb0ff9187bade450d5d101889a4781031982c9b Author: foxyz Date: Wed Sep 2 21:58:54 2026 +0300 initial commit: LeafViewer, LeafZoomable, LeafContextMenu, LeafPopover, LeafImage, misc widgets + tests diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b415f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..e7bada2 --- /dev/null +++ b/.metadata @@ -0,0 +1,10 @@ +# 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: "9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c" + channel: "beta" + +project_type: package diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..2afa72f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,120 @@ +# AGENTS.md — leaf_widgets + +## Overview + +Reusable Flutter UI widgets with **zero external dependencies** (pure `flutter`). Extracted from the Kemono Browser app (`S:\G_drive_backup\.Projects\SoyDev\Flutter\kemono_browser_project`) — that repo's AGENTS.md has the app-side context, and its `docs/photo-view-evaluation.md` is the **design bible** for the viewer: findings 1–12 from a photo_view feel-test, locked decisions in §6, and the package-extraction rationale in §6.1. Read it before touching the viewer. + +Current contents: + +| Widget | File | Notes | +|--------|------|-------| +| `LeafViewer` | `lib/src/viewer/leaf_viewer.dart` | Fullscreen pager: per-page zoom, edge-release, dismiss, desktop controls | +| `LeafZoomable` | `lib/src/viewer/leaf_zoomable.dart` | Per-page opt-in zoom wrapper (pages without it: paging + dismiss only) | +| `LeafZoomController` | `lib/src/viewer/leaf_zoom_controller.dart` | Pure math + animation state, `ChangeNotifier` | +| `LeafPanZoomRecognizer` | `lib/src/viewer/leaf_pan_zoom_recognizer.dart` | Arena pan/zoom recognizer (photo_view port) | +| `LeafViewerScope`/`LeafPageIndexScope`/`LeafViewerRegistry` | `lib/src/viewer/leaf_viewer_internal.dart` | Internal plumbing, **not** exported from the barrel | +| `LeafContextMenu` | `lib/src/context_menu/leaf_context_menu.dart` | Right-click / long-press menu | +| `LeafPopover` | `lib/src/popover/leaf_popover.dart` | Anchored overlay popover | +| `LeafImage` | `lib/src/image/leaf_image.dart` | Image widget: reveal animations, skeleton, retry | +| `AnimatedFavoriteButton` / `AnimatedStar` | `lib/src/misc/` | Async-aware heart toggle / spinning star | + +## Commands + +```bash +flutter analyze # package must stay at zero issues +flutter test # full suite +flutter test test/viewer # viewer subset (controller + widget tests) +cd example && flutter run -d windows # feel-test harness (gallery + 3-image viewer demo) +cd example && flutter test +``` + +Convention: analyze + test on every change to the package (unlike the app, the package is small and the loop is cheap). No commit unless asked. + +## LeafViewer API + +```dart +LeafViewer( + pageCount, pageBuilder, + pageController?, initialPage, scrollDirection, + onPageChanged, // external page-change notification + dismissEnabled, onDismissed, // onDismissed == null → Navigator.maybePop(context) + onTapOutside, // quick tap outside the active image at 1× + backgroundBuilder, // (context, dismissProgress) → backdrop layer + controlsBuilder, // media_kit-style chrome slot + enableSwipeGestures, // null = platform default; true = phone emulation anywhere +) +``` + +`controlsBuilder(context, LeafViewerControls)` receives `pageCount`, `currentIndex`, `canGoPrevious/Next`, `goToPage(index)` (animated). When null: a default control set (prev/next chevrons, close, counter) renders **on desktop only**. + +`LeafZoomable(child, childSize, originalSize?, maxScale, enabled)` — `childSize` is the contained (fit-to-screen) size, `originalSize` enables the 1:1 double-tap step. `enabled: false` renders content without zoom (until an image loads). + +## Gesture architecture (how it works and why) + +**The arbitration lives in the gesture arena — never in ScrollPhysics.** `Scrollable.setCanDrag` **removes the drag recognizer entirely** when physics is `NeverScrollableScrollPhysics` (`scrollable.dart`, `_gestureRecognizers = {}`), so a PageView with locked physics never tracks the in-flight pointer. Mid-drag physics unlocking is therefore impossible. Do not reintroduce physics-locking for paging control. + +The flow: + +1. Each `LeafZoomable` registers a `LeafPanZoomRecognizer` (extends `ScaleGestureRecognizer`, ported from photo_view's `PhotoViewGestureRecognizer`). On the **first non-zero move** it resolves immediately: + - `controller.shouldClaim(fingerDelta)` (`shouldMoveX || shouldMoveY` — the LoliSnatcher `Axis.values` port) → `acceptGesture` → pan/pinch callbacks drive the controller + - otherwise → `resolve(rejected)` → the arena hands the gesture to the PageView's drag (horizontal) or the viewer's dismiss drag (perpendicular) — **this is the edge-release behaviour**: a drag starting at a fully clamped position pages/dismisses instead of panning +2. `shouldClaim` is false at 1× (the child fits → `HitCorners(true,true)` → blocked), so at 1× every drag goes to the pager/dismiss. +3. Dismiss is viewer-level (LoliSnatcher pattern): the whole PageView translates + scales, the backdrop fades with progress. Thresholds: velocity > 800 px/s **or** offset > 25% of the perpendicular extent → fly-off to `dir * extent * 1.5` (200 ms easeIn) → `onDismissed ?? Navigator.maybePop`; otherwise spring back (`SpringDescription(mass 1, stiffness 600, damping 50)`). Progress = `|offset| / (extent * 0.5)`. +4. Wheel zooms from **any** scale (user decision: no wheel-paging), cursor-anchored: `scale * (1 - scrollDy * 0.001)` clamped `[1, maxScale]`. +5. Once a pan is claimed it stays claimed (sticky) — mid-drag clamp→page transitions do **not** exist (same as photo_view; they never existed in the app either). + +### Desktop mode + +Windows/Linux/macOS (auto-detected, `leafIsDesktopPlatform()`): no mouse drag paging, no drag dismiss, no double-tap — the wheel zooms, the default controls page, the close button closes. Mouse-drag **panning when zoomed stays** (recognizer-based, device-agnostic). `enableSwipeGestures: true` forces the full touch set anywhere (mouse paging + dismiss + double-tap) for phone emulation. + +## Ported math (photo_view 0.15.0, MIT) + +Source-verified against the installed package in the pub cache (`photo_view-0.15.0/lib/...`): + +| Piece | Where | Notes | +|-------|-------|-------| +| Corners/clamp | `photo_view_controller_delegate.dart` `cornersX/Y`/`clampPosition` | Our model: scale relative to contained (1.0 = resting); position in screen px. Property-tested against photo_view's formulas | +| HitCornersDetector | `photo_view_hit_corners.dart` | Ported verbatim (private `_HitCorners`/`_shouldMoveAxis`) | +| Double-tap cycle | `photo_view.dart` `defaultScaleStateCycle` + `nextScaleState` | 1× → covered → 1:1 → 1×, with the no-op-skip loop; zoom-in targets the **tap point**, zoom-out animates to `(1.0, zero)` | +| Contained/covered | `src/utils/photo_view_utils.dart` | `min`/`max` of viewport/child ratios | + +**Deliberately NOT ported** (evaluation findings 2/3/9/11): the friction-tail animations (`AnimationController.fling(velocity: 0.4)`), the fixed +100 px pan glide, center-targeted double-tap. Replaced by: our velocity-proportional fling (Ticker, friction 0.92/frame, `v/60` per frame, stop < 5, trigger > 300 px/s, tap-to-stop), 200 ms easeOut Matrix4Tween zoom animation, tap-point anchoring, and cancel-and-snap-to-1× on gesture interrupt. Rotation not ported (YAGNI). + +## Critical gotchas (hard-won — read before changing anything) + +1. **Never physics-lock the PageView** — see above. The arena recognizer is load-bearing. +2. **The recognizer must resolve on the first non-zero move** — otherwise `ScaleGestureRecognizer._advanceStateMachine` auto-accepts at `kPanSlop` (36 px) and can win the arena tie-break against the PageView's 18 px accept on large per-event deltas (fast flicks, tests), swallowing the drag. +3. **After `resolve(rejected)`, skip `super.handleEvent`** — the base asserts `_state != ready` on subsequent events. +4. **Never `setState` the viewer on page changes** — `PageView.builder` re-invokes `itemBuilder` on rebuild → new `ImageProvider` instances → `ImageCache` identity-key misses → re-downloads → **black flash**. The page index lives in a `ValueNotifier` (`_indexNotifier`); only the controls listen. There is a regression test asserting pageBuilder is not re-invoked for existing pages. +5. **`allowImplicitScrolling: true` is required** — default cache extent 0 disposes neighbor pages, destroying per-page zoom state on swipe. +6. **`shouldClaim` sign convention** — public API takes raw finger delta; negated internally to photo_view's `move = initialFocalPoint - currentFocalPoint` convention. The corner-block matrix tests depend on this. +7. **`onDismissed` defaults to `Navigator.maybePop`** — standalone dismissals close the route; the app passes its own for custom cleanup. +8. **`_indexNotifier` + `_currentIndex`**: keep both in sync (`_onPageIndexChanged`). The registry's `activeController` reads `_currentIndex` (event-time); the notifier drives UI only. + +## Testing conventions + +- Controller math: plain `test()` with `TestVSync()` (no binding needed for pure math). Animation/fling tests: `testWidgets`. +- **Ticker pattern**: `pump()` (zero duration — starts the ticker, elapsed 0) *then* `pump(duration)`. A single timed pump only starts the ticker. +- **Fling tests**: pump a frame loop (16 ms steps) until it stops, and never end a test with a running fling/ticker. +- **`debugDefaultTargetPlatformOverride` must be reset inside the test body** (last line) — the binding's invariant check runs before any `tearDown`/`addTearDown`. +- Taps start the `DoubleTapGestureRecognizer`'s 40 ms countdown — flush with `pump(350 ms)` or the test fails on pending timers. +- `Offset.toString()` rounds to 1 decimal — use `closeTo`, not exact equality, for float-derived values. +- `pumpAndSettle` never settles with perpetual animations on screen (the example gallery's `AnimatedStar`); use fixed pumps there. +- Widget tests drive gestures with `tester.startGesture` / `moveBy` / `timedDrag`; the slow-drag helper (~8 px steps, 200 ms pumps) keeps per-event deltas realistic (see gotcha 2). + +## References & inspirations + +- **Design bible**: `kemono_browser_project/docs/photo-view-evaluation.md` — findings 1–12 (zoom feel, double-tap, fling, single-axis scope flaw, wheel, mouse dragDevices, phone findings, lag), §5 LoliSnatcher architecture, §6 locked decisions, §6.1 package layout +- **photo_view** (upstream, MIT): `https://github.com/bluefireteam/photo_view`, installed at `C:\Users\timka\AppData\Local\Pub\Cache\hosted\pub.dev\photo_view-0.15.0\lib\` — `photo_view_gallery.dart`, `src/core/photo_view_gesture_detector.dart`, `src/core/photo_view_hit_corners.dart`, `src/core/photo_view_core.dart`, `src/controller/photo_view_controller_delegate.dart`, `src/utils/photo_view_utils.dart`, `src/photo_view_scale_state.dart` +- **LoliSnatcher** (architecture): `https://github.com/NO-ob/LoliSnatcher_Droid` — `lib/src/pages/gallery_view_page.dart` (local copy: `C:\Users\timka\AppData\Local\Temp\loli_gallery_view_page.dart`): viewer-level dismiss, `dismissProgress` mapping, videos as dumb children. Their photo_view fork (`github.com/NANI-SORE/photo_view` @ `410b4c2`) is the `Axis.values` both-axes validation — our `shouldClaim` is that rule in recognizer form +- **Flutter internals** (this SDK, `Z:\.Programs\flutter`): `scrollable.dart` `setCanDrag` (drag recognizer removal), `gestures/scale.dart` `_advanceStateMachine` (36 px auto-accept), `painting/image_stream.dart` `reportError` (error routing to listeners), `widgets/image.dart` listener wiring, `scroll_configuration.dart` `_kTouchLikeDeviceTypes` (mouse removed from default dragDevices in 3.47) +- **media_kit**: `controlsBuilder` inspiration for `LeafViewer.controlsBuilder` +- **The app**: `kemono_browser_project/lib/src/screens/fullscreen_image_viewer_screen.dart` — the `_ZoomableMixin` this viewer replaces (parameters ported: slop 12 px, fling 300, dismiss 800/25%, spring params); integration is still pending there + +## Status & known future work + +- Package 0.0.1, `publish_to: none`, git repo initialized — no commits made by the agent +- **App integration pending**: replace `_ZoomableMixin` + the 4 page types' gesture code with `LeafViewer`, delete `_ZoomableMixin`/`_ZoomReporter`/video dismiss copies, remove `photo_view` dep + demo screen +- Decode-size cap for huge images (51 MP, evaluation finding 12) — test on phone after integration +- Trackpad pinch (PointerPanZoomEvent) works through the base recognizer but is untested on hardware +- Example's `_HeaderImageProvider` has value equality so recreated pages reuse the cache; the app's `KemonoImageProvider` must keep stable instances across rebuilds (create once in `initState`, like `_FullscreenPage` does) diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..64c21a1 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..97cfb48 --- /dev/null +++ b/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e31423e --- /dev/null +++ b/README.md @@ -0,0 +1,130 @@ +# leaf_widgets + +Leaf UI widgets — zero external dependencies. + +- `LeafViewer` — a self-contained, photo_view-style fullscreen viewer: + clamped zoom + pan, swipe-to-dismiss, double-tap zoom, mouse-wheel zoom, + native keyboard controls and tap-outside dismissal. Desktop + mobile + behaviour out of the box. +- `LeafZoomable` — opt-in per-page zoom wrapper for `LeafViewer` (also usable + standalone); auto-sizes itself from an image's pixel dimensions via + `LeafZoomable.image`. +- `LeafZoomController` — the zoom/pan state machine behind both (clamped, + fling, double-tap staging, wheel zoom). +- Plus: `LeafContextMenu`, `LeafPopover`, `LeafImage`, `AnimatedFavoriteButton`, + `AnimatedStar`. + +## Features + +- Clamped zoom (1x–maxScale) and pan (corners cannot escape the viewport) +- Edge-release: a drag at a fully zoomed-out, fully clamped position pages or + dismisses instead of panning (gesture-arena based, no raw pointer routing) +- Mobile: swipe to page, drag perpendicular to dismiss, double-tap zooms + (1x → contained → 1:1 when dimensions are known) +- Desktop (Windows/Linux/macOS): mouse-wheel zoom (cursor-anchored), no drag + paging/dismiss/double-tap by default, default on-screen controls + (previous/next, close, page counter) — or your own via `controlsBuilder` +- Keyboard when focused: ←/→ (or ↑/↓ for vertical paging) + Esc dismiss + (opt-out with `enableKeyboard: false`) +- Tap outside the active image fires `onTapOutside` +- `LeafZoomable.image`: pixel dimensions extracted from the image stream at + load time — contained size and 1:1 double-tap step work without passing + anything (falls back to viewport clamping until decoded) + +## Getting started + +Add to `pubspec.yaml`: + +```yaml +dependencies: + leaf_widgets: + path: ../leaf_widgets +``` + +## Usage + +```dart +import 'package:flutter/material.dart'; +import 'package:leaf_widgets/leaf_widgets.dart'; + +class PostViewer extends StatelessWidget { + const PostViewer({super.key, required this.posts}); + + final List urls; + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + body: LeafViewer( + pageCount: urls.length, + onDismissed: () => Navigator.of(context).maybePop(), + pageBuilder: (context, index) => LeafZoomable.image( + image: Image.network( + urls[index], + fit: BoxFit.contain, + errorBuilder: (context, error, stackTrace) => + const Center(child: Icon(Icons.broken_image, color: Colors.white38)), + ), + ), + ), + ); + } +} +``` + +That is the full viewer: paging, clamped zoom/pan, swipe-dismiss, double-tap +(1:1 included — the pixel dimensions are resolved automatically), wheel zoom, +keyboard, tap-outside, and desktop controls. + +### Sizing control + +`LeafZoomable` sizes the zoom clamp itself when possible: + +- `LeafZoomable.image` resolves the image's pixel dimensions from its stream + (no second download — the image cache dedupes) and uses them for the + contained size and the 1:1 stage. +- Plain `LeafZoomable(child: ...)` clamps against the viewport until you pass + explicit sizes: + +```dart +// Contained (fit-to-screen) render size + full-resolution size. +LeafZoomable( + childSize: myContainedSize, // optional — defaults to the viewport + originalSize: myFullSize, // optional — null disables the 1:1 stage + child: myWidget, +) +``` + +### Custom chrome + +```dart +LeafViewer( + pageCount: urls.length, + controlsBuilder: (context, controls) => Row( + children: [ + IconButton( + onPressed: controls.canGoPrevious ? () => controls.goToPage(controls.currentIndex - 1) : null, + icon: const Icon(Icons.chevron_left), + ), + Text('${controls.currentIndex + 1} / ${controls.pageCount}'), + ], + ), + pageBuilder: (context, index) => /* ... */, +) +``` + +### Platforms + +- Touch: swipe paging, perpendicular drag dismiss, double-tap zoom. +- Desktop: wheel zoom, keyboard, default controls; swipe gestures are off + unless `enableSwipeGestures: true` forces them on. +- `scrollDirection` flips paging to vertical; the dismiss gesture then runs + along the other axis. + +## Additional information + +- Example: `example/lib/viewer_demo.dart` +- All viewer code lives in `lib/src/viewer/` — zoom math in + `leaf_zoom_controller.dart` (property-tested), gesture arbitration in + `leaf_pan_zoom_recognizer.dart` (ported from photo_view, MIT). diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..489a9e6 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,14 @@ +include: package:flutter_lints/flutter.yaml + +analyzer: + exclude: + - build/** + - android/** + - ios/** + - web/** + - windows/** + - macos/** + - linux/** + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..36905b4 --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,48 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Widget Preview related +.widget_preview/ diff --git a/example/.metadata b/example/.metadata new file mode 100644 index 0000000..010eedb --- /dev/null +++ b/example/.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: "9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c" + channel: "beta" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + base_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + - platform: android + create_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + base_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + - platform: ios + create_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + base_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + - platform: linux + create_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + base_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + - platform: macos + create_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + base_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + - platform: web + create_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + base_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + - platform: windows + create_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + base_revision: 9e68281b1f23c4a2a32c2255d7628ba2d58b7c4c + + # 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/example/README.md b/example/README.md new file mode 100644 index 0000000..bda91db --- /dev/null +++ b/example/README.md @@ -0,0 +1,17 @@ +# example + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml new file mode 100644 index 0000000..8365773 --- /dev/null +++ b/example/analysis_options.yaml @@ -0,0 +1,38 @@ +# 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 + +analyzer: + exclude: + - build/** + - android/** + - ios/** + - web/** + - windows/** + - macos/** + - linux/** + +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/example/android/.gitignore b/example/android/.gitignore new file mode 100644 index 0000000..c908258 --- /dev/null +++ b/example/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/example/android/app/build.gradle.kts b/example/android/app/build.gradle.kts new file mode 100644 index 0000000..d1ba679 --- /dev/null +++ b/example/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.example" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.example" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION + // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) + // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` + // flag during build. + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/example/android/app/src/debug/AndroidManifest.xml b/example/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..8ffe024 --- /dev/null +++ b/example/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9101605 --- /dev/null +++ b/example/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt b/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt new file mode 100644 index 0000000..0f88299 --- /dev/null +++ b/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.example + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/example/android/app/src/main/res/drawable-v21/launch_background.xml b/example/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..1cb7aa2 --- /dev/null +++ b/example/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/drawable/launch_background.xml b/example/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..8403758 --- /dev/null +++ b/example/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/values-night/styles.xml b/example/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..360a160 --- /dev/null +++ b/example/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/main/res/values/styles.xml b/example/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..5fac679 --- /dev/null +++ b/example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/profile/AndroidManifest.xml b/example/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..8ffe024 --- /dev/null +++ b/example/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/example/android/build.gradle.kts b/example/android/build.gradle.kts new file mode 100644 index 0000000..1f88145 --- /dev/null +++ b/example/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/example/android/gradle.properties b/example/android/gradle.properties new file mode 100644 index 0000000..118d7d0 --- /dev/null +++ b/example/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bcef617 --- /dev/null +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip diff --git a/example/android/settings.gradle.kts b/example/android/settings.gradle.kts new file mode 100644 index 0000000..c0298e3 --- /dev/null +++ b/example/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false +} + +include(":app") diff --git a/example/ios/.gitignore b/example/ios/.gitignore new file mode 100644 index 0000000..ad322bc --- /dev/null +++ b/example/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/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..256cf28 --- /dev/null +++ b/example/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/example/ios/Flutter/Debug.xcconfig b/example/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..0b2d479 --- /dev/null +++ b/example/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/example/ios/Flutter/Release.xcconfig b/example/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..0b2d479 --- /dev/null +++ b/example/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..2756def --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,647 @@ +// !$*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 */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 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 = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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 */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + 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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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.example.example; + 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.example.example.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.example.example.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.example.example.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 = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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.example.example; + 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.example.example; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..c4b79bd --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..fc6bf80 --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..af0309c --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..ee31721 --- /dev/null +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..59c6d39 --- /dev/null +++ b/example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..fc6bf80 --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..af0309c --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..ed1c097 --- /dev/null +++ b/example/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..1950fd8 --- /dev/null +++ b/example/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/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/example/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/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..d08a4de --- /dev/null +++ b/example/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/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..65a94b5 --- /dev/null +++ b/example/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/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..497371e --- /dev/null +++ b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner/Base.lproj/Main.storyboard b/example/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..bbb83ca --- /dev/null +++ b/example/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist new file mode 100644 index 0000000..4f24f57 --- /dev/null +++ b/example/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Example + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + example + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/example/ios/Runner/Runner-Bridging-Header.h b/example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..fae207f --- /dev/null +++ b/example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/example/ios/Runner/SceneDelegate.swift b/example/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b79be9b --- /dev/null +++ b/example/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/example/ios/RunnerTests/RunnerTests.swift b/example/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..4d206de --- /dev/null +++ b/example/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/example/lib/main.dart b/example/lib/main.dart new file mode 100644 index 0000000..32d2b8d --- /dev/null +++ b/example/lib/main.dart @@ -0,0 +1,171 @@ +import 'package:flutter/material.dart'; +import 'package:leaf_widgets/leaf_widgets.dart'; + +import 'viewer_demo.dart'; + +void main() { + runApp(const LeafWidgetsGalleryApp()); +} + +class LeafWidgetsGalleryApp extends StatelessWidget { + const LeafWidgetsGalleryApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'leaf_widgets gallery', + debugShowCheckedModeBanner: false, + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.green, brightness: Brightness.dark), + ), + home: const _GalleryHome(), + ); + } +} + +class _GalleryHome extends StatefulWidget { + const _GalleryHome(); + + @override + State<_GalleryHome> createState() => _GalleryHomeState(); +} + +class _GalleryHomeState extends State<_GalleryHome> { + bool _favorited = false; + bool _swipeEmulation = false; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return Scaffold( + appBar: AppBar(title: const Text('leaf_widgets gallery')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + _Section(title: 'AnimatedStar', child: const Row(children: [AnimatedStar(), SizedBox(width: 24), AnimatedStar(size: 36, color: Colors.cyanAccent)])), + _Section( + title: 'AnimatedFavoriteButton', + child: Row( + children: [ + AnimatedFavoriteButton(isFavorited: _favorited, onChanged: (v) async { + await Future.delayed(const Duration(milliseconds: 600)); + if (!mounted) return false; + setState(() => _favorited = v); + return true; + }), + const SizedBox(width: 24), + const AnimatedFavoriteButton(), + ], + ), + ), + _Section( + title: 'LeafPopover (tap trigger)', + child: LeafPopover( + popoverAnchor: Alignment.topCenter, + childAnchor: Alignment.bottomCenter, + spacing: 8, + popoverBuilder: (context, controller) => Card( + margin: EdgeInsets.zero, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Popover content'), + TextButton(onPressed: controller.hide, child: const Text('Close')), + ], + ), + ), + ), + child: const Chip(label: Text('Open popover')), + ), + ), + _Section( + title: 'LeafContextMenu (right-click / long-press)', + child: LeafContextMenu( + entries: const [ + ContextMenuAction(label: 'Copy', icon: Icons.copy, shortcut: 'Ctrl+C'), + ContextMenuAction(label: 'Open', icon: Icons.open_in_new), + ContextMenuDivider(), + ContextMenuAction(label: 'Delete', icon: Icons.delete, destructive: true), + ], + onDismissed: () => debugPrint('menu dismissed'), + child: Container( + height: 100, + alignment: Alignment.center, + decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(12)), + child: const Text('Right-click me'), + ), + ), + ), + _Section( + title: 'LeafImage (network + reveal)', + child: LeafImage( + image: const NetworkImage('https://picsum.photos/seed/leaf/800/500'), + height: 220, + width: double.infinity, + fit: BoxFit.cover, + imageBuilder: (context, child) => ClipRRect(borderRadius: BorderRadius.circular(12), child: child), + revealAnimation: const GradientRevealAnimation(), + loadingBuilder: (context, progress) => Container( + decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(12)), + child: progress > 0 + ? Center(child: LinearProgressIndicator(value: progress)) + : const Center(child: CircularProgressIndicator()), + ), + errorBuilder: (context, error, retry) => Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [const Icon(Icons.error_outline), TextButton(onPressed: retry, child: const Text('Retry'))], + ), + ), + ), + ), + _Section( + title: 'LeafViewer (fullscreen feel test)', + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + FilledButton.icon( + icon: const Icon(Icons.fullscreen), + label: const Text('Open 3-image viewer'), + onPressed: () => openLeafViewerDemo(context, enableSwipeGestures: _swipeEmulation), + ), + const SizedBox(height: 8), + SwitchListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: const Text('Swipe gestures (phone emulation)'), + value: _swipeEmulation, + onChanged: (v) => setState(() => _swipeEmulation = v), + ), + ], + ), + ), + ], + ), + ); + } +} + +class _Section extends StatelessWidget { + final String title; + final Widget child; + + const _Section({required this.title, required this.child}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: Theme.of(context).textTheme.titleSmall), + const SizedBox(height: 12), + child, + ], + ), + ); + } +} diff --git a/example/lib/viewer_demo.dart b/example/lib/viewer_demo.dart new file mode 100644 index 0000000..246d8e3 --- /dev/null +++ b/example/lib/viewer_demo.dart @@ -0,0 +1,131 @@ +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:leaf_widgets/leaf_widgets.dart'; + +class _DemoImage { + const _DemoImage(this.url, this.size); + final String url; + final Size size; +} + +const _demoImages = [ + _DemoImage( + 'https://file.pawchive.pw/data/82/91/829126892beebd0a7ff5b5a398e63a760b53162b15323ce900d944d126aa69ec.png?f=829126892beebd0a7ff5b5a398e63a760b53162b15323ce900d944d126aa69ec.png', + Size(1457, 2048), + ), + _DemoImage( + 'https://file.pawchive.pw/data/09/f4/09f4e606de27786cf633282b8d3e194b62a0b6859368f8ac38d28300972f763c.jpeg?f=09f4e606de27786cf633282b8d3e194b62a0b6859368f8ac38d28300972f763c.jpeg', + Size(8500, 6000), + ), + _DemoImage( + 'https://file.pawchive.pw/data/79/e9/79e996f02a2700dbc38c590057d027b7566608be8e87e49950cec165d6f8b525.png?f=79e996f02a2700dbc38c590057d027b7566608be8e87e49950cec165d6f8b525.png', + Size(3267, 1634), + ), +]; + +Size _containSize(Size viewport, Size image) { + final scale = viewport.width / image.width < viewport.height / image.height + ? viewport.width / image.width + : viewport.height / image.height; + return Size(image.width * scale, image.height * scale); +} + +void openLeafViewerDemo(BuildContext context, {bool enableSwipeGestures = false}) { + Navigator.of(context).push( + PageRouteBuilder( + // Transparent route so the scrim fade reveals the gallery behind it, + // like the real app's fullscreen viewer. + opaque: false, + barrierColor: Colors.transparent, + barrierDismissible: true, + transitionDuration: const Duration(milliseconds: 200), + reverseTransitionDuration: const Duration(milliseconds: 200), + transitionsBuilder: (context, animation, secondaryAnimation, child) => + FadeTransition(opacity: CurvedAnimation(parent: animation, curve: Curves.easeOut), child: child), + pageBuilder: (context, animation, secondaryAnimation) => Scaffold( + backgroundColor: Colors.transparent, + body: Stack( + children: [ + LeafViewer( + pageCount: _demoImages.length, + enableSwipeGestures: enableSwipeGestures, + backgroundBuilder: (context, progress) => + Container(color: Colors.black.withValues(alpha: 0.87 * (1 - progress))), + pageBuilder: (context, index) { + final demo = _demoImages[index]; + return LayoutBuilder( + builder: (context, constraints) { + return LeafZoomable( + childSize: _containSize(constraints.biggest, demo.size), + originalSize: demo.size, + child: Image( + image: _HeaderImageProvider(demo.url), + fit: BoxFit.contain, + filterQuality: FilterQuality.high, + errorBuilder: (context, error, stackTrace) => const ColoredBox( + color: Color(0xFF1A1A1A), + child: Center(child: Icon(Icons.broken_image, color: Colors.white38)), + ), + ), + ); + }, + ); + }, + ), + Positioned( + top: 8, + right: 8, + child: IconButton( + icon: const Icon(Icons.close), + color: Colors.white70, + onPressed: () => Navigator.of(context).pop(), + ), + ), + ], + ), + ), + ), + ); +} + +/// ImageProvider for `file.pawchive.pw` (requires Referer + browser UA). +class _HeaderImageProvider extends ImageProvider<_HeaderImageProvider> { + const _HeaderImageProvider(this.url); + + final String url; + + @override + bool operator ==(Object other) => other is _HeaderImageProvider && other.url == url; + + @override + int get hashCode => url.hashCode; + + @override + Future<_HeaderImageProvider> obtainKey(ImageConfiguration configuration) => SynchronousFuture(this); + + @override + ImageStreamCompleter loadImage(_HeaderImageProvider key, ImageDecoderCallback decode) { + return MultiFrameImageStreamCompleter(codec: _loadAsync(decode), scale: 1.0); + } + + Future _loadAsync(ImageDecoderCallback decode) async { + final client = HttpClient(); + try { + final request = await client.getUrl(Uri.parse(url)); + request.headers.set('Referer', 'https://pawchive.pw/'); + request.headers.set('User-Agent', + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'); + final response = await request.close(); + if (response.statusCode != 200) { + throw HttpException('GET $url -> ${response.statusCode}', uri: Uri.parse(url)); + } + final bytes = await consolidateHttpClientResponseBytes(response); + return await decode(await ui.ImmutableBuffer.fromUint8List(bytes)); + } finally { + client.close(); + } + } +} diff --git a/example/linux/.gitignore b/example/linux/.gitignore new file mode 100644 index 0000000..c7ea17f --- /dev/null +++ b/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/example/linux/CMakeLists.txt b/example/linux/CMakeLists.txt new file mode 100644 index 0000000..025e743 --- /dev/null +++ b/example/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 "example") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.example") + +# 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/example/linux/flutter/CMakeLists.txt b/example/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..27860e8 --- /dev/null +++ b/example/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/example/linux/flutter/generated_plugin_registrant.cc b/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/example/linux/flutter/generated_plugin_registrant.h b/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/example/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/example/linux/flutter/generated_plugins.cmake b/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e1de87 --- /dev/null +++ b/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +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/example/linux/runner/CMakeLists.txt b/example/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..7ed6f3e --- /dev/null +++ b/example/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/example/linux/runner/main.cc b/example/linux/runner/main.cc new file mode 100644 index 0000000..4340ffc --- /dev/null +++ b/example/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/example/linux/runner/my_application.cc b/example/linux/runner/my_application.cc new file mode 100644 index 0000000..cd3dee9 --- /dev/null +++ b/example/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, "example"); + 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, "example"); + } + + 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/example/linux/runner/my_application.h b/example/linux/runner/my_application.h new file mode 100644 index 0000000..c4c4a71 --- /dev/null +++ b/example/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/example/macos/.gitignore b/example/macos/.gitignore new file mode 100644 index 0000000..d4e0569 --- /dev/null +++ b/example/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/example/macos/Flutter/Flutter-Debug.xcconfig b/example/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..f022c34 --- /dev/null +++ b/example/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/example/macos/Flutter/Flutter-Release.xcconfig b/example/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..f022c34 --- /dev/null +++ b/example/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/example/macos/Flutter/GeneratedPluginRegistrant.swift b/example/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..cccf817 --- /dev/null +++ b/example/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,10 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { +} diff --git a/example/macos/Runner.xcodeproj/project.pbxproj b/example/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..385dfa9 --- /dev/null +++ b/example/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*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 */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* 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 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "example.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 = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + 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 /* example.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 = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* example.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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; + }; + 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.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; + }; + 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.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; + }; + 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 = 12.0; + 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 = 12.0; + 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 = 12.0; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..fc6bf80 --- /dev/null +++ b/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..fe55a1d --- /dev/null +++ b/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/macos/Runner.xcworkspace/contents.xcworkspacedata b/example/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..59c6d39 --- /dev/null +++ b/example/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..fc6bf80 --- /dev/null +++ b/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/macos/Runner/AppDelegate.swift b/example/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..c5c474d --- /dev/null +++ b/example/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/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..8d4e7cb --- /dev/null +++ b/example/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/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/example/macos/Runner/Base.lproj/MainMenu.xib b/example/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..4632c69 --- /dev/null +++ b/example/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/macos/Runner/Configs/AppInfo.xcconfig b/example/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..bcb65c2 --- /dev/null +++ b/example/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 = example + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.example + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/example/macos/Runner/Configs/Debug.xcconfig b/example/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..b398823 --- /dev/null +++ b/example/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/example/macos/Runner/Configs/Release.xcconfig b/example/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..d93e5dc --- /dev/null +++ b/example/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/example/macos/Runner/Configs/Warnings.xcconfig b/example/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..fb4d7d3 --- /dev/null +++ b/example/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/example/macos/Runner/DebugProfile.entitlements b/example/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..51d0967 --- /dev/null +++ b/example/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/example/macos/Runner/Info.plist b/example/macos/Runner/Info.plist new file mode 100644 index 0000000..3733c1a --- /dev/null +++ b/example/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/example/macos/Runner/MainFlutterWindow.swift b/example/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..ab30cba --- /dev/null +++ b/example/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/example/macos/Runner/Release.entitlements b/example/macos/Runner/Release.entitlements new file mode 100644 index 0000000..04336df --- /dev/null +++ b/example/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/example/macos/RunnerTests/RunnerTests.swift b/example/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..21fe1ab --- /dev/null +++ b/example/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/example/pubspec.lock b/example/pubspec.lock new file mode 100644 index 0000000..0c99dcc --- /dev/null +++ b/example/pubspec.lock @@ -0,0 +1,220 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + 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" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + leaf_widgets: + dependency: "direct main" + description: + path: ".." + relative: true + source: path + version: "0.0.1" + 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" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.dev" + source: hosted + version: "1.19.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + url: "https://pub.dev" + source: hosted + version: "0.7.12" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" +sdks: + dart: ">=3.13.0-282.3.beta <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/example/pubspec.yaml b/example/pubspec.yaml new file mode 100644 index 0000000..9c51371 --- /dev/null +++ b/example/pubspec.yaml @@ -0,0 +1,91 @@ +name: example +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.13.0-282.3.beta + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + leaf_widgets: + path: ../ + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/example/test/widget_test.dart b/example/test/widget_test.dart new file mode 100644 index 0000000..a331adc --- /dev/null +++ b/example/test/widget_test.dart @@ -0,0 +1,39 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:example/main.dart'; +import 'package:leaf_widgets/leaf_widgets.dart'; + +void main() { + testWidgets('gallery builds and shows all sections', (tester) async { + await tester.pumpWidget(const LeafWidgetsGalleryApp()); + + expect(find.text('leaf_widgets gallery'), findsOneWidget); + expect(find.byType(AnimatedStar), findsNWidgets(2)); + expect(find.byType(AnimatedFavoriteButton), findsNWidgets(2)); + expect(find.byType(LeafPopover), findsOneWidget); + expect(find.byType(LeafContextMenu), findsOneWidget); + expect(find.byType(LeafImage), findsOneWidget); + }); + + testWidgets('LeafViewer demo opens and closes', (tester) async { + await tester.pumpWidget(const LeafWidgetsGalleryApp()); + + // The gallery has perpetual animations, so pumpAndSettle can never settle. + await tester.scrollUntilVisible(find.text('Open 3-image viewer'), 200); + await tester.ensureVisible(find.text('Open 3-image viewer')); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('Open 3-image viewer')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); // route transition + await tester.pump(); // let image loads fail while the widgets are alive + + expect(find.byType(LeafViewer), findsOneWidget); + expect(find.byType(LeafZoomable), findsWidgets); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); // route pop + expect(find.byType(LeafViewer), findsNothing); + }); +} diff --git a/example/web/favicon.png b/example/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/example/web/favicon.png differ diff --git a/example/web/icons/Icon-192.png b/example/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/example/web/icons/Icon-192.png differ diff --git a/example/web/icons/Icon-512.png b/example/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/example/web/icons/Icon-512.png differ diff --git a/example/web/icons/Icon-maskable-192.png b/example/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/example/web/icons/Icon-maskable-192.png differ diff --git a/example/web/icons/Icon-maskable-512.png b/example/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/example/web/icons/Icon-maskable-512.png differ diff --git a/example/web/index.html b/example/web/index.html new file mode 100644 index 0000000..1ef78cc --- /dev/null +++ b/example/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + example + + + + + + + diff --git a/example/web/manifest.json b/example/web/manifest.json new file mode 100644 index 0000000..d74fa59 --- /dev/null +++ b/example/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "example", + "short_name": "example", + "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/example/windows/.gitignore b/example/windows/.gitignore new file mode 100644 index 0000000..ec4098a --- /dev/null +++ b/example/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/example/windows/CMakeLists.txt b/example/windows/CMakeLists.txt new file mode 100644 index 0000000..cff7110 --- /dev/null +++ b/example/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(example 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 "example") + +# 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/example/windows/flutter/CMakeLists.txt b/example/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..efb62eb --- /dev/null +++ b/example/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/example/windows/flutter/generated_plugin_registrant.cc b/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/example/windows/flutter/generated_plugin_registrant.h b/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/example/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/example/windows/flutter/generated_plugins.cmake b/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b93c4c3 --- /dev/null +++ b/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +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/example/windows/runner/CMakeLists.txt b/example/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..2041a04 --- /dev/null +++ b/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/example/windows/runner/Runner.rc b/example/windows/runner/Runner.rc new file mode 100644 index 0000000..add1026 --- /dev/null +++ b/example/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.example" "\0" + VALUE "FileDescription", "example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "example.exe" "\0" + VALUE "ProductName", "example" "\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/example/windows/runner/flutter_window.cpp b/example/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..c819cb0 --- /dev/null +++ b/example/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/example/windows/runner/flutter_window.h b/example/windows/runner/flutter_window.h new file mode 100644 index 0000000..28c2383 --- /dev/null +++ b/example/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/example/windows/runner/main.cpp b/example/windows/runner/main.cpp new file mode 100644 index 0000000..9632f06 --- /dev/null +++ b/example/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"example", 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/example/windows/runner/resource.h b/example/windows/runner/resource.h new file mode 100644 index 0000000..ddc7f3e --- /dev/null +++ b/example/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/example/windows/runner/resources/app_icon.ico b/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/example/windows/runner/resources/app_icon.ico differ diff --git a/example/windows/runner/runner.exe.manifest b/example/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..4b962bb --- /dev/null +++ b/example/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/example/windows/runner/utils.cpp b/example/windows/runner/utils.cpp new file mode 100644 index 0000000..b7f62cc --- /dev/null +++ b/example/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/example/windows/runner/utils.h b/example/windows/runner/utils.h new file mode 100644 index 0000000..3f0e05c --- /dev/null +++ b/example/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/example/windows/runner/win32_window.cpp b/example/windows/runner/win32_window.cpp new file mode 100644 index 0000000..b5ba2a0 --- /dev/null +++ b/example/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/example/windows/runner/win32_window.h b/example/windows/runner/win32_window.h new file mode 100644 index 0000000..49b847f --- /dev/null +++ b/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/lib/leaf_widgets.dart b/lib/leaf_widgets.dart new file mode 100644 index 0000000..5cbb364 --- /dev/null +++ b/lib/leaf_widgets.dart @@ -0,0 +1,12 @@ +/// Leaf UI widgets — zero external dependencies. +library; + +export 'src/context_menu/leaf_context_menu.dart'; +export 'src/image/leaf_image.dart'; +export 'src/misc/animated_favorite_button.dart'; +export 'src/misc/animated_star.dart'; +export 'src/misc/leaf_async_chip.dart'; +export 'src/popover/leaf_popover.dart'; +export 'src/viewer/leaf_viewer.dart'; +export 'src/viewer/leaf_zoom_controller.dart'; +export 'src/viewer/leaf_zoomable.dart'; diff --git a/lib/src/context_menu/leaf_context_menu.dart b/lib/src/context_menu/leaf_context_menu.dart new file mode 100644 index 0000000..a46b449 --- /dev/null +++ b/lib/src/context_menu/leaf_context_menu.dart @@ -0,0 +1,572 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +// ───────────────────────────────────────────────────────────────────────────── +// Data types +// ───────────────────────────────────────────────────────────────────────────── + +/// Base class for entries in a [LeafContextMenu]. +sealed class ContextMenuEntry { + const ContextMenuEntry(); +} + +/// A tappable menu action. +/// +/// Layout: `[icon] label [shortcut]` with an optional subtitle below the label. +class ContextMenuAction extends ContextMenuEntry { + /// Label text. Required. + final String label; + + /// Optional leading icon. + final IconData? icon; + + /// Optional subtitle shown below the label. + final String? subtitle; + + /// Optional shortcut hint shown right-aligned (e.g. `Ctrl+C`). + final String? shortcut; + + /// Called when the action is tapped. + final VoidCallback? onTap; + + /// Whether the action is interactive. Defaults to true. + final bool enabled; + + /// When true the label and icon are rendered in the error colour. + final bool destructive; + + const ContextMenuAction({ + required this.label, + this.icon, + this.subtitle, + this.shortcut, + this.onTap, + this.enabled = true, + this.destructive = false, + }); +} + +/// A visual separator between groups of actions. +class ContextMenuDivider extends ContextMenuEntry { + const ContextMenuDivider(); +} + +/// A menu action that runs an async [task] and reports its progress and +/// result in place, inside the menu item. +/// +/// While the task runs the item's icon becomes a spinner and its label +/// switches to [runningLabel] (with a thin determinate progress bar when the +/// task reports progress via [task]'s callback); the rest of the menu is +/// locked (other items disabled, outside taps and Escape ignored) until the +/// task completes. On success the item shows a check + [doneLabel] for +/// [doneDuration], on failure an error icon + [errorLabel] for +/// [errorDuration]; then the menu dismisses itself. +class ContextMenuAsyncAction extends ContextMenuAction { + /// The async task. [onProgress] reports 0..1 when the total is known; + /// never calling it keeps the spinner indeterminate. + final Future Function(ValueChanged? onProgress) task; + + /// Label shown while [task] runs. + final String runningLabel; + + /// Label shown briefly on success. + final String doneLabel; + + /// Label shown briefly on failure. + final String errorLabel; + + /// How long the success state stays visible before the menu dismisses. + final Duration doneDuration; + + /// How long the error state stays visible before the menu dismisses. + final Duration errorDuration; + + /// Called with the task's error + stack trace when it throws. The error is + /// always debugPrinted regardless. + final void Function(Object error, StackTrace stackTrace)? onError; + + const ContextMenuAsyncAction({ + required super.label, + required this.task, + super.icon, + super.subtitle, + super.shortcut, + super.enabled, + super.destructive, + this.runningLabel = 'Copying…', + this.doneLabel = 'Copied', + this.errorLabel = 'Failed', + this.doneDuration = const Duration(milliseconds: 700), + this.errorDuration = const Duration(milliseconds: 1400), + this.onError, + }) : super(onTap: null); +} + +// ───────────────────────────────────────────────────────────────────────────── +// LeafContextMenu +// ───────────────────────────────────────────────────────────────────────────── + +/// A Material-styled context menu that opens on right-click (desktop) or +/// long-press (touch). +/// +/// Usage: +/// ```dart +/// LeafContextMenu( +/// entries: [ +/// const ContextMenuAction(label: 'Copy', icon: Icons.copy, onTap: _onCopy), +/// const ContextMenuDivider(), +/// const ContextMenuAction(label: 'Delete', icon: Icons.delete, destructive: true, onTap: _onDelete), +/// ], +/// child: MyWidget(...), +/// ) +/// ``` +class LeafContextMenu extends StatefulWidget { + /// The menu entries ([ContextMenuAction]s and [ContextMenuDivider]s). + final List entries; + + /// The widget that acts as the trigger area. + final Widget child; + + /// Optional callback fired when the menu is dismissed (by action, outside + /// tap, or Escape). + final VoidCallback? onDismissed; + + const LeafContextMenu({required this.entries, required this.child, this.onDismissed, super.key}); + + @override + State createState() => _LeafContextMenuState(); +} + +class _LeafContextMenuState extends State { + final _overlayController = OverlayPortalController(); + Offset? _globalPosition; + + // ── helpers ─────────────────────────────────────────────────────────────── + + static bool get _isTouchDevice => + defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.fuchsia; + + void _showAtGlobal(Offset globalPosition) { + _globalPosition = globalPosition; + setState(() {}); + _overlayController.show(); + } + + void _hide() { + _globalPosition = null; + _overlayController.hide(); + widget.onDismissed?.call(); + } + + void _onPrimaryTap(PointerEvent e) { + // Hide only when the menu is already visible and a primary click happens + // on the trigger (acts as a toggle-off). + if (_overlayController.isShowing) { + _hide(); + } + } + + // ── build ───────────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + Widget child = widget.child; + + // Right-click (desktop) / secondary button. + child = Listener( + onPointerDown: (e) { + if (e.buttons & kSecondaryButton != 0) { + _showAtGlobal(e.position); + } else if (e.buttons & kPrimaryButton != 0) { + _onPrimaryTap(e); + } + }, + child: child, + ); + + // Long-press (touch). + if (_isTouchDevice) { + child = GestureDetector( + onLongPressStart: (details) => _showAtGlobal(details.globalPosition), + behavior: HitTestBehavior.translucent, + child: child, + ); + } + + return OverlayPortal( + controller: _overlayController, + overlayChildBuilder: (_) { + if (_globalPosition == null) { + return const SizedBox.shrink(); + } + return _ContextMenuOverlay(globalPosition: _globalPosition!, entries: widget.entries, onDismiss: _hide); + }, + child: child, + ); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// _ContextMenuOverlay +// ───────────────────────────────────────────────────────────────────────────── + +class _ContextMenuOverlay extends StatefulWidget { + final Offset globalPosition; + final List entries; + final VoidCallback onDismiss; + + const _ContextMenuOverlay({required this.globalPosition, required this.entries, required this.onDismiss}); + + @override + State<_ContextMenuOverlay> createState() => _ContextMenuOverlayState(); +} + +class _ContextMenuOverlayState extends State<_ContextMenuOverlay> with SingleTickerProviderStateMixin { + late final AnimationController _animCtrl; + late final Animation _fade; + late final Animation _scale; + + /// Key attached to the menu Card so we can measure its actual size. + final _menuKey = GlobalKey(); + + /// Adjusted position after overflow detection. + Offset? _adjustedPos; + + /// Whether the exit animation is running. + bool _dismissing = false; + + /// Whether an async action is currently running. While true, outside taps + /// and Escape are ignored and all other items are disabled. + bool _busy = false; + + // ── lifecycle ───────────────────────────────────────────────────────────── + + @override + void initState() { + super.initState(); + + _animCtrl = AnimationController(duration: const Duration(milliseconds: 100), vsync: this); + + _fade = CurvedAnimation(parent: _animCtrl, curve: Curves.linear); + _scale = CurvedAnimation(parent: _animCtrl, curve: Curves.easeOutCubic); + + _animCtrl.addStatusListener(_onStatusChanged); + // Start entrance. + _animCtrl.forward(); + + // Measure and adjust position after first frame. + WidgetsBinding.instance.addPostFrameCallback((_) => _adjustPosition()); + } + + @override + void dispose() { + _animCtrl.removeStatusListener(_onStatusChanged); + _animCtrl.dispose(); + super.dispose(); + } + + void _onStatusChanged(AnimationStatus status) { + if (status == AnimationStatus.dismissed && _dismissing) { + widget.onDismiss(); + } + } + + // ── positioning ─────────────────────────────────────────────────────────── + + void _adjustPosition() { + final menuBox = _menuKey.currentContext?.findRenderObject() as RenderBox?; + if (menuBox == null || !menuBox.hasSize) return; + + final menuSize = menuBox.size; + final mediaQuery = MediaQuery.of(context); + final screen = mediaQuery.size; + final padding = mediaQuery.padding; + + var x = widget.globalPosition.dx; + var y = widget.globalPosition.dy; + + // Horizontal flip. + if (x + menuSize.width > screen.width) { + x = screen.width - menuSize.width - padding.right; + } + // Vertical flip. + if (y + menuSize.height > screen.height) { + y = screen.height - menuSize.height - padding.bottom; + } + + // Ensure minimum edge padding. + x = x.clamp(padding.left, screen.width - menuSize.width - padding.right); + y = y.clamp(padding.top, screen.height - menuSize.height - padding.bottom); + + if (_adjustedPos == null || _adjustedPos!.dx != x || _adjustedPos!.dy != y) { + setState(() => _adjustedPos = Offset(x, y)); + } + } + + void _setBusy(bool busy) { + if (_busy != busy) setState(() => _busy = busy); + } + + // ── dismiss ─────────────────────────────────────────────────────────────── + + void _dismiss() { + if (_dismissing) return; + _dismissing = true; + _animCtrl.reverse(); + } + + // ── build ───────────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + final pos = _adjustedPos ?? widget.globalPosition; + final theme = Theme.of(context); + final cs = theme.colorScheme; + + return Stack( + children: [ + // Invisible barrier. Listener catches ALL pointer events (left, + // right, middle click). Menu items (above in the stack) take + // priority via InkWell gesture absorption. Ignored while an async + // action is running so its feedback isn't cut short. + Positioned.fill( + child: Listener( + onPointerDown: (_) { + if (!_busy) _dismiss(); + }, + behavior: HitTestBehavior.translucent, + child: Container(color: Colors.transparent), + ), + ), + // The menu itself. + Positioned( + left: pos.dx, + top: pos.dy, + child: Material( + type: MaterialType.transparency, + child: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.escape): () { + if (!_busy) _dismiss(); + }, + }, + child: FocusScope( + child: FadeTransition( + opacity: Tween(begin: 0, end: 1).animate(_fade), + child: ScaleTransition( + scale: Tween(begin: 0.93, end: 1).animate(_scale), + child: Card( + key: _menuKey, + margin: EdgeInsets.zero, + elevation: 8, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + color: cs.surfaceContainerHighest, + surfaceTintColor: Colors.transparent, + clipBehavior: Clip.antiAlias, + child: IntrinsicWidth( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: _buildEntries(theme), + ), + ), + ), + ), + ), + ), + ), + ), + ), + ], + ); + } + + List _buildEntries(ThemeData theme) { + final children = []; + for (final entry in widget.entries) { + switch (entry) { + case ContextMenuAction action: + children.add(_ContextMenuActionWidget( + action: action, + busy: _busy, + onBusyChanged: _setBusy, + onDismiss: _dismiss, + )); + case ContextMenuDivider _: + children.add(Divider(height: 1, thickness: 1, color: theme.dividerColor)); + } + } + return children; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// _ContextMenuActionWidget +// ───────────────────────────────────────────────────────────────────────────── + +enum _AsyncActionState { idle, running, done, error } + +class _ContextMenuActionWidget extends StatefulWidget { + final ContextMenuAction action; + + /// Whether some async action is currently running (this one or another). + /// While true, this item is disabled. + final bool busy; + + final ValueChanged onBusyChanged; + + /// Dismisses the menu (with its exit animation). + final VoidCallback onDismiss; + + const _ContextMenuActionWidget({ + required this.action, + required this.busy, + required this.onBusyChanged, + required this.onDismiss, + }); + + @override + State<_ContextMenuActionWidget> createState() => _ContextMenuActionWidgetState(); +} + +class _ContextMenuActionWidgetState extends State<_ContextMenuActionWidget> { + _AsyncActionState _state = _AsyncActionState.idle; + double? _progress; + Timer? _timer; + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + ContextMenuAsyncAction? get _async => + widget.action is ContextMenuAsyncAction ? widget.action as ContextMenuAsyncAction : null; + + Future _runAsync() async { + final async = _async!; + if (_state == _AsyncActionState.running) return; + _timer?.cancel(); + setState(() { + _state = _AsyncActionState.running; + _progress = null; + }); + widget.onBusyChanged(true); + try { + await async.task((p) { + if (mounted) setState(() => _progress = p.clamp(0.0, 1.0)); + }); + if (!mounted) return; + setState(() => _state = _AsyncActionState.done); + widget.onBusyChanged(false); + _timer = Timer(async.doneDuration, widget.onDismiss); + } catch (e, st) { + debugPrint('ContextMenuAsyncAction "${async.label}" failed: $e\n$st'); + if (!mounted) return; + setState(() => _state = _AsyncActionState.error); + widget.onBusyChanged(false); + _timer = Timer(async.errorDuration, widget.onDismiss); + async.onError?.call(e, st); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final cs = theme.colorScheme; + final text = theme.textTheme; + final action = widget.action; + final async = _async; + final running = async != null && _state == _AsyncActionState.running; + final done = async != null && _state == _AsyncActionState.done; + final failed = async != null && _state == _AsyncActionState.error; + final interactive = action.enabled && !widget.busy; + + final foreground = failed + ? cs.error + : running + ? cs.onSurface + : done + ? cs.onSurface + : action.destructive + ? cs.error + : interactive + ? cs.onSurface + : cs.onSurface.withValues(alpha: 0.38); + + final label = running + ? async.runningLabel + : done + ? async.doneLabel + : failed + ? async.errorLabel + : action.label; + + final VoidCallback? onTap = async != null + ? (_state == _AsyncActionState.running ? null : interactive ? _runAsync : null) + : (interactive + ? () { + action.onTap?.call(); + widget.onDismiss(); + } + : null); + + final leading = switch ((running, done, failed)) { + (true, _, _) => const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + (_, true, _) => const Icon(Icons.check, size: 18, color: Color(0xFF7CF29C)), + (_, _, true) => Icon(Icons.error_outline, size: 18, color: cs.error), + _ => action.icon == null ? null : Icon(action.icon, size: 18, color: foreground), + }; + + return InkWell( + onTap: onTap, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (leading != null) ...[leading, const SizedBox(width: 12)], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(label, style: text.bodyLarge?.copyWith(color: foreground)), + if (action.subtitle != null) + Text(action.subtitle!, style: text.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6))), + ], + ), + ), + if (action.shortcut != null) ...[ + const SizedBox(width: 24), + Text(action.shortcut!, style: text.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.5))), + ], + ], + ), + ), + if (running && _progress != null) + LinearProgressIndicator( + value: _progress, + minHeight: 2, + color: cs.primary, + backgroundColor: cs.surfaceContainerHighest, + ), + ], + ), + ); + } +} diff --git a/lib/src/image/leaf_image.dart b/lib/src/image/leaf_image.dart new file mode 100644 index 0000000..ca54fa1 --- /dev/null +++ b/lib/src/image/leaf_image.dart @@ -0,0 +1,407 @@ +import 'dart:ui' show lerpDouble; + +import 'package:flutter/material.dart'; + +// ═══════════════════════════════════════════════════════════════════════════════ +// Reveal Animation Interface +// ═══════════════════════════════════════════════════════════════════════════════ + +/// Pluggable reveal effect that plays when an image finishes loading. +/// +/// Implementors own an [AnimationController] with the given [duration] and +/// return the wrapped [child] from [build]. +abstract class LeafRevealAnimation { + const LeafRevealAnimation(); + + /// How long the reveal animation takes. + Duration get duration; + + /// Wrap [child] (the loaded image) with the reveal effect. + /// + /// [controller] is pre-configured with [duration] and will be + /// `.forward()`-ed by [LeafImage] when the first frame arrives. + Widget build(BuildContext context, Widget child, AnimationController controller); +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// Built-in Animations +// ═══════════════════════════════════════════════════════════════════════════════ + +/// Sweeps a gradient mask across the image from left-to-right (or top-to-bottom). +class GradientRevealAnimation extends LeafRevealAnimation { + /// Direction of the sweep. + final Axis direction; + + /// Width of the gradient transition zone as a fraction of the image width. + final double window; + + /// Final position of the trailing gradient stop (1.0 = fully revealed). + final double finalStop2; + + @override + final Duration duration; + + /// Animation curve. + final Curve curve; + + const GradientRevealAnimation({ + this.direction = Axis.horizontal, + this.window = 0.3, + this.finalStop2 = 1.3, + this.duration = const Duration(milliseconds: 400), + this.curve = Curves.fastLinearToSlowEaseIn, + }); + + @override + Widget build(BuildContext context, Widget child, AnimationController controller) { + return AnimatedBuilder( + animation: CurvedAnimation(parent: controller, curve: curve), + builder: (context, child) { + final t = controller.value; + final startStop1 = -window; + final startStop2 = 0.0; + final stop1 = lerpDouble(startStop1, finalStop2 - window, t)!; + final stop2 = lerpDouble(startStop2, finalStop2, t)!; + return ShaderMask( + shaderCallback: (bounds) => LinearGradient( + begin: direction == Axis.horizontal ? Alignment.centerLeft : Alignment.topCenter, + end: direction == Axis.horizontal ? Alignment.centerRight : Alignment.bottomCenter, + colors: const [Colors.white, Colors.transparent], + stops: [stop1, stop2], + ).createShader(bounds), + blendMode: BlendMode.dstIn, + child: child!, + ); + }, + child: child, + ); + } +} + +/// Simple opacity fade-in. +class FadeRevealAnimation extends LeafRevealAnimation { + @override + final Duration duration; + final Curve curve; + + const FadeRevealAnimation({this.duration = const Duration(milliseconds: 300), this.curve = Curves.easeIn}); + + @override + Widget build(BuildContext context, Widget child, AnimationController controller) { + return FadeTransition( + opacity: CurvedAnimation(parent: controller, curve: curve), + child: child, + ); + } +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// LeafImage +// ═══════════════════════════════════════════════════════════════════════════════ + +/// Configurable image widget with pluggable reveal animations, built-in +/// interactivity, loading skeleton support, and one-tap retry on error. +/// +/// Wraps Flutter's [Image] and manages its three builders internally so you +/// never have to write `Stack` + `Material` + `InkWell` + `loadingBuilder` + +/// `errorBuilder` yourself. +/// +/// ```dart +/// LeafImage( +/// image: KemonoImageProvider(url, creatorId: id, postId: pid), +/// fit: BoxFit.cover, +/// loadingBuilder: (ctx, progress) => SkeletonTile(progress: progress), +/// onTap: () => FullscreenImageViewerScreen.open(...), +/// revealAnimation: const GradientRevealAnimation(), +/// ) +/// ``` +class LeafImage extends StatefulWidget { + // ── Required ────────────────────────────────────────────────────────────── + + /// The source image. + final ImageProvider image; + + // ── Standard Image passthrough ──────────────────────────────────────────── + + final BoxFit? fit; + final AlignmentGeometry alignment; + final double? width; + final double? height; + final int? cacheWidth; + final int? cacheHeight; + final FilterQuality filterQuality; + + // ── Loading ─────────────────────────────────────────────────────────────── + + /// Called with a [progress] value in `[0.0, 1.0]` while the image downloads. + /// + /// This is the right place for loading skeletons — the skeleton fills the + /// same layout space the final image will occupy. + /// + /// When `null`, no custom loading state is shown and Flutter's default + /// behaviour applies. + final Widget Function(BuildContext context, double progress)? loadingBuilder; + + // ── Error ───────────────────────────────────────────────────────────────── + + /// Called when the image fails to load. + /// + /// The [retry] callback bumps an internal key so the image reloads from + /// scratch. + /// + /// When `null`, a default grey box with a refresh icon is shown. + final Widget Function(BuildContext context, Object error, VoidCallback retry)? errorBuilder; + + // ── Reveal ──────────────────────────────────────────────────────────────── + + /// Animation that plays once when the first image frame is decoded. + /// + /// Defaults to [GradientRevealAnimation] when `null`. + final LeafRevealAnimation? revealAnimation; + + // ── Decoration ──────────────────────────────────────────────────────────── + + /// Wraps the loaded image (e.g. with [ClipRRect] or [DecoratedBox]). + /// + /// This runs **before** the reveal animation, so the clip applies to both + /// the image and its reveal effect. + final Widget Function(BuildContext context, Widget child)? imageBuilder; + + // ── Interactivity ───────────────────────────────────────────────────────── + + /// Tapping the loaded image area. + /// + /// Applying a handler wraps the image in a transparent [Material] + + /// [InkWell] so you get the standard ripple/splash behaviour without + /// needing an external `Stack`. + final VoidCallback? onTap; + final VoidCallback? onDoubleTap; + final VoidCallback? onLongPress; + final VoidCallback? onSecondaryTap; + + // ── Lifecycle ───────────────────────────────────────────────────────────── + + /// Called when the image fails to load. + final void Function(Object error, StackTrace? stack)? onError; + + // ── Semantics ───────────────────────────────────────────────────────────── + + final String? semanticLabel; + final bool excludeFromSemantics; + + // ── Gapless playback ────────────────────────────────────────────────────── + + /// If `true`, keeps showing the old image while a new [image] provider loads. + final bool gaplessPlayback; + + // ────────────────────────────────────────────────────────────────────────── + + const LeafImage({ + super.key, + required this.image, + this.fit, + this.alignment = Alignment.center, + this.width, + this.height, + this.cacheWidth, + this.cacheHeight, + this.filterQuality = FilterQuality.low, + this.loadingBuilder, + this.errorBuilder, + this.revealAnimation = const GradientRevealAnimation(), + this.imageBuilder, + this.onTap, + this.onDoubleTap, + this.onLongPress, + this.onSecondaryTap, + this.onError, + this.semanticLabel, + this.excludeFromSemantics = false, + this.gaplessPlayback = false, + }); + + @override + State createState() => _LeafImageState(); +} + +class _LeafImageState extends State with SingleTickerProviderStateMixin { + late final AnimationController _revealController; + int _retryKey = 0; + bool _imageReady = false; + bool _wasSync = false; + bool _revealStarted = false; + + // ── Lifecycle ─────────────────────────────────────────────────────────── + + @override + void initState() { + super.initState(); + _revealController = AnimationController(duration: widget.revealAnimation?.duration ?? Duration.zero, vsync: this); + } + + @override + void dispose() { + _revealController.dispose(); + super.dispose(); + } + + @override + void didUpdateWidget(LeafImage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.image != widget.image || + oldWidget.cacheWidth != widget.cacheWidth || + oldWidget.cacheHeight != widget.cacheHeight) { + _retryKey = 0; + _imageReady = false; + _wasSync = false; + _revealStarted = false; + _revealController + ..reset() + ..duration = widget.revealAnimation?.duration ?? Duration.zero; + } + } + + // ── Retry ──────────────────────────────────────────────────────────────── + + void _handleRetry() { + setState(() { + _retryKey++; + _imageReady = false; + _wasSync = false; + _revealStarted = false; + _revealController.reset(); + }); + } + + void _startReveal(bool wasSync) { + if (_revealStarted) return; + _revealStarted = true; + _wasSync = wasSync; + + if (wasSync) { + _revealController.value = 1.0; + } else { + _revealController.forward(); + } + } + + // ── Helpers ────────────────────────────────────────────────────────────── + + bool get _hasTapHandler => + widget.onTap != null || widget.onDoubleTap != null || widget.onLongPress != null || widget.onSecondaryTap != null; + + /// Wraps the rendered image with decoration → reveal animation. + /// Interactivity is applied at the outermost layer in [build] so it's + /// present even during loading and error states. + Widget _wrapLoaded(Widget child) { + // 1. Custom decoration (ClipRRect, border, etc.) + if (widget.imageBuilder != null) { + child = widget.imageBuilder!(context, child); + } + + // 2. Reveal animation (null = disabled) + if (widget.revealAnimation != null && !_wasSync) { + child = widget.revealAnimation!.build(context, child, _revealController); + } + + return child; + } + + // ── Build ──────────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + final imageInkwell = _hasTapHandler + ? Positioned.fill( + child: Material( + type: MaterialType.transparency, + child: InkWell( + onTap: widget.onTap, + onDoubleTap: widget.onDoubleTap, + onLongPress: widget.onLongPress, + onSecondaryTap: widget.onSecondaryTap, + ), + ), + ) + : null; + final effectiveImage = (widget.cacheWidth != null || widget.cacheHeight != null) + ? ResizeImage.resizeIfNeeded(widget.cacheWidth, widget.cacheHeight, widget.image) + : widget.image; + Widget imageWidget = Image( + key: ValueKey('leaf_$_retryKey'), + image: effectiveImage, + fit: widget.fit, + alignment: widget.alignment, + width: widget.width, + height: widget.height, + filterQuality: widget.filterQuality, + gaplessPlayback: widget.gaplessPlayback, + semanticLabel: widget.semanticLabel, + excludeFromSemantics: widget.excludeFromSemantics, + loadingBuilder: imageInkwell != null + ? (context, child, loadingProgress) { + return Stack(children: [_loadingBuilder(context, child, loadingProgress), imageInkwell]); + } + : (widget.loadingBuilder != null ? _loadingBuilder : null), + frameBuilder: _frameBuilder, + errorBuilder: (context, error, stackTrace) { + final errorContent = _errorBuilder(context, error, stackTrace); + if (imageInkwell == null) return errorContent; + return SizedBox.expand(child: Stack(children: [imageInkwell, errorContent])); + }, + ); + + return SizedBox(width: widget.width, height: widget.height, child: imageWidget); + } + + Widget _loadingBuilder(BuildContext context, Widget child, ImageChunkEvent? progress) { + if (_imageReady || progress == null) { + // Already decoded or download complete — pass through to frameBuilder + return child; + } + + if (widget.loadingBuilder == null) { + // No custom skeleton — show the default placeholder + return child; + } + + final p = progress.expectedTotalBytes != null ? progress.cumulativeBytesLoaded / progress.expectedTotalBytes! : 0.0; + + return widget.loadingBuilder!(context, p); + } + + Widget _frameBuilder(BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { + if (frame != null) { + // First frame decoded + _imageReady = true; + _startReveal(wasSynchronouslyLoaded); + return _wrapLoaded(child); + } + return child; + } + + Widget _errorBuilder(BuildContext context, Object error, StackTrace? stackTrace) { + widget.onError?.call(error, stackTrace); + + if (widget.errorBuilder != null) { + return widget.errorBuilder!(context, error, _handleRetry); + } + + return _defaultError(); + } + + Widget _defaultError() { + return Container( + color: Colors.grey.shade800, + alignment: Alignment.center, + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 4, + children: [ + const Icon(Icons.image_not_supported, color: Colors.white38), + IconButton.outlined(icon: const Icon(Icons.refresh), onPressed: _handleRetry), + ], + ), + ); + } +} diff --git a/lib/src/misc/animated_favorite_button.dart b/lib/src/misc/animated_favorite_button.dart new file mode 100644 index 0000000..a7709ab --- /dev/null +++ b/lib/src/misc/animated_favorite_button.dart @@ -0,0 +1,239 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; + +/// The kind of animation currently playing. +enum _AnimKind { pop, shake } + +/// Heart toggle button with async-aware animation. +/// +/// All motion uses Flutter's built-in [Curves] for smooth 120 Hz output. +/// +/// - **idle** — shows the current heart (outlined / filled) +/// - **pending** — a network call is in flight; icon pulses gently +/// - **animating (pop)** — server accepted → `easeOut` up + `elasticOut` settle +/// - **animating (shake)** — server rejected → horizontal wobble via `easeOutBack` +/// +/// If [onChanged] is omitted the toggle is instant (no pending state). +class AnimatedFavoriteButton extends StatefulWidget { + final bool isFavorited; + final double size; + final Future Function(bool newIsFavorited)? onChanged; + + const AnimatedFavoriteButton({ + super.key, + this.isFavorited = false, + this.size = 24, + this.onChanged, + }); + + @override + State createState() => _AnimatedFavoriteButtonState(); +} + +class _AnimatedFavoriteButtonState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _ctrl; + + late bool _current; + bool? _target; + _AnimKind? _animKind; + + // ── Pre-built animation tweens (reusable across frames) ──────────────────── + + late final Animatable _favPop = TweenSequence([ + TweenSequenceItem( + weight: 35, + tween: Tween(begin: 1.0, end: 1.40).chain(CurveTween(curve: Curves.easeOut)), + ), + TweenSequenceItem( + weight: 65, + tween: Tween(begin: 1.40, end: 1.0).chain(CurveTween(curve: Curves.elasticOut)), + ), + ]); + + late final Animatable _unfavPop = TweenSequence([ + TweenSequenceItem( + weight: 30, + tween: Tween(begin: 1.0, end: 0.82).chain(CurveTween(curve: Curves.easeIn)), + ), + TweenSequenceItem( + weight: 70, + tween: Tween(begin: 0.82, end: 1.0).chain(CurveTween(curve: Curves.elasticOut)), + ), + ]); + + @override + void initState() { + super.initState(); + _current = widget.isFavorited; + _ctrl = AnimationController(vsync: this, duration: const Duration(milliseconds: 450)); + _ctrl.addListener(() => setState(() {})); + } + + @override + void didUpdateWidget(AnimatedFavoriteButton oldWidget) { + super.didUpdateWidget(oldWidget); + // Sync internal state with external prop when not mid-animation. + if (_animKind == null && _target == null) { + if (widget.isFavorited != _current) { + _current = widget.isFavorited; + setState(() {}); + } + } + } + + @override + void dispose() { + _ctrl.dispose(); + super.dispose(); + } + + Future _handleTap() async { + if (_ctrl.isAnimating || _target != null) return; + + final desired = !_current; + _target = desired; + + if (widget.onChanged == null) { + _current = desired; + _animKind = _AnimKind.pop; + await _ctrl.forward(from: 0.0); + if (mounted) _cleanUp(); + return; + } + + // ── 1. Pending ────────────────────────────────────────────────────────── + setState(() {}); + + try { + final success = await widget.onChanged!(desired); + if (!mounted) return; + + if (success) { + _current = desired; + _animKind = _AnimKind.pop; + } else { + _animKind = _AnimKind.shake; + } + } catch (_) { + if (!mounted) return; + _animKind = _AnimKind.shake; + } + + // ── 2. Animate ────────────────────────────────────────────────────────── + await _ctrl.forward(from: 0.0); + if (mounted) _cleanUp(); + } + + void _cleanUp() { + _animKind = null; + _target = null; + setState(() {}); + } + + // ── Build ────────────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final t = _ctrl.value; + final pending = widget.onChanged != null && _target != null && _animKind == null; + + // Icon & colour + bool showFilled; + Color color; + + if (_animKind == _AnimKind.pop) { + final filling = _target ?? true; + showFilled = filling ? t > 0.35 : t < 0.30; + color = showFilled ? Colors.red : cs.onSurfaceVariant; + } else if (_animKind == _AnimKind.shake) { + showFilled = _current; + color = Colors.red.shade200; + } else { + showFilled = _current; + color = _current ? Colors.red : cs.onSurfaceVariant; + } + + Widget icon = Icon( + showFilled ? Icons.favorite : Icons.favorite_border, + size: widget.size, + color: color, + ); + + // Transforms + if (pending) { + icon = _Pulse(child: icon); + } else if (_animKind == _AnimKind.pop) { + final scale = (_target ?? true) ? _favPop.evaluate(_ctrl) : _unfavPop.evaluate(_ctrl); + icon = Transform.scale(scale: scale, child: icon); + } else if (_animKind == _AnimKind.shake) { + // Decaying oscillation: easeOut envelope × sine + final amplitude = Curves.easeOut.transform(t) * 5.0; + final offset = amplitude * sin(t * pi * 6); // 3 full wobbles + icon = Transform.translate(offset: Offset(offset, 0), child: icon); + } + + // Material tap target: 40 dp circle, red-tinted hover, ink splash. + const tapSize = 40.0; + return SizedBox( + width: tapSize, + height: tapSize, + child: Material( + type: MaterialType.transparency, + child: InkWell( + borderRadius: BorderRadius.circular(tapSize / 2), + hoverColor: Colors.red.withValues(alpha: 0.10), + splashColor: Colors.red.withValues(alpha: 0.20), + highlightColor: Colors.red.withValues(alpha: 0.08), + onTap: _handleTap, + child: Center(child: icon), + ), + ), + ); + } +} + +/// Subtle opacity + scale pulse for the pending (in-flight) state. +class _Pulse extends StatefulWidget { + final Widget child; + const _Pulse({required this.child}); + + @override + State<_Pulse> createState() => _PulseState(); +} + +class _PulseState extends State<_Pulse> with SingleTickerProviderStateMixin { + late final AnimationController _ctrl; + + @override + void initState() { + super.initState(); + _ctrl = AnimationController(vsync: this, duration: const Duration(milliseconds: 900)) + ..repeat(reverse: true); + } + + @override + void dispose() { + _ctrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: _ctrl, + builder: (context, _) { + final v = Curves.easeInOutSine.transform(_ctrl.value); + return Opacity( + opacity: 0.45 + 0.55 * v, + child: Transform.scale( + scale: 0.92 + 0.08 * v, + child: widget.child, + ), + ); + }, + ); + } +} diff --git a/lib/src/misc/animated_star.dart b/lib/src/misc/animated_star.dart new file mode 100644 index 0000000..18a3e9c --- /dev/null +++ b/lib/src/misc/animated_star.dart @@ -0,0 +1,203 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; + +/// A 4-pointed sparkle star that continuously rotates and pulses in size. +/// Use as a "New posts" indicator icon. +/// +/// The silhouette is a concave-edged sparkle (sharp tips, curved bellies) +/// with an optional white-core shine gradient and a soft glow. +class AnimatedStar extends StatefulWidget { + /// Base size of the canvas in logical pixels. + final double size; + + /// Base color of the star (tips, glow, and the outer edge of the shine). + final Color color; + + /// Inner (elbow) radius as a fraction of the outer radius. + /// Smaller = deeper notches = sharper points. + final double innerRatio; + + /// Concave curvature of the edges, 0..1. + /// 0 = straight edges (classic star), ~0.3 = sparkle silhouette. + final double edgeCurve; + + /// Distance of the star tips from the center, as a fraction of the half-size. + /// Keep enough margin for [glowRatio] so the glow isn't clipped. + final double outerRatio; + + /// Glow blur radius as a fraction of [size]. 0 = no glow. + final double glowRatio; + + /// Opacity of the glow pass. + final double glowOpacity; + + /// Whether to fill with a white-core shine gradient instead of flat color. + final bool shine; + + const AnimatedStar({ + super.key, + this.size = 24, + this.color = Colors.amberAccent, + this.innerRatio = 0.25, + this.edgeCurve = 0.3, + this.outerRatio = 0.8, + this.glowRatio = 0.2, + this.glowOpacity = 0.3, + this.shine = true, + }); + + @override + State createState() => _AnimatedStarState(); +} + +class _AnimatedStarState extends State with SingleTickerProviderStateMixin { + late final AnimationController _ctrl; + + @override + void initState() { + super.initState(); + _ctrl = AnimationController(vsync: this, duration: const Duration(seconds: 2)) + ..repeat(); + } + + @override + void dispose() { + _ctrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: _ctrl, + builder: (context, _) { + final v = _ctrl.value; + + // Smooth ease-in-out twinkle: 2 pulses per full rotation. + final triangle = 1.0 - 2.0 * ((v * 2) % 1.0 - 0.5).abs(); + final scale = 0.70 + 0.30 * Curves.easeInOutSine.transform(triangle); + + return Transform.scale( + scale: scale, + child: Transform.rotate( + angle: v * 2 * pi, // linear rotation — constant speed + child: CustomPaint( + size: Size.square(widget.size), + painter: _FourPointStarPainter( + color: widget.color, + innerRatio: widget.innerRatio, + edgeCurve: widget.edgeCurve, + outerRatio: widget.outerRatio, + glowRatio: widget.glowRatio, + glowOpacity: widget.glowOpacity, + shine: widget.shine, + ), + ), + ), + ); + }, + ); + } +} + +class _FourPointStarPainter extends CustomPainter { + final Color color; + final double innerRatio; + final double edgeCurve; + final double outerRatio; + final double glowRatio; + final double glowOpacity; + final bool shine; + + const _FourPointStarPainter({ + required this.color, + required this.innerRatio, + required this.edgeCurve, + required this.outerRatio, + required this.glowRatio, + required this.glowOpacity, + required this.shine, + }); + + @override + void paint(Canvas canvas, Size size) { + final half = size.width / 2; + final center = Offset(half, half); + final outer = half * outerRatio; + final inner = outer * innerRatio; + final curve = edgeCurve.clamp(0.0, 1.0); + + final path = Path(); + for (var i = 0; i < 4; i++) { + final tipAngle = i * pi / 2 - pi / 2; + final tip = center + Offset(cos(tipAngle), sin(tipAngle)) * outer; + final nextTip = center + Offset(cos(tipAngle + pi / 2), sin(tipAngle + pi / 2)) * outer; + final elbowAngle = tipAngle + pi / 4; + final elbow = center + Offset(cos(elbowAngle), sin(elbowAngle)) * inner; + + if (i == 0) { + path.moveTo(tip.dx, tip.dy); + } else { + path.lineTo(tip.dx, tip.dy); + } + + if (curve > 0) { + // Each edge bows toward the center: control point pulled from the + // edge midpoint toward the star's center. + final mid1 = Offset((tip.dx + elbow.dx) / 2, (tip.dy + elbow.dy) / 2); + final mid2 = Offset((elbow.dx + nextTip.dx) / 2, (elbow.dy + nextTip.dy) / 2); + path.quadraticBezierTo( + mid1.dx + (center.dx - mid1.dx) * curve, + mid1.dy + (center.dy - mid1.dy) * curve, + elbow.dx, + elbow.dy, + ); + path.quadraticBezierTo( + mid2.dx + (center.dx - mid2.dx) * curve, + mid2.dy + (center.dy - mid2.dy) * curve, + nextTip.dx, + nextTip.dy, + ); + } else { + path.lineTo(elbow.dx, elbow.dy); + path.lineTo(nextTip.dx, nextTip.dy); + } + } + path.close(); + + // Glow pass + if (glowRatio > 0 && glowOpacity > 0) { + canvas.drawPath( + path, + Paint() + ..color = color.withValues(alpha: glowOpacity) + ..maskFilter = MaskFilter.blur(BlurStyle.normal, glowRatio * size.width), + ); + } + + // Fill pass — white-core radial gradient, light from the top-left + final fill = Paint()..style = PaintingStyle.fill; + if (shine) { + fill.shader = RadialGradient( + center: const Alignment(-0.25, -0.25), + radius: 1.2, + colors: [Color.lerp(color, Colors.white, 0.85)!, color], + stops: const [0.0, 0.45], + ).createShader(Rect.fromCircle(center: center, radius: outer)); + } else { + fill.color = color; + } + canvas.drawPath(path, fill); + } + + @override + bool shouldRepaint(_FourPointStarPainter old) => + old.color != color || + old.innerRatio != innerRatio || + old.edgeCurve != edgeCurve || + old.outerRatio != outerRatio || + old.glowRatio != glowRatio || + old.glowOpacity != glowOpacity || + old.shine != shine; +} diff --git a/lib/src/misc/leaf_async_chip.dart b/lib/src/misc/leaf_async_chip.dart new file mode 100644 index 0000000..285d736 --- /dev/null +++ b/lib/src/misc/leaf_async_chip.dart @@ -0,0 +1,176 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +/// Status of the async task shown by [LeafAsyncChip]. +enum LeafAsyncStatus { idle, running, done, error } + +/// Overlay chip that reports the progress and result of an async task. +/// +/// Trigger the task imperatively via `GlobalKey` and +/// `LeafAsyncChipState.run()`. While the task runs a spinner pill is shown +/// over [child] (determinate when the task reports progress, indeterminate +/// otherwise); on success it pops into a check + [doneLabel] pill that +/// auto-resets after [doneDuration]; on failure it shows an error pill for +/// [errorDuration], logs the error, and forwards it to [onError]. +class LeafAsyncChip extends StatefulWidget { + /// The widget the overlay renders on top of. + final Widget child; + + /// Label shown next to the spinner while the task runs. + final String runningLabel; + + /// Label shown next to the check when the task completes. Can be overridden + /// per-run via [LeafAsyncChipState.run]. + final String doneLabel; + + /// Label shown when the task throws. + final String errorLabel; + + /// How long the success pill stays visible before resetting to idle. + final Duration doneDuration; + + /// How long the error pill stays visible before resetting to idle. + final Duration errorDuration; + + /// Called with the task's error + stack trace when it throws. The error is + /// always debugPrinted regardless. + final void Function(Object error, StackTrace stackTrace)? onError; + + const LeafAsyncChip({ + super.key, + required this.child, + this.runningLabel = 'Working…', + this.doneLabel = 'Done', + this.errorLabel = 'Failed', + this.doneDuration = const Duration(milliseconds: 1200), + this.errorDuration = const Duration(milliseconds: 3000), + this.onError, + }); + + @override + State createState() => LeafAsyncChipState(); +} + +class LeafAsyncChipState extends State { + LeafAsyncStatus _status = LeafAsyncStatus.idle; + double? _progress; + String _doneLabel = ''; + Timer? _timer; + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + /// Runs [task], showing the running → done/error overlay. Ignores the call + /// while a task is already running. [doneLabel] overrides the widget's + /// default label for this run. + Future run({ + required Future Function(ValueChanged? onProgress) task, + String? doneLabel, + }) async { + if (_status == LeafAsyncStatus.running) return; + _timer?.cancel(); + setState(() { + _status = LeafAsyncStatus.running; + _progress = null; + _doneLabel = doneLabel ?? widget.doneLabel; + }); + try { + await task((p) { + if (mounted) setState(() => _progress = p.clamp(0.0, 1.0)); + }); + if (!mounted) return; + setState(() => _status = LeafAsyncStatus.done); + _timer = Timer(widget.doneDuration, _reset); + } catch (e, st) { + debugPrint('LeafAsyncChip: task failed: $e\n$st'); + if (!mounted) return; + setState(() => _status = LeafAsyncStatus.error); + _timer = Timer(widget.errorDuration, _reset); + widget.onError?.call(e, st); + } + } + + void _reset() { + if (mounted) setState(() => _status = LeafAsyncStatus.idle); + } + + @override + Widget build(BuildContext context) { + return Stack( + alignment: Alignment.center, + children: [ + widget.child, + if (_status != LeafAsyncStatus.idle) + IgnorePointer( + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 220), + transitionBuilder: (child, anim) => FadeTransition( + opacity: anim, + child: ScaleTransition( + scale: Tween(begin: 0.6, end: 1.0).animate( + CurvedAnimation(parent: anim, curve: Curves.easeOutBack), + ), + child: child, + ), + ), + child: _Pill(key: ValueKey(_status), status: _status, progress: _progress, label: _label), + ), + ), + ], + ); + } + + String get _label => switch (_status) { + LeafAsyncStatus.running => widget.runningLabel, + LeafAsyncStatus.done => _doneLabel, + LeafAsyncStatus.error => widget.errorLabel, + LeafAsyncStatus.idle => '', + }; +} + +class _Pill extends StatelessWidget { + final LeafAsyncStatus status; + final double? progress; + final String label; + + const _Pill({super.key, required this.status, required this.progress, required this.label}); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.75), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + switch (status) { + LeafAsyncStatus.running => SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + strokeWidth: 2, + value: progress, + color: Colors.white, + ), + ), + LeafAsyncStatus.done => const Icon(Icons.check, size: 16, color: Color(0xFF7CF29C)), + LeafAsyncStatus.error => const Icon(Icons.error_outline, size: 16, color: Color(0xFFFF6B6B)), + LeafAsyncStatus.idle => const SizedBox.shrink(), + }, + const SizedBox(width: 8), + Text( + label, + style: const TextStyle(color: Colors.white, fontSize: 12.5, fontWeight: FontWeight.w600), + ), + ], + ), + ); + } +} diff --git a/lib/src/popover/leaf_popover.dart b/lib/src/popover/leaf_popover.dart new file mode 100644 index 0000000..3d0b70e --- /dev/null +++ b/lib/src/popover/leaf_popover.dart @@ -0,0 +1,389 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +// ───────────────────────────────────────────────────────────────────────────── +// LeafPopoverController +// ───────────────────────────────────────────────────────────────────────────── + +/// Controls the visibility of an [LeafPopover] programmatically. +/// +/// Pass an instance to [LeafPopover.controller]. The controller is also passed to +/// the `popoverBuilder` so the popover content can dismiss itself. +class LeafPopoverController { + bool _isShowing = false; + + /// Whether the popover is currently showing. + bool get isShowing => _isShowing; + + /// Callbacks wired by the owning [LeafPopover] state. + void Function()? _onShow; + void Function()? _onHide; + + /// Show the popover. + void show() { + if (!_isShowing) { + _isShowing = true; + _onShow?.call(); + } + } + + /// Hide the popover. + void hide() { + if (_isShowing) { + _isShowing = false; + _onHide?.call(); + } + } + + /// Toggle visibility. + void toggle() { + if (_isShowing) { + hide(); + } else { + show(); + } + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// LeafPopover +// ───────────────────────────────────────────────────────────────────────────── + +/// A Material-styled popover that shows arbitrary content anchored to a child. +/// +/// On tap of [child], the content built by [popoverBuilder] is displayed in an +/// anchored overlay. Tap outside or press Escape to dismiss. +/// +/// The [popoverBuilder] receives the [LeafPopoverController] so the popover +/// content can dismiss itself (e.g. a close button inside the popover). +/// +/// Pass an optional [controller] for external show/hide control. If omitted, +/// the popover manages visibility internally. +/// +/// ```dart +/// LeafPopover( +/// popoverAnchor: Alignment.topCenter, +/// childAnchor: Alignment.bottomCenter, +/// spacing: 4, +/// popoverBuilder: (context, controller) => Card( +/// child: Padding( +/// padding: EdgeInsets.all(16), +/// child: Text('Popover content'), +/// ), +/// ), +/// child: TextButton(onPressed: null, child: Text('Open')), +/// ) +/// ``` +class LeafPopover extends StatefulWidget { + /// Builder for the popover overlay content. + /// + /// Receives the [LeafPopoverController] so the popover content can call + /// `controller.hide()` to dismiss itself. + final Widget Function(BuildContext context, LeafPopoverController controller) popoverBuilder; + + /// The trigger widget. Tapping it toggles the popover. + final Widget child; + + /// Anchor point on the popover itself. Defaults to [Alignment.topCenter]. + /// + /// Together with [childAnchor] this controls where the popover appears + /// relative to the child. For example with the default values the popover + /// appears centered above the child. + final AlignmentGeometry popoverAnchor; + + /// Anchor point on the child. Defaults to [Alignment.bottomCenter]. + /// + /// Together with [popoverAnchor] this controls where the popover appears + /// relative to the child. For example with the default values the popover + /// appears centered above the child, positioned just below the child. + final AlignmentGeometry childAnchor; + + /// Gap between the child edge and the popover edge. Defaults to 4. + final double spacing; + + /// Optional external controller for programmatic show/hide. + /// + /// If omitted, the popover creates its own internal controller. Either way + /// the controller is passed to [popoverBuilder] for self-dismiss. + final LeafPopoverController? controller; + + /// Called when the popover is dismissed. + final VoidCallback? onDismissed; + + const LeafPopover({ + required this.popoverBuilder, + required this.child, + this.popoverAnchor = Alignment.topCenter, + this.childAnchor = Alignment.bottomCenter, + this.spacing = 4, + this.controller, + this.onDismissed, + super.key, + }); + + @override + State createState() => _LeafPopoverState(); +} + +class _LeafPopoverState extends State { + final _overlayController = OverlayPortalController(); + final _childKey = GlobalKey(); + final _fallbackController = LeafPopoverController(); + + late final LeafPopoverController _controller; + Offset? _childGlobalPosition; + Size? _childSize; + + @override + void initState() { + super.initState(); + _controller = widget.controller ?? _fallbackController; + _controller._onShow = _show; + _controller._onHide = _hide; + } + + @override + void dispose() { + // Unwire callbacks so the controller doesn't call into disposed state. + if (!identical(_controller, _fallbackController)) { + _controller._onShow = null; + _controller._onHide = null; + } + _fallbackController._onShow = null; + _fallbackController._onHide = null; + super.dispose(); + } + + void _show() { + if (_overlayController.isShowing) return; + final renderBox = _childKey.currentContext?.findRenderObject() as RenderBox?; + if (renderBox == null || !renderBox.attached) return; + + _childGlobalPosition = renderBox.localToGlobal(Offset.zero); + _childSize = renderBox.size; + setState(() {}); + _overlayController.show(); + } + + void _hide() { + _overlayController.hide(); + widget.onDismissed?.call(); + } + + void _onChildTap() { + _controller.toggle(); + } + + @override + Widget build(BuildContext context) { + return OverlayPortal( + controller: _overlayController, + overlayChildBuilder: (_) { + if (_childGlobalPosition == null || _childSize == null) { + return const SizedBox.shrink(); + } + return _PopoverOverlay( + childGlobalPosition: _childGlobalPosition!, + childSize: _childSize!, + popoverAnchor: widget.popoverAnchor, + childAnchor: widget.childAnchor, + spacing: widget.spacing, + popoverBuilder: widget.popoverBuilder, + controller: _controller, + onDismiss: () => _controller.hide(), + ); + }, + child: GestureDetector( + onTap: _onChildTap, + behavior: HitTestBehavior.translucent, + child: KeyedSubtree(key: _childKey, child: widget.child), + ), + ); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// _PopoverOverlay +// ───────────────────────────────────────────────────────────────────────────── + +class _PopoverOverlay extends StatefulWidget { + final Offset childGlobalPosition; + final Size childSize; + final AlignmentGeometry popoverAnchor; + final AlignmentGeometry childAnchor; + final double spacing; + final Widget Function(BuildContext context, LeafPopoverController controller) popoverBuilder; + final LeafPopoverController controller; + final VoidCallback onDismiss; + + const _PopoverOverlay({ + required this.childGlobalPosition, + required this.childSize, + required this.popoverAnchor, + required this.childAnchor, + required this.spacing, + required this.popoverBuilder, + required this.controller, + required this.onDismiss, + }); + + @override + State<_PopoverOverlay> createState() => _PopoverOverlayState(); +} + +class _PopoverOverlayState extends State<_PopoverOverlay> with SingleTickerProviderStateMixin { + late final AnimationController _animCtrl; + late final Animation _fade; + late final Animation _scale; + + /// Key on the popover content so we can measure its actual size for + /// positioning. + final _menuKey = GlobalKey(); + + /// Adjusted position after overflow detection. + Offset? _adjustedPos; + + /// Whether the exit animation is running. + bool _dismissing = false; + + // ── lifecycle ───────────────────────────────────────────────────────────── + + @override + void initState() { + super.initState(); + + _animCtrl = AnimationController(duration: const Duration(milliseconds: 100), vsync: this); + + _fade = CurvedAnimation(parent: _animCtrl, curve: Curves.linear); + _scale = CurvedAnimation(parent: _animCtrl, curve: Curves.easeOutCubic); + + _animCtrl.addStatusListener(_onStatusChanged); + _animCtrl.forward(); + + // Measure and adjust position after first layout. + WidgetsBinding.instance.addPostFrameCallback((_) => _adjustPosition()); + } + + @override + void dispose() { + _animCtrl.removeStatusListener(_onStatusChanged); + _animCtrl.dispose(); + super.dispose(); + } + + void _onStatusChanged(AnimationStatus status) { + if (status == AnimationStatus.dismissed && _dismissing) { + widget.onDismiss(); + } + } + + // ── positioning ─────────────────────────────────────────────────────────── + + /// Compute the desired popover position given its size. + /// + /// Pass [Size.zero] for a rough estimate before measurement. + Offset _computeDesiredPosition(Size popoverSize) { + final dir = Directionality.of(context); + final childAnchor = widget.childAnchor.resolve(dir); + final popoverAnchor = widget.popoverAnchor.resolve(dir); + + // Offset from top-left of each rect to the anchor point. + final childOffset = Offset(widget.childSize.width / 2 * (childAnchor.x + 1), widget.childSize.height / 2 * (childAnchor.y + 1)); + final popoverOffset = Offset(popoverSize.width / 2 * (popoverAnchor.x + 1), popoverSize.height / 2 * (popoverAnchor.y + 1)); + + // Base position: the childAnchor point on the child aligns with the + // popoverAnchor point on the popover. + final baseX = widget.childGlobalPosition.dx + childOffset.dx - popoverOffset.dx; + final baseY = widget.childGlobalPosition.dy + childOffset.dy - popoverOffset.dy; + + // Spacing pushes the popover further away from the child, in the direction + // normal to the anchored edge. + final spacingDirX = (childAnchor.x - popoverAnchor.x).sign; + final spacingDirY = (childAnchor.y - popoverAnchor.y).sign; + + return Offset(baseX + spacingDirX * widget.spacing, baseY + spacingDirY * widget.spacing); + } + + void _adjustPosition() { + final menuBox = _menuKey.currentContext?.findRenderObject() as RenderBox?; + if (menuBox == null || !menuBox.hasSize) return; + + final menuSize = menuBox.size; + final mediaQuery = MediaQuery.of(context); + final screen = mediaQuery.size; + final padding = mediaQuery.padding; + + var pos = _computeDesiredPosition(menuSize); + + // Horizontal overflow → slide left. + if (pos.dx + menuSize.width > screen.width - padding.right) { + pos = Offset(screen.width - menuSize.width - padding.right, pos.dy); + } + // Vertical overflow → slide up. + if (pos.dy + menuSize.height > screen.height - padding.bottom) { + pos = Offset(pos.dx, screen.height - menuSize.height - padding.bottom); + } + + // Edge clamping (positive padding only). + pos = Offset( + pos.dx.clamp(padding.left, screen.width - menuSize.width - padding.right), + pos.dy.clamp(padding.top, screen.height - menuSize.height - padding.bottom), + ); + + if (_adjustedPos == null || _adjustedPos! != pos) { + setState(() => _adjustedPos = pos); + } + } + + // ── dismiss ─────────────────────────────────────────────────────────────── + + void _dismiss() { + if (_dismissing) return; + _dismissing = true; + _animCtrl.reverse(); + } + + // ── build ───────────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + // Use a rough estimate (popover at Size.zero) for the initial frame before + // _adjustPosition runs. The entrance animation starts at opacity 0.0 / + // scale 0.93, so the flash is imperceptible. + final pos = _adjustedPos ?? _computeDesiredPosition(Size.zero); + + return Stack( + children: [ + // Invisible barrier catching all pointer events. Menu items (above in + // the stack) take priority via their own gesture absorption. + Positioned.fill( + child: Listener( + onPointerDown: (_) => _dismiss(), + behavior: HitTestBehavior.translucent, + child: Container(color: Colors.transparent), + ), + ), + // The popover content itself. + Positioned( + left: pos.dx, + top: pos.dy, + child: Material( + type: MaterialType.transparency, + child: CallbackShortcuts( + bindings: {const SingleActivator(LogicalKeyboardKey.escape): _dismiss}, + child: FocusScope( + child: FadeTransition( + opacity: Tween(begin: 0, end: 1).animate(_fade), + child: ScaleTransition( + scale: Tween(begin: 0.93, end: 1).animate(_scale), + child: KeyedSubtree(key: _menuKey, child: widget.popoverBuilder(context, widget.controller)), + ), + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/src/viewer/leaf_pan_zoom_recognizer.dart b/lib/src/viewer/leaf_pan_zoom_recognizer.dart new file mode 100644 index 0000000..5d50252 --- /dev/null +++ b/lib/src/viewer/leaf_pan_zoom_recognizer.dart @@ -0,0 +1,89 @@ +import 'package:flutter/gestures.dart'; + +/// Multi-touch pan/pinch recognizer for [LeafViewer] pages. +/// +/// Ported from photo_view's `PhotoViewGestureRecognizer` (MIT): a +/// [ScaleGestureRecognizer] that decides per move event whether to claim the +/// gesture via [shouldClaim]. +/// +/// Unlike photo_view, the decision is made once on the first meaningful move +/// (beyond finger-jitter tolerance) and resolved immediately (accept or +/// reject) — this prevents the recognizer's own slop-based auto-accept +/// (18-36px, see `_advanceStateMachine`) from outracing the PageView's drag +/// (18px) on large per-event deltas. +/// +/// Rejecting leaves the arena to the parent (the PageView's horizontal drag +/// or the viewer's dismiss drag) — this is what makes edge-release work: a +/// drag starting at a fully clamped position pages/dismisses instead of +/// panning. +/// +/// This recognizer must NOT touch the base's private bookkeeping +/// (`_pointerLocations`, `_initialFocalPoint`, `_currentFocalPoint`): +/// [ScaleGestureRecognizer.handleEvent] recomputes its own focal/span state +/// from those fields on every event, and re-stamping them here corrupts the +/// pinch anchor and the double-tap arena. +class LeafPanZoomRecognizer extends ScaleGestureRecognizer { + LeafPanZoomRecognizer({required this.shouldClaim, super.debugOwner}); + + /// Whether a pan with the given finger delta should be claimed. + final bool Function(Offset fingerDelta) shouldClaim; + + /// Movement under this distance is treated as finger jitter — it never + /// decides the claim, letting a double-tap run its course on a noisy tap. + static const double _jitterSlop = 4.0; + + int _activePointers = 0; + Offset _moveDelta = Offset.zero; + int? _movingPointer; + bool _claimDecided = false; + bool _claimed = false; + + @override + void addAllowedPointer(PointerDownEvent event) { + _activePointers++; + super.addAllowedPointer(event); + } + + @override + void didStopTrackingLastPointer(int pointer) { + _activePointers = 0; + _moveDelta = Offset.zero; + _movingPointer = null; + _claimDecided = false; + _claimed = false; + super.didStopTrackingLastPointer(pointer); + } + + @override + void handleEvent(PointerEvent event) { + if (event is PointerMoveEvent && !event.synthesized) { + if (event.pointer == _movingPointer) { + _moveDelta += event.localDelta; + } else { + _movingPointer = event.pointer; + _moveDelta = event.localDelta; + } + + if (!_claimDecided && !_claimed && _moveDelta.distance > _jitterSlop) { + _claimDecided = true; + if (_activePointers > 1 || shouldClaim(_moveDelta)) { + _claimed = true; + // Full arena claim (NOT acceptGesture alone — that only sets the + // local state, leaving the arena open so another member can later + // win and reject us while `started`). The base handler then runs + // safely: the arena is already resolved in our favor. + resolve(GestureDisposition.accepted); + super.handleEvent(event); + return; + } + // Reject BEFORE the base's own auto-accept (pan slop 18-36px): the + // arena removes us and stops tracking (state becomes `ready`), so + // `super.handleEvent` must not run — it asserts on `ready` state. + resolve(GestureDisposition.rejected); + return; + } + } + + super.handleEvent(event); + } +} diff --git a/lib/src/viewer/leaf_viewer.dart b/lib/src/viewer/leaf_viewer.dart new file mode 100644 index 0000000..98d330f --- /dev/null +++ b/lib/src/viewer/leaf_viewer.dart @@ -0,0 +1,415 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/physics.dart'; +import 'package:flutter/rendering.dart' show RenderViewportBase; +import 'package:flutter/services.dart'; + +import 'leaf_viewer_internal.dart'; +import 'leaf_zoom_controller.dart'; + +/// Fullscreen pager with per-page zoom, boundary-aware edge release and a +/// viewer-level dismiss gesture. +/// +/// Pages are built by [pageBuilder]. Wrap a page's content in [LeafZoomable] +/// to give it zoom/pan/double-tap; pages without one get paging + dismiss +/// only. +/// +/// Gesture arbitration happens in the gesture arena (no raw pointer routing): +/// - [LeafZoomable]'s pan/zoom recognizer claims drags only when the child +/// can actually move (zoomed + a free axis); otherwise the PageView's drag +/// (horizontal) or the dismiss drag (perpendicular) wins — edge-release +/// - the mouse wheel zooms cursor-anchored on all platforms; a plain wheel +/// over a scrollable under the viewer scrolls that scrollable instead +/// - a quick tap outside the active image fires [onTapOutside] +/// - keyboard (when the viewer has focus): the arrows page prev/next, +/// Esc dismisses (via [onDismissed] or pop); disabled with +/// [enableKeyboard] +/// +/// Desktop (Windows/Linux/macOS) differs from touch: no mouse drag paging, no +/// drag dismiss and no double-tap ([enableSwipeGestures] forces the touch +/// behaviour anywhere — the close button / wheel / keyboard replace them). +/// When [controlsBuilder] is null on desktop a default control set +/// (previous/next, close, page counter) is shown. +class LeafViewer extends StatefulWidget { + const LeafViewer({ + super.key, + required this.pageCount, + required this.pageBuilder, + this.pageController, + this.initialPage = 0, + this.scrollDirection = Axis.horizontal, + this.onPageChanged, + this.dismissEnabled = true, + this.onDismissed, + this.onTapOutside, + this.backgroundBuilder, + this.controlsBuilder, + this.enableSwipeGestures, + this.enableKeyboard = true, + }); + + final int pageCount; + final Widget Function(BuildContext context, int index) pageBuilder; + final PageController? pageController; + final int initialPage; + final Axis scrollDirection; + final ValueChanged? onPageChanged; + final bool dismissEnabled; + final VoidCallback? onDismissed; + final VoidCallback? onTapOutside; + + /// Builds the layer behind the pager. Receives the dismiss progress in + /// `[0, 1]` for backdrop fading. + final Widget Function(BuildContext context, double progress)? backgroundBuilder; + + /// Builds the chrome overlay on top of the pager (media_kit `controlsBuilder` + /// style). When null, a default control set is shown on desktop and nothing + /// on touch platforms. + final Widget Function(BuildContext context, LeafViewerControls controls)? controlsBuilder; + + /// Force the touch gesture set (swipe paging, drag dismiss, double-tap) on + /// any platform. Null = platform default (off on desktop, on elsewhere). + final bool? enableSwipeGestures; + + /// Whether the viewer grabs keyboard focus and handles the arrows for + /// paging and Esc for dismissal (default true). + final bool enableKeyboard; + + /// The zoom controller of the currently active page, if any. + static LeafZoomController? controllerOf(BuildContext context) { + return LeafViewerScope.maybeOf(context)?.registry.activeController; + } + + @override + State createState() => _LeafViewerState(); +} + +/// State passed to [LeafViewer.controlsBuilder]. +class LeafViewerControls { + const LeafViewerControls({required this.pageCount, required this.currentIndex, required this.goToPage}); + + final int pageCount; + final int currentIndex; + + /// Animates to the given page index (clamped by [pageCount]). + final void Function(int index) goToPage; + + bool get canGoPrevious => currentIndex > 0; + bool get canGoNext => currentIndex < pageCount - 1; +} + +class _LeafViewerState extends State with TickerProviderStateMixin implements LeafViewerRegistry { + late final PageController _pageController; + late final AnimationController _dismissCtrl; + final Map _controllers = {}; + final ValueNotifier _indexNotifier = ValueNotifier(0); + final FocusNode _focusNode = FocusNode(); + + int _currentIndex = 0; + bool _dismissing = false; + Size _viewerSize = Size.zero; + + LeafZoomController? get _activeController => _controllers[_currentIndex]; + + bool get _swipeMode => widget.enableSwipeGestures ?? !leafIsDesktopPlatform(); + + @override + bool get swipeGesturesEnabled => _swipeMode; + + KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) { + if (event is! KeyDownEvent && event is! KeyRepeatEvent) return KeyEventResult.ignored; + final horizontal = widget.scrollDirection == Axis.horizontal; + final prev = horizontal ? LogicalKeyboardKey.arrowLeft : LogicalKeyboardKey.arrowUp; + final next = horizontal ? LogicalKeyboardKey.arrowRight : LogicalKeyboardKey.arrowDown; + final key = event.logicalKey; + if (key == prev) { + _goToPage(_currentIndex - 1); + return KeyEventResult.handled; + } + if (key == next) { + _goToPage(_currentIndex + 1); + return KeyEventResult.handled; + } + if (key == LogicalKeyboardKey.escape) { + if (widget.onDismissed != null) { + widget.onDismissed!(); + } else { + Navigator.maybePop(context); + } + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + } + + @override + void initState() { + super.initState(); + _currentIndex = widget.pageController?.initialPage ?? widget.initialPage; + _indexNotifier.value = _currentIndex; + _pageController = widget.pageController ?? PageController(initialPage: _currentIndex); + _dismissCtrl = AnimationController.unbounded(vsync: this) + ..addListener(() { + if (mounted) setState(() {}); + }); + } + + @override + void dispose() { + _focusNode.dispose(); + _dismissCtrl.dispose(); + _indexNotifier.dispose(); + if (widget.pageController == null) _pageController.dispose(); + super.dispose(); + } + + // ── Controller registry ───────────────────────────────────────────────── + + @override + void register(int index, LeafZoomController ctrl) { + _controllers[index] = ctrl; + } + + @override + void unregister(int index, LeafZoomController ctrl) { + if (_controllers[index] == ctrl) _controllers.remove(index); + } + + @override + LeafZoomController? get activeController => _controllers[_currentIndex]; + + void _onPageIndexChanged(int index) { + _currentIndex = index; + _indexNotifier.value = index; + } + + void _goToPage(int index) { + if (index < 0 || index >= widget.pageCount) return; + _pageController.animateToPage(index, duration: const Duration(milliseconds: 200), curve: Curves.easeOut); + } + + // ── Dismiss ───────────────────────────────────────────────────────────── + + double get _dismissOffset => _dismissCtrl.value; + double get _dismissExtent => widget.scrollDirection == Axis.horizontal ? _viewerSize.height : _viewerSize.width; + double get _dismissProgress => _dismissExtent > 0 ? (_dismissOffset.abs() / (_dismissExtent * 0.5)).clamp(0.0, 1.0) : 0.0; + + Offset get _dismissOffsetVector => widget.scrollDirection == Axis.horizontal ? Offset(0, _dismissOffset) : Offset(_dismissOffset, 0); + + void _onDismissStart(DragStartDetails details) { + _activeController?.cancelGesture(); + } + + void _onDismissUpdate(DragUpdateDetails details) { + _dismissCtrl.value += widget.scrollDirection == Axis.horizontal ? details.delta.dy : details.delta.dx; + } + + void _onDismissEnd(DragEndDetails details) { + _endDismissDrag(details.primaryVelocity ?? 0); + } + + void _endDismissDrag(double velocity) { + if (_dismissing || !widget.dismissEnabled) return; + final offset = _dismissCtrl.value; + final extent = _dismissExtent; + if (velocity.abs() > 800 || offset.abs() > extent * 0.25) { + _dismissing = true; + final dir = velocity.abs() > 50 ? velocity.sign : (offset.sign == 0 ? 1.0 : offset.sign); + _dismissCtrl.animateTo(dir * extent * 1.5, duration: const Duration(milliseconds: 200), curve: Curves.easeIn).then((_) { + if (!mounted) return; + final onDismissed = widget.onDismissed; + if (onDismissed != null) { + onDismissed(); + } else { + Navigator.maybePop(context); + } + }); + } else { + _dismissCtrl.animateWith(SpringSimulation(const SpringDescription(mass: 1, stiffness: 600, damping: 50), offset, 0, velocity)); + } + } + + void _onTapUp(TapUpDetails details) { + final ctrl = _activeController; + if (ctrl != null && !ctrl.zoomed && !ctrl.imageRect.contains(details.localPosition)) { + widget.onTapOutside?.call(); + } + } + + void _onPointerSignal(PointerSignalEvent e) { + if (e is! PointerScrollEvent) return; + final ctrl = _activeController; + if (ctrl == null || _viewerSize == Size.zero) return; + // Plain wheel over a scrollable under the viewer scrolls that scrollable + // (it registers deeper, so the resolver picks it first); everywhere else, + // and on Ctrl+wheel or once zoomed, the wheel zooms cursor-anchored. + if (!HardwareKeyboard.instance.isControlPressed && !ctrl.zoomed) { + final hit = HitTestResult(); + GestureBinding.instance.hitTestInView(hit, e.position, e.viewId); + final overScrollable = hit.path.any((entry) => + entry.target is RenderViewportBase && + (entry.target as RenderViewportBase).axis == Axis.vertical); + if (overScrollable) return; + } + GestureBinding.instance.pointerSignalResolver.register(e, (event) { + final scroll = event as PointerScrollEvent; + ctrl.wheelZoom(scroll.scrollDelta.dy, scroll.localPosition); + }); + } + + // ── Build ─────────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + final progress = _dismissProgress; + final behavior = ScrollConfiguration.of(context); + final horizontal = widget.scrollDirection == Axis.horizontal; + final desktop = leafIsDesktopPlatform(); + final swipeMode = _swipeMode; + return Focus( + focusNode: _focusNode, + autofocus: widget.enableKeyboard, + onKeyEvent: widget.enableKeyboard ? _onKeyEvent : null, + child: LeafViewerScope( + registry: this, + child: LayoutBuilder( + builder: (context, constraints) { + _viewerSize = constraints.biggest; + return Stack( + fit: StackFit.expand, + children: [ + if (widget.backgroundBuilder != null) widget.backgroundBuilder!(context, progress), + Listener( + behavior: HitTestBehavior.opaque, + onPointerSignal: _onPointerSignal, + child: GestureDetector( + onVerticalDragStart: horizontal && widget.dismissEnabled && swipeMode ? _onDismissStart : null, + onVerticalDragUpdate: horizontal && widget.dismissEnabled && swipeMode ? _onDismissUpdate : null, + onVerticalDragEnd: horizontal && widget.dismissEnabled && swipeMode ? _onDismissEnd : null, + onHorizontalDragStart: !horizontal && widget.dismissEnabled && swipeMode ? _onDismissStart : null, + onHorizontalDragUpdate: !horizontal && widget.dismissEnabled && swipeMode ? _onDismissUpdate : null, + onHorizontalDragEnd: !horizontal && widget.dismissEnabled && swipeMode ? _onDismissEnd : null, + onTapUp: _onTapUp, + child: Transform.translate( + offset: _dismissOffsetVector, + child: Transform.scale( + scale: 1.0 - _dismissProgress * 0.15, + child: ScrollConfiguration( + behavior: behavior.copyWith( + dragDevices: swipeMode ? {...behavior.dragDevices, PointerDeviceKind.mouse} : behavior.dragDevices, + ), + child: PageView.builder( + controller: _pageController, + physics: const PageScrollPhysics(), + scrollDirection: widget.scrollDirection, + // Keep adjacent pages alive so their zoom state + // survives swipes (and preloads neighbors). + allowImplicitScrolling: true, + itemCount: widget.pageCount, + onPageChanged: (index) { + widget.onPageChanged?.call(index); + _onPageIndexChanged(index); + }, + itemBuilder: (context, index) { + return LeafPageIndexScope(index: index, child: widget.pageBuilder(context, index)); + }, + ), + ), + ), + ), + ), + ), + if (widget.controlsBuilder != null) + ValueListenableBuilder( + valueListenable: _indexNotifier, + builder: (context, index, _) => widget.controlsBuilder!( + context, + LeafViewerControls(pageCount: widget.pageCount, currentIndex: index, goToPage: _goToPage), + ), + ) + else if (desktop) + ValueListenableBuilder( + valueListenable: _indexNotifier, + builder: (context, index, _) => + _LeafViewerDefaultControls(controls: LeafViewerControls(pageCount: widget.pageCount, currentIndex: index, goToPage: _goToPage)), + ), + ], + ); + }, + ), + ), + ); + } +} + +class _LeafViewerDefaultControls extends StatelessWidget { + const _LeafViewerDefaultControls({required this.controls}); + + final LeafViewerControls controls; + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + Positioned( + left: 8, + top: 0, + bottom: 0, + child: Center( + child: _ControlButton( + icon: Icons.chevron_left, + onTap: controls.canGoPrevious ? () => controls.goToPage(controls.currentIndex - 1) : null, + ), + ), + ), + Positioned( + right: 8, + top: 0, + bottom: 0, + child: Center( + child: _ControlButton( + icon: Icons.chevron_right, + onTap: controls.canGoNext ? () => controls.goToPage(controls.currentIndex + 1) : null, + ), + ), + ), + Positioned( + top: 8, + right: 8, + child: _ControlButton(icon: Icons.close, onTap: () => Navigator.maybePop(context)), + ), + Positioned( + left: 0, + right: 0, + bottom: 16, + child: IgnorePointer( + child: Text( + '${controls.currentIndex + 1} / ${controls.pageCount}', + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white70, fontSize: 14, fontFeatures: [FontFeature.tabularFigures()]), + ), + ), + ), + ], + ); + } +} + +class _ControlButton extends StatelessWidget { + const _ControlButton({required this.icon, required this.onTap}); + + final IconData icon; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + return IconButton( + onPressed: onTap, + icon: Icon(icon), + tooltip: null, + style: IconButton.styleFrom( + backgroundColor: Colors.black.withValues(alpha: 0.45), + foregroundColor: Colors.white, + ), + ); + } +} diff --git a/lib/src/viewer/leaf_viewer_internal.dart b/lib/src/viewer/leaf_viewer_internal.dart new file mode 100644 index 0000000..42ec0d2 --- /dev/null +++ b/lib/src/viewer/leaf_viewer_internal.dart @@ -0,0 +1,53 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +import 'leaf_zoom_controller.dart'; + +/// Whether the current platform is a desktop OS. Desktop viewers swap swipe +/// gestures for controls: no mouse paging, no drag dismiss, no double-tap. +bool leafIsDesktopPlatform() { + if (kIsWeb) return false; + return defaultTargetPlatform == TargetPlatform.windows || + defaultTargetPlatform == TargetPlatform.linux || + defaultTargetPlatform == TargetPlatform.macOS; +} + +/// Internal: registry contract between [LeafViewer] and [LeafZoomable]. +/// Not exported from the package barrel. +abstract class LeafViewerRegistry { + void register(int index, LeafZoomController ctrl); + void unregister(int index, LeafZoomController ctrl); + LeafZoomController? get activeController; + + /// Whether the touch gesture set (double-tap etc.) is active. + bool get swipeGesturesEnabled; +} + +/// Internal: registry scope shared between [LeafViewer] and [LeafZoomable]. +class LeafViewerScope extends InheritedWidget { + const LeafViewerScope({required this.registry, super.key, required super.child}); + + final LeafViewerRegistry registry; + + static LeafViewerScope? maybeOf(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType(); + } + + @override + bool updateShouldNotify(LeafViewerScope oldWidget) => false; +} + +/// Internal: provides a page's index to [LeafZoomable] so it can register its +/// controller with the viewer. +class LeafPageIndexScope extends InheritedWidget { + const LeafPageIndexScope({required this.index, super.key, required super.child}); + + final int index; + + static int? maybeOf(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType()?.index; + } + + @override + bool updateShouldNotify(LeafPageIndexScope oldWidget) => oldWidget.index != index; +} diff --git a/lib/src/viewer/leaf_zoom_controller.dart b/lib/src/viewer/leaf_zoom_controller.dart new file mode 100644 index 0000000..7c02f9e --- /dev/null +++ b/lib/src/viewer/leaf_zoom_controller.dart @@ -0,0 +1,387 @@ +import 'dart:math' as math; + +import 'package:flutter/scheduler.dart'; +import 'package:flutter/widgets.dart'; + +/// Double-tap cycle position (ported from photo_view's scale-state cycle, +/// adapted to our scale convention where 1.0 = contained). +enum _LeafZoomState { initial, covering, originalSize, zoomedIn, zoomedOut } + +class _CornersRange { + const _CornersRange(this.min, this.max); + final double min; + final double max; +} + +class _HitCorners { + const _HitCorners(this.hasHitMin, this.hasHitMax); + final bool hasHitMin; + final bool hasHitMax; + bool get hasHitAny => hasHitMin || hasHitMax; + bool get hasHitBoth => hasHitMin && hasHitMax; +} + +/// Per-page zoom state for [LeafViewer]. +/// +/// Scale is relative to the contained (fit-to-screen) size, so 1.0 is the +/// resting scale. Position is the translation in screen pixels. +/// +/// Boundary math (pan corners, clamping) and the double-tap cycle are ported +/// from photo_view (MIT) and verified by property tests; input handling, +/// fling physics and animation curves are our own. +class LeafZoomController extends ChangeNotifier { + LeafZoomController({this.maxScale = 5.0, required TickerProvider vsync}) + : _vsync = vsync { + _animCtrl = AnimationController(vsync: vsync, duration: _animDuration) + ..addListener(_onAnimTick); + } + + static const double _minScale = 1.0; + static const Duration _animDuration = Duration(milliseconds: 200); + + /// Upper zoom limit (relative to contained). + final double maxScale; + final TickerProvider _vsync; + late final AnimationController _animCtrl; + + /// Viewport (page) size in pixels. Set by [LeafZoomable] on layout. + Size viewport = Size.zero; + + /// Contained (fit-to-screen) render size of the child. Set by + /// [LeafZoomable] on layout. + Size childSize = Size.zero; + + /// Full-resolution child size (for the 1:1 double-tap step). + /// Null disables the 1:1 step. + Size? originalSize; + + double _scale = 1.0; + Offset _position = Offset.zero; + + _LeafZoomState _state = _LeafZoomState.initial; + bool _snapOnCancel = false; + Animation? _matrixAnim; + + Ticker? _flingTicker; + double _flingVx = 0, _flingVy = 0; + int _flingId = 0; + bool _disposed = false; + + /// Fired when the scale reaches the 1.0 or max limit (haptics hook). + VoidCallback? onZoomLimit; + + double get scale => _scale; + Offset get position => _position; + + /// Whether the child is zoomed beyond the resting scale. + bool get zoomed => _scale > 1.001; + bool get isAnimating => _animCtrl.isAnimating; + bool get isFlinging => _flingTicker?.isActive ?? false; + bool get isInteracting => isAnimating || isFlinging; + + /// The on-screen rect of the child at the current scale/position. + Rect get imageRect { + final w = childSize.width * _scale; + final h = childSize.height * _scale; + return Rect.fromLTWH( + (viewport.width - w) / 2 + _position.dx, + (viewport.height - h) / 2 + _position.dy, + w, + h, + ); + } + + /// Notify layout changes. Recomputes cycle-state scales and reclamps. + void updateLayout({required Size viewport, required Size childSize, Size? originalSize}) { + final changed = viewport != this.viewport || childSize != this.childSize || originalSize != this.originalSize; + this.viewport = viewport; + this.childSize = childSize; + this.originalSize = originalSize; + if (!changed || isInteracting) return; + if (_state != _LeafZoomState.zoomedIn && _state != _LeafZoomState.zoomedOut) { + _scale = _scaleForState(_state); + } + _position = _clampPosition(_position, _scale); + notifyListeners(); + } + + // ── Gestures ──────────────────────────────────────────────────────────── + + /// Cancel any running fling/animation. If the animation was heading back to + /// 1×, snap there instantly so a following swipe pages instead of panning. + void cancelGesture() { + _cancelFling(); + if (_animCtrl.isAnimating) { + _animCtrl.stop(); + if (_snapOnCancel) { + _snapToInitial(); + } + } + } + + /// Single-finger pan while zoomed. + void panBy(Offset delta) { + _setZoom(_scale, _position + delta); + } + + /// Unified pan/pinch update: scale to [newScale] while keeping the child + /// point under [prevFocal] anchored to [curFocal]. For a pure pan the scale + /// is unchanged and this reduces to `position += curFocal - prevFocal`. + void scaleUpdate(double newScale, Offset prevFocal, Offset curFocal) { + final oldScale = _scale; + final clamped = newScale.clamp(_minScale, maxScale); + final anchored = curFocal + (_position - prevFocal) * (clamped / oldScale); + _setZoom(clamped, anchored); + _checkHaptic(oldScale, _scale); + } + + /// Cursor-anchored wheel zoom. + void wheelZoom(double scrollDy, Offset cursor) { + _cancelFling(); + final oldScale = _scale; + final newScale = (_scale * (1 - scrollDy * 0.001)).clamp(_minScale, maxScale); + if (newScale == oldScale) return; + final vpc = Offset(viewport.width / 2, viewport.height / 2); + final anchored = (cursor - vpc) + (_position - (cursor - vpc)) * (newScale / oldScale); + _setZoom(newScale, anchored); + _checkHaptic(oldScale, _scale); + } + + /// Double-tap: advance the 1× → covered → 1:1 → 1× cycle, zooming in + /// around [tapPoint]. + void doubleTap(Offset tapPoint) { + cancelGesture(); + final state = _state; + if (state == _LeafZoomState.zoomedIn || state == _LeafZoomState.zoomedOut) { + _animateToState(_LeafZoomState.initial, tapPoint); + return; + } + var prevScale = _scaleForState(state); + var prevState = state; + var nextScale = prevScale; + var nextState = state; + do { + prevScale = nextScale; + prevState = nextState; + nextState = _cycle(prevState); + nextScale = _scaleForState(nextState); + } while (prevScale == nextScale && state != nextState); + if (prevScale == nextScale) return; + _animateToState(nextState, tapPoint); + } + + /// Velocity-proportional pan fling (friction 0.92/frame, tap-to-stop). + void startFling(Offset velocity) { + _cancelFling(); + final speed = velocity.distance; + if (speed < 50) return; + _flingVx = velocity.dx; + _flingVy = velocity.dy; + _flingId++; + final id = _flingId; + const friction = 0.92; + _flingTicker = _vsync.createTicker((elapsed) { + if (_disposed || _flingId != id) { + _cancelFling(); + return; + } + if (Offset(_flingVx, _flingVy).distance < 5) { + _cancelFling(); + return; + } + _setZoom(_scale, _position + Offset(_flingVx / 60, _flingVy / 60)); + _flingVx *= friction; + _flingVy *= friction; + })..start(); + } + + // ── Edge-release (ported from photo_view's HitCornersDetector) ────────── + + /// Whether a drag with per-event [fingerDelta] should be claimed as a pan. + /// Claims when either axis can still move the child; releases only when + /// fully clamped (the LoliSnatcher `Axis.values` behaviour). + /// + /// [fingerDelta] is the raw finger movement. The ported corner rules use + /// photo_view's sign convention (negated movement), so the delta is + /// inverted internally. + bool shouldClaim(Offset fingerDelta) => shouldMoveX(fingerDelta) || shouldMoveY(fingerDelta); + + bool shouldMoveX(Offset fingerDelta) => _shouldMoveAxis(_hitCornersX(), -fingerDelta.dx, -fingerDelta.dy); + bool shouldMoveY(Offset fingerDelta) => _shouldMoveAxis(_hitCornersY(), -fingerDelta.dy, -fingerDelta.dx); + + bool _shouldMoveAxis(_HitCorners corners, double mainAxisMove, double crossAxisMove) { + if (mainAxisMove == 0) return false; + if (!corners.hasHitAny) return true; + final axisBlocked = corners.hasHitBoth || (corners.hasHitMax ? mainAxisMove > 0 : mainAxisMove < 0); + return !axisBlocked; + } + + _HitCorners _hitCornersX() { + final childWidth = childSize.width * _scale; + if (viewport.width >= childWidth) return const _HitCorners(true, true); + final x = -_position.dx; + final corners = _cornersX(); + return _HitCorners(x <= corners.min, x >= corners.max); + } + + _HitCorners _hitCornersY() { + final childHeight = childSize.height * _scale; + if (viewport.height >= childHeight) return const _HitCorners(true, true); + final y = -_position.dy; + final corners = _cornersY(); + return _HitCorners(y <= corners.min, y >= corners.max); + } + + _CornersRange _cornersX({double? scale}) { + final widthDiff = childSize.width * (scale ?? _scale) - viewport.width; + return _CornersRange(-widthDiff / 2, widthDiff / 2); + } + + _CornersRange _cornersY({double? scale}) { + final heightDiff = childSize.height * (scale ?? _scale) - viewport.height; + return _CornersRange(-heightDiff / 2, heightDiff / 2); + } + + Offset _clampPosition(Offset position, double scale) { + final computedWidth = childSize.width * scale; + final computedHeight = childSize.height * scale; + double finalX = 0; + if (viewport.width < computedWidth) { + final c = _cornersX(scale: scale); + finalX = position.dx.clamp(c.min, c.max); + } + double finalY = 0; + if (viewport.height < computedHeight) { + final c = _cornersY(scale: scale); + finalY = position.dy.clamp(c.min, c.max); + } + return Offset(finalX, finalY); + } + + // ── Double-tap cycle (ported from photo_view's nextScaleState) ────────── + + double _scaleForState(_LeafZoomState state) { + switch (state) { + case _LeafZoomState.initial: + case _LeafZoomState.zoomedIn: + case _LeafZoomState.zoomedOut: + return _minScale; + case _LeafZoomState.covering: + return _clampScale(math.max(viewport.width / childSize.width, viewport.height / childSize.height)); + case _LeafZoomState.originalSize: + final o = originalSize; + if (o == null || o.width <= 0 || o.height <= 0) return _minScale; + final contained = math.min(viewport.width / o.width, viewport.height / o.height); + return _clampScale(1 / contained); + } + } + + double _clampScale(double s) => s.clamp(_minScale, maxScale); + + _LeafZoomState _cycle(_LeafZoomState s) { + switch (s) { + case _LeafZoomState.initial: + return _LeafZoomState.covering; + case _LeafZoomState.covering: + return _LeafZoomState.originalSize; + case _LeafZoomState.originalSize: + return _LeafZoomState.initial; + case _LeafZoomState.zoomedIn: + case _LeafZoomState.zoomedOut: + return _LeafZoomState.initial; + } + } + + void _animateToState(_LeafZoomState target, Offset tapPoint) { + final targetScale = _scaleForState(target); + final Offset targetPosition; + if (targetScale > _scale) { + final vpc = Offset(viewport.width / 2, viewport.height / 2); + targetPosition = _clampPosition( + (tapPoint - vpc) + (_position - (tapPoint - vpc)) * (targetScale / _scale), + targetScale, + ); + } else { + targetPosition = Offset.zero; + } + _state = target; + _animateZoomTo(targetScale, targetPosition); + } + + void _animateZoomTo(double targetScale, Offset targetPosition) { + _cancelFling(); + final begin = Matrix4.identity() + ..setEntry(0, 3, _position.dx) + ..setEntry(1, 3, _position.dy) + ..setEntry(0, 0, _scale) + ..setEntry(1, 1, _scale); + final end = Matrix4.identity() + ..setEntry(0, 3, targetPosition.dx) + ..setEntry(1, 3, targetPosition.dy) + ..setEntry(0, 0, targetScale) + ..setEntry(1, 1, targetScale); + _snapOnCancel = targetScale == _minScale; + _matrixAnim = Matrix4Tween(begin: begin, end: end) + .animate(CurvedAnimation(parent: _animCtrl, curve: Curves.easeOut)); + _animCtrl.forward(from: 0).whenCompleteOrCancel(() { + if (_disposed) return; + _scale = targetScale; + _position = _clampPosition(targetPosition, targetScale); + _snapOnCancel = false; + notifyListeners(); + }); + } + + void _onAnimTick() { + final anim = _matrixAnim; + if (anim == null) return; + _scale = anim.value.getMaxScaleOnAxis(); + final t = anim.value.getTranslation(); + _position = Offset(t.x, t.y); + notifyListeners(); + } + + void _setZoom(double newScale, Offset newPosition) { + if (newScale != _minScale) { + _state = newScale > _minScale ? _LeafZoomState.zoomedIn : _LeafZoomState.zoomedOut; + } else { + _state = _LeafZoomState.initial; + } + final clamped = _clampPosition(newPosition, newScale); + if (_scale == newScale && _position == clamped) return; + _scale = newScale; + _position = clamped; + notifyListeners(); + } + + void _checkHaptic(double oldScale, double newScale) { + if (oldScale == newScale) return; + if ((newScale == _minScale && oldScale != _minScale) || (newScale == maxScale && oldScale != maxScale)) { + onZoomLimit?.call(); + } + } + + void _cancelFling() { + final t = _flingTicker; + if (t != null && t.isActive) t.stop(); + _flingTicker = null; + _flingId++; + } + + void _snapToInitial() { + _scale = _minScale; + _position = Offset.zero; + _state = _LeafZoomState.initial; + _snapOnCancel = false; + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _cancelFling(); + _animCtrl.removeListener(_onAnimTick); + _animCtrl.dispose(); + super.dispose(); + } +} diff --git a/lib/src/viewer/leaf_zoomable.dart b/lib/src/viewer/leaf_zoomable.dart new file mode 100644 index 0000000..6b0ba2c --- /dev/null +++ b/lib/src/viewer/leaf_zoomable.dart @@ -0,0 +1,243 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'leaf_pan_zoom_recognizer.dart'; +import 'leaf_viewer_internal.dart'; +import 'leaf_zoom_controller.dart'; + +/// Opt-in per-page zoom wrapper for [LeafViewer]. +/// +/// Wrap a page's content to give it zoom/pan/double-tap behaviour. Pages +/// without a [LeafZoomable] only get paging and dismiss. +/// +/// [childSize] is the contained (fit-to-screen) render size of the child. +/// Optional: when null the zoom clamps against the viewport (always works, +/// slightly loose for letterboxed images). [originalSize] is the +/// full-resolution size of the child and enables the 1:1 double-tap step; +/// when null that step is skipped. +/// +/// Use [LeafZoomable.image] to render a plain image: its pixel dimensions +/// are extracted from the image stream at load time, so both the contained +/// size and the 1:1 step work without passing anything. +/// +/// Set [enabled] to false to render content without zoom (e.g. until the +/// image has loaded). +class LeafZoomable extends StatefulWidget { + const LeafZoomable({ + super.key, + required this.child, + this.childSize, + this.originalSize, + this.maxScale = 5.0, + this.enabled = true, + }) : image = null; + + const LeafZoomable.image({ + super.key, + required Image image, + this.maxScale = 5.0, + this.enabled = true, + }) : child = image, + childSize = null, + originalSize = null, + image = image; + + final Widget child; + final Size? childSize; + final Size? originalSize; + + /// Non-null when created via [LeafZoomable.image]: the image's pixel + /// dimensions are resolved from its stream to size the zoom correctly. + final Image? image; + + final double maxScale; + final bool enabled; + + /// The contained (letterboxed) size of [source] inside [viewport]. + static Size containSize(Size viewport, Size source) { + final ratio = source.width / source.height; + if (viewport.width / viewport.height > ratio) { + return Size(viewport.height * ratio, viewport.height); + } + return Size(viewport.width, viewport.width / ratio); + } + + @override + State createState() => _LeafZoomableState(); +} + +class _LeafZoomableState extends State with TickerProviderStateMixin { + late final LeafZoomController _controller; + int? _index; + LeafViewerRegistry? _registry; + double _scaleBefore = 1.0; + Offset _prevFocal = Offset.zero; + + ImageStream? _imageStream; + ImageStreamListener? _imageListener; + Size? _decodedSize; + bool _imageResolved = false; + + @override + void initState() { + super.initState(); + _controller = LeafZoomController(maxScale: widget.maxScale, vsync: this) + ..onZoomLimit = () => HapticFeedback.mediumImpact(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final index = LeafPageIndexScope.maybeOf(context); + final registry = LeafViewerScope.maybeOf(context)?.registry; + if (index != _index || registry != _registry) { + _unregister(); + _index = index; + _registry = registry; + _register(); + } + if (widget.image != null && !_imageResolved) { + _imageResolved = true; + _resolveImageDimensions(); + } + } + + @override + void didUpdateWidget(LeafZoomable oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.maxScale != widget.maxScale) { + _controller.updateLayout(viewport: _controller.viewport, childSize: _controller.childSize, originalSize: _controller.originalSize); + } + if (oldWidget.enabled != widget.enabled) { + if (widget.enabled) { + _register(); + } else { + _unregister(); + } + } + } + + void _register() { + final index = _index; + if (index == null || !widget.enabled) return; + _registry?.register(index, _controller); + } + + void _unregister() { + final index = _index; + if (index == null) return; + _registry?.unregister(index, _controller); + } + + void _resolveImageDimensions() { + final image = widget.image!; + final stream = image.image.resolve(createLocalImageConfiguration(context)); + final listener = ImageStreamListener((info, _) { + if (!mounted) return; + setState(() { + _decodedSize = Size(info.image.width.toDouble(), info.image.height.toDouble()); + }); + }); + stream.addListener(listener); + _imageStream = stream; + _imageListener = listener; + } + + @override + void dispose() { + if (_imageStream != null && _imageListener != null) { + _imageStream!.removeListener(_imageListener!); + } + _unregister(); + _controller.dispose(); + super.dispose(); + } + + void _onScaleStart(ScaleStartDetails details) { + _controller.cancelGesture(); + _scaleBefore = _controller.scale; + _prevFocal = details.localFocalPoint; + } + + void _onScaleUpdate(ScaleUpdateDetails details) { + final newScale = _scaleBefore * details.scale; + _controller.scaleUpdate(newScale, _prevFocal, details.localFocalPoint); + _prevFocal = details.localFocalPoint; + } + + void _onScaleEnd(ScaleEndDetails details) { + if ((_controller.scale - _scaleBefore).abs() < 0.001) { + final v = details.velocity.pixelsPerSecond; + if (v.distance > 300) _controller.startFling(v); + } + } + + void _onPointerSignal(PointerSignalEvent event) { + if (event is! PointerScrollEvent) return; + if (!widget.enabled) return; + // Ctrl+scroll always zooms; plain scroll also zooms once zoomed (so the + // wheel can zoom back out). Otherwise the event passes through to the + // enclosing scrollable. + if (!HardwareKeyboard.instance.isControlPressed && !_controller.zoomed) return; + GestureBinding.instance.pointerSignalResolver.register(event, (event) { + final scroll = event as PointerScrollEvent; + _controller.wheelZoom(scroll.scrollDelta.dy, scroll.localPosition); + }); + } + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) { + final viewport = constraints.biggest; + final decoded = _decodedSize; + final contained = widget.childSize ?? + (decoded != null ? LeafZoomable.containSize(viewport, decoded) : viewport); + final original = widget.originalSize ?? decoded; + final content = Center( + child: SizedBox( + width: contained.width, + height: contained.height, + child: widget.child, + ), + ); + if (!widget.enabled) return content; + _controller.updateLayout(viewport: viewport, childSize: contained, originalSize: original); + return ListenableBuilder( + listenable: _controller, + builder: (context, _) { + final transform = Matrix4.identity() + ..setEntry(0, 3, _controller.position.dx) + ..setEntry(1, 3, _controller.position.dy) + ..setEntry(0, 0, _controller.scale) + ..setEntry(1, 1, _controller.scale); + final gestures = { + LeafPanZoomRecognizer: GestureRecognizerFactoryWithHandlers( + () => LeafPanZoomRecognizer(shouldClaim: _controller.shouldClaim, debugOwner: this), + (instance) => instance + ..onStart = _onScaleStart + ..onUpdate = _onScaleUpdate + ..onEnd = _onScaleEnd, + ), + }; + if (LeafViewerScope.maybeOf(context)?.registry.swipeGesturesEnabled ?? false) { + gestures[DoubleTapGestureRecognizer] = GestureRecognizerFactoryWithHandlers( + () => DoubleTapGestureRecognizer(debugOwner: this), + (instance) => instance.onDoubleTapDown = (details) => _controller.doubleTap(details.localPosition), + ); + } + return Listener( + onPointerSignal: _onPointerSignal, + child: RawGestureDetector( + behavior: HitTestBehavior.translucent, + gestures: gestures, + child: Transform(transform: transform, alignment: Alignment.center, child: content), + ), + ); + }, + ); + }, + ); + } +} diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..badbc81 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,19 @@ +name: leaf_widgets +description: "Leaf UI widgets: fullscreen page viewer, context menu, popover, image widget, animated star/favorite. Zero external dependencies." +version: 0.0.1 +publish_to: 'none' + +environment: + sdk: ^3.13.0-282.3.beta + flutter: ">=1.17.0" + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: diff --git a/test/leaf_async_chip_test.dart b/test/leaf_async_chip_test.dart new file mode 100644 index 0000000..7015153 --- /dev/null +++ b/test/leaf_async_chip_test.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:leaf_widgets/leaf_widgets.dart'; + +Widget _host(LeafAsyncChip chip) => MaterialApp(home: Scaffold(body: Center(child: chip))); + +void main() { + testWidgets('shows running spinner, then done label, then resets', (tester) async { + final key = GlobalKey(); + await tester.pumpWidget(_host(LeafAsyncChip( + key: key, + doneLabel: 'Copied', + child: const SizedBox(width: 100, height: 100), + ))); + + key.currentState!.run(task: (_) => Future.delayed(const Duration(seconds: 1)), doneLabel: 'Image copied'); + await tester.pump(); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + + await tester.pump(const Duration(seconds: 1)); + expect(find.text('Image copied'), findsOneWidget); + + await tester.pump(const Duration(milliseconds: 300)); + expect(find.byType(CircularProgressIndicator), findsNothing); + + await tester.pump(const Duration(seconds: 2)); + expect(find.text('Image copied'), findsNothing); + }); + + testWidgets('reports progress to a determinate spinner', (tester) async { + final key = GlobalKey(); + await tester.pumpWidget(_host(LeafAsyncChip( + key: key, + child: const SizedBox(width: 100, height: 100), + ))); + + key.currentState!.run(task: (onProgress) async { + onProgress?.call(0.5); + await Future.delayed(const Duration(milliseconds: 50)); + }); + await tester.pump(); + + final spinner = tester.widget(find.byType(CircularProgressIndicator)); + expect(spinner.value, 0.5); + + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(const Duration(milliseconds: 1300)); + }); + + testWidgets('shows error label, calls onError, then resets', (tester) async { + final key = GlobalKey(); + Object? seenError; + StackTrace? seenStack; + await tester.pumpWidget(_host(LeafAsyncChip( + key: key, + errorLabel: 'Copy failed', + onError: (e, st) { + seenError = e; + seenStack = st; + }, + child: const SizedBox(width: 100, height: 100), + ))); + + key.currentState!.run(task: (_) async => throw StateError('boom')); + await tester.pump(); + + expect(find.text('Copy failed'), findsOneWidget); + expect(seenError, isA()); + expect(seenStack, isNotNull); + + await tester.pump(const Duration(seconds: 4)); + expect(find.text('Copy failed'), findsNothing); + }); + + testWidgets('ignores run() while a task is running', (tester) async { + final key = GlobalKey(); + var runs = 0; + await tester.pumpWidget(_host(LeafAsyncChip( + key: key, + doneLabel: 'Copied', + child: const SizedBox(width: 100, height: 100), + ))); + + key.currentState!.run(task: (_) async { + runs++; + await Future.delayed(const Duration(milliseconds: 100)); + }, doneLabel: 'First'); + await tester.pump(); + key.currentState!.run(task: (_) async => runs++, doneLabel: 'Second'); + await tester.pump(); + + await tester.pump(const Duration(milliseconds: 200)); + expect(runs, 1); + expect(find.text('First'), findsOneWidget); + expect(find.text('Second'), findsNothing); + + await tester.pump(const Duration(milliseconds: 1200)); + }); +} diff --git a/test/leaf_context_menu_test.dart b/test/leaf_context_menu_test.dart new file mode 100644 index 0000000..4699bb1 --- /dev/null +++ b/test/leaf_context_menu_test.dart @@ -0,0 +1,120 @@ +import 'dart:async'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:leaf_widgets/leaf_widgets.dart'; + +Future _openMenu(WidgetTester tester) async { + final gesture = await tester.startGesture( + tester.getCenter(find.byType(LeafContextMenu)), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryButton, + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); // entrance animation + await gesture.up(); +} + +Widget _host(List entries) => MaterialApp( + home: Scaffold( + body: Center( + child: LeafContextMenu(entries: entries, child: const Text('trigger')), + ), + ), + ); + +void main() { + testWidgets('async action: spinner → check, menu locked while running, auto-dismiss on success', (tester) async { + final completer = Completer(); + await tester.pumpWidget(_host([ContextMenuAsyncAction(label: 'Copy image', task: (_) => completer.future)])); + + await _openMenu(tester); + expect(find.text('Copy image'), findsOneWidget); + + await tester.tap(find.text('Copy image')); + await tester.pump(); + expect(find.text('Copying…'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + + // Outside taps are ignored while the task runs. + await tester.tapAt(const Offset(5, 5)); + await tester.pump(); + expect(find.text('Copying…'), findsOneWidget); + + completer.complete(); + await tester.pump(); + expect(find.text('Copied'), findsOneWidget); + expect(find.byIcon(Icons.check), findsOneWidget); + + await tester.pump(const Duration(milliseconds: 700)); // doneDuration + await tester.pump(const Duration(milliseconds: 150)); // exit animation + expect(find.text('Copied'), findsNothing); + }); + + testWidgets('async action: reported progress drives a determinate bar', (tester) async { + final completer = Completer(); + await tester.pumpWidget(_host([ + ContextMenuAsyncAction(label: 'Copy image', task: (onProgress) { + onProgress?.call(0.5); + return completer.future; + }), + ])); + + await _openMenu(tester); + await tester.tap(find.text('Copy image')); + await tester.pump(); + + final bar = tester.widget(find.byType(LinearProgressIndicator)); + expect(bar.value, 0.5); + + completer.complete(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 900)); + }); + + testWidgets('async action: failure shows error label and calls onError', (tester) async { + Object? seen; + await tester.pumpWidget(_host([ + ContextMenuAsyncAction( + label: 'Copy image', + task: (_) async => throw StateError('boom'), + onError: (e, _) => seen = e, + ), + ])); + + await _openMenu(tester); + await tester.tap(find.text('Copy image')); + await tester.pump(); + + expect(find.text('Failed'), findsOneWidget); + expect(find.byIcon(Icons.error_outline), findsOneWidget); + expect(seen, isA()); + + await tester.pump(const Duration(milliseconds: 1400)); // errorDuration + await tester.pump(const Duration(milliseconds: 150)); // exit animation + expect(find.text('Failed'), findsNothing); + }); + + testWidgets('other entries are disabled while an async action runs', (tester) async { + final completer = Completer(); + var syncTaps = 0; + await tester.pumpWidget(_host([ + ContextMenuAction(label: 'Sync item', onTap: () => syncTaps++), + ContextMenuAsyncAction(label: 'Copy image', task: (_) => completer.future), + ])); + + await _openMenu(tester); + await tester.tap(find.text('Copy image')); + await tester.pump(); + + await tester.tap(find.text('Sync item')); + await tester.pump(); + expect(syncTaps, 0); + expect(find.text('Copying…'), findsOneWidget); + + completer.complete(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 900)); + }); +} diff --git a/test/leaf_widgets_test.dart b/test/leaf_widgets_test.dart new file mode 100644 index 0000000..7d861d9 --- /dev/null +++ b/test/leaf_widgets_test.dart @@ -0,0 +1,37 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:leaf_widgets/leaf_widgets.dart'; + +void main() { + testWidgets('barrel exports build all widgets', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Column( + children: [ + const AnimatedStar(), + const AnimatedFavoriteButton(), + LeafImage(image: MemoryImage(Uint8List(0))), + LeafPopover( + popoverBuilder: (context, controller) => const Card(child: Text('popover')), + child: const Text('trigger'), + ), + LeafContextMenu( + entries: const [ContextMenuAction(label: 'Copy')], + child: const Text('menu'), + ), + ], + ), + ), + ), + ); + expect(find.byType(AnimatedStar), findsOneWidget); + expect(find.byType(AnimatedFavoriteButton), findsOneWidget); + expect(find.byType(LeafImage), findsOneWidget); + expect(find.byType(LeafPopover), findsOneWidget); + expect(find.byType(LeafContextMenu), findsOneWidget); + }); +} diff --git a/test/viewer/leaf_viewer_test.dart b/test/viewer/leaf_viewer_test.dart new file mode 100644 index 0000000..427bf86 --- /dev/null +++ b/test/viewer/leaf_viewer_test.dart @@ -0,0 +1,482 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:leaf_widgets/leaf_widgets.dart'; + +Widget _zoomablePage(BuildContext context, int i) => LeafZoomable( + childSize: const Size(400, 300), + originalSize: const Size(1600, 1200), + child: Container(color: const Color(0xFF112233)), + ); + +Widget _harness({ + Widget Function(BuildContext, int)? pageBuilder, + ValueChanged? onPageChanged, + VoidCallback? onDismissed, + VoidCallback? onTapOutside, + ValueChanged? onProgress, + bool? enableSwipeGestures, +}) { + return MaterialApp( + home: Scaffold( + body: LeafViewer( + pageCount: 3, + pageBuilder: pageBuilder ?? _zoomablePage, + onPageChanged: onPageChanged, + onDismissed: onDismissed, + onTapOutside: onTapOutside, + enableSwipeGestures: enableSwipeGestures, + backgroundBuilder: onProgress == null + ? null + : (context, p) { + onProgress(p); + return Container(color: Colors.black); + }, + ), + ), + ); +} + +LeafZoomController _controller(WidgetTester tester) { + return LeafViewer.controllerOf(tester.element(find.byType(LeafZoomable)))!; +} + +Future _slowDrag(WidgetTester tester, Offset from, Offset delta, {int steps = 8}) async { + final g = await tester.startGesture(from); + await tester.pump(); + final step = delta / steps.toDouble(); + for (var i = 0; i < steps; i++) { + await g.moveBy(step); + await tester.pump(const Duration(milliseconds: 200)); + } + await g.up(); + await tester.pumpAndSettle(); +} + +Future _doubleTapAt(WidgetTester tester, Offset pos) async { + await tester.tapAt(pos); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tapAt(pos); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 250)); +} + +Future _wheel(WidgetTester tester, double dy) async { + await tester.sendEventToBinding(PointerScrollEvent( + position: const Offset(400, 300), + scrollDelta: Offset(0, dy), + kind: PointerDeviceKind.mouse, + )); + await tester.pump(); +} + +// Pinch from (300,300)/(500,300) outward so the finger distance reaches [targetDist]. +Future _pinchOut(WidgetTester tester, double targetDist) async { + final g1 = await tester.startGesture(const Offset(300, 300)); + final g2 = await tester.startGesture(const Offset(500, 300)); + await tester.pump(); + final spread = targetDist - 200; + await g1.moveTo(Offset(300 - spread / 2, 300)); + await g2.moveTo(Offset(500 + spread / 2, 300)); + await tester.pump(); + await g1.up(); + await g2.up(); + await tester.pump(const Duration(milliseconds: 350)); // flush double-tap countdown +} + +void main() { + testWidgets('1× horizontal drag pages', (tester) async { + var page = 0; + await tester.pumpWidget(_harness(onPageChanged: (i) => page = i)); + await _slowDrag(tester, const Offset(700, 300), const Offset(-500, 0)); + expect(page, 1); + }); + + testWidgets('mouse drag pages (dragDevices fix)', (tester) async { + var page = 0; + await tester.pumpWidget(_harness(onPageChanged: (i) => page = i)); + final g = await tester.startGesture(const Offset(700, 300), kind: PointerDeviceKind.mouse); + await tester.pump(); + for (var i = 0; i < 8; i++) { + await g.moveBy(const Offset(-62.5, 0)); + await tester.pump(const Duration(milliseconds: 50)); + } + await g.up(); + await tester.pumpAndSettle(); + expect(page, 1); + }); + + testWidgets('zoomed pan does not page', (tester) async { + var page = 0; + await tester.pumpWidget(_harness(onPageChanged: (i) => page = i)); + await _pinchOut(tester, 600); // 3×, anchored at (-50,-150) + final ctrl = _controller(tester); + expect(ctrl.scale, 3.0); + await _slowDrag(tester, const Offset(700, 300), const Offset(150, 0)); // pan right + expect(ctrl.position.dx, 100); + expect(page, 0); + }); + + testWidgets('zoomed + clamped at edge releases mid-drag and pages', (tester) async { + var page = 0; + await tester.pumpWidget(_harness(onPageChanged: (i) => page = i)); + await _pinchOut(tester, 600); // 3× at (-50,-150) + final ctrl = _controller(tester); + await _slowDrag(tester, const Offset(700, 300), const Offset(-250, 0)); // pan to X clamp + expect(ctrl.position.dx, -200); + expect(page, 0); + await _slowDrag(tester, const Offset(700, 300), const Offset(-500, 0)); // released at edge → pages + expect(page, 1); + }); + + testWidgets('zoomed + clamped vertically: continuing the drag dismisses', (tester) async { + var dismissed = false; + await tester.pumpWidget(_harness(onDismissed: () => dismissed = true)); + await _pinchOut(tester, 600); // 3×, Y clamped at -150 + // Drag further up from the top clamp → edge-release dismiss (offset > 25%). + await _slowDrag(tester, const Offset(400, 400), const Offset(0, -300), steps: 6); + expect(dismissed, isTrue); + }); + + testWidgets('1× small vertical drag springs back without dismissing', (tester) async { + var dismissed = false; + var progress = 1.0; + await tester.pumpWidget(_harness(onDismissed: () => dismissed = true, onProgress: (p) => progress = p)); + await tester.timedDrag(find.byType(LeafViewer), const Offset(0, 100), const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + expect(dismissed, isFalse); + expect(progress, lessThan(0.001)); // spring settles asymptotically, never exactly 0 + }); + + testWidgets('1× vertical drag past 25% flies off and dismisses', (tester) async { + var dismissed = false; + var sawProgress = false; + await tester.pumpWidget(_harness(onDismissed: () => dismissed = true, onProgress: (p) { + if (p > 0.2) sawProgress = true; + })); + await tester.timedDrag(find.byType(LeafViewer), const Offset(0, 400), const Duration(milliseconds: 200)); + await tester.pumpAndSettle(); + expect(dismissed, isTrue); + expect(sawProgress, isTrue); + }); + + testWidgets('1× fast small drag flies off via velocity', (tester) async { + var dismissed = false; + await tester.pumpWidget(_harness(onDismissed: () => dismissed = true)); + await tester.timedDrag(find.byType(LeafViewer), const Offset(0, 100), const Duration(milliseconds: 50)); + await tester.pumpAndSettle(); + expect(dismissed, isTrue); + }); + + testWidgets('1× vertical drag anywhere dismisses (no off-image gate)', (tester) async { + var dismissed = false; + await tester.pumpWidget(_harness(onDismissed: () => dismissed = true)); + // Image rect is (200,150,400,300) — starting above it still dismisses. + await tester.timedDragFrom(const Offset(400, 40), const Offset(0, 400), const Duration(milliseconds: 200)); + await tester.pumpAndSettle(); + expect(dismissed, isTrue); + }); + + testWidgets('tap outside the image pops, tap on the image does not', (tester) async { + var outside = 0; + await tester.pumpWidget(_harness(onTapOutside: () => outside++)); + await tester.tapAt(const Offset(10, 10)); + await tester.pump(const Duration(milliseconds: 350)); // flush double-tap countdown + expect(outside, 1); + await tester.tapAt(const Offset(400, 300)); + await tester.pump(const Duration(milliseconds: 350)); + expect(outside, 1); + }); + + testWidgets('wheel zooms from any scale in both directions', (tester) async { + await tester.pumpWidget(_harness()); + await _wheel(tester, -1000); + expect(_controller(tester).scale, closeTo(2.0, 0.01)); // zooms from 1× + await _wheel(tester, -1000); + expect(_controller(tester).scale, closeTo(4.0, 0.01)); + await _wheel(tester, 3000); + expect(_controller(tester).scale, closeTo(1.0, 0.01)); + await _wheel(tester, 1000); // at 1×, wheel down clamps + expect(_controller(tester).scale, 1.0); + }); + + testWidgets('double-tap cycles 1× → covered → 1:1 → 1× through the viewer', (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: LeafViewer( + pageCount: 3, + pageBuilder: (context, i) => LeafZoomable( + childSize: const Size(360, 300), + originalSize: const Size(1440, 1200), + child: Container(color: const Color(0xFF112233)), + ), + ), + ), + )); + await _doubleTapAt(tester, const Offset(400, 300)); + expect(_controller(tester).scale, closeTo(2.22, 0.01)); // covered + await _doubleTapAt(tester, const Offset(400, 300)); + expect(_controller(tester).scale, closeTo(2.0, 0.01)); // 1:1 + await _doubleTapAt(tester, const Offset(400, 300)); + expect(_controller(tester).scale, closeTo(1.0, 0.01)); + }); + + testWidgets('pinch zooms around the focal point and focal-pans', (tester) async { + await tester.pumpWidget(_harness()); + final g1 = await tester.startGesture(const Offset(300, 300)); + final g2 = await tester.startGesture(const Offset(500, 300)); + await tester.pump(); + await g1.moveTo(const Offset(100, 300)); // dist 400 → 2×, clamped to (0,0) + await tester.pump(); + await g2.moveTo(const Offset(700, 300)); // dist 600 → 3×, anchored at (-50,-150) + await tester.pump(); + final ctrl = _controller(tester); + expect(ctrl.scale, closeTo(3.0, 1e-6)); + expect(ctrl.position, const Offset(-50, -150)); + await g1.moveBy(const Offset(50, 0)); // focal pan, distance unchanged + await g2.moveBy(const Offset(50, 0)); + await tester.pump(); + expect(ctrl.position.dx, closeTo(0, 0.01)); + expect(ctrl.position.dy, closeTo(-150, 0.01)); + await g1.up(); + await g2.up(); + await tester.pump(const Duration(milliseconds: 350)); // flush double-tap countdown + }); + + testWidgets('per-page zoom state survives page switches', (tester) async { + var page = 0; + await tester.pumpWidget(_harness(onPageChanged: (i) => page = i)); + await _pinchOut(tester, 600); // page 0 zoomed to 3× + await _slowDrag(tester, const Offset(700, 300), const Offset(-250, 0)); // pan to X clamp + await _slowDrag(tester, const Offset(700, 300), const Offset(-500, 0)); // released at edge → page 1 + expect(page, 1); + await _slowDrag(tester, const Offset(100, 300), const Offset(500, 0)); // page 0 + expect(page, 0); + final ctrl = _controller(tester); + expect(ctrl.scale, 3.0); // still zoomed + expect(ctrl.position, const Offset(-200, -150)); // still clamped + }); + + testWidgets('pages without LeafZoomable dismiss and page but never pop', (tester) async { + var dismissed = false; + var outside = 0; + var page = 0; + await tester.pumpWidget(_harness( + pageBuilder: (context, i) => Center(child: Text('page $i')), + onDismissed: () => dismissed = true, + onTapOutside: () => outside++, + onPageChanged: (i) => page = i, + )); + await tester.tapAt(const Offset(10, 10)); + await tester.pump(const Duration(milliseconds: 350)); + expect(outside, 0); + await _slowDrag(tester, const Offset(700, 300), const Offset(-500, 0)); + expect(page, 1); + await tester.timedDrag(find.byType(LeafViewer), const Offset(0, 400), const Duration(milliseconds: 200)); + await tester.pumpAndSettle(); + expect(dismissed, isTrue); + }); + + group('desktop mode', () { + testWidgets('mouse drag at 1× neither pages nor dismisses', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + var page = 0; + var dismissed = false; + await tester.pumpWidget(_harness(onPageChanged: (i) => page = i, onDismissed: () => dismissed = true)); + final g = await tester.startGesture(const Offset(600, 300), kind: PointerDeviceKind.mouse); + await tester.pump(); + for (var i = 0; i < 8; i++) { + await g.moveBy(const Offset(-62.5, 0)); + await tester.pump(const Duration(milliseconds: 50)); + } + await g.up(); + await tester.pump(const Duration(milliseconds: 350)); + expect(page, 0); + final g2 = await tester.startGesture(const Offset(400, 200), kind: PointerDeviceKind.mouse); + await tester.pump(); + for (var i = 0; i < 8; i++) { + await g2.moveBy(const Offset(0, 37.5)); + await tester.pump(const Duration(milliseconds: 25)); + } + await g2.up(); + await tester.pump(const Duration(milliseconds: 350)); + expect(dismissed, isFalse); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('double-tap does nothing on desktop', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + await tester.pumpWidget(_harness()); + await _doubleTapAt(tester, const Offset(400, 300)); + expect(_controller(tester).scale, 1.0); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('zoomed mouse drag pans', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + await tester.pumpWidget(_harness()); + await _pinchOut(tester, 600); // 3× via touch pinch + final ctrl = _controller(tester); + final g = await tester.startGesture(const Offset(700, 300), kind: PointerDeviceKind.mouse); + await tester.pump(); + for (var i = 0; i < 8; i++) { + await g.moveBy(const Offset(-18.75, 0)); + await tester.pump(const Duration(milliseconds: 50)); + } + await g.up(); + await tester.pump(const Duration(milliseconds: 350)); + expect(ctrl.position.dx, lessThan(0)); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('default controls show on desktop and page via buttons', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + var page = 0; + await tester.pumpWidget(_harness(onPageChanged: (i) => page = i)); + expect(find.byIcon(Icons.chevron_right), findsOneWidget); + expect(find.byIcon(Icons.chevron_left), findsOneWidget); + expect(find.byIcon(Icons.close), findsOneWidget); + expect(find.text('1 / 3'), findsOneWidget); + await tester.tap(find.byIcon(Icons.chevron_right)); + await tester.pumpAndSettle(); + expect(page, 1); + expect(find.text('2 / 3'), findsOneWidget); + await tester.tap(find.byIcon(Icons.chevron_left)); + await tester.pumpAndSettle(); + expect(page, 0); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('custom controlsBuilder replaces the default', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: LeafViewer( + pageCount: 3, + pageBuilder: _zoomablePage, + controlsBuilder: (context, controls) => Text('custom ${controls.currentIndex}'), + ), + ), + )); + expect(find.text('custom 0'), findsOneWidget); + expect(find.byIcon(Icons.chevron_right), findsNothing); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('close button pops the route', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => Center( + child: ElevatedButton( + onPressed: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => Scaffold(body: LeafViewer(pageCount: 3, pageBuilder: _zoomablePage)), + )), + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.byType(LeafViewer), findsOneWidget); + await tester.tap(find.byIcon(Icons.close)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + expect(find.byType(LeafViewer), findsNothing); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('paging via buttons does not rebuild pages (no black flash)', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + final counts = {}; + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: LeafViewer( + pageCount: 3, + pageBuilder: (context, i) { + counts[i] = (counts[i] ?? 0) + 1; + return _zoomablePage(context, i); + }, + ), + ), + )); + expect(counts[0], 1); + await tester.tap(find.byIcon(Icons.chevron_right)); + await tester.pumpAndSettle(); + expect(find.text('2 / 3'), findsOneWidget); + expect(counts[0], 1); // existing pages are never re-invoked + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('enableSwipeGestures: true emulates touch on desktop', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + var page = 0; + var dismissed = false; + await tester.pumpWidget(_harness( + enableSwipeGestures: true, + onPageChanged: (i) => page = i, + onDismissed: () => dismissed = true, + )); + final g = await tester.startGesture(const Offset(600, 300), kind: PointerDeviceKind.mouse); + await tester.pump(); + for (var i = 0; i < 8; i++) { + await g.moveBy(const Offset(-62.5, 0)); + await tester.pump(const Duration(milliseconds: 50)); + } + await g.up(); + await tester.pumpAndSettle(); + expect(page, 1); // mouse swipe pages + await tester.timedDrag(find.byType(LeafViewer), const Offset(0, 400), const Duration(milliseconds: 200)); + await tester.pumpAndSettle(); + expect(dismissed, isTrue); // mouse drag dismisses + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('enableSwipeGestures: true enables double-tap on desktop', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + await tester.pumpWidget(_harness(enableSwipeGestures: true)); + await _doubleTapAt(tester, const Offset(400, 300)); + expect(_controller(tester).scale, greaterThan(1.0)); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('enableSwipeGestures: false disables touch gestures on touch platforms', (tester) async { + var dismissed = false; + await tester.pumpWidget(_harness(enableSwipeGestures: false, onDismissed: () => dismissed = true)); + await tester.timedDrag(find.byType(LeafViewer), const Offset(0, 400), const Duration(milliseconds: 200)); + await tester.pumpAndSettle(); + expect(dismissed, isFalse); + await _doubleTapAt(tester, const Offset(400, 300)); + expect(_controller(tester).scale, 1.0); + }); + + testWidgets('dismiss without onDismissed pops the route', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => Center( + child: ElevatedButton( + onPressed: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => Scaffold( + body: LeafViewer(pageCount: 3, pageBuilder: _zoomablePage, enableSwipeGestures: true), + ), + )), + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.timedDrag(find.byType(LeafViewer), const Offset(0, 400), const Duration(milliseconds: 200)); + await tester.pumpAndSettle(); + expect(find.byType(LeafViewer), findsNothing); + debugDefaultTargetPlatformOverride = null; + }); + }); +} diff --git a/test/viewer/leaf_zoom_controller_test.dart b/test/viewer/leaf_zoom_controller_test.dart new file mode 100644 index 0000000..dcd283f --- /dev/null +++ b/test/viewer/leaf_zoom_controller_test.dart @@ -0,0 +1,329 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:leaf_widgets/leaf_widgets.dart'; + +const viewport = Size(800, 600); + +LeafZoomController _make({Size child = const Size(400, 300), Size? original, double maxScale = 5.0}) { + final ctrl = LeafZoomController(maxScale: maxScale, vsync: TestVSync()); + ctrl.updateLayout(viewport: viewport, childSize: child, originalSize: original); + return ctrl; +} + +// photo_view reference implementations (verified against 0.15.0 source) +(double, double) _pvCorners(Size outer, Size child, double scale, bool vertical) { + final dim = vertical ? child.height : child.width; + final outerDim = vertical ? outer.height : outer.width; + final diff = dim * scale - outerDim; + return (-diff / 2, diff / 2); +} + +Offset _pvClamp(Offset pos, double scale, Size outer, Size child) { + double fx = 0; + if (outer.width < child.width * scale) { + final (min, max) = _pvCorners(outer, child, scale, false); + fx = pos.dx.clamp(min, max); + } + double fy = 0; + if (outer.height < child.height * scale) { + final (min, max) = _pvCorners(outer, child, scale, true); + fy = pos.dy.clamp(min, max); + } + return Offset(fx, fy); +} + +// First pump starts the ticker (elapsed 0), the second advances past the +// 200ms zoom animation. +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 250)); +} + +void main() { + group('clamp & corners (property test vs photo_view formulas)', () { + for (final child in const [Size(400, 300), Size(300, 200), Size(200, 300), Size(1000, 500)]) { + for (final scale in const [1.0, 2.0, 3.5, 5.0]) { + test('viewport $viewport child $child scale $scale', () { + final ctrl = _make(child: child); + ctrl.wheelZoom(-(scale - 1) * 1000, viewport.center(Offset.zero)); + ctrl.panBy(const Offset(100000, -100000)); + final expected = _pvClamp(const Offset(100000, -100000), scale.clamp(1.0, 5.0), viewport, child); + expect(ctrl.scale, scale.clamp(1.0, 5.0)); + expect(ctrl.position.dx, closeTo(expected.dx, 1e-6)); + expect(ctrl.position.dy, closeTo(expected.dy, 1e-6)); + }); + } + } + }); + + group('edge-release (HitCorners port)', () { + // child 400x300, scale 3 → X corners ±200, Y corners ±150 + LeafZoomController zoomed() { + final ctrl = _make(child: const Size(400, 300)); + ctrl.wheelZoom(-2000, const Offset(400, 300)); + expect(ctrl.scale, 3.0); + return ctrl; + } + + test('at 1× never claims', () { + final ctrl = _make(); + expect(ctrl.shouldClaim(const Offset(10, 10)), isFalse); + expect(ctrl.shouldClaim(const Offset(-10, 0)), isFalse); + }); + + test('free position claims any direction', () { + final ctrl = zoomed(); + expect(ctrl.shouldClaim(const Offset(10, 10)), isTrue); + expect(ctrl.shouldClaim(const Offset(-10, 0)), isTrue); + expect(ctrl.shouldClaim(const Offset(0, -10)), isTrue); + }); + + test('panned right: release on rightward drag, claim on leftward', () { + final ctrl = zoomed(); + ctrl.panBy(const Offset(10000, 0)); + expect(ctrl.position.dx, 200); + expect(ctrl.shouldClaim(const Offset(10, 0)), isFalse); + expect(ctrl.shouldClaim(const Offset(-10, 0)), isTrue); + }); + + test('panned down: release on downward drag, claim on upward', () { + final ctrl = zoomed(); + ctrl.panBy(const Offset(0, 10000)); + expect(ctrl.position.dy, 150); + expect(ctrl.shouldClaim(const Offset(0, 10)), isFalse); + expect(ctrl.shouldClaim(const Offset(0, -10)), isTrue); + }); + + test('fully clamped: release; one free axis: claim (Axis.values)', () { + final ctrl = zoomed(); + ctrl.panBy(const Offset(10000, 10000)); + expect(ctrl.shouldClaim(const Offset(10, 10)), isFalse); + ctrl.panBy(const Offset(-10000, 0)); + expect(ctrl.shouldClaim(const Offset(10, 10)), isTrue); + }); + + test('cross-axis drag at edge is a claim when the other axis is free', () { + final ctrl = zoomed(); + ctrl.panBy(const Offset(10000, 0)); // X max, Y free + expect(ctrl.shouldClaim(const Offset(0, 10)), isTrue); + expect(ctrl.shouldClaim(const Offset(10, 10)), isTrue); + }); + }); + + group('double-tap cycle', () { + testWidgets('1× → covered → 1:1 → 1×', (tester) async { + final ctrl = _make(child: const Size(300, 200), original: const Size(1200, 800)); + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); + expect(ctrl.scale, closeTo(3.0, 1e-6)); // covered + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); + expect(ctrl.scale, closeTo(1.5, 1e-6)); // 1:1 = 1/contained(0.667) + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); + expect(ctrl.scale, closeTo(1.0, 1e-6)); + }); + + testWidgets('skips states that change nothing (no originalSize)', (tester) async { + final ctrl = _make(child: const Size(300, 200)); + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); + expect(ctrl.scale, closeTo(3.0, 1e-6)); + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); + expect(ctrl.scale, closeTo(1.0, 1e-6)); + }); + + testWidgets('small image: 1:1 clamps to 1× and is skipped', (tester) async { + final ctrl = _make(child: const Size(400, 300), original: const Size(400, 300)); + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); + expect(ctrl.scale, closeTo(2.0, 1e-6)); // covered + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); + expect(ctrl.scale, closeTo(1.0, 1e-6)); // 1:1=0.5 clamped → skipped + }); + + testWidgets('panned/pinched state resets to 1× on double-tap', (tester) async { + final ctrl = _make(child: const Size(400, 300)); + ctrl.wheelZoom(-2000, const Offset(400, 300)); // zoomedIn via gesture + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); + expect(ctrl.scale, closeTo(1.0, 1e-6)); + expect(ctrl.position, Offset.zero); + }); + + testWidgets('zoom-in anchors the tap point', (tester) async { + final ctrl = _make(child: const Size(300, 200), original: const Size(1200, 800)); + // At covered (3×) the Y axis exactly fits (200·3 == 600) → clamped to 0, + // so tap along X only: target (−20, 0) is inside the ±50 X corners. + final tap = const Offset(410, 300); + ctrl.doubleTap(tap); + await _settle(tester); + final vpc = viewport.center(Offset.zero); + final expected = (tap - vpc) * (1 - 3.0); + expect(ctrl.position.dx, closeTo(expected.dx, 1e-6)); + expect(ctrl.position.dy, closeTo(expected.dy, 1e-6)); + final screen = vpc + ctrl.position + (tap - vpc) * ctrl.scale; + expect(screen.dx, closeTo(tap.dx, 1e-4)); + expect(screen.dy, closeTo(tap.dy, 1e-4)); + }); + }); + + group('gestures', () { + test('scaleUpdate scales around the focal point and focal-pans', () { + final ctrl = _make(child: const Size(500, 400)); + ctrl.scaleUpdate(2.0, const Offset(400, 300), const Offset(400, 300)); + expect(ctrl.scale, 2.0); + expect(ctrl.position, const Offset(-100, -100)); // clamped anchor + ctrl.scaleUpdate(2.0, const Offset(400, 300), const Offset(430, 320)); + expect(ctrl.position, const Offset(-70, -80)); // focal delta (30, 20) + expect(ctrl.scale, 2.0); + }); + + test('scaleUpdate with unchanged scale is a pure pan', () { + final ctrl = _make(child: const Size(500, 400)); + ctrl.scaleUpdate(2.0, const Offset(400, 300), const Offset(400, 300)); + ctrl.scaleUpdate(2.0, const Offset(400, 300), const Offset(430, 320)); + expect(ctrl.position, const Offset(-70, -80)); + }); + + test('scaleUpdate clamps to max and fires zoom limit', () { + var limits = 0; + final ctrl = _make(child: const Size(400, 300), maxScale: 5.0)..onZoomLimit = () => limits++; + ctrl.scaleUpdate(100, const Offset(400, 300), const Offset(400, 300)); + expect(ctrl.scale, 5.0); + expect(limits, 1); + }); + + test('wheel zooms cursor-anchored and clamps', () { + final ctrl = _make(child: const Size(400, 300)); + ctrl.wheelZoom(-2000, const Offset(200, 150)); + expect(ctrl.scale, 3.0); + expect(ctrl.position, const Offset(200, 150)); // clamped corner anchor + ctrl.wheelZoom(2000, const Offset(200, 150)); + expect(ctrl.scale, 1.0); + expect(ctrl.position, Offset.zero); + }); + + test('wheel fires zoom limit at 1.0 and max', () { + var limits = 0; + final ctrl = _make(child: const Size(400, 300))..onZoomLimit = () => limits++; + ctrl.wheelZoom(-4000, const Offset(400, 300)); // → 5.0 + expect(limits, 1); + ctrl.wheelZoom(4000, const Offset(400, 300)); // → 1.0 + expect(limits, 2); + }); + + test('pan clamps to corners per axis', () { + final ctrl = _make(child: const Size(400, 300)); + ctrl.wheelZoom(-2000, const Offset(400, 300)); // 3× → X corners ±200, Y ±150 + ctrl.panBy(const Offset(1000, 1000)); + expect(ctrl.position, const Offset(200, 150)); + ctrl.panBy(const Offset(-3000, -3000)); + expect(ctrl.position, const Offset(-200, -150)); + }); + + test('fits axis stays zeroed while the other pans', () { + final ctrl = _make(child: const Size(300, 200)); + ctrl.wheelZoom(-2000, const Offset(400, 300)); // 3× → X overhang 100 (±50), Y exactly fits → zeroed + ctrl.panBy(const Offset(1000, 1000)); + expect(ctrl.position.dx, 50); + expect(ctrl.position.dy, 0); + }); + + test('imageRect is the centered contained rect', () { + final ctrl = _make(child: const Size(400, 300)); + expect(ctrl.imageRect, const Rect.fromLTWH(200, 150, 400, 300)); + ctrl.wheelZoom(-2000, const Offset(400, 300)); // 3× → 1200×900, corners ±200/±150 + ctrl.panBy(const Offset(100, 50)); + expect(ctrl.imageRect, const Rect.fromLTWH(-100, -100, 1200, 900)); + }); + }); + + group('fling', () { + // Scale 3× with child 400×300 → X overhang 400 (corners ±200), Y overhang 300 (±150). + LeafZoomController flingZoomed() { + final ctrl = _make(child: const Size(400, 300)); + ctrl.wheelZoom(-2000, const Offset(400, 300)); + return ctrl; + } + + testWidgets('decays with friction and stops', (tester) async { + final ctrl = flingZoomed(); + ctrl.startFling(const Offset(2000, 0)); + expect(ctrl.isFlinging, isTrue); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 16)); + expect(ctrl.position.dx, greaterThan(0)); + for (var i = 0; i < 300; i++) { + await tester.pump(const Duration(milliseconds: 16)); + if (!ctrl.isFlinging) break; + } + expect(ctrl.isFlinging, isFalse); + }); + + testWidgets('clamps while flinging', (tester) async { + final ctrl = flingZoomed(); + ctrl.startFling(const Offset(100000, 0)); + await tester.pump(); + for (var i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + expect(ctrl.position.dx, 200); + ctrl.cancelGesture(); + await tester.pump(); + }); + + testWidgets('tap-to-stop via cancelGesture', (tester) async { + final ctrl = flingZoomed(); + ctrl.startFling(const Offset(2000, 0)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 16)); + ctrl.cancelGesture(); + expect(ctrl.isFlinging, isFalse); + await tester.pump(); + }); + }); + + group('animation interrupt', () { + testWidgets('cancel mid-zoom-in keeps the current frame', (tester) async { + final ctrl = _make(child: const Size(300, 200)); + ctrl.doubleTap(const Offset(400, 300)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + ctrl.cancelGesture(); + expect(ctrl.scale, greaterThan(1.0)); + expect(ctrl.scale, lessThan(3.0)); + }); + + testWidgets('cancel mid-zoom-out snaps to 1×', (tester) async { + final ctrl = _make(child: const Size(300, 200)); + ctrl.doubleTap(const Offset(400, 300)); + await _settle(tester); // covered + ctrl.doubleTap(const Offset(400, 300)); // → 1× + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + ctrl.cancelGesture(); + expect(ctrl.scale, 1.0); + expect(ctrl.position, Offset.zero); + }); + }); + + group('layout changes', () { + test('cycle states recompute on layout change', () { + final ctrl = _make(child: const Size(300, 200)); + // covered = 3 at 800×600 + // force state via wheel? states only change via doubleTap/gestures; use doubleTap in testWidgets? plain test: wheelZoom sets zoomedIn (kept). + ctrl.updateLayout(viewport: const Size(400, 300), childSize: const Size(300, 200)); + expect(ctrl.scale, 1.0); + // zoomedIn state keeps its scale + ctrl.wheelZoom(-1000, const Offset(200, 150)); + expect(ctrl.scale, 2.0); + ctrl.updateLayout(viewport: const Size(400, 300), childSize: const Size(300, 200)); + expect(ctrl.scale, 2.0); + expect(ctrl.position, Offset.zero); // reclamped + }); + }); +}