Repository: chooyan-eng/crop_your_image Branch: main Commit: 134bd3a2bd3d Files: 140 Total size: 322.7 KB Directory structure: gitextract_jpj4whwb/ ├── .fvmrc ├── .github/ │ └── workflows/ │ └── run_test.yaml ├── .gitignore ├── .metadata ├── .vscode/ │ └── settings.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── docs/ │ └── architecture.md ├── example/ │ ├── .gitignore │ ├── .metadata │ ├── README.md │ ├── analysis_options.yaml │ ├── android/ │ │ ├── .gitignore │ │ ├── app/ │ │ │ ├── build.gradle │ │ │ └── src/ │ │ │ ├── debug/ │ │ │ │ └── AndroidManifest.xml │ │ │ ├── main/ │ │ │ │ ├── AndroidManifest.xml │ │ │ │ ├── kotlin/ │ │ │ │ │ └── com/ │ │ │ │ │ └── example/ │ │ │ │ │ └── example/ │ │ │ │ │ └── MainActivity.kt │ │ │ │ └── res/ │ │ │ │ ├── drawable/ │ │ │ │ │ └── launch_background.xml │ │ │ │ ├── drawable-v21/ │ │ │ │ │ └── launch_background.xml │ │ │ │ ├── values/ │ │ │ │ │ └── styles.xml │ │ │ │ └── values-night/ │ │ │ │ └── styles.xml │ │ │ └── profile/ │ │ │ └── AndroidManifest.xml │ │ ├── build.gradle │ │ ├── gradle/ │ │ │ └── wrapper/ │ │ │ └── gradle-wrapper.properties │ │ ├── gradle.properties │ │ └── settings.gradle │ ├── ios/ │ │ ├── .gitignore │ │ ├── Flutter/ │ │ │ ├── AppFrameworkInfo.plist │ │ │ ├── Debug.xcconfig │ │ │ └── Release.xcconfig │ │ ├── Runner/ │ │ │ ├── AppDelegate.swift │ │ │ ├── Assets.xcassets/ │ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ │ └── Contents.json │ │ │ │ └── LaunchImage.imageset/ │ │ │ │ ├── Contents.json │ │ │ │ └── README.md │ │ │ ├── Base.lproj/ │ │ │ │ ├── LaunchScreen.storyboard │ │ │ │ └── Main.storyboard │ │ │ ├── Info.plist │ │ │ └── Runner-Bridging-Header.h │ │ ├── Runner.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace/ │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcshareddata/ │ │ │ │ ├── IDEWorkspaceChecks.plist │ │ │ │ └── WorkspaceSettings.xcsettings │ │ │ └── xcshareddata/ │ │ │ └── xcschemes/ │ │ │ └── Runner.xcscheme │ │ └── Runner.xcworkspace/ │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata/ │ │ ├── IDEWorkspaceChecks.plist │ │ └── WorkspaceSettings.xcsettings │ ├── lib/ │ │ ├── main.dart │ │ └── my_cropper.dart │ ├── linux/ │ │ ├── .gitignore │ │ ├── CMakeLists.txt │ │ ├── flutter/ │ │ │ ├── CMakeLists.txt │ │ │ ├── generated_plugin_registrant.cc │ │ │ ├── generated_plugin_registrant.h │ │ │ └── generated_plugins.cmake │ │ ├── main.cc │ │ ├── my_application.cc │ │ └── my_application.h │ ├── macos/ │ │ ├── .gitignore │ │ ├── Flutter/ │ │ │ ├── Flutter-Debug.xcconfig │ │ │ ├── Flutter-Release.xcconfig │ │ │ └── GeneratedPluginRegistrant.swift │ │ ├── Runner/ │ │ │ ├── AppDelegate.swift │ │ │ ├── Assets.xcassets/ │ │ │ │ └── AppIcon.appiconset/ │ │ │ │ └── Contents.json │ │ │ ├── Base.lproj/ │ │ │ │ └── MainMenu.xib │ │ │ ├── Configs/ │ │ │ │ ├── AppInfo.xcconfig │ │ │ │ ├── Debug.xcconfig │ │ │ │ ├── Release.xcconfig │ │ │ │ └── Warnings.xcconfig │ │ │ ├── DebugProfile.entitlements │ │ │ ├── Info.plist │ │ │ ├── MainFlutterWindow.swift │ │ │ └── Release.entitlements │ │ ├── Runner.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace/ │ │ │ │ └── xcshareddata/ │ │ │ │ └── IDEWorkspaceChecks.plist │ │ │ └── xcshareddata/ │ │ │ └── xcschemes/ │ │ │ └── Runner.xcscheme │ │ ├── Runner.xcworkspace/ │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata/ │ │ │ └── IDEWorkspaceChecks.plist │ │ └── RunnerTests/ │ │ └── RunnerTests.swift │ ├── pubspec.yaml │ ├── test/ │ │ └── widget_test.dart │ ├── web/ │ │ ├── index.html │ │ └── manifest.json │ └── windows/ │ ├── .gitignore │ ├── CMakeLists.txt │ ├── flutter/ │ │ ├── CMakeLists.txt │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugin_registrant.h │ │ └── generated_plugins.cmake │ └── runner/ │ ├── CMakeLists.txt │ ├── Runner.rc │ ├── flutter_window.cpp │ ├── flutter_window.h │ ├── main.cpp │ ├── resource.h │ ├── runner.exe.manifest │ ├── utils.cpp │ ├── utils.h │ ├── win32_window.cpp │ └── win32_window.h ├── lib/ │ ├── crop_your_image.dart │ └── src/ │ ├── logic/ │ │ ├── cropper/ │ │ │ ├── default_rect_validator.dart │ │ │ ├── errors.dart │ │ │ ├── image_cropper.dart │ │ │ ├── image_image_cropper.dart │ │ │ └── legacy_image_image_cropper.dart │ │ ├── format_detector/ │ │ │ ├── default_format_detector.dart │ │ │ ├── format.dart │ │ │ └── format_detector.dart │ │ ├── logic.dart │ │ ├── parser/ │ │ │ ├── errors.dart │ │ │ ├── image_detail.dart │ │ │ ├── image_image_parser.dart │ │ │ └── image_parser.dart │ │ └── shape.dart │ └── widget/ │ ├── calculator.dart │ ├── circle_crop_area_clipper.dart │ ├── constants.dart │ ├── controller.dart │ ├── crop.dart │ ├── crop_editor_view_state.dart │ ├── crop_result.dart │ ├── dot_control.dart │ ├── edge_alignment.dart │ ├── history_state.dart │ ├── initial_rect_builder.dart │ ├── rect_crop_area_clipper.dart │ └── widget.dart ├── pubspec.yaml └── test/ ├── logic/ │ ├── cropper/ │ │ └── image_image_cropper_test.dart │ └── parser/ │ └── image_image_parser_test.dart └── widget/ ├── calculator_test.dart ├── circle_crop_area_clipper_test.dart ├── controller_test.dart ├── crop_editor_view_state_test.dart ├── crop_test.dart ├── helper.dart ├── history_state_test.dart └── rect_crop_area_clipper_test.dart ================================================ FILE CONTENTS ================================================ ================================================ FILE: .fvmrc ================================================ { "flutter": "3.22.1", "flavors": {} } ================================================ FILE: .github/workflows/run_test.yaml ================================================ name: run-flutter-test on: [push] jobs: flutter-test: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Setup Flutter uses: subosito/flutter-action@v2 - name: Install depencencies run: flutter pub get - name: Run tests and generate coverage run: flutter test --no-pub --coverage - name: Install lcov run: sudo apt-get -y install lcov - name: Convert lcov.info to HTML run: genhtml coverage/lcov.info -o coverage/html - name: Upload coverage directory uses: actions/upload-artifact@v4 with: path: coverage ================================================ FILE: .gitignore ================================================ # Miscellaneous *.class *.log *.pyc *.swp .DS_Store .atom/ .buildlog/ .history .svn/ # 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/ .dart_tool/ .flutter-plugins .flutter-plugins-dependencies .packages .pub-cache/ .pub/ build/ # Android related **/android/**/gradle-wrapper.jar **/android/.gradle **/android/captures/ **/android/gradlew **/android/gradlew.bat **/android/local.properties **/android/**/GeneratedPluginRegistrant.java # iOS/XCode related **/ios/**/*.mode1v3 **/ios/**/*.mode2v3 **/ios/**/*.moved-aside **/ios/**/*.pbxuser **/ios/**/*.perspectivev3 **/ios/**/*sync/ **/ios/**/.sconsign.dblite **/ios/**/.tags* **/ios/**/.vagrant/ **/ios/**/DerivedData/ **/ios/**/Icon? **/ios/**/Pods/ **/ios/**/.symlinks/ **/ios/**/profile **/ios/**/xcuserdata **/ios/.generated/ **/ios/Flutter/App.framework **/ios/Flutter/Flutter.framework **/ios/Flutter/Flutter.podspec **/ios/Flutter/Generated.xcconfig **/ios/Flutter/app.flx **/ios/Flutter/app.zip **/ios/Flutter/flutter_assets/ **/ios/Flutter/flutter_export_environment.sh **/ios/ServiceDefinitions.json **/ios/Runner/GeneratedPluginRegistrant.* # Exceptions to above rules. !**/ios/**/default.mode1v3 !**/ios/**/default.mode2v3 !**/ios/**/default.pbxuser !**/ios/**/default.perspectivev3 # FVM Version Cache .fvm/ ================================================ FILE: .metadata ================================================ # 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: 60bd88df915880d23877bfc1602e8ddcf4c4dd2a channel: stable project_type: package ================================================ FILE: .vscode/settings.json ================================================ { "dart.flutterSdkPath": ".fvm/versions/3.22.1" } ================================================ FILE: CHANGELOG.md ================================================ ## [2.0.0] - 2024.12.13 ### Breaking Changes This major update includes some breaking changes. See [migration guide](https://github.com/chooyan-eng/crop_your_image/issues/176) for more details. ### Interface Enhancements * Change the argument type exposed by `onCropped` callback into `CropResult` from `Uint8List`. This allows to handle errors as well as cropped image data. Thank you [@justprodev](https://github.com/justprodev) for your idea at [#145](https://github.com/chooyan-eng/crop_your_image/issues/145)! * Change how to implement `ImageCropper` to make it more flexibly customizable. * `onMoved` callback passes additional `imageRect` parameter. * Errors are now implementing `Exception` instead of `Error`. * Change the type of `initialRectBuilder` to `InitialRectBuilder`, and now legacy `initialArea` and `initialSize` are removed and merged into `InitialRectBuilder` to avoid confusion. ### New Features * Add undo / redo related features. See [README.md](README.md) for more details. * Respect original image format and output with the same format. Thank you [@komakur](https://github.com/komakur) for your idea and sample code at [#48](https://github.com/chooyan-eng/crop_your_image/issues/48)! * Add `filterQuality` argument to `Crop` widget. Thank you [@abichinger](https://github.com/abichinger) for your discussion and contribution at [#108](https://github.com/chooyan-eng/crop_your_image/pull/108)! * Add `onImageMoved` callback that notifies image moved when `interactive` is enabled. Thank you [@yujune](https://github.com/yujune) and [@eidolonFIRE](https://github.com/eidolonFIRE) for your contribution at [#159](https://github.com/chooyan-eng/crop_your_image/pull/159)! and [#92](https://github.com/chooyan-eng/crop_your_image/pull/92)! * Add `overlayBuilder` argument to `Crop` widget that enables to configure overlay on cropping area. Thank you [@abichinger](https://github.com/abichinger) for your contribution at [#107](https://github.com/chooyan-eng/crop_your_image/pull/107)! ### Bug Fixes * Fix a bug of circle crop not working with JPEG images. * Fix a bug of `InvalidRectError` happening unexpectedly. Thank you [@feimenggo](https://github.com/feimenggo) and [@Lenkomotive](https://github.com/Lenkomotive) for your fixes at [#163](https://github.com/chooyan-eng/crop_your_image/pull/163)! and [#153](https://github.com/chooyan-eng/crop_your_image/pull/153)! * Fix a bug of using unmounted context. * Fix a bug of crashing after disposing `Crop` widget. Big appreciation to all the contributors joining discussions and sending PRs! ## [1.1.0] - 2024.5.29 * apply changes of latest version of `image` package ## [1.0.2] - 2024.2.26 * fix bug of causing `InvalidRectError` unexpectedly ## [1.0.1] - 2024.2.11 * fix bug of `withCircleUi` not working ## [1.0.0] - 2024.2.11 * `crop_your_image` is now stable! * well architectured and tested * works also on Web / Desktop * backend logic is also interchangeable * some breaking changes. see [migration guide](https://github.com/chooyan-eng/crop_your_image/issues/133). ## [1.0.0-dev.4] - 2024.2.10 * `interactive` is now available for macOS! * fix a tiny bug ## [1.0.0-dev.3] - 2024.2.10 * Rename some arguments of `Crop` and setter of `CropController`. See [migration guide](https://github.com/chooyan-eng/crop_your_image/issues/133). * `interactive` is now available for Web! ## [1.0.0-dev.2] - 2024.2.9 * Add test codes and fix some bugs. * Update README.md * Add `clipBehavior`. * Rename `allowScale` to `willUpdateScale`. ## [1.0.0-dev.1] - 2024.2.8 * Refactor and update the architecture of the entire codebase. * Add injecting backend logic features. * Add `allowScale` flag. ## [0.7.5] - 2023.6.5 * Update Fluter version to 3.10.3 ## [0.7.4] - 2023.1.10 * Update versions of depencencies. ## [0.7.3] - 2022.11.15 * Add `progressIndicator` parameter to pass a Widget indicating progress. * Updated versions of dependencies. ## [0.7.2] - 2022.03.16 * Enhanced zooming / panning behavior ## [0.7.1] - 2022.03.13 * Add `initialAreaBuilder` parameter to configure inital cropping area based on viewport of `Crop`. * Add `radius` parameter to configure corner radius of cropping area. * Control image scale not to be smaller than cropping area. * Calculate initial scale to cover cropping area. * Fix bug image could't be bigger than certain scale. ## [0.7.0] - 2022.03.08 * Add _experimental_ feature of moving and zooming images. * setting `interactive: true` enables the feature. * Add `fixArea` flag to fix cropping area. ## [0.6.0+1] - 2021.08.14 * Fix static analysis issues. ## [0.6.0] - 2021.08.14 * _Braking Change:_ The second argument of `cornerDotBuilder` is now enum of `EdgeAlignment`, not meaningful index. * Add callback for `CropStatus`. * Enhancement of not to block UI when loading image data. ## [0.5.3] - 2021.03.28 * Fix a bug that calcuration of cropping area is wrong when Exif has orientation data. ## [0.5.2+2] - 2021.03.28 * Update Readme ## [0.5.2+1] - 2021.03.28 * Fix problems of static analysis. * Update Readme ## [0.5.2] - 2021.03.28 * Update Readme * Remove unused code ## [0.5.1+1] - 2021.03.25 * Enable to set initial cropping area with `initialArea` property. ## [0.5.0] - 2021.03.18 * Enable to configure corner Dots with whatever Widget. * Enable to configure cropping mask colors and base colors. ## [0.4.0] - 2021.03.18 * Enable to change original image via `CropController` * Add callback when cropping area moves. * Enable to control cropping area programmatically via `CropController` * Fix bug that wrong cropping area is calculated when image is smaller than display. ## [0.3.0] - 2021.03.17 * Add example project in `example` directory. ## [0.2.3] - 2021.03.17 * Fix a bug of wrong cropping rect when vertically longer image is set. * Make the size of dots smaller. ## [0.2.2] - 2021.03.16 * Rename `isCircle` flag into `withCircleUi`. This flag no more affects the result of the shape of cropped images. * Add `CropController.cropCircle` method so that images are cropped with circle shape. ## [0.2.1] - 2021.03.16 * Enable to pass `isCircle` property to crop with circle shape. This flag can also be changed via `CropController`. ## [0.2.0] - 2021.03.16 * Enable to change `aspectRatio` dynamically via `CropController`. * Enable to set `initialSize` via `Crop` constructor. ## [0.1.4] - 2021.03.16 * Bug fixed. and improve performance. ## [0.1.3] - 2021.03.16 * Fix not to block UI update when cropping image. ## [0.1.2] - 2021.03.15 * Enable to fix aspect ratio if `aspectRatio` property is given. ## [0.1.1] - 2021.03.14 * Fix README.md ## [0.1.0] - 2021.03.14 * prevent Dot controls from exceeding thier horizontal / vertical limits. ## [0.0.6] - 2021.03.12 * change the type of `image` parameters to `UInt8List`. * return cropped data via `onCropped` callback. * now Crop Widget is available at any place and any size. ## [0.0.5] - 2021.03.12 * Enable controling crop actions via CropController. ## [0.0.4] - 2021.03.12 * Rename classes. ## [0.0.3] - 2021.03.12 * Add first implementation of crop_your_image. ## [0.0.2] - 2021.03.12 * Update information about this package. ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2021 Tsuyoshi Chujo Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # crop_your_image A flutter plugin that provides `Crop` widget for cropping images. ![Image Cropping Preview](https://github.com/chooyan-eng/crop_your_image/raw/main/assets/cropyourimage.gif) # Philosophy crop_your_image provides _flexible_ and _customizable_ `Crop` widget that can be placed at anywhere in your well designed apps. As `Crop` is a simple widget displaying minimum cropping UI, `Crop` can be placed anywhere such as, for example, occupying entire screen, at top half of the screen, or even on dialogs or bottom sheets. It's totally up to you! Users' cropping operation is also customizable. By default, images are fixed on the screen and users can move crop rect to decide where to crop. Once configured _interactive_ mode, images can be zoomed/panned, and crop rect can be configured as fixed. `CropController` enables you to control _crop rect_ from outside of `Crop`. The controller allows you to run cropping (or related actions) from anywhere on your codebase. Enjoy building your own cropping UI with __crop_your_image__! ## Features - __Minimum UI restrictions__ - Flexible `Crop` widget __that can be placed anywhere__ on your widget tree - `CropController` to control `Crop` - __Zooming / panning__ images - Crop with __rect__ or __circle__ whichever you want - Fix __aspect ratio__ - Configure `Rect` of _crop rect_ programmatically - Detect events of users' operation - Undo / Redo operation - (advanced) Cropping backend logics are also customizable Note that this package _DON'T_ - read / download image data from any storages, such as gallery, internet, etc. - resize, tilt, or other conversions which can be done with [image](https://pub.dev/packages/image) package directly. - provide UI parts other than cropping editor, such as buttons to control. Building UI is fully UP TO YOU! ## Usage ### Basics Place `Crop` Widget wherever you want to place image cropping UI. ```dart final _controller = CropController(); @override Widget build(BuildContext context) { return Crop( image: _imageData, controller: _controller, onCropped: (result) { switch(result) { case CropResult.success(:final croppedImage): // do something with cropped image data case CropResult.error(:final error): // do something with error } } ); } ``` Then, `Crop` widget will automatically display cropping editor UI on users screen with given image. By passing `CropController` instance to `controller` argument of `Crop`'s constructor, you can control the `Crop` widget from anywhere on your source code. For example, when you want to crop the image with the current crop rect, you can just call `_controller.crop()` whenever you want, such like the code below. ```dart ElevatedButton( child: Text('Crop it!') onPressed: () => _cropController.crop(), ), ``` Because `_controller.crop()` only kicks the cropping process, this method returns immediately without any cropped image data. You can obtain the result of cropping images via `onCropped` callback of `Crop` Widget. ### Undo / Redo `CropController` also provides `undo` and `redo` methods. ```dart ElevatedButton( child: Text('Undo') onPressed: () => _cropController.undo(), ), ``` You can also detect history of crop rect changes via `onHistoryChanged` callback of `Crop` Widget. This callback exposes `History` object, which contains `undoCount` and `redoCount`, that indicates how many times undo / redo operation is available. ```dart Crop( onHistoryChanged: (history) { setState(() { _undoEnabled = history.undoCount > 0; _redoEnabled = history.redoCount > 0; }); }, ) ``` ### List of configurations All the arguments of `Crop` and usages are below. ```dart final _controller = CropController(); Widget build(BuildContext context) { return Crop( image: _imageData, controller: _controller, onCropped: (result) { switch(result) { case CropResult.success(:final croppedImage): // do something with cropped image data case CropResult.error(:final error): // do something with error } }, aspectRatio: 4 / 3, initialRectBuilder: InitialRectBuilder.withBuilder((viewportRect, imageRect) { return Rect.fromLTRB( viewportRect.left + 24, viewportRect.top + 32, viewportRect.right - 24, viewportRect.bottom - 32, ); }), // initialRectBuilder: InitialRectBuilder.withArea( // ImageBasedRect.fromLTWH(240, 212, 800, 600), // ), // initialRectBuilder: InitialRectBuilder.withSizeAndRatio( // size: 0.5, // aspectRatio: 4 / 3, // ), // withCircleUi: true, baseColor: Colors.blue.shade900, maskColor: Colors.white.withAlpha(100), overlayBuilder: (context, rect) { return CustomPaint(painter: MyPainter(rect)); }, progressIndicator: const CircularProgressIndicator(), radius: 20, onMoved: (newRect) { // do something with current crop rect. }, onImageMoved: (newImageRect) { // do something with current image rect. }, onStatusChanged: (status) { // do something with current CropStatus }, willUpdateScale: (newScale) { // if returning false, scaling will be canceled return newScale < 5; }, cornerDotBuilder: (size, edgeAlignment) => const DotControl(color: Colors.blue), clipBehavior: Clip.none, interactive: true, // fixCropRect: true, // formatDetector: (image) {}, // imageCropper: myCustomImageCropper, // imageParser: (image, {format}) {}, ); } ``` |argument|type|description| |-|-|-| |image|Uint8List|Original image data to be cropped. The result of cropping operation can be obtained via `onCropped` callback.| |onCropped|void Function(CropResult)|Callback called when cropping operation is completed. The result is exposed as `CropResult` object. `CropResult.success()` contains cropped image data, and `CropResult.error()` contains error object.| |controller|CropController|Controller for managing cropping operation.| |aspectRatio|double?| Initial aspect ratio of crop rect. Set `null` or just omit if you want to crop images with any aspect ratio. `aspectRatio` can be changed dynamically via setter of `CropController.aspectRatio`. (see below)| |initialSize|double?| is the initial size of crop rect. `1.0` (or `null`, by default) fits the size of image, which means crop rect extends as much as possible. `0.5` would be the half. This value is also referred when `aspectRatio` changes via `CropController.aspectRatio`.| |initialRectBuilder|InitialRectBuilder?|An object preserving configuration for building the initial crop rect. `InitialRectBuilder.withBuilder` enables you to configure the rect with a function to decide initial `Rect` of crop rect based on viewport of `Crop` itself. `InitialRectBuilder.withArea` enables you to configure the rect with `ImageBasedRect` which is based on actual image size. `InitialRectBuilder.withSizeAndRatio` enables you to configure the rect with `size` and `aspectRatio`.| |withCircleUi|bool|Flag to decide the shape of cropping UI. If `true`, the shape of cropping UI is circle and `aspectRatio` is automatically set `1.0`. Note that this flag does NOT affect to the result of cropping image. If you want cropped images with circle shape, call `CropController.cropCircle` instead of `CropController.crop`.| |maskColor|Color?|Color of the mask widget which is placed over the cropping editor.| |baseColor|Color?|Color of the base color of the cropping editor.| |overlayBuilder|Widget Function(BuildContext, ViewportBasedRect)?|Builder function to build Widget placed over the cropping rect. `rect` of argument is current `ViewportBasedRect` of crop rect.| |radius|double?|Corner radius of crop rect.| |onMoved|void Function(ViewportBasedRect)?|Callback called when crop rect is moved regardless of its reasons. `newRect` of argument is current `ViewportBasedRect` of crop rect.| |onImageMoved|void Function(ViewportBasedRect)?|Callback called when image is moved regardless of its reasons. `newImageRect` of argument is current `ViewportBasedRect` of image.| |onHistoryChanged|void Function(History)?|Callback called when history of crop rect is changed. This history allows you to undo / redo feature is available or not.| |onStatusChanged|void Function(CropStatus)?|Callback called when status of Crop is changed.| |willUpdateScale|bool Function(double)?|Callback called before scale changes on _interactive_ mode. By returning `false` to this callback, updating scale will be canceled.| |cornerDotBuilder|Widget Function(Size, EdgeAlignment)?|Builder function to build Widget placed at four corners used to move crop rect. The builder passes `size` which widget must follow and `edgeAlignment` which indicates the position.| |progressIndicator|Widget?|Widget for showing preparing image is in progress. Nothing (`SizedBox.shrink()` actually) is shown by default.| |interactive|bool?|Flag to enable _interactive_ mode that users can move / zoom images. `false` by default| |fixCropRect|bool?|Flag if crop rect should be fixed on _interactive_ mode. `false` by default| |clipBehavior|Clip?|Decide clipping strategy for `Crop`. `Clip.hardEdge` by default| |filterQuality|FilterQuality?|Decide filter quality for `Image` showing target image. `FilterQuality.low` by default| ### for Web |argument|type|description| |-|-|-| |scrollZoomSensitivity|double?|Sensitivity for zoom gesture using mouse-wheel. For web applications only.| ### Advanced `crop_your_image` also allows you to customize backend logic for - detecting the format of the image - detecting detail information (width / height) of the image - cropping by passing the arguments below. |argument|type|description| |-|-|-| |formatDetector|ImageFormat Function(Uint8List)?|Function to detect the format of original image. By detecting the format before `imageParser` parses the original image from `Uint8List` to `ImageDetail`, `imageParser` will sufficiently parse the binary, which means the initializing operation speeds up. `defaultFormatDetector` is used by default| |imageParser|ImageDetail Function(Uint8List, {ImageFormat})?|Function for parsing original image from `Uint8List` to `ImageDetail`, which preserve `height`, `width` and parsed `image` with generic type ``. `image` is passed to `imageCropper` with `Rect` to be cropped. `defaultImageParser` is used by default| |imageCropper|ImageCropper?|By implementing `ImageCropper` and passing its instance to this argument, you can exchange cropping logic. `defaultImageCropper` is used by default| # Gallery App The repository below is for a sample app of using crop_your_image. | [chooyan-eng/crop_your_image_gallery](https://github.com/chooyan-eng/crop_your_image_gallery) You can find several examples with executable source codes here. # Contact If you have anything you want to inform me ([@chooyan-eng](https://github.com/chooyan-eng)), such as suggestions to enhance this package or functionalities you want etc, feel free to make [issues on GitHub](https://github.com/chooyan-eng/crop_your_image/issues) or send messages on X [@tsuyoshi_chujo](https://x.com/tsuyoshi_chujo) (Japanese [@chooyan_i18n](https://x.com/chooyan_i18n)). ================================================ FILE: analysis_options.yaml ================================================ analyzer: errors: todo: ignore ================================================ FILE: docs/architecture.md ================================================ This document describes how crop_your_image is implemented. This is not only for the maintainers but also Cursor editor, which supports coding and refactoring using AI. # Architecture of crop_your_image ## Overview At first, crop_your_image is a Flutter package that provides a widget named `Crop` and its controller `CropController`. Because this package requires a lot of calculations for detecting the cropping area, we have internally `Calculator` class. In addition, `Crop` also provides a mechanism to interchange backend logics for: - Determining the given image format - Parsing the image from `Uint8List` to whatever data type - Cropping the image with given rect The default backend uses `image` package for all the image processing, but this mechanism allows you to use other packages, or even delegate the processing to your server side. ## Crop `Crop` is designed to be a handy widget that can be used at anywhere; this may be used in a `Dialog`, or a `BottomSheet`, etc. To achieve the design, `Crop` first checks the size of its viewport respecting the given constraints, then it overrides the `MediaQueryData.size` with the size so that its subtree can find the desired size calling `MediaQuery.sizeOf(context)`. This mechanism introduces one restriction that the user must supply the size of the viewport to `Crop` explicitly, typically using `SizedBox`, `AspectRatio`, or `Expanded`. `Crop`, or internal `_CropEditor` widget, doesn't use `InteractiveViewer` but does all the calculations for zooming and panning based on the given info by `GestureDetector`. This is because `InteractiveViewer` doesn't provide a handy way to get the current zoom level and pan position, which are required for the cropping area calculation. ## CropController Users may want to imperatively control `Crop` widget, as in `TextField` has `TextEditingController`. Thus, `Crop` provides `CropController` to allow users to control the widget, such as calling `crop()`. Once the controller is given to `Crop`, this initializes the controller in `initState()` with attaching `CropControllerDelegate` and its methods declared with `late` keyword. TODO(chooyan-eng): Revise the implementation of `TextEditingController` or other controller patterns and if `CropController` follows the same pattern. ## Calculator `Calculator` class is a utility to calculate various data for cropping. crop_your_image requires various kinds of data, such as: - Actual image size - Displaying image size on viewport - Current zoom level - Current pan position - The rect of the cropping area based on given viewport - The rect of the cropping area based on given image size - Given aspect ratio for cropping area - Given initial size for cropping area meaning the calculation logic is always complex. To keep the code clean and testable, `Calculator` provides all the calculation logic in a pure Dart logic. The calculation logic changes depending on the given image fits vertically or horizontally to the viewport. So `Calculator` has two implementations, `VerticalCalculator` and `HorizontalCalculator`. TODO(chooyan-eng): Revise the calculation logic must be separated depending on the given image aspect ratio. There can be a nice calculation to be applied regardless of the image orientation. TODO(chooyan-eng): Currently, `Calculator` exposes the *methods* for calculation and `Crop` calls the methods whenever it needs, however, this can be refactored with the idea mentioned in https://github.com/chooyan-eng/complex_local_state_management/blob/main/docs/local_state.md ================================================ FILE: example/.gitignore ================================================ # Miscellaneous *.class *.log *.pyc *.swp .DS_Store .atom/ .buildlog/ .history .svn/ # 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 .flutter-plugins-dependencies .packages .pub-cache/ .pub/ /build/ # Web related lib/generated_plugin_registrant.dart # 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 ================================================ FILE: example/.metadata ================================================ # 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: "41456452f29d64e8deb623a3c927524bcf9f111b" channel: "stable" project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: 41456452f29d64e8deb623a3c927524bcf9f111b base_revision: 41456452f29d64e8deb623a3c927524bcf9f111b - platform: macos create_revision: 41456452f29d64e8deb623a3c927524bcf9f111b base_revision: 41456452f29d64e8deb623a3c927524bcf9f111b - platform: windows create_revision: 41456452f29d64e8deb623a3c927524bcf9f111b base_revision: 41456452f29d64e8deb623a3c927524bcf9f111b # 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' ================================================ FILE: example/README.md ================================================ # 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: - [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) - [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) For help getting started with Flutter, view our [online documentation](https://flutter.dev/docs), which offers tutorials, samples, guidance on mobile development, and a full API reference. ================================================ FILE: example/analysis_options.yaml ================================================ # 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. 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 ================================================ FILE: example/android/.gitignore ================================================ gradle-wrapper.jar /.gradle /captures/ /gradlew /gradlew.bat /local.properties GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app key.properties ================================================ FILE: example/android/app/build.gradle ================================================ def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 33 sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.example" minSdkVersion 16 targetSdkVersion 33 versionCode flutterVersionCode.toInteger() versionName flutterVersionName } 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.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } ================================================ FILE: example/android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: example/android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: example/android/app/src/main/kotlin/com/example/example/MainActivity.kt ================================================ package com.example.example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { } ================================================ FILE: example/android/app/src/main/res/drawable/launch_background.xml ================================================ ================================================ FILE: example/android/app/src/main/res/drawable-v21/launch_background.xml ================================================ ================================================ FILE: example/android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: example/android/app/src/main/res/values-night/styles.xml ================================================ ================================================ FILE: example/android/app/src/profile/AndroidManifest.xml ================================================ ================================================ FILE: example/android/build.gradle ================================================ buildscript { ext.kotlin_version = '1.7.20' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.1.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } ================================================ FILE: example/android/gradle/wrapper/gradle-wrapper.properties ================================================ #Fri Jun 23 08:50:38 CEST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip ================================================ FILE: example/android/gradle.properties ================================================ org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true ================================================ FILE: example/android/settings.gradle ================================================ include ':app' def localPropertiesFile = new File(rootProject.projectDir, "local.properties") def properties = new Properties() assert localPropertiesFile.exists() localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" ================================================ FILE: example/ios/.gitignore ================================================ *.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/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 ================================================ FILE: example/ios/Flutter/AppFrameworkInfo.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable App CFBundleIdentifier io.flutter.flutter.app CFBundleInfoDictionaryVersion 6.0 CFBundleName App CFBundlePackageType FMWK CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1.0 MinimumOSVersion 12.0 ================================================ FILE: example/ios/Flutter/Debug.xcconfig ================================================ #include "Generated.xcconfig" ================================================ FILE: example/ios/Flutter/Release.xcconfig ================================================ #include "Generated.xcconfig" ================================================ FILE: example/ios/Runner/AppDelegate.swift ================================================ import UIKit import Flutter @main @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } ================================================ FILE: example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "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" } } ================================================ FILE: example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json ================================================ { "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" } } ================================================ FILE: example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md ================================================ # 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. ================================================ FILE: example/ios/Runner/Base.lproj/LaunchScreen.storyboard ================================================ ================================================ FILE: example/ios/Runner/Base.lproj/Main.storyboard ================================================ ================================================ FILE: example/ios/Runner/Info.plist ================================================ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName example CFBundlePackageType APPL CFBundleShortVersionString $(FLUTTER_BUILD_NAME) CFBundleSignature ???? CFBundleVersion $(FLUTTER_BUILD_NUMBER) LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance CADisableMinimumFrameDurationOnPhone UIApplicationSupportsIndirectInputEvents ================================================ FILE: example/ios/Runner/Runner-Bridging-Header.h ================================================ #import "GeneratedPluginRegistrant.h" ================================================ FILE: example/ios/Runner.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 54; objects = { /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; /* End PBXBuildFile section */ /* Begin 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 = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 97C146EB1CF9000F007C117D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 9740EEB31CF90195004384FC /* Generated.xcconfig */, ); name = Flutter; sourceTree = ""; }; 97C146E51CF9000F007C117D = { isa = PBXGroup; children = ( 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, ); sourceTree = ""; }; 97C146EF1CF9000F007C117D /* Products */ = { isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, ); name = Products; sourceTree = ""; }; 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, ); path = Runner; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, ); buildRules = ( ); dependencies = ( ); name = Runner; productName = Runner; productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 1510; ORGANIZATIONNAME = ""; TargetAttributes = { 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; LastSwiftMigration = 1100; }; }; }; buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 97C146E51CF9000F007C117D; productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 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 */ 97C146EA1CF9000F007C117D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase 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; 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; 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 = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Profile; }; 249021D4217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.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; }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; 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; 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 = 12.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; 97C147041CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; 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; 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 = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; 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 */ 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 97C147031CF9000F007C117D /* Debug */, 97C147041CF9000F007C117D /* Release */, 249021D3217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 97C147061CF9000F007C117D /* Debug */, 97C147071CF9000F007C117D /* Release */, 249021D4217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 97C146E61CF9000F007C117D /* Project object */; } ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings ================================================ PreviewsEnabled ================================================ FILE: example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme ================================================ ================================================ FILE: example/ios/Runner.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings ================================================ PreviewsEnabled ================================================ FILE: example/lib/main.dart ================================================ import 'dart:typed_data'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show rootBundle; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('Crop Your Image Demo'), ), body: CropSample(), ), ); } } class CropSample extends StatefulWidget { @override _CropSampleState createState() => _CropSampleState(); } class _CropSampleState extends State { static const _images = const [ 'assets/images/city.png', 'assets/images/lake.png', 'assets/images/train.png', 'assets/images/turtois.png', ]; final _cropController = CropController(); final _imageDataList = []; var _loadingImage = false; var _currentImage = 0; set currentImage(int value) { setState(() { _currentImage = value; }); _cropController.image = _imageDataList[_currentImage]; } var _isThumbnail = false; var _isCropping = false; var _isCircleUi = false; Uint8List? _croppedData; var _statusText = ''; var _isOverlayActive = true; var _undoEnabled = false; var _redoEnabled = false; @override void initState() { _loadAllImages(); super.initState(); } Future _loadAllImages() async { setState(() { _loadingImage = true; }); for (final assetName in _images) { _imageDataList.add(await _load(assetName)); } setState(() { _loadingImage = false; }); } Future _load(String assetName) async { final assetData = await rootBundle.load(assetName); return assetData.buffer.asUint8List(); } @override Widget build(BuildContext context) { return Container( width: double.infinity, height: double.infinity, child: Center( child: Visibility( visible: !_loadingImage && !_isCropping, child: Column( children: [ if (_imageDataList.length >= 4) Padding( padding: const EdgeInsets.all(16), child: Row( children: [ _buildThumbnail(_imageDataList[0]), const SizedBox(width: 16), _buildThumbnail(_imageDataList[1]), const SizedBox(width: 16), _buildThumbnail(_imageDataList[2]), const SizedBox(width: 16), _buildThumbnail(_imageDataList[3]), ], ), ), Expanded( child: Visibility( visible: _croppedData == null, child: Stack( children: [ if (_imageDataList.isNotEmpty) ...[ Crop( willUpdateScale: (newScale) => newScale < 5, controller: _cropController, image: _imageDataList[_currentImage], onCropped: (result) { switch (result) { case CropSuccess(:final croppedImage): _croppedData = croppedImage; case CropFailure(:final cause): showDialog( context: context, builder: (context) => AlertDialog( title: Text('Error'), content: Text('Failed to crop image: ${cause}'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text('OK')), ], ), ); } setState(() => _isCropping = false); }, withCircleUi: _isCircleUi, onStatusChanged: (status) => setState(() { _statusText = { CropStatus.nothing: 'Crop has no image data', CropStatus.loading: 'Crop is now loading given image', CropStatus.ready: 'Crop is now ready!', CropStatus.cropping: 'Crop is now cropping image', }[status] ?? ''; }), maskColor: _isThumbnail ? Colors.white : null, cornerDotBuilder: (size, edgeAlignment) => const SizedBox.shrink(), interactive: true, fixCropRect: true, radius: 20, initialRectBuilder: InitialRectBuilder.withBuilder( (viewportRect, imageRect) { return Rect.fromLTRB( viewportRect.left + 24, viewportRect.top + 24, viewportRect.right - 24, viewportRect.bottom - 24, ); }, ), onHistoryChanged: (history) => setState(() { _undoEnabled = history.undoCount > 0; _redoEnabled = history.redoCount > 0; }), overlayBuilder: _isOverlayActive ? (context, rect) { final overlay = CustomPaint( painter: GridPainter(), ); return _isCircleUi ? ClipOval( child: overlay, ) : overlay; } : null, ), IgnorePointer( child: Padding( padding: const EdgeInsets.all(24), child: Container( decoration: BoxDecoration( border: Border.all(width: 4, color: Colors.white), borderRadius: BorderRadius.circular(20), ), ), ), ), ], Positioned( right: 16, bottom: 16, child: GestureDetector( onTapDown: (_) => setState(() => _isThumbnail = true), onTapUp: (_) => setState(() => _isThumbnail = false), child: CircleAvatar( backgroundColor: _isThumbnail ? Colors.blue.shade50 : Colors.blue, child: Center( child: Icon(Icons.crop_free_rounded), ), ), ), ), ], ), replacement: Center( child: _croppedData == null ? SizedBox.shrink() : Image.memory(_croppedData!), ), ), ), if (_croppedData == null) Padding( padding: const EdgeInsets.all(16), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( icon: Icon(Icons.crop_7_5), onPressed: () { _isCircleUi = false; _cropController.aspectRatio = 16 / 4; }, ), IconButton( icon: Icon(Icons.crop_16_9), onPressed: () { _isCircleUi = false; _cropController.aspectRatio = 16 / 9; }, ), IconButton( icon: Icon(Icons.crop_5_4), onPressed: () { _isCircleUi = false; _cropController.aspectRatio = 4 / 3; }, ), IconButton( icon: Icon(Icons.crop_square), onPressed: () { _isCircleUi = false; _cropController ..withCircleUi = false ..aspectRatio = 1; }, ), IconButton( icon: Icon(Icons.circle), onPressed: () { _isCircleUi = true; _cropController.withCircleUi = true; }), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ Text('Show Grid'), Switch( value: _isOverlayActive, onChanged: (value) { setState(() { _isOverlayActive = value; }); }, ) ], ), const SizedBox(height: 16), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: _undoEnabled ? () => _cropController.undo() : null, child: Text('UNDO'), ), const SizedBox(width: 16), ElevatedButton( onPressed: _redoEnabled ? () => _cropController.redo() : null, child: Text('REDO'), ), ], ), const SizedBox(height: 16), Container( width: double.infinity, child: ElevatedButton( onPressed: () { setState(() { _isCropping = true; }); _isCircleUi ? _cropController.cropCircle() : _cropController.crop(); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 16), child: Text('CROP IT!'), ), ), ), ], ), ), const SizedBox(height: 16), Text(_statusText), const SizedBox(height: 16), ], ), replacement: const CircularProgressIndicator(), ), ), ); } Expanded _buildThumbnail(Uint8List data) { final index = _imageDataList.indexOf(data); return Expanded( child: InkWell( onTap: () { _croppedData = null; currentImage = index; }, child: Container( height: 100, decoration: BoxDecoration( border: index == _currentImage ? Border.all( width: 8, color: Colors.blue, ) : null, ), child: Image.memory( data, fit: BoxFit.cover, ), ), ), ); } } class GridPainter extends CustomPainter { final divisions = 2; final strokeWidth = 1.0; final Color color = Colors.black54; @override void paint(Canvas canvas, Size size) { final paint = Paint() ..strokeWidth = strokeWidth ..color = color; final spacing = size / (divisions + 1); for (var i = 1; i < divisions + 1; i++) { // draw vertical line canvas.drawLine( Offset(spacing.width * i, 0), Offset(spacing.width * i, size.height), paint, ); // draw horizontal line canvas.drawLine( Offset(0, spacing.height * i), Offset(size.width, spacing.height * i), paint, ); } } @override bool shouldRepaint(GridPainter oldDelegate) => false; } ================================================ FILE: example/lib/my_cropper.dart ================================================ import 'dart:ui'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:image/image.dart' as image hide ImageFormat; class MyImageCropper extends ImageCropper { const MyImageCropper(); @override RectValidator get rectValidator => defaultRectValidator; @override RectCropper get rectCropper => _rectCropper; @override CircleCropper get circleCropper => _circleCropper; } final RectCropper _rectCropper = ( image.Image original, { required Offset topLeft, required Size size, required ImageFormat? outputFormat, }) { /// crop image with low quality return image.encodeJpg( quality: 10, image.copyCrop( original, x: topLeft.dx.toInt(), y: topLeft.dy.toInt(), width: size.width.toInt(), height: size.height.toInt(), ), ); }; final CircleCropper _circleCropper = ( image.Image original, { required Offset center, required double radius, required ImageFormat? outputFormat, }) { /// crop image with low quality /// note: jpg can't cropped circle return image.encodeJpg( quality: 10, image.copyCropCircle( original, centerX: center.dx.toInt(), centerY: center.dy.toInt(), radius: radius.toInt(), ), ); }; ================================================ FILE: example/linux/.gitignore ================================================ flutter/ephemeral ================================================ FILE: example/linux/CMakeLists.txt ================================================ # Project-level configuration. cmake_minimum_required(VERSION 3.10) 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) add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Define the application target. To change its name, change BINARY_NAME above, # 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 dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) # 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() ================================================ FILE: example/linux/flutter/CMakeLists.txt ================================================ # 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} ) ================================================ FILE: example/linux/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" void fl_register_plugins(FlPluginRegistry* registry) { } ================================================ FILE: example/linux/flutter/generated_plugin_registrant.h ================================================ // // 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_ ================================================ FILE: example/linux/flutter/generated_plugins.cmake ================================================ # # 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) ================================================ FILE: example/linux/main.cc ================================================ #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); } ================================================ FILE: example/linux/my_application.cc ================================================ #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) // 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); gtk_widget_show(GTK_WIDGET(window)); 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); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), 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() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", G_APPLICATION_NON_UNIQUE, nullptr)); } ================================================ FILE: example/linux/my_application.h ================================================ #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_ ================================================ FILE: example/macos/.gitignore ================================================ # Flutter-related **/Flutter/ephemeral/ **/Pods/ # Xcode-related **/dgph **/xcuserdata/ ================================================ FILE: example/macos/Flutter/Flutter-Debug.xcconfig ================================================ #include "ephemeral/Flutter-Generated.xcconfig" ================================================ FILE: example/macos/Flutter/Flutter-Release.xcconfig ================================================ #include "ephemeral/Flutter-Generated.xcconfig" ================================================ FILE: example/macos/Flutter/GeneratedPluginRegistrant.swift ================================================ // // Generated file. Do not edit. // import FlutterMacOS import Foundation func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { } ================================================ FILE: example/macos/Runner/AppDelegate.swift ================================================ import Cocoa import FlutterMacOS @NSApplicationMain class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } } ================================================ FILE: example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "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" } } ================================================ FILE: example/macos/Runner/Base.lproj/MainMenu.xib ================================================ ================================================ FILE: example/macos/Runner/Configs/AppInfo.xcconfig ================================================ // 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 © 2024 com.example. All rights reserved. ================================================ FILE: example/macos/Runner/Configs/Debug.xcconfig ================================================ #include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig" ================================================ FILE: example/macos/Runner/Configs/Release.xcconfig ================================================ #include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig" ================================================ FILE: example/macos/Runner/Configs/Warnings.xcconfig ================================================ 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 ================================================ FILE: example/macos/Runner/DebugProfile.entitlements ================================================ com.apple.security.app-sandbox com.apple.security.cs.allow-jit com.apple.security.network.server ================================================ FILE: example/macos/Runner/Info.plist ================================================ 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 ================================================ FILE: example/macos/Runner/MainFlutterWindow.swift ================================================ 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() } } ================================================ FILE: example/macos/Runner/Release.entitlements ================================================ com.apple.security.app-sandbox ================================================ FILE: example/macos/Runner.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 54; objects = { /* Begin PBXAggregateTarget section */ 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { isa = PBXAggregateTarget; buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; buildPhases = ( 33CC111E2044C6BF0003C045 /* ShellScript */, ); dependencies = ( ); name = "Flutter Assemble"; productName = FLX; }; /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 33CC10E52044A3C60003C045 /* Project object */; proxyType = 1; remoteGlobalIDString = 33CC10EC2044A3C60003C045; remoteInfo = Runner; }; 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 33CC10E52044A3C60003C045 /* Project object */; proxyType = 1; remoteGlobalIDString = 33CC111A2044C6BA0003C045; remoteInfo = FLX; }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ 33CC110E2044A8840003C045 /* Bundle Framework */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( ); name = "Bundle Framework"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 33CC10ED2044A3C60003C045 /* 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 = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 331C80D2294CF70F00263BE5 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 33CC10EA2044A3C60003C045 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 331C80D6294CF71000263BE5 /* RunnerTests */ = { isa = PBXGroup; children = ( 331C80D7294CF71000263BE5 /* RunnerTests.swift */, ); path = RunnerTests; sourceTree = ""; }; 33BA886A226E78AF003329D5 /* Configs */ = { isa = PBXGroup; children = ( 33E5194F232828860026EE4D /* AppInfo.xcconfig */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, ); path = Configs; sourceTree = ""; }; 33CC10E42044A3C60003C045 = { isa = PBXGroup; children = ( 33FAB671232836740065AC1E /* Runner */, 33CEB47122A05771004F2AC0 /* Flutter */, 331C80D6294CF71000263BE5 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, D73912EC22F37F3D000D13A0 /* Frameworks */, ); sourceTree = ""; }; 33CC10EE2044A3C60003C045 /* Products */ = { isa = PBXGroup; children = ( 33CC10ED2044A3C60003C045 /* 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 = ( 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, ); path = Flutter; sourceTree = ""; }; 33FAB671232836740065AC1E /* Runner */ = { isa = PBXGroup; children = ( 33CC10F02044A3C60003C045 /* AppDelegate.swift */, 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, 33E51913231747F40026EE4D /* DebugProfile.entitlements */, 33E51914231749380026EE4D /* Release.entitlements */, 33CC11242044D66E0003C045 /* Resources */, 33BA886A226E78AF003329D5 /* Configs */, ); path = Runner; sourceTree = ""; }; D73912EC22F37F3D000D13A0 /* Frameworks */ = { isa = PBXGroup; children = ( ); name = Frameworks; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 331C80D4294CF70F00263BE5 /* RunnerTests */ = { isa = PBXNativeTarget; buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( 331C80D1294CF70F00263BE5 /* Sources */, 331C80D2294CF70F00263BE5 /* Frameworks */, 331C80D3294CF70F00263BE5 /* Resources */, ); buildRules = ( ); dependencies = ( 331C80DA294CF71000263BE5 /* PBXTargetDependency */, ); name = RunnerTests; productName = RunnerTests; productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 33CC10EC2044A3C60003C045 /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, 33CC110E2044A8840003C045 /* Bundle Framework */, 3399D490228B24CF009A79C7 /* ShellScript */, ); buildRules = ( ); dependencies = ( 33CC11202044C79F0003C045 /* PBXTargetDependency */, ); name = Runner; productName = Runner; productReference = 33CC10ED2044A3C60003C045 /* example.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 33CC10E52044A3C60003C045 /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0920; LastUpgradeCheck = 1430; ORGANIZATIONNAME = ""; TargetAttributes = { 331C80D4294CF70F00263BE5 = { CreatedOnToolsVersion = 14.0; TestTargetID = 33CC10EC2044A3C60003C045; }; 33CC10EC2044A3C60003C045 = { CreatedOnToolsVersion = 9.2; LastSwiftMigration = 1100; ProvisioningStyle = Automatic; SystemCapabilities = { com.apple.Sandbox = { enabled = 1; }; }; }; 33CC111A2044C6BA0003C045 = { CreatedOnToolsVersion = 9.2; ProvisioningStyle = Manual; }; }; }; buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 33CC10E42044A3C60003C045; productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 33CC10EC2044A3C60003C045 /* Runner */, 331C80D4294CF70F00263BE5 /* RunnerTests */, 33CC111A2044C6BA0003C045 /* Flutter Assemble */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 331C80D3294CF70F00263BE5 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 33CC10EB2044A3C60003C045 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( ); outputFileListPaths = ( ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; }; 33CC111E2044C6BF0003C045 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( Flutter/ephemeral/FlutterInputs.xcfilelist, ); inputPaths = ( Flutter/ephemeral/tripwire, ); outputFileListPaths = ( Flutter/ephemeral/FlutterOutputs.xcfilelist, ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 331C80D1294CF70F00263BE5 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 33CC10E92044A3C60003C045 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 33CC10EC2044A3C60003C045 /* Runner */; targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; }; 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { isa = PBXVariantGroup; children = ( 33CC10F52044A3C60003C045 /* Base */, ); name = MainMenu.xib; path = Runner; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 331C80DB294CF71000263BE5 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.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; 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; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.14; 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; 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; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.14; 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; 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; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.14; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; 33CC10FC2044A3C60003C045 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; }; name = Debug; }; 33CC10FD2044A3C60003C045 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_VERSION = 5.0; }; name = Release; }; 33CC111C2044C6BA0003C045 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Manual; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 33CC111D2044C6BA0003C045 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { isa = XCConfigurationList; buildConfigurations = ( 331C80DB294CF71000263BE5 /* Debug */, 331C80DC294CF71000263BE5 /* Release */, 331C80DD294CF71000263BE5 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC10F92044A3C60003C045 /* Debug */, 33CC10FA2044A3C60003C045 /* Release */, 338D0CE9231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC10FC2044A3C60003C045 /* Debug */, 33CC10FD2044A3C60003C045 /* Release */, 338D0CEA231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC111C2044C6BA0003C045 /* Debug */, 33CC111D2044C6BA0003C045 /* Release */, 338D0CEB231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 33CC10E52044A3C60003C045 /* Project object */; } ================================================ FILE: example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme ================================================ ================================================ FILE: example/macos/Runner.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/macos/RunnerTests/RunnerTests.swift ================================================ import FlutterMacOS import Cocoa 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. } } ================================================ FILE: example/pubspec.yaml ================================================ name: example description: A new Flutter project. # The following line prevents the package from being accidentally published to # pub.dev using `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 used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0-dev.1 environment: sdk: '>=3.0.0 <4.0.0' dependencies: flutter: sdk: flutter crop_your_image: path: ../ # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 dev_dependencies: flutter_test: sdk: flutter # 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. 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: - assets/images/ # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages # 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/custom-fonts/#from-packages ================================================ FILE: example/test/widget_test.dart ================================================ import 'package:crop_your_image/crop_your_image.dart'; import 'package:example/main.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Show Crop', (tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: CropSample(), ), ), ); await tester.pumpAndSettle(); expect(find.byType(Crop), findsOneWidget); }); } ================================================ FILE: example/web/index.html ================================================ example ================================================ FILE: example/web/manifest.json ================================================ { "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" } ] } ================================================ FILE: example/windows/.gitignore ================================================ 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/ ================================================ FILE: example/windows/CMakeLists.txt ================================================ # 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) ================================================ FILE: example/windows/flutter/CMakeLists.txt ================================================ # 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} ) ================================================ FILE: example/windows/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" void RegisterPlugins(flutter::PluginRegistry* registry) { } ================================================ FILE: example/windows/flutter/generated_plugin_registrant.h ================================================ // // 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_ ================================================ FILE: example/windows/flutter/generated_plugins.cmake ================================================ # # 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) ================================================ FILE: example/windows/runner/CMakeLists.txt ================================================ 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) ================================================ FILE: example/windows/runner/Runner.rc ================================================ // 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) 2024 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 ================================================ FILE: example/windows/runner/flutter_window.cpp ================================================ #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); } ================================================ FILE: example/windows/runner/flutter_window.h ================================================ #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_ ================================================ FILE: example/windows/runner/main.cpp ================================================ #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; } ================================================ FILE: example/windows/runner/resource.h ================================================ //{{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 ================================================ FILE: example/windows/runner/runner.exe.manifest ================================================ PerMonitorV2 ================================================ FILE: example/windows/runner/utils.cpp ================================================ #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(); } int target_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, nullptr, 0, nullptr, nullptr) -1; // remove the trailing null character int input_length = (int)wcslen(utf16_string); std::string utf8_string; if (target_length <= 0 || target_length > utf8_string.max_size()) { return utf8_string; } utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, input_length, utf8_string.data(), target_length, nullptr, nullptr); if (converted_length == 0) { return std::string(); } return utf8_string; } ================================================ FILE: example/windows/runner/utils.h ================================================ #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_ ================================================ FILE: example/windows/runner/win32_window.cpp ================================================ #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)); } } ================================================ FILE: example/windows/runner/win32_window.h ================================================ #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_ ================================================ FILE: lib/crop_your_image.dart ================================================ import 'package:crop_your_image/src/logic/cropper/image_image_cropper.dart'; import 'package:crop_your_image/src/logic/cropper/legacy_image_image_cropper.dart'; import 'package:crop_your_image/src/logic/format_detector/default_format_detector.dart'; import 'package:crop_your_image/src/logic/parser/image_image_parser.dart'; export 'src/widget/widget.dart'; export 'src/logic/logic.dart'; final defaultImageParser = imageImageParser; final defaultFormatDetector = imageFormatDetector; const defaultImageCropper = ImageImageCropper(); const legacyImageCropper = LegacyImageImageCropper(); ================================================ FILE: lib/src/logic/cropper/default_rect_validator.dart ================================================ import 'dart:ui'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:crop_your_image/src/logic/cropper/errors.dart'; import 'package:image/image.dart'; /// default implementation of [RectValidator] /// this checks if the rect is inside the image, not negative, and not negative size final RectValidator defaultRectValidator = (Image original, Offset topLeft, Offset bottomRight) { if (topLeft.dx.toInt().isNegative || topLeft.dy.toInt().isNegative || bottomRight.dx.toInt().isNegative || bottomRight.dy.toInt().isNegative || topLeft.dx.toInt() > original.width || topLeft.dy.toInt() > original.height || bottomRight.dx.toInt() > original.width || bottomRight.dy.toInt() > original.height) { return InvalidRectException(topLeft: topLeft, bottomRight: bottomRight); } if (topLeft.dx > bottomRight.dx || topLeft.dy > bottomRight.dy) { return NegativeSizeException(topLeft: topLeft, bottomRight: bottomRight); } return null; }; ================================================ FILE: lib/src/logic/cropper/errors.dart ================================================ import 'dart:ui'; class NegativeSizeException implements Exception { final Offset topLeft; final Offset bottomRight; NegativeSizeException({ required this.topLeft, required this.bottomRight, }); } class InvalidRectException implements Exception { final Offset topLeft; final Offset bottomRight; InvalidRectException({ required this.topLeft, required this.bottomRight, }); } ================================================ FILE: lib/src/logic/cropper/image_cropper.dart ================================================ import 'dart:async'; import 'dart:math'; import 'dart:typed_data'; import 'dart:ui'; import 'package:crop_your_image/src/logic/format_detector/format.dart'; import 'package:crop_your_image/src/logic/shape.dart'; /// Interface for cropping logic abstract class ImageCropper { const ImageCropper(); FutureOr call({ required T original, required Offset topLeft, required Offset bottomRight, ImageFormat? outputFormat, ImageShape shape = ImageShape.rectangle, }) async { final error = rectValidator(original, topLeft, bottomRight); if (error != null) { throw error; } final size = Size( bottomRight.dx - topLeft.dx, bottomRight.dy - topLeft.dy, ); return switch (shape) { ImageShape.rectangle => rectCropper( original, topLeft: topLeft, size: size, outputFormat: outputFormat, ), ImageShape.circle => circleCropper( original, center: Offset( topLeft.dx + size.width / 2, topLeft.dy + size.height / 2, ), radius: min(size.width, size.height) / 2, outputFormat: outputFormat, ), }; } RectValidator get rectValidator; RectCropper get rectCropper; CircleCropper get circleCropper; } typedef RectValidator = Exception? Function( T original, Offset topLeft, Offset bottomRight); typedef RectCropper = Uint8List Function( T original, { required Offset topLeft, required Size size, required ImageFormat? outputFormat, }); typedef CircleCropper = Uint8List Function( T original, { required Offset center, required double radius, required ImageFormat? outputFormat, }); ================================================ FILE: lib/src/logic/cropper/image_image_cropper.dart ================================================ import 'dart:typed_data'; import 'dart:ui'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:image/image.dart' hide ImageFormat; /// an implementation of [ImageCropper] using image package class ImageImageCropper extends ImageCropper { const ImageImageCropper(); @override RectCropper get rectCropper => defaultRectCropper; @override CircleCropper get circleCropper => defaultCircleCropper; @override RectValidator get rectValidator => defaultRectValidator; } /// process cropping image. /// this method is supposed to be called only via compute() final RectCropper defaultRectCropper = ( Image original, { required Offset topLeft, required Size size, required ImageFormat? outputFormat, }) { return _findEncodeFunc(outputFormat)( copyCrop( original, x: topLeft.dx.toInt(), y: topLeft.dy.toInt(), width: size.width.toInt(), height: size.height.toInt(), ), ); }; /// process cropping image with circle shape. /// this method is supposed to be called only via compute() final CircleCropper defaultCircleCropper = ( Image original, { required Offset center, required double radius, required ImageFormat? outputFormat, }) { // convert to rgba if necessary final target = original.numChannels == 4 ? original : original.convert(numChannels: 4); return _findCircleEncodeFunc(outputFormat)( copyCropCircle( target, centerX: center.dx.toInt(), centerY: center.dy.toInt(), radius: radius.toInt(), ), ); }; Uint8List Function(Image) _findEncodeFunc(ImageFormat? outputFormat) { return switch (outputFormat) { ImageFormat.bmp => encodeBmp, ImageFormat.ico => encodeIco, ImageFormat.jpeg => encodeJpg, ImageFormat.png => encodePng, _ => encodePng, }; } Uint8List Function(Image) _findCircleEncodeFunc(ImageFormat? outputFormat) { return switch (outputFormat) { ImageFormat.bmp => encodeBmp, ImageFormat.ico => encodeIco, ImageFormat.jpeg => encodePng, // jpeg does not support circle crop ImageFormat.png => encodePng, _ => encodePng, }; } ================================================ FILE: lib/src/logic/cropper/legacy_image_image_cropper.dart ================================================ import 'dart:ui'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:image/image.dart' hide ImageFormat; /// an implementation of [ImageCropper] using image package /// this implementation is legacy that behaves the same as the version 1.1.0 or earlier /// meaning that it doesn't respect the outputFormat and always encode result as png class LegacyImageImageCropper extends ImageCropper { const LegacyImageImageCropper(); @override RectCropper get rectCropper => legacyRectCropper; @override CircleCropper get circleCropper => legacyCircleCropper; @override RectValidator get rectValidator => defaultRectValidator; } /// process cropping image. /// this method is supposed to be called only via compute() final RectCropper legacyRectCropper = ( Image original, { required Offset topLeft, required Size size, required ImageFormat? outputFormat, }) { return encodePng( copyCrop( original, x: topLeft.dx.toInt(), y: topLeft.dy.toInt(), width: size.width.toInt(), height: size.height.toInt(), ), ); }; /// process cropping image with circle shape. /// this method is supposed to be called only via compute() final CircleCropper legacyCircleCropper = ( Image original, { required Offset center, required double radius, required ImageFormat? outputFormat, }) { // convert to rgba if necessary final target = original.numChannels == 4 ? original : original.convert(numChannels: 4); return encodePng( copyCropCircle( target, centerX: center.dx.toInt(), centerY: center.dy.toInt(), radius: radius.toInt(), ), ); }; ================================================ FILE: lib/src/logic/format_detector/default_format_detector.dart ================================================ import 'dart:typed_data'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:image/image.dart' as img; final FormatDetector imageFormatDetector = (Uint8List data) { final format = img.findFormatForData(data); return switch (format) { img.ImageFormat.png => ImageFormat.png, img.ImageFormat.jpg => ImageFormat.jpeg, img.ImageFormat.webp => ImageFormat.webp, img.ImageFormat.bmp => ImageFormat.bmp, img.ImageFormat.ico => ImageFormat.ico, _ => ImageFormat.png, }; }; ================================================ FILE: lib/src/logic/format_detector/format.dart ================================================ /// Enum for the format of an image enum ImageFormat { png, jpeg, webp, bmp, ico, } ================================================ FILE: lib/src/logic/format_detector/format_detector.dart ================================================ import 'dart:typed_data'; import 'package:crop_your_image/src/logic/format_detector/format.dart'; /// Interface for detecting image format from given [data]. typedef FormatDetector = ImageFormat Function(Uint8List data); ================================================ FILE: lib/src/logic/logic.dart ================================================ export 'cropper/image_cropper.dart'; export 'cropper/default_rect_validator.dart'; export 'format_detector/format_detector.dart'; export 'format_detector/format.dart'; export 'parser/image_parser.dart'; export 'parser/image_detail.dart'; ================================================ FILE: lib/src/logic/parser/errors.dart ================================================ import 'package:crop_your_image/src/logic/format_detector/format.dart'; class InvalidInputFormatException implements Exception { final ImageFormat? inputFormat; InvalidInputFormatException(this.inputFormat); } ================================================ FILE: lib/src/logic/parser/image_detail.dart ================================================ /// Image with detail information. class ImageDetail { ImageDetail({ required this.image, required this.width, required this.height, }); final T image; final double width; final double height; late final bool isLandscape = width >= height; late final bool isPortrait = width < height; } ================================================ FILE: lib/src/logic/parser/image_image_parser.dart ================================================ import 'dart:typed_data'; import 'package:crop_your_image/src/logic/format_detector/format.dart'; import 'package:crop_your_image/src/logic/parser/errors.dart'; import 'package:crop_your_image/src/logic/parser/image_detail.dart'; import 'package:image/image.dart' as image; import 'image_parser.dart'; /// Implementation of [ImageParser] using image package /// Parsed image is represented as [image.Image] final ImageParser imageImageParser = (data, {inputFormat}) { late final image.Image? tempImage; try { tempImage = _decodeWith(data, format: inputFormat); } on InvalidInputFormatException { rethrow; } assert(tempImage != null); // check orientation final parsed = switch (tempImage?.exif.exifIfd.orientation ?? -1) { 3 => image.copyRotate(tempImage!, angle: 180), 6 => image.copyRotate(tempImage!, angle: 90), 8 => image.copyRotate(tempImage!, angle: -90), _ => tempImage!, }; return ImageDetail( image: parsed, width: parsed.width.toDouble(), height: parsed.height.toDouble(), ); }; image.Image? _decodeWith(Uint8List data, {ImageFormat? format}) { try { return switch (format) { ImageFormat.jpeg => image.decodeJpg(data), ImageFormat.png => image.decodePng(data), ImageFormat.bmp => image.decodeBmp(data), ImageFormat.ico => image.decodeIco(data), ImageFormat.webp => image.decodeWebP(data), _ => image.decodeImage(data), }; } on image.ImageException { throw InvalidInputFormatException(format); } } ================================================ FILE: lib/src/logic/parser/image_parser.dart ================================================ import 'dart:typed_data'; import 'package:crop_your_image/src/logic/format_detector/format.dart'; import 'package:crop_your_image/src/logic/parser/image_detail.dart'; /// Interface for parsing image and build [ImageDetail] from given [data]. typedef ImageParser = ImageDetail Function( Uint8List data, { ImageFormat? inputFormat, }); ================================================ FILE: lib/src/logic/shape.dart ================================================ /// Enum for the shape of a cropped image enum ImageShape { rectangle, circle, } ================================================ FILE: lib/src/widget/calculator.dart ================================================ import 'dart:math'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:flutter/widgets.dart'; /// Calculation logics for various [Rect] data. abstract class Calculator { const Calculator(); /// calculates [ViewportBasedRect] of image to fit the screenSize. ViewportBasedRect imageRect(Size screenSize, double imageAspectRatio); /// calculates [ViewportBasedRect] of initial cropping area. ViewportBasedRect initialCropRect(Size screenSize, ViewportBasedRect imageRect, double aspectRatio, double sizeRatio); /// calculates initial scale of image to cover _CropEditor double scaleToCover(Size screenSize, ViewportBasedRect imageRect); /// calculates ratio of [targetImage] and [screenSize] double screenSizeRatio(Size imageSize, Size screenSize); /// calculates [ViewportBasedRect] of the result of user moving the cropping area. ViewportBasedRect moveRect( ViewportBasedRect original, double deltaX, double deltaY, ViewportBasedRect imageRect, ) { if (original.left + deltaX < imageRect.left) { deltaX = (original.left - imageRect.left) * -1; } if (original.right + deltaX > imageRect.right) { deltaX = imageRect.right - original.right; } if (original.top + deltaY < imageRect.top) { deltaY = (original.top - imageRect.top) * -1; } if (original.bottom + deltaY > imageRect.bottom) { deltaY = imageRect.bottom - original.bottom; } return Rect.fromLTWH( original.left + deltaX, original.top + deltaY, original.width, original.height, ); } /// calculates [ViewportBasedRect] of the result of user moving the top-left dot. ViewportBasedRect moveTopLeft( ViewportBasedRect original, double deltaX, double deltaY, ViewportBasedRect imageRect, double? aspectRatio, ) { final newLeft = max(imageRect.left, min(original.left + deltaX, original.right - 40)); final newTop = min(max(original.top + deltaY, imageRect.top), original.bottom - 40); if (aspectRatio == null) { return Rect.fromLTRB( newLeft, newTop, original.right, original.bottom, ); } else { if (deltaX.abs() > deltaY.abs()) { var newWidth = original.right - newLeft; var newHeight = newWidth / aspectRatio; if (original.bottom - newHeight < imageRect.top) { newHeight = original.bottom - imageRect.top; newWidth = newHeight * aspectRatio; } return Rect.fromLTRB( original.right - newWidth, original.bottom - newHeight, original.right, original.bottom, ); } else { var newHeight = original.bottom - newTop; var newWidth = newHeight * aspectRatio; if (original.right - newWidth < imageRect.left) { newWidth = original.right - imageRect.left; newHeight = newWidth / aspectRatio; } return Rect.fromLTRB( original.right - newWidth, original.bottom - newHeight, original.right, original.bottom, ); } } } /// calculates [ViewportBasedRect] of the result of user moving the top-right dot. ViewportBasedRect moveTopRight( ViewportBasedRect original, double deltaX, double deltaY, ViewportBasedRect imageRect, double? aspectRatio, ) { final newTop = min(max(original.top + deltaY, imageRect.top), original.bottom - 40); final newRight = max(min(original.right + deltaX, imageRect.right), original.left + 40); if (aspectRatio == null) { return Rect.fromLTRB( original.left, newTop, newRight, original.bottom, ); } else { if (deltaX.abs() > deltaY.abs()) { var newWidth = newRight - original.left; var newHeight = newWidth / aspectRatio; if (original.bottom - newHeight < imageRect.top) { newHeight = original.bottom - imageRect.top; newWidth = newHeight * aspectRatio; } return Rect.fromLTWH( original.left, original.bottom - newHeight, newWidth, newHeight, ); } else { var newHeight = original.bottom - newTop; var newWidth = newHeight * aspectRatio; if (original.left + newWidth > imageRect.right) { newWidth = imageRect.right - original.left; newHeight = newWidth / aspectRatio; } return Rect.fromLTRB( original.left, original.bottom - newHeight, original.left + newWidth, original.bottom, ); } } } /// calculates [ViewportBasedRect] of the result of user moving the bottom-left dot. ViewportBasedRect moveBottomLeft( ViewportBasedRect original, double deltaX, double deltaY, ViewportBasedRect imageRect, double? aspectRatio, ) { final newLeft = max(imageRect.left, min(original.left + deltaX, original.right - 40)); final newBottom = max(min(original.bottom + deltaY, imageRect.bottom), original.top + 40); if (aspectRatio == null) { return Rect.fromLTRB( newLeft, original.top, original.right, newBottom, ); } else { if (deltaX.abs() > deltaY.abs()) { var newWidth = original.right - newLeft; var newHeight = newWidth / aspectRatio; if (original.top + newHeight > imageRect.bottom) { newHeight = imageRect.bottom - original.top; newWidth = newHeight * aspectRatio; } return Rect.fromLTRB( original.right - newWidth, original.top, original.right, original.top + newHeight, ); } else { var newHeight = newBottom - original.top; var newWidth = newHeight * aspectRatio; if (original.right - newWidth < imageRect.left) { newWidth = original.right - imageRect.left; newHeight = newWidth / aspectRatio; } return Rect.fromLTRB( original.right - newWidth, original.top, original.right, original.top + newHeight, ); } } } /// calculates [ViewportBasedRect] of the result of user moving the bottom-right dot. ViewportBasedRect moveBottomRight( ViewportBasedRect original, double deltaX, double deltaY, ViewportBasedRect imageRect, double? aspectRatio, ) { final newRight = min(imageRect.right, max(original.right + deltaX, original.left + 40)); final newBottom = max(min(original.bottom + deltaY, imageRect.bottom), original.top + 40); if (aspectRatio == null) { return Rect.fromLTRB( original.left, original.top, newRight, newBottom, ); } else { if (deltaX.abs() > deltaY.abs()) { var newWidth = newRight - original.left; var newHeight = newWidth / aspectRatio; if (original.top + newHeight > imageRect.bottom) { newHeight = imageRect.bottom - original.top; newWidth = newHeight * aspectRatio; } return Rect.fromLTWH( original.left, original.top, newWidth, newHeight, ); } else { var newHeight = newBottom - original.top; var newWidth = newHeight * aspectRatio; if (original.left + newWidth > imageRect.right) { newWidth = imageRect.right - original.left; newHeight = newWidth / aspectRatio; } return Rect.fromLTWH( original.left, original.top, newWidth, newHeight, ); } } } /// correct [ViewportBasedRect] not to exceed [ViewportBasedRect] of image. ViewportBasedRect correct( ViewportBasedRect rect, ViewportBasedRect imageRect, ) { return Rect.fromLTRB( max(rect.left, imageRect.left), max(rect.top, imageRect.top), min(rect.right, imageRect.right), min(rect.bottom, imageRect.bottom), ); } } class HorizontalCalculator extends Calculator { const HorizontalCalculator(); @override ViewportBasedRect imageRect(Size screenSize, double imageRatio) { final imageScreenHeight = screenSize.width / imageRatio; final top = (screenSize.height - imageScreenHeight) / 2; final bottom = top + imageScreenHeight; return Rect.fromLTWH(0, top, screenSize.width, bottom - top); } @override ViewportBasedRect initialCropRect( Size screenSize, ViewportBasedRect imageRect, double aspectRatio, double sizeRatio, ) { final imageRatio = imageRect.width / imageRect.height; // consider crop area will fit vertically or horizontally to image final initialSize = imageRatio > aspectRatio ? Size((imageRect.height * aspectRatio) * sizeRatio, imageRect.height * sizeRatio) : Size(screenSize.width * sizeRatio, (screenSize.width / aspectRatio) * sizeRatio); return Rect.fromLTWH( (screenSize.width - initialSize.width) / 2, (screenSize.height - initialSize.height) / 2, initialSize.width, initialSize.height, ); } @override double scaleToCover(Size screenSize, ViewportBasedRect imageRect) { return screenSize.height / imageRect.height; } @override double screenSizeRatio(Size imageSize, Size screenSize) { return imageSize.width / screenSize.width; } } class VerticalCalculator extends Calculator { const VerticalCalculator(); @override ViewportBasedRect imageRect(Size screenSize, double imageRatio) { final imageScreenWidth = screenSize.height * imageRatio; final left = (screenSize.width - imageScreenWidth) / 2; final right = left + imageScreenWidth; return Rect.fromLTWH(left, 0, right - left, screenSize.height); } @override ViewportBasedRect initialCropRect( Size screenSize, ViewportBasedRect imageRect, double aspectRatio, double sizeRatio, ) { final imageRatio = imageRect.width / imageRect.height; final initialSize = imageRatio < aspectRatio ? Size(imageRect.width * sizeRatio, imageRect.width / aspectRatio * sizeRatio) : Size((screenSize.height * aspectRatio) * sizeRatio, screenSize.height * sizeRatio); return Rect.fromLTWH( (screenSize.width - initialSize.width) / 2, (screenSize.height - initialSize.height) / 2, initialSize.width, initialSize.height, ); } @override double scaleToCover(Size screenSize, ViewportBasedRect imageRect) { return screenSize.width / imageRect.width; } @override double screenSizeRatio(Size imageSize, Size screenSize) { return imageSize.height / screenSize.height; } } ================================================ FILE: lib/src/widget/circle_crop_area_clipper.dart ================================================ import 'package:flutter/material.dart'; class CircleCropAreaClipper extends CustomClipper { final Rect rect; CircleCropAreaClipper(this.rect); @override Path getClip(Size size) { return Path() ..addOval(Rect.fromCircle(center: rect.center, radius: rect.width / 2)) ..addRect(Rect.fromLTWH(0.0, 0.0, size.width, size.height)) ..fillType = PathFillType.evenOdd; } @override bool shouldReclip(CustomClipper oldClipper) => true; } ================================================ FILE: lib/src/widget/constants.dart ================================================ const dotTotalSize = 32.0; // fixed corner dot size. ================================================ FILE: lib/src/widget/controller.dart ================================================ import 'dart:typed_data'; import 'package:crop_your_image/src/widget/crop.dart'; import 'package:flutter/widgets.dart'; /// Controller to control crop actions. class CropController { late CropControllerDelegate _delegate; /// setter for [CropControllerDelegate] set delegate(CropControllerDelegate value) => _delegate = value; /// crop given image with current configuration void crop() => _delegate.onCrop(false); /// crop given image with current configuration and circle shape. void cropCircle() => _delegate.onCrop(true); /// Change image to be cropped. /// When image is changed, [Rect] of cropping area will be reset. set image(Uint8List value) => _delegate.onImageChanged(value); /// change fixed aspect ratio /// if [value] is null, cropping area can be moved without fixed aspect ratio. set aspectRatio(double? value) => _delegate.onChangeAspectRatio(value); /// change if cropping with circle shaped UI. /// if [value] is true, [aspectRatio] automatically fixed with 1 set withCircleUi(bool value) => _delegate.onChangeWithCircleUi(value); /// change [ViewportBasedRect] of crop rect. /// the value is corrected if it indicates outside of the image. set cropRect(ViewportBasedRect value) => _delegate.onChangeCropRect(value); /// change [ViewportBasedRect] of crop rect /// based on [ImageBasedRect] of original image. set area(ImageBasedRect value) => _delegate.onChangeArea(value); /// request undo void undo() => _delegate.onUndo(); /// request redo void redo() => _delegate.onRedo(); } /// Delegate of actions from [CropController] class CropControllerDelegate { /// callback that [CropController.crop] is called. /// the meaning of the value is if cropping a image with circle shape. late ValueChanged onCrop; /// callback that [CropController.image] is set. late ValueChanged onImageChanged; /// callback that [CropController.aspectRatio] is set. late ValueChanged onChangeAspectRatio; /// callback that [CropController.withCircleUi] is changed. late ValueChanged onChangeWithCircleUi; /// callback that [CropController.cropRect] is changed. late ValueChanged onChangeCropRect; /// callback that [CropController.area] is changed. late ValueChanged onChangeArea; /// callback that [CropController.undo] is called. late VoidCallback onUndo; /// callback that [CropController.redo] is called. late VoidCallback onRedo; } ================================================ FILE: lib/src/widget/crop.dart ================================================ import 'dart:async'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:crop_your_image/src/logic/shape.dart'; import 'package:crop_your_image/src/widget/circle_crop_area_clipper.dart'; import 'package:crop_your_image/src/widget/constants.dart'; import 'package:crop_your_image/src/widget/crop_editor_view_state.dart'; import 'package:crop_your_image/src/widget/history_state.dart'; import 'package:crop_your_image/src/widget/rect_crop_area_clipper.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; typedef ViewportBasedRect = Rect; typedef ImageBasedRect = Rect; typedef History = ({int undoCount, int redoCount}); typedef HistoryChangedCallback = void Function(History history); typedef WillUpdateScale = bool Function(double newScale); typedef CornerDotBuilder = Widget Function( double size, EdgeAlignment edgeAlignment); typedef CroppingRectBuilder = ViewportBasedRect Function( ViewportBasedRect viewportRect, ImageBasedRect imageRect, ); typedef OnMovedCallback = void Function( ViewportBasedRect viewportRect, ImageBasedRect imageRect, ); typedef OverlayBuilder = Widget Function(BuildContext context, Rect rect); enum CropStatus { nothing, loading, ready, cropping } /// Widget for the entry point of crop_your_image. class Crop extends StatelessWidget { /// original image data final Uint8List image; /// callback when cropping completed final ValueChanged onCropped; /// fixed aspect ratio of cropping rect. /// null, by default, means no fixed aspect ratio. final double? aspectRatio; /// builder object for initial cropping rect. /// the legacy arguments of [initialSize], [initialArea], and [initialRectBuilder] are removed. /// you can migrate to those arguments by passing [InitialRectBuilder.withSizeAndRatio], [InitialRectBuilder.withBuilder], /// or [InitialRectBuilder.withArea]. /// /// [InitialRectBuilder.withSizeAndRatio] enables you to set initial size and aspect ratio of cropping rect. /// [size] need to be between 0.0 and 1.0, or null. /// [aspectRatio] is an initial aspect ratio of cropping rect, which means user's interaction /// will change this ratio. /// /// [InitialRectBuilder.withBuilder] enables you to build an initial [ViewportBasedRect] of cropping rect /// with passed [ViewportBasedRect] of [viewportRect] and [imageRect]. /// /// [InitialRectBuilder.withArea] enables you to set an initial [ViewportBasedRect] of cropping rect. /// you can configure the rect based on [ImageBasedRect] and [Crop] will convert it to [ViewportBasedRect]. /// /// Note that [ImageBasedRect] is [Rect] based on original [image] data, not screen. /// /// e.g. If the original image size is 1280x1024, /// giving [Rect.fromLTWH(240, 212, 800, 600)] as [area] would /// result in covering exact center of the image with 800x600 image size /// regardless of the size of viewport. /// /// If [aspectRatio] is given at the same time, [Crop] will NOT cause error. /// In that case, once user moves cropping rect with their hand, /// the shape of cropping area is soon re-calculated depending on [aspectRatio]. final InitialRectBuilder? initialRectBuilder; /// flag if cropping image with circle shape. /// As oval shape is not supported, [aspectRatio] is fixed to 1 if [withCircleUi] is true. final bool withCircleUi; /// controller for control crop actions final CropController? controller; /// Callback called when cropping rect changes for any reasons. final OnMovedCallback? onMoved; final void Function(Rect imageRect)? onImageMoved; /// Callback called when status of Crop widget is changed. /// /// note: Currently, the very first callback is [CropStatus.ready] /// which is called after loading [image] data for the first time. final ValueChanged? onStatusChanged; /// [Color] of the mask widget which is placed over the cropping editor. final Color? maskColor; /// [Color] of the base color of the cropping editor. final Color baseColor; /// Corner radius of cropping rect final double radius; /// Builder function for corner dot widgets. /// [CornerDotBuilder] passes [size] which indicates a desired size of each dots /// and [EdgeAlignment] which indicates the position of each dot. /// If you want default dot widget with different color, [DotControl] is available. final CornerDotBuilder? cornerDotBuilder; /// [Clip] configuration for crop editor, especially corner dots. /// [Clip.hardEdge] by default. final Clip clipBehavior; /// [Widget] for showing preparing for image is in progress. /// [SizedBox.shrink()] is used by default. final Widget progressIndicator; /// If [true], the cropping editor is changed to _interactive_ mode /// and users can zoom and pan the image. /// [false] by default. final bool interactive; /// If [fixCropRect] and [interactive] are both [true], cropping rect is fixed and can't be moved. /// [false] by default. final bool fixCropRect; /// Function called before scaling image. /// Note that this function is called multiple times during user tries to scale image. /// If this function returns [false], scaling is canceled. final WillUpdateScale? willUpdateScale; /// Callback called when history of crop editor operation is changed. final HistoryChangedCallback? onHistoryChanged; /// (for Web) Sets the mouse-wheel zoom sensitivity for web applications. final double scrollZoomSensitivity; /// (Advanced) Injected logic for cropping image. final ImageCropper imageCropper; /// (Advanced) Injected logic for detecting image format. final FormatDetector? formatDetector; /// (Advanced) Injected logic for parsing image detail. final ImageParser imageParser; /// builder to place a widget inside the cropping area final OverlayBuilder? overlayBuilder; /// The rendering quality of the image final FilterQuality filterQuality; Crop({ super.key, required this.image, required this.onCropped, this.aspectRatio, this.initialRectBuilder, this.withCircleUi = false, this.controller, this.onMoved, this.onImageMoved, this.onStatusChanged, this.maskColor, this.baseColor = Colors.white, this.radius = 0, this.cornerDotBuilder, this.clipBehavior = Clip.hardEdge, this.fixCropRect = false, this.progressIndicator = const SizedBox.shrink(), this.interactive = false, this.willUpdateScale, this.onHistoryChanged, FormatDetector? formatDetector, this.imageCropper = defaultImageCropper, ImageParser? imageParser, this.scrollZoomSensitivity = 0.05, this.overlayBuilder, this.filterQuality = FilterQuality.medium, }) : this.imageParser = imageParser ?? defaultImageParser, this.formatDetector = formatDetector ?? defaultFormatDetector; @override Widget build(BuildContext context) { return LayoutBuilder( builder: (c, constraints) { final newData = MediaQuery.of(c).copyWith( size: constraints.biggest, ); return MediaQuery( data: newData, child: _CropEditor( key: key, image: image, onCropped: onCropped, aspectRatio: aspectRatio, initialRectBuilder: initialRectBuilder, withCircleUi: withCircleUi, controller: controller, onMoved: onMoved, onImageMoved: onImageMoved, onStatusChanged: onStatusChanged, maskColor: maskColor, baseColor: baseColor, radius: radius, cornerDotBuilder: cornerDotBuilder, clipBehavior: clipBehavior, fixCropRect: fixCropRect, progressIndicator: progressIndicator, interactive: interactive, willUpdateScale: willUpdateScale, onHistoryChanged: onHistoryChanged, scrollZoomSensitivity: scrollZoomSensitivity, imageCropper: imageCropper, formatDetector: formatDetector, imageParser: imageParser, overlayBuilder: overlayBuilder, filterQuality: filterQuality, ), ); }, ); } } class _CropEditor extends StatefulWidget { final Uint8List image; final ValueChanged onCropped; final double? aspectRatio; final InitialRectBuilder? initialRectBuilder; final bool withCircleUi; final CropController? controller; final OnMovedCallback? onMoved; final void Function(Rect imageRect)? onImageMoved; final ValueChanged? onStatusChanged; final Color? maskColor; final Color baseColor; final double radius; final CornerDotBuilder? cornerDotBuilder; final Clip clipBehavior; final bool fixCropRect; final Widget progressIndicator; final bool interactive; final WillUpdateScale? willUpdateScale; final HistoryChangedCallback? onHistoryChanged; final ImageCropper imageCropper; final FormatDetector? formatDetector; final ImageParser imageParser; final double scrollZoomSensitivity; final OverlayBuilder? overlayBuilder; final FilterQuality filterQuality; const _CropEditor({ super.key, required this.image, required this.onCropped, required this.aspectRatio, required this.initialRectBuilder, this.withCircleUi = false, required this.controller, required this.onMoved, required this.onImageMoved, required this.onStatusChanged, required this.maskColor, required this.baseColor, required this.radius, required this.cornerDotBuilder, required this.clipBehavior, required this.fixCropRect, required this.progressIndicator, required this.interactive, required this.willUpdateScale, required this.onHistoryChanged, required this.imageCropper, required this.formatDetector, required this.imageParser, required this.scrollZoomSensitivity, this.overlayBuilder, required this.filterQuality, }); @override _CropEditorState createState() => _CropEditorState(); } class _CropEditorState extends State<_CropEditor> { /// controller for crop actions late CropController _cropController; /// an object that preserve and expose all the state for _CropEditor late CropEditorViewState _viewState; /// history state of crop editor operation for undo / redo /// history is stored when zoom / pan is changed, as well as crop rect moved. late final HistoryState _historyState; ReadyCropEditorViewState get _readyState => _viewState as ReadyCropEditorViewState; /// image with detail info parsed with [widget.imageParser] ImageDetail? _parsedImageDetail; /// detected image format with [widget.formatDetector] ImageFormat? _detectedFormat; double? _sizeCache; @override void initState() { super.initState(); // prepare for controller _cropController = widget.controller ?? CropController(); _cropController.delegate = CropControllerDelegate() ..onCrop = _crop ..onChangeAspectRatio = (aspectRatio) { _resizeWithSizeAndRatio(_sizeCache, aspectRatio); } ..onChangeWithCircleUi = (withCircleUi) { _viewState = _readyState.copyWith(withCircleUi: withCircleUi); _resizeWithSizeAndRatio(_sizeCache, null); } ..onImageChanged = _resetImage ..onChangeCropRect = (newCropRect) { _updateCropRect(_readyState.correct(newCropRect)); } ..onChangeArea = (newArea) { _resizeWithArea(newArea); } ..onUndo = _undo ..onRedo = _redo; // prepare for history state _historyState = HistoryState(onHistoryChanged: widget.onHistoryChanged); } @override void didChangeDependencies() { /// parse image with given parser and format detector _parseImageWith( parser: widget.imageParser, formatDetector: widget.formatDetector, image: widget.image, ).then((parsed) { if (!mounted) { return; } if (parsed != null) { if (_viewState is PreparingCropEditorViewState) { setState(() { _viewState = (_viewState as PreparingCropEditorViewState).prepared( Size(parsed.width, parsed.height), ); }); } _resetCropRect(); widget.onStatusChanged?.call(CropStatus.ready); } }); super.didChangeDependencies(); } /// apply crop rect changed to view state void _updateCropRect(CropEditorViewState newState) { setState(() => _viewState = newState); widget.onMoved?.call(_readyState.cropRect, _readyState.rectToCrop); } /// reset image to be cropped void _resetImage(Uint8List targetImage) { if (!mounted) { return; } widget.onStatusChanged?.call(CropStatus.loading); _parseImageWith( parser: widget.imageParser, formatDetector: widget.formatDetector, image: targetImage, ).then((parsed) { if (!mounted) { return; } if (parsed != null) { if (_viewState is PreparingCropEditorViewState) { setState(() { _viewState = (_viewState as PreparingCropEditorViewState).prepared( Size(parsed.width, parsed.height), ); }); } _resetCropRect(); widget.onStatusChanged?.call(CropStatus.ready); } }); } /// temporary field to detect last computed. ImageParser? _lastParser; FormatDetector? _lastFormatDetector; Uint8List? _lastImage; Future? _lastComputed; Future _parseImageWith({ required ImageParser parser, required FormatDetector? formatDetector, required Uint8List image, }) async { if (_lastParser == parser && _lastImage == image && _lastFormatDetector == formatDetector) { // no change return _parsedImageDetail; } _lastParser = parser; _lastFormatDetector = formatDetector; _lastImage = image; _viewState = PreparingCropEditorViewState( viewportSize: MediaQuery.of(context).size, withCircleUi: widget.withCircleUi, aspectRatio: widget.aspectRatio, ); final format = formatDetector?.call(image); final future = compute( _parseFunc, [widget.imageParser, format, image], ); _lastComputed = future; final parsed = await future; // check if Crop is still alive if (!mounted) { return null; } // if _parseImageWith() is called again before future completed, // just skip and the last future is used. if (_lastComputed == future) { // cache parsed image for future use of _crop() _parsedImageDetail = parsed; _lastComputed = null; _detectedFormat = format; return parsed; } return null; } /// reset [ViewportBasedRect] of crop rect with current state void _resetCropRect() { setState(() { _viewState = _readyState.resetCropRect(); widget.onImageMoved?.call(_readyState.imageRect); }); final builder = widget.initialRectBuilder; switch (builder) { case (WithBuilderInitialRectBuilder()): _updateCropRect( _readyState.copyWith( cropRect: builder.build( Rect.fromLTWH( 0, 0, _readyState.viewportSize.width, _readyState.viewportSize.height, ), _readyState.imageRect, ), ), ); case (WithAreaInitialRectBuilder()): _resizeWithArea(builder.area); case (WithSizeAndRatioInitialRectBuilder()): _resizeWithSizeAndRatio(builder.size, builder.aspectRatio); _sizeCache = builder.size; default: _resizeWithSizeAndRatio(null, widget.aspectRatio); } if (widget.interactive) { _applyScale(_readyState.scaleToCover); } } void _resizeWithArea(ImageBasedRect area) { // calculate how smaller the viewport is than the image _updateCropRect(_readyState.cropRectWith(area)); } /// resize crop rect with given aspect ratio and area. void _resizeWithSizeAndRatio(double? size, double? aspectRatio) { _updateCropRect( _readyState.cropRectInitialized( initialSize: size, aspectRatio: aspectRatio, ), ); } void _undo() { final last = _historyState.requestUndo(_readyState); if (last != null) { _updateCropRect(last); } } void _redo() { final last = _historyState.requestRedo(_readyState); if (last != null) { _updateCropRect(last); } } /// crop given image with given area. Future _crop(bool withCircleShape) async { assert(_parsedImageDetail != null); widget.onStatusChanged?.call(CropStatus.cropping); // use compute() not to block UI update late CropResult cropResult; try { final image = await compute( _cropFunc, [ widget.imageCropper, _parsedImageDetail!.image, _readyState.rectToCrop, withCircleShape, _detectedFormat, ], ); cropResult = CropSuccess(image); } catch (e, trace) { cropResult = CropFailure(e, trace); } widget.onCropped(cropResult); widget.onStatusChanged?.call(CropStatus.ready); } // for zooming double _baseScale = 1.0; /// handle scale events with pinching void _handleScaleStart(ScaleStartDetails detail) { _historyState.pushHistory(_readyState); _baseScale = _readyState.scale; } void _handleScaleUpdate(ScaleUpdateDetails detail) { setState(() { _viewState = _readyState.offsetUpdated(detail.focalPointDelta); widget.onImageMoved?.call(_readyState.imageRect); }); _applyScale( _baseScale * detail.scale, focalPoint: detail.localFocalPoint, ); } DateTime? _pointerSignalLastUpdated; /// handle mouse pointer signal event void _handlePointerSignal(PointerSignalEvent signal) { if (signal is PointerScrollEvent) { final now = DateTime.now(); if (_pointerSignalLastUpdated == null || now.difference(_pointerSignalLastUpdated!).inMilliseconds > 500) { _pointerSignalLastUpdated = now; _historyState.pushHistory(_readyState); } if (signal.scrollDelta.dy > 0) { _applyScale( _readyState.scale - widget.scrollZoomSensitivity, focalPoint: signal.localPosition, ); } else if (signal.scrollDelta.dy < 0) { _applyScale( _readyState.scale + widget.scrollZoomSensitivity, focalPoint: signal.localPosition, ); } } } /// apply scale updated to view state void _applyScale( double nextScale, { Offset? focalPoint, }) { final allowScale = widget.willUpdateScale?.call(nextScale) ?? true; if (!allowScale) { return; } setState(() { _viewState = _readyState.scaleUpdated( nextScale, focalPoint: focalPoint, ); widget.onImageMoved?.call(_readyState.imageRect); }); } @override Widget build(BuildContext context) { return !_viewState.isReady ? Center(child: widget.progressIndicator) : Stack( clipBehavior: widget.clipBehavior, children: [ Listener( onPointerSignal: _handlePointerSignal, child: GestureDetector( onScaleStart: widget.interactive ? _handleScaleStart : null, onScaleUpdate: widget.interactive ? _handleScaleUpdate : null, child: Container( color: widget.baseColor, width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: Stack( children: [ SizedBox.expand(), Positioned( left: _readyState.imageRect.left, top: _readyState.imageRect.top, child: Image.memory( widget.image, width: _readyState.imageRect.width, height: _readyState.imageRect.height, fit: BoxFit.contain, filterQuality: widget.filterQuality, ), ), ], ), ), ), ), if (widget.overlayBuilder != null) Positioned.fromRect( rect: _readyState.cropRect, child: IgnorePointer( child: widget.overlayBuilder!(context, _readyState.cropRect), ), ), IgnorePointer( child: ClipPath( clipper: _readyState.withCircleUi ? CircleCropAreaClipper(_readyState.cropRect) : CropAreaClipper(_readyState.cropRect, widget.radius), child: Container( width: double.infinity, height: double.infinity, color: widget.maskColor ?? Colors.black.withAlpha(100), ), ), ), if (!widget.interactive && !widget.fixCropRect) Positioned( left: _readyState.cropRect.left, top: _readyState.cropRect.top, child: GestureDetector( onPanStart: (details) => _historyState.pushHistory(_readyState), onPanUpdate: (details) => _updateCropRect( _readyState.moveRect(details.delta), ), child: Container( width: _readyState.cropRect.width, height: _readyState.cropRect.height, color: Colors.transparent, ), ), ), Positioned( left: _readyState.cropRect.left - (dotTotalSize / 2), top: _readyState.cropRect.top - (dotTotalSize / 2), child: GestureDetector( onPanStart: (details) => _historyState.pushHistory(_readyState), onPanUpdate: widget.fixCropRect ? null : (details) => _updateCropRect( _readyState.moveTopLeft(details.delta), ), child: widget.cornerDotBuilder ?.call(dotTotalSize, EdgeAlignment.topLeft) ?? const DotControl(), ), ), Positioned( left: _readyState.cropRect.right - (dotTotalSize / 2), top: _readyState.cropRect.top - (dotTotalSize / 2), child: GestureDetector( onPanStart: (details) => _historyState.pushHistory(_readyState), onPanUpdate: widget.fixCropRect ? null : (details) => _updateCropRect( _readyState.moveTopRight(details.delta), ), child: widget.cornerDotBuilder ?.call(dotTotalSize, EdgeAlignment.topRight) ?? const DotControl(), ), ), Positioned( left: _readyState.cropRect.left - (dotTotalSize / 2), top: _readyState.cropRect.bottom - (dotTotalSize / 2), child: GestureDetector( onPanStart: (details) => _historyState.pushHistory(_readyState), onPanUpdate: widget.fixCropRect ? null : (details) => _updateCropRect( _readyState.moveBottomLeft(details.delta), ), child: widget.cornerDotBuilder ?.call(dotTotalSize, EdgeAlignment.bottomLeft) ?? const DotControl(), ), ), Positioned( left: _readyState.cropRect.right - (dotTotalSize / 2), top: _readyState.cropRect.bottom - (dotTotalSize / 2), child: GestureDetector( onPanStart: (details) => _historyState.pushHistory(_readyState), onPanUpdate: widget.fixCropRect ? null : (details) => _updateCropRect( _readyState.moveBottomRight(details.delta), ), child: widget.cornerDotBuilder ?.call(dotTotalSize, EdgeAlignment.bottomRight) ?? const DotControl(), ), ), ], ); } } /// top-level function for [compute] /// calls [ImageParser.call] with given arguments ImageDetail _parseFunc(List args) { final parser = args[0] as ImageParser; final format = args[1] as ImageFormat?; return parser(args[2] as Uint8List, inputFormat: format); } /// top-level function for [compute] /// calls [ImageCropper.call] with given arguments FutureOr _cropFunc(List args) { final cropper = args[0] as ImageCropper; final originalImage = args[1]; final rect = args[2] as Rect; final withCircleShape = args[3] as bool; final outputFormat = args[4] as ImageFormat; return cropper.call( original: originalImage, topLeft: Offset(rect.left, rect.top), bottomRight: Offset(rect.right, rect.bottom), shape: withCircleShape ? ImageShape.circle : ImageShape.rectangle, outputFormat: outputFormat, ); } ================================================ FILE: lib/src/widget/crop_editor_view_state.dart ================================================ import 'dart:math'; import 'package:crop_your_image/src/widget/calculator.dart'; import 'package:flutter/widgets.dart'; import 'package:crop_your_image/crop_your_image.dart'; /// state management class for _CropEditor /// see the link below for more details /// https://github.com/chooyan-eng/complex_local_state_management/blob/main/docs/local_state.md interface class CropEditorViewState { final Size viewportSize; final bool withCircleUi; final double? aspectRatio; late final bool isReady; CropEditorViewState({ required this.viewportSize, required this.withCircleUi, required this.aspectRatio, }); } /// implementation of [CropEditorViewState] for preparing state class PreparingCropEditorViewState extends CropEditorViewState { PreparingCropEditorViewState({ required super.viewportSize, required super.withCircleUi, required super.aspectRatio, }); @override bool isReady = false; ReadyCropEditorViewState prepared(Size imageSize) { return ReadyCropEditorViewState.prepared( imageSize, viewportSize: viewportSize, withCircleUi: withCircleUi, aspectRatio: aspectRatio, scale: 1.0, ); } } /// implementation of [CropEditorViewState] for ready state class ReadyCropEditorViewState extends CropEditorViewState { final Size imageSize; final ViewportBasedRect cropRect; final ViewportBasedRect imageRect; final double scale; final Offset offset; factory ReadyCropEditorViewState.prepared( Size imageSize, { required Size viewportSize, required double scale, required double? aspectRatio, required bool withCircleUi, }) { final isFitVertically = imageSize.aspectRatio < viewportSize.aspectRatio; final calculator = isFitVertically ? VerticalCalculator() : HorizontalCalculator(); return ReadyCropEditorViewState( viewportSize: viewportSize, imageSize: imageSize, imageRect: calculator.imageRect(viewportSize, imageSize.aspectRatio), cropRect: ViewportBasedRect.zero, scale: scale, aspectRatio: aspectRatio, withCircleUi: withCircleUi, ); } ReadyCropEditorViewState({ required super.viewportSize, required this.imageSize, required this.imageRect, required this.cropRect, required this.scale, this.offset = Offset.zero, required super.aspectRatio, required super.withCircleUi, }); @override bool isReady = true; late final isFitVertically = imageSize.aspectRatio < viewportSize.aspectRatio; late final calculator = isFitVertically ? VerticalCalculator() : HorizontalCalculator(); late final screenSizeRatio = calculator.screenSizeRatio( imageSize, viewportSize, ); late final rectToCrop = ImageBasedRect.fromLTWH( (max(0, cropRect.left - imageRect.left)) * screenSizeRatio / scale, (max(0, cropRect.top - imageRect.top)) * screenSizeRatio / scale, cropRect.width * screenSizeRatio / scale, cropRect.height * screenSizeRatio / scale, ); late final scaleToCover = calculator.scaleToCover(viewportSize, imageRect); ReadyCropEditorViewState imageSizeDetected(Size size) { return copyWith(imageSize: size); } ReadyCropEditorViewState resetCropRect() { return copyWith( imageRect: calculator.imageRect(viewportSize, imageSize.aspectRatio), ); } ReadyCropEditorViewState correct(ViewportBasedRect newCropRect) { return copyWith(cropRect: calculator.correct(newCropRect, imageRect)); } ReadyCropEditorViewState cropRectInitialized({ double? initialSize, double? aspectRatio, }) { final effectiveAspectRatio = withCircleUi ? 1.0 : aspectRatio ?? 1.0; return copyWith( cropRect: calculator.initialCropRect( viewportSize, imageRect, effectiveAspectRatio, initialSize ?? 1, ), ); } ReadyCropEditorViewState cropRectWith(ImageBasedRect area) { return copyWith( cropRect: Rect.fromLTWH( imageRect.left + area.left / screenSizeRatio, imageRect.top + area.top / screenSizeRatio, area.width / screenSizeRatio, area.height / screenSizeRatio, ), ); } // Methods for state updates ReadyCropEditorViewState moveRect(Offset delta) { final newCropRect = calculator.moveRect( cropRect, delta.dx, delta.dy, imageRect, ); return copyWith(cropRect: newCropRect); } ReadyCropEditorViewState moveTopLeft(Offset delta) { final newCropRect = calculator.moveTopLeft( cropRect, delta.dx, delta.dy, imageRect, aspectRatio, ); return copyWith(cropRect: newCropRect); } ReadyCropEditorViewState moveTopRight(Offset delta) { final newCropRect = calculator.moveTopRight( cropRect, delta.dx, delta.dy, imageRect, aspectRatio, ); return copyWith(cropRect: newCropRect); } ReadyCropEditorViewState moveBottomLeft(Offset delta) { final newCropRect = calculator.moveBottomLeft( cropRect, delta.dx, delta.dy, imageRect, aspectRatio, ); return copyWith(cropRect: newCropRect); } ReadyCropEditorViewState moveBottomRight(Offset delta) { final newCropRect = calculator.moveBottomRight( cropRect, delta.dx, delta.dy, imageRect, aspectRatio, ); return copyWith(cropRect: newCropRect); } ReadyCropEditorViewState offsetUpdated(Offset delta) { var movedLeft = imageRect.left + delta.dx; if (movedLeft + imageRect.width < cropRect.right) { movedLeft = cropRect.right - imageRect.width; } var movedTop = imageRect.top + delta.dy; if (movedTop + imageRect.height < cropRect.bottom) { movedTop = cropRect.bottom - imageRect.height; } return copyWith( imageRect: ViewportBasedRect.fromLTWH( min(cropRect.left, movedLeft), min(cropRect.top, movedTop), imageRect.width, imageRect.height, ), ); } ReadyCropEditorViewState scaleUpdated( double nextScale, { Offset? focalPoint, }) { final baseSize = isFitVertically ? Size( viewportSize.height * imageSize.aspectRatio, viewportSize.height, ) : Size( viewportSize.width, viewportSize.width / imageSize.aspectRatio, ); // clamp the scale nextScale = max( nextScale, max(cropRect.width / baseSize.width, cropRect.height / baseSize.height), ); // no change if (scale == nextScale) { return this; } // width final newWidth = baseSize.width * nextScale; final horizontalFocalPointBias = focalPoint == null ? 0.5 : (focalPoint.dx - imageRect.left) / imageRect.width; final leftPositionDelta = (newWidth - imageRect.width) * horizontalFocalPointBias; // height final newHeight = baseSize.height * nextScale; final verticalFocalPointBias = focalPoint == null ? 0.5 : (focalPoint.dy - imageRect.top) / imageRect.height; final topPositionDelta = (newHeight - imageRect.height) * verticalFocalPointBias; // position final newLeft = max(min(cropRect.left, imageRect.left - leftPositionDelta), cropRect.right - newWidth); final newTop = max(min(cropRect.top, imageRect.top - topPositionDelta), cropRect.bottom - newHeight); return copyWith( scale: nextScale, imageRect: ViewportBasedRect.fromLTWH( newLeft, newTop, newWidth, newHeight, ), ); } ReadyCropEditorViewState copyWith({ Size? viewportSize, Size? imageSize, ViewportBasedRect? imageRect, ViewportBasedRect? cropRect, double? scale, Offset? offset, double? aspectRatio, bool? withCircleUi, }) { return ReadyCropEditorViewState( viewportSize: viewportSize ?? this.viewportSize, imageSize: imageSize ?? this.imageSize, imageRect: imageRect ?? this.imageRect, cropRect: cropRect ?? this.cropRect, scale: scale ?? this.scale, offset: offset ?? this.offset, aspectRatio: aspectRatio ?? this.aspectRatio, withCircleUi: withCircleUi ?? this.withCircleUi, ); } } ================================================ FILE: lib/src/widget/crop_result.dart ================================================ // Created by alex@justprodev.com on 04.03.2024. import 'dart:typed_data'; sealed class CropResult { const CropResult(); } class CropSuccess extends CropResult { const CropSuccess(this.croppedImage); final Uint8List croppedImage; } class CropFailure extends CropResult { const CropFailure(this.cause, [this.stackTrace]); final Object cause; final StackTrace? stackTrace; } ================================================ FILE: lib/src/widget/dot_control.dart ================================================ import 'package:crop_your_image/src/widget/constants.dart'; import 'package:flutter/material.dart'; /// Default dot widget placed on corners to control cropping area. /// This Widget automatically fits the appropriate size. class DotControl extends StatelessWidget { const DotControl({ Key? key, this.color = Colors.white, this.padding = 8, }) : super(key: key); /// [Color] of this widget. [Colors.white] by default. final Color color; /// The size of transparent padding which exists to make dot easier to touch. /// Though total size of this widget cannot be changed, /// but visible size can be changed by setting this value. final double padding; @override Widget build(BuildContext context) { return Container( color: Colors.transparent, width: dotTotalSize, height: dotTotalSize, child: Center( child: ClipRRect( borderRadius: BorderRadius.circular(dotTotalSize), child: Container( width: dotTotalSize - (padding * 2), height: dotTotalSize - (padding * 2), color: color, ), ), ), ); } } ================================================ FILE: lib/src/widget/edge_alignment.dart ================================================ /// position of dot control enum EdgeAlignment { topLeft, topRight, bottomLeft, bottomRight, } ================================================ FILE: lib/src/widget/history_state.dart ================================================ import 'package:crop_your_image/crop_your_image.dart'; import 'package:crop_your_image/src/widget/crop_editor_view_state.dart'; import 'package:flutter/foundation.dart'; class HistoryState { HistoryState({required this.onHistoryChanged}); /// history of crop editor operation for undo /// history is stored when zoom / pan is changed, as well as crop rect moved. @visibleForTesting final List history = []; /// history of crop editor operation for redo @visibleForTesting final List redoHistory = []; final HistoryChangedCallback? onHistoryChanged; /// push current view state to history /// this operation will clear redo history void pushHistory(CropEditorViewState viewState) { history.add(viewState); redoHistory.clear(); onHistoryChanged?.call( (undoCount: history.length, redoCount: redoHistory.length), ); } /// request [CropEditorViewState] for undo /// this method will pop last history and push to redo history CropEditorViewState? requestUndo(CropEditorViewState current) { if (history.isEmpty) { return null; } redoHistory.add(current); final last = history.removeLast(); onHistoryChanged?.call( (undoCount: history.length, redoCount: redoHistory.length), ); return last; } /// request [CropEditorViewState] for redo /// this method will pop last redo history CropEditorViewState? requestRedo(CropEditorViewState current) { if (redoHistory.isEmpty) { return null; } history.add(current); final last = redoHistory.removeLast(); onHistoryChanged?.call( (undoCount: history.length, redoCount: redoHistory.length), ); return last; } } ================================================ FILE: lib/src/widget/initial_rect_builder.dart ================================================ import 'package:crop_your_image/src/widget/crop.dart'; /// an interface for initial rect builder. abstract class InitialRectBuilder { /// create [InitialRectBuilder] with builder function, with passed [viewportRect] and [imageRect]. /// see also [Crop.initialRectBuilder]. factory InitialRectBuilder.withBuilder(CroppingRectBuilder builder) => WithBuilderInitialRectBuilder(builder); /// create [InitialRectBuilder] with [ImageBasedRect] named [area]. /// see also [Crop.initialRectBuilder]. factory InitialRectBuilder.withArea(ImageBasedRect area) => WithAreaInitialRectBuilder(area); /// create [InitialRectBuilder] with [size] and [aspectRatio]. /// see also [Crop.initialRectBuilder]. factory InitialRectBuilder.withSizeAndRatio({ double? size, double? aspectRatio, }) => WithSizeAndRatioInitialRectBuilder(size, aspectRatio); } /// [InitialRectBuilder] with builder function. final class WithBuilderInitialRectBuilder implements InitialRectBuilder { WithBuilderInitialRectBuilder(this._builder); final CroppingRectBuilder _builder; ViewportBasedRect build( ViewportBasedRect viewportRect, ImageBasedRect imageRect, ) { return _builder(viewportRect, imageRect); } } /// [InitialRectBuilder] with [ImageBasedRect] named [area]. final class WithAreaInitialRectBuilder implements InitialRectBuilder { WithAreaInitialRectBuilder(this._area); final ImageBasedRect _area; ImageBasedRect get area => _area; } /// [InitialRectBuilder] with [size] and [aspectRatio]. final class WithSizeAndRatioInitialRectBuilder implements InitialRectBuilder { WithSizeAndRatioInitialRectBuilder( this._size, this._aspectRatio, ); final double? _size; final double? _aspectRatio; double? get size => _size; double? get aspectRatio => _aspectRatio; } ================================================ FILE: lib/src/widget/rect_crop_area_clipper.dart ================================================ import 'package:flutter/material.dart'; class CropAreaClipper extends CustomClipper { CropAreaClipper(this.rect, this.radius); final Rect rect; final double radius; @override Path getClip(Size size) { return Path() ..addPath( Path() ..moveTo(rect.left, rect.top + radius) ..arcToPoint(Offset(rect.left + radius, rect.top), radius: Radius.circular(radius)) ..lineTo(rect.right - radius, rect.top) ..arcToPoint(Offset(rect.right, rect.top + radius), radius: Radius.circular(radius)) ..lineTo(rect.right, rect.bottom - radius) ..arcToPoint(Offset(rect.right - radius, rect.bottom), radius: Radius.circular(radius)) ..lineTo(rect.left + radius, rect.bottom) ..arcToPoint(Offset(rect.left, rect.bottom - radius), radius: Radius.circular(radius)) ..close(), Offset.zero, ) ..addRect(Rect.fromLTWH(0.0, 0.0, size.width, size.height)) ..fillType = PathFillType.evenOdd; } @override bool shouldReclip(CustomClipper oldClipper) => true; } ================================================ FILE: lib/src/widget/widget.dart ================================================ export 'crop.dart'; export 'controller.dart'; export 'dot_control.dart'; export 'edge_alignment.dart'; export 'crop_result.dart'; export 'initial_rect_builder.dart'; ================================================ FILE: pubspec.yaml ================================================ name: crop_your_image description: crop_your_image helps your app to embed Widgets for cropping images. version: 2.0.0 homepage: https://github.com/chooyan-eng/crop_your_image topics: - crop - image-cropper - image environment: sdk: '>=3.0.0 <4.0.0' dependencies: flutter: sdk: flutter image: ^4.3.0 dev_dependencies: flutter_test: sdk: flutter # 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. flutter: # To add assets to your package, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # # For details regarding assets in packages, see # https://flutter.dev/assets-and-images/#from-packages # # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. # To add custom fonts to your package, 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 in packages, see # https://flutter.dev/custom-fonts/#from-packages ================================================ FILE: test/logic/cropper/image_image_cropper_test.dart ================================================ import 'dart:io'; import 'package:crop_your_image/src/logic/cropper/errors.dart'; import 'package:crop_your_image/src/logic/cropper/image_image_cropper.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:image/image.dart'; void main() { late ImageImageCropper cropper; setUp(() { cropper = ImageImageCropper(); }); group('when png image with the size of 656 x 453 is given', () { late Image testImage; setUpAll(() { // read a test image file with the size of 656 x 453 final data = File('test_resources/snow_landscape.png').readAsBytesSync(); testImage = decodeImage(data)!; }); test( 'crop from Offset(100, 50) to Offset(200, 150)' 'generates the image sized 100 x 100', () async { final croppedImage = await cropper.call( original: testImage, topLeft: Offset(100, 50), bottomRight: Offset(200, 150), ); final imageDetail = decodeImage(croppedImage); expect(imageDetail, isNotNull); expect(imageDetail!.width, 100); expect(imageDetail.height, 100); }, ); test('the format of the cropped image is always png, not jpeg', () async { final croppedImage = await cropper.call( original: testImage, topLeft: Offset(100, 50), bottomRight: Offset(200, 150), ); expect(PngDecoder().isValidFile(croppedImage), isTrue); expect(JpegDecoder().isValidFile(croppedImage), isFalse); }); test( 'InvalidRangeError is thrown if given Offset has negative value', () async { expect( () async => await cropper.call( original: testImage, topLeft: Offset(-100, -50), bottomRight: Offset(200, 150), ), throwsA(const TypeMatcher()), ); expect( () async => await cropper.call( original: testImage, topLeft: Offset(0, 0), bottomRight: Offset(-200, -150), ), throwsA(const TypeMatcher()), ); }, ); test( 'NegativeSizeError is thrown if the value of bottomRight is smaller than topLeft', () async { expect( () async => await cropper.call( original: testImage, topLeft: Offset(200, 50), bottomRight: Offset(100, 100), ), throwsA(const TypeMatcher()), ); }, ); test( 'NegativeSizeError is NOT thrown' 'if the value of bottomRight is slightly greater than image size', () async { final croppedImage = await cropper.call( original: testImage, topLeft: Offset(100, 50), bottomRight: Offset(656.0004, 453.00005), ); final imageDetail = decodeImage(croppedImage); expect(imageDetail, isNotNull); expect(imageDetail!.width, 556); expect(imageDetail.height, 403); }, ); }); } ================================================ FILE: test/logic/parser/image_image_parser_test.dart ================================================ import 'dart:io'; import 'dart:typed_data'; import 'package:crop_your_image/src/logic/format_detector/format.dart'; import 'package:crop_your_image/src/logic/parser/errors.dart'; import 'package:crop_your_image/src/logic/parser/image_image_parser.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final imageParser = imageImageParser; group('when png image with the size of 656 x 453 is given', () { late Uint8List testImage; setUpAll(() { // read a test image file with the size of 656 x 453 testImage = File('test_resources/snow_landscape.png').readAsBytesSync(); }); test( 'imageParser generates ImageDetail with width: 656, height: 453', () { final actual = imageParser(testImage); expect(actual.width, 656); expect(actual.height, 453); expect(actual.image, isNotNull); }, ); test( 'imageParser generates ImageDetail with width: 656, height: 453' 'when passing inputFormat: ImageFormat.png', () { final actual = imageParser( testImage, inputFormat: ImageFormat.png, ); expect(actual.width, 656); expect(actual.height, 453); expect(actual.image, isNotNull); }, ); test( 'imageParser throws InvalidInputFormatError' 'when passing wrong inputFormat, ImageFormat.jpeg', () { expect( () => imageParser( testImage, inputFormat: ImageFormat.jpeg, ), throwsA(const TypeMatcher()), ); }, ); }); } ================================================ FILE: test/widget/calculator_test.dart ================================================ import 'dart:ui'; import 'package:crop_your_image/src/widget/calculator.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { late Calculator calculator; group( 'when image of original size (600, 400) fits horizontally' 'at screen size (300, 600)', () { late Size originalImageSize; late Size viewportSize; setUpAll(() { calculator = HorizontalCalculator(); originalImageSize = Size(600, 400); viewportSize = Size(300, 600); }); test('Rect of image is Rect.fromLTRB(0, 200, 300, 400)', () { final actual = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); expect(actual, Rect.fromLTRB(0, 200, 300, 400)); }); test( 'Rect of crop area is Rect.fromLTRB(50, 200, 250, 400)' 'when aspectRatio: 1, sizeRatio: 1', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.initialCropRect(viewportSize, imageRect, 1, 1); expect(actual, Rect.fromLTRB(50, 200, 250, 400)); }); test( 'Rect of crop area is Rect.fromLTRB(100, 250, 200, 350)' 'when aspectRatio: 1, sizeRatio: 0.5', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.initialCropRect(viewportSize, imageRect, 1, 0.5); expect(actual, Rect.fromLTRB(100, 250, 200, 350)); }); test( 'Rect of crop area is Rect.fromLTRB(100, 250, 200, 350)' 'when aspectRatio: 3 / 4, sizeRatio: 1', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.initialCropRect(viewportSize, imageRect, 3 / 4, 1); expect(actual, Rect.fromLTRB(75, 200, 225, 400)); }); test( 'Rect of crop area is Rect.fromLTRB(100, 250, 200, 350)' 'when aspectRatio: 3 / 4, sizeRatio: 0.5', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.initialCropRect(viewportSize, imageRect, 3 / 4, 0.5); expect(actual, Rect.fromLTRB(112.5, 250, 187.5, 350)); }); test('Scale is 3.0 to cover viewport', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.scaleToCover(viewportSize, imageRect); // scale Size(300, 200) to Size(900, 600) fits in Size(300, 600) of viewport expect(actual, 3.0); }); test('screenSizeRatio is 2.0', () { final actual = calculator.screenSizeRatio( Size(originalImageSize.width, originalImageSize.height), viewportSize, ); // viewport Size(300, 600) to original image Size(600, 400) // comparing width, 600 / 300 = 2.0 expect(actual, 2.0); }); }, ); group( 'when image of original size (400, 600) fits vertically' 'at screen size (400, 300)', () { late Size originalImageSize; late Size viewportSize; setUpAll(() { calculator = VerticalCalculator(); originalImageSize = Size(400, 600); viewportSize = Size(400, 300); }); test('Rect of image is Rect.fromLTRB(100, 0, 300, 300)', () { final actual = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); expect(actual, Rect.fromLTRB(100, 0, 300, 300)); }); test( 'Rect of crop area is Rect.fromLTRB(100, 50, 300, 250)' 'when aspectRatio: 1, sizeRatio: 1', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.initialCropRect(viewportSize, imageRect, 1, 1); expect(actual, Rect.fromLTRB(100, 50, 300, 250)); }); test( 'Rect of crop area is Rect.fromLTRB(150, 100, 250, 200)' 'when aspectRatio: 1, sizeRatio: 0.5', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.initialCropRect(viewportSize, imageRect, 1, 0.5); expect(actual, Rect.fromLTRB(150, 100, 250, 200)); }); test( 'Rect of crop area is about Rect.fromLTRB(100.0, 16, 300.0, 283)' 'when aspectRatio: 3 / 4, sizeRatio: 1', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.initialCropRect(viewportSize, imageRect, 3 / 4, 1); expect(actual.left, 100.0); expect(actual.top.floor(), 16); expect(actual.right, 300.0); expect(actual.bottom.floor(), 283); }); test( 'Rect of crop area is Rect.fromLTRB(150, 83, 250, 216)' 'when aspectRatio: 3 / 4, sizeRatio: 0.5', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.initialCropRect(viewportSize, imageRect, 3 / 4, 0.5); expect(actual.left, 150.0); expect(actual.top.floor(), 83); expect(actual.right, 250.0); expect(actual.bottom.floor(), 216); }); test('Scale is 2.0 to cover viewport', () { final imageRect = calculator.imageRect( viewportSize, originalImageSize.width / originalImageSize.height); final actual = calculator.scaleToCover(viewportSize, imageRect); // scale Size(300, 200) to Size(600, 400) fits in Size(300, 400) of viewport expect(actual, 2.0); }); test('screenSizeRatio is 2.0', () { final actual = calculator.screenSizeRatio( Size(originalImageSize.width, originalImageSize.height), viewportSize, ); // viewport Size(400, 300) to original image Size(400, 600) // comparing width, 600 / 300 = 2.0 expect(actual, 2.0); }); }, ); group( 'when image fits crop editor horizontally' 'with Rect.fromLTWH(0, 50, 300, 250)', () { late Rect imageRect; setUpAll(() { calculator = HorizontalCalculator(); imageRect = Rect.fromLTRB(0, 50, 300, 300); }); group('starts with crop rect of ViewportBasedRect(50, 80, 150, 200)', () { late Rect original; setUpAll(() { original = Rect.fromLTRB(50, 80, 150, 200); }); test( 'moving crop rect by dx:10, dy:10' 'result in Rect(60, 90, 160, 210)', () { final actual = calculator.moveRect(original, 10, 10, imageRect); expect(actual, Rect.fromLTRB(60, 90, 160, 210)); }); test( 'moving crop rect by dx:150, dy:150' 'result in Rect(200, 180, 300, 300)', () { final actual = calculator.moveRect(original, 150, 150, imageRect); // considering image size, dy of crop rect // can't be greater than imageRect.bottom expect(actual, Rect.fromLTRB(200, 180, 300, 300)); }); test( 'moving crop rect by dx:-50, dy:-50' 'result in Rect(0, 50, 100, 170)', () { final actual = calculator.moveRect(original, -50, -50, imageRect); // considering image size, dx, dy of crop rect // can't be smaller than imageRect.left, imageRect.top expect(actual, Rect.fromLTRB(0, 50, 100, 170)); }); test( 'moving crop rect by dx:200, dy:50' 'result in Rect(200, 130, 300, 250)', () { final actual = calculator.moveRect(original, 200, 50, imageRect); // considering image size, dy of crop rect // can't be greater than imageRect.bottom expect(actual, Rect.fromLTRB(200, 130, 300, 250)); }); test( 'moving topLeft dot by dx:10, dy:10' 'result in Rect(60, 90, 150, 200)', () { final actual = calculator.moveTopLeft(original, 10, 10, imageRect, null); expect(actual, Rect.fromLTRB(60, 90, 150, 200)); }); test( 'moving topLeft dot by dx:150, dy:150' 'result in Rect(110, 160, 150, 200)', () { final actual = calculator.moveTopLeft(original, 150, 150, imageRect, null); // considering DotControl's size, topLeft can't be greater than // Offset(dx: bottomRight.left - 40, dy: bottomRight.top - 40) expect(actual, Rect.fromLTRB(110, 160, 150, 200)); }); test( 'moving topRight dot by dx:10, dy:10' 'result in Rect(50, 90, 160, 200)', () { final actual = calculator.moveTopRight(original, 10, 10, imageRect, null); expect(actual, Rect.fromLTRB(50, 90, 160, 200)); }); test( 'moving topRight dot by dx:150, dy:150' 'result in Rect(50, 160, 300, 200)', () { final actual = calculator.moveTopRight(original, 150, 150, imageRect, null); // considering DotControl's size, // dy of topRight can't be greater than bottomRight.top - 40 expect(actual, Rect.fromLTRB(50, 160, 300, 200)); }); test( 'moving bottomLeft dot by dx:10, dy:10' 'result in Rect(60, 80, 150, 210)', () { final actual = calculator.moveBottomLeft(original, 10, 10, imageRect, null); expect(actual, Rect.fromLTRB(60, 80, 150, 210)); }); test( 'moving bottomLeft dot by dx:150, dy:150' 'result in Rect(50, 160, 300, 200)', () { final actual = calculator.moveBottomLeft(original, 150, 150, imageRect, null); // considering Image size, // bottom of bottomLeft can't be greater than imageRect.bottom expect(actual, Rect.fromLTRB(110, 80, 150, 300)); }); test( 'moving bottomRight dot by dx:10, dy:10' 'result in Rect(50, 80, 160, 210)', () { final actual = calculator.moveBottomRight(original, 10, 10, imageRect, null); expect(actual, Rect.fromLTRB(50, 80, 160, 210)); }); test( 'moving bottomRight dot by dx:150, dy:150' 'result in Rect(50, 80, 300, 300)', () { final actual = calculator.moveBottomRight(original, 150, 150, imageRect, null); // considering Image size, // bottom of bottomRight can't be greater than imageRect.bottom expect(actual, Rect.fromLTRB(50, 80, 300, 300)); }); }); group( 'when image rect is Rect.fromLTWH(0, 50, 300, 250)' 'regardless of fits horizontal or vertical', () { late Rect imageRect; setUpAll(() { calculator = HorizontalCalculator(); imageRect = Rect.fromLTRB(0, 50, 300, 300); }); group('starts with crop rect of ViewportBasedRect(50, 80, 150, 200)', () { late Rect original; setUpAll(() { original = Rect.fromLTRB(50, 80, 150, 200); }); test( 'moving crop rect by dx:10, dy:10' 'result in Rect(60, 90, 160, 210)', () { final actual = calculator.moveRect(original, 10, 10, imageRect); expect(actual, Rect.fromLTRB(60, 90, 160, 210)); }); test( 'moving crop rect by dx:150, dy:150' 'result in Rect(200, 180, 300, 300)', () { final actual = calculator.moveRect(original, 150, 150, imageRect); // considering image size, dy of crop rect // can't be greater than imageRect.bottom expect(actual, Rect.fromLTRB(200, 180, 300, 300)); }); test( 'moving topLeft dot by dx:10, dy:10' 'result in Rect(60, 90, 150, 200)', () { final actual = calculator.moveTopLeft(original, 10, 10, imageRect, null); expect(actual, Rect.fromLTRB(60, 90, 150, 200)); }); test( 'moving topLeft dot by dx:150, dy:150' 'result in Rect(110, 160, 150, 200)', () { final actual = calculator.moveTopLeft(original, 150, 150, imageRect, null); // considering DotControl's size, topLeft can't be greater than // Offset(dx: bottomRight.left - 40, dy: bottomRight.top - 40) expect(actual, Rect.fromLTRB(110, 160, 150, 200)); }); test( 'moving topRight dot by dx:10, dy:10' 'result in Rect(50, 90, 160, 200)', () { final actual = calculator.moveTopRight(original, 10, 10, imageRect, null); expect(actual, Rect.fromLTRB(50, 90, 160, 200)); }); test( 'moving topRight dot by dx:150, dy:150' 'result in Rect(50, 160, 300, 200)', () { final actual = calculator.moveTopRight(original, 150, 150, imageRect, null); // considering DotControl's size, // dy of topRight can't be greater than bottomRight.top - 40 expect(actual, Rect.fromLTRB(50, 160, 300, 200)); }); test( 'moving bottomLeft dot by dx:10, dy:10' 'result in Rect(60, 80, 150, 210)', () { final actual = calculator.moveBottomLeft(original, 10, 10, imageRect, null); expect(actual, Rect.fromLTRB(60, 80, 150, 210)); }); test( 'moving bottomLeft dot by dx:150, dy:150' 'result in Rect(50, 160, 300, 200)', () { final actual = calculator.moveBottomLeft(original, 150, 150, imageRect, null); // considering Image size, // bottom of bottomLeft can't be greater than imageRect.bottom expect(actual, Rect.fromLTRB(110, 80, 150, 300)); }); test( 'moving bottomRight dot by dx:10, dy:10' 'result in Rect(50, 80, 160, 210)', () { final actual = calculator.moveBottomRight(original, 10, 10, imageRect, null); expect(actual, Rect.fromLTRB(50, 80, 160, 210)); }); test( 'moving bottomRight dot by dx:150, dy:150' 'result in Rect(50, 80, 300, 300)', () { final actual = calculator.moveBottomRight(original, 150, 150, imageRect, null); // considering Image size, // bottom of bottomRight can't be greater than imageRect.bottom expect(actual, Rect.fromLTRB(50, 80, 300, 300)); }); }); }); }); } ================================================ FILE: test/widget/circle_crop_area_clipper_test.dart ================================================ import 'package:crop_your_image/src/widget/circle_crop_area_clipper.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('shouldReclip is always true', () { final oldClipper = CircleCropAreaClipper(Rect.fromLTWH(50, 50, 100, 100)); final clipper = CircleCropAreaClipper(Rect.fromLTWH(50, 50, 100, 100)); expect(clipper.shouldReclip(oldClipper), true); }); group('when viewport is 200 x 200', () { final viewportSize = 200.0; testWidgets( 'CircleCropAreaClipper clips center with 100x100 size of circle shape' 'if passing Rect.fromLTWH(50, 50, 100, 100)', (WidgetTester tester) async { Widget actual = Center( child: SizedBox( width: viewportSize, height: viewportSize, child: RepaintBoundary( child: ClipPath( clipper: CircleCropAreaClipper(Rect.fromLTWH(50, 50, 100, 100)), child: ColoredBox( color: Colors.grey, ), ), ), ), ); await tester.pumpWidget(actual); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile( 'circle_crop_area_clipper.viewportSize200x200.crop_center.png'), ); }, ); }); } ================================================ FILE: test/widget/controller_test.dart ================================================ import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'dart:ui'; import 'package:crop_your_image/src/widget/controller.dart'; import 'package:crop_your_image/src/widget/crop.dart'; import 'package:flutter_test/flutter_test.dart'; import 'helper.dart'; void main() { late Uint8List testLandscapeImage; late Uint8List testPortraitImage; group('when png image with the size of 656 x 453 is given', () { setUpAll(() { // read a test image file with the size of 656 x 453 testLandscapeImage = File('test_resources/snow_landscape.png').readAsBytesSync(); testPortraitImage = File('test_resources/snow_portrait.png').readAsBytesSync(); }); testWidgets( 'onCropped is called after calling CropController.crop()', (tester) async { // to ensure callback is called final completer = Completer(); final controller = CropController(); final widget = withMaterial( Crop( image: testLandscapeImage, controller: controller, onCropped: (value) => completer.complete(), ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); controller.crop(); // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(completer.isCompleted, isTrue); }, ); testWidgets( 'onCropped is called after calling CropController.cropCircle()', (tester) async { // to ensure callback is called final completer = Completer(); final controller = CropController(); final widget = withMaterial( Crop( image: testLandscapeImage, controller: controller, onCropped: (value) => completer.complete(), ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); controller.cropCircle(); // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(completer.isCompleted, isTrue); }, ); testWidgets( 'Rect of cropping area changes after setting another image', (tester) async { Rect? initialRect; Rect? lastRect; final controller = CropController(); final widget = withMaterial( Crop( image: testLandscapeImage, controller: controller, onCropped: (value) {}, onMoved: (rect, _) { initialRect ??= rect; lastRect = rect; }, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); controller.image = testPortraitImage; // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(initialRect != lastRect, isTrue); }, ); testWidgets( 'aspect ratio of Rect of cropping area is 4:6 if aspectRatio is set to 4/6', (tester) async { Rect? initialRect; Rect? lastRect; final controller = CropController(); final widget = withMaterial( Crop( image: testLandscapeImage, controller: controller, aspectRatio: 1, onCropped: (value) {}, onMoved: (rect, _) { initialRect ??= rect; lastRect = rect; }, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); controller.aspectRatio = 4 / 6; // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(initialRect != lastRect, isTrue); expect(initialRect!.width / initialRect!.height, 1); expect(lastRect!.width / lastRect!.height, 4 / 6); }, ); testWidgets( 'Rect of cropping area is Rect(10, 50, 50, 100) after setting via controller.rect', (tester) async { Rect? lastRect; final controller = CropController(); final widget = withMaterial( Crop( image: testLandscapeImage, controller: controller, aspectRatio: 1, onCropped: (value) {}, onMoved: (rect, _) => lastRect = rect, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); controller.cropRect = Rect.fromLTRB(10, 50, 50, 100); // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(lastRect!.left, 10); expect(lastRect!.top, 50); expect(lastRect!.right, 50); expect(lastRect!.bottom, 100); }, ); testWidgets( 'Rect of cropping area is Rect(10, 46.4, 50, 100)' 'after setting Rect(10, 10, 50, 100) via controller.rect', (tester) async { Rect? lastRect; final controller = CropController(); final widget = withMaterial( Crop( image: testLandscapeImage, controller: controller, aspectRatio: 1, onCropped: (value) {}, onMoved: (rect, _) => lastRect = rect, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); controller.cropRect = Rect.fromLTRB(10, 10, 50, 100); // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(lastRect!.left, 10); // Because top: 10 is out of the image, // it is corrected to 46.4, which is top bound of the image. expect(lastRect!.top.floor(), 46); expect(lastRect!.right, 50); expect(lastRect!.bottom, 100); }, ); testWidgets( 'Rect of cropping area is Rect(4, 50, 22, 92)' 'after setting Rect(10, 10, 50, 100) via controller.area', (tester) async { Rect? lastRect; final controller = CropController(); final widget = withMaterial( Crop( image: testLandscapeImage, controller: controller, aspectRatio: 1, onCropped: (value) {}, onMoved: (rect, _) => lastRect = rect, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); // set Rect based on original image size controller.area = Rect.fromLTRB(10, 10, 50, 100); // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); // expected Rect is based on viewport expect(lastRect!.left.floor(), 4); expect(lastRect!.top.floor(), 50); expect(lastRect!.right.floor(), 22); expect(lastRect!.bottom.floor(), 92); }, ); }); } ================================================ FILE: test/widget/crop_editor_view_state_test.dart ================================================ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:crop_your_image/src/widget/crop_editor_view_state.dart'; void main() { group('PreparingCropEditorViewState', () { final defaultViewportSize = Size(360, 200); late PreparingCropEditorViewState state; setUp(() { state = PreparingCropEditorViewState( viewportSize: defaultViewportSize, withCircleUi: false, aspectRatio: 1.5, ); }); test('preserves all the given values', () { expect(state.viewportSize, defaultViewportSize); expect(state.withCircleUi, false); expect(state.aspectRatio, 1.5); }); test('state is not ready', () { expect(state.isReady, false); }); test('prepared method creates ReadyCropEditorViewState', () { final imageSize = Size(800, 600); final readyState = state.prepared(imageSize); expect(readyState, isA()); expect(readyState.isReady, true); expect(readyState.viewportSize, defaultViewportSize); expect(readyState.imageSize, imageSize); expect(readyState.scale, 1.0); expect(readyState.withCircleUi, false); expect(readyState.aspectRatio, 1.5); }); }); group('ReadyCropEditorViewState', () { final defaultViewportSize = Size(360, 200); final defaultImageSize = Size(800, 600); late ReadyCropEditorViewState state; setUp(() { state = ReadyCropEditorViewState.prepared( defaultImageSize, viewportSize: defaultViewportSize, scale: 1.0, aspectRatio: null, withCircleUi: false, ); }); test('prepared factory creates correct initial state', () { expect(state.isReady, true); expect(state.viewportSize, defaultViewportSize); expect(state.imageSize, defaultImageSize); expect(state.scale, 1.0); expect(state.withCircleUi, false); expect(state.aspectRatio, null); }); test('isFitVertically calculates correctly', () { final verticalState = ReadyCropEditorViewState.prepared( Size(300, 800), // vertical image viewportSize: defaultViewportSize, scale: 1.0, aspectRatio: null, withCircleUi: false, ); final horizontalState = ReadyCropEditorViewState.prepared( Size(800, 300), // horizontal image viewportSize: defaultViewportSize, scale: 1.0, aspectRatio: null, withCircleUi: false, ); expect(verticalState.isFitVertically, true); expect(horizontalState.isFitVertically, false); }); group('moveRect', () { test('moves rect within bounds', () { final initialRect = Rect.fromLTWH(30, 30, 50, 50); final stateWithRect = state.copyWith(cropRect: initialRect); final movedState = stateWithRect.moveRect(const Offset(50, 30)); expect(movedState.cropRect.left, 80); expect(movedState.cropRect.top, 60); expect(movedState.cropRect.width, 50); expect(movedState.cropRect.height, 50); }); test('constrains movement within image bounds', () { final initialRect = Rect.fromLTWH(50, 50, 100, 100); final stateWithRect = state.copyWith(cropRect: initialRect); final movedState = stateWithRect.moveRect(const Offset(-100, -100)); // Check that the rect stays within bounds expect(movedState.cropRect.left, closeTo(46, 1)); expect(movedState.cropRect.top, 0); expect(movedState.cropRect.width, 100); expect(movedState.cropRect.height, 100); }); }); group('scaleUpdated', () { test('updates scale with constraints', () { final initialRect = Rect.fromLTWH(100, 100, 200, 200); final stateWithRect = state.copyWith(cropRect: initialRect); final scaledState = stateWithRect.scaleUpdated(2.0); expect(scaledState.scale, 2.0); expect(scaledState.imageRect.width, greaterThan(stateWithRect.imageRect.width)); expect(scaledState.imageRect.height, greaterThan(stateWithRect.imageRect.height)); }); test('maintains minimum scale to cover crop rect', () { final initialRect = Rect.fromLTWH(100, 100, 200, 200); final stateWithRect = state.copyWith(cropRect: initialRect); // Try to scale smaller than minimum allowed final scaledState = stateWithRect.scaleUpdated(0.1); // Scale should be constrained to minimum required to cover crop rect expect(scaledState.imageRect.width, greaterThanOrEqualTo(initialRect.width)); expect(scaledState.imageRect.height, greaterThanOrEqualTo(initialRect.height)); }); }); test('cropRectInitialized respects aspect ratio', () { final initializedState = state.cropRectInitialized( aspectRatio: 1.5, initialSize: 0.8, ); final ratio = initializedState.cropRect.width / initializedState.cropRect.height; expect(ratio, closeTo(1.5, 0.01)); }); test('withCircleUi forces aspect ratio to 1.0', () { final state = ReadyCropEditorViewState.prepared( defaultImageSize, viewportSize: defaultViewportSize, scale: 1.0, aspectRatio: 1.5, // This should be ignored when withCircleUi is true withCircleUi: true, ); final initializedState = state.cropRectInitialized(); final ratio = initializedState.cropRect.width / initializedState.cropRect.height; expect(ratio, closeTo(1.0, 0.01)); }); }); } ================================================ FILE: test/widget/crop_test.dart ================================================ import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:crop_your_image/crop_your_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'helper.dart'; void main() { late Uint8List testImage; group('when png image with the size of 656 x 453 is given', () { setUpAll(() { // read a test image file with the size of 656 x 453 testImage = File('test_resources/snow_landscape.png').readAsBytesSync(); }); testWidgets( 'pump Crop with minimum arguments works without errors', (tester) async { final widget = withMaterial( Crop( image: testImage, onCropped: (value) {}, ), ); await tester.pumpWidget(widget); }, ); group('onCropped', () { testWidgets( 'onCropped is called after calling CropController.crop()', (tester) async { // to ensure callback is called final completer = Completer(); final controller = CropController(); final widget = withMaterial( Crop( image: testImage, onCropped: (value) => completer.complete(), controller: controller, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); controller.crop(); // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(completer.isCompleted, isTrue); }, ); testWidgets( 'onCropped returns an error if cropping fails', (tester) async { // to ensure callback is called bool hasError = false; final controller = CropController(); final widget = withMaterial( Crop( image: testImage, onCropped: (value) { hasError = value is CropFailure; }, controller: controller, imageCropper: FailureCropper(), ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); controller.crop(); // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(hasError, isTrue); }, ); }); testWidgets( 'status is changing with null -> .ready -> .cropping -> .ready', (tester) async { // to ensure status is changing CropStatus? lastStatus; final controller = CropController(); final widget = withMaterial( Crop( image: testImage, onCropped: (value) {}, controller: controller, onStatusChanged: (status) => lastStatus = status, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); expect(lastStatus, isNull); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); expect(lastStatus, CropStatus.ready); controller.crop(); expect(lastStatus, CropStatus.cropping); // wait for cropping image await Future.delayed(const Duration(seconds: 2)); }); expect(lastStatus, CropStatus.ready); }, ); testWidgets( 'initialRectBuilder is called right after pumpWidget', (tester) async { // to ensure callback is called final completer = Completer(); final widget = withMaterial( Crop( image: testImage, onCropped: (value) {}, initialRectBuilder: InitialRectBuilder.withBuilder( (viewportRect, imageRect) { completer.complete(); return imageRect; }, ), ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 2)); }); expect(completer.isCompleted, isTrue); }, ); testWidgets( 'onMoved is called when dragging DotControl', (tester) async { // to ensure callback is called final completer = Completer(); final widget = withMaterial( Crop( image: testImage, onCropped: (value) {}, onMoved: (_, __) { if (!completer.isCompleted) { completer.complete(); } }, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 4)); await tester.pumpAndSettle(); final dotControl = find.byType(DotControl); expect(dotControl, findsNWidgets(4)); await tester.drag(dotControl.first, Offset(10, 10)); }); expect(completer.isCompleted, isTrue); }, ); testWidgets( 'customized dot controls from cornerDotBuilder is visible and available', (tester) async { // to ensure callback is called final completer = Completer(); final widget = withMaterial( Crop( image: testImage, onCropped: (value) {}, onMoved: (_, __) { if (!completer.isCompleted) { completer.complete(); } }, cornerDotBuilder: (size, edgeAlignment) { return const Icon(Icons.circle); }, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 4)); await tester.pumpAndSettle(); final customDotControl = find.byType(Icon); expect(customDotControl, findsNWidgets(4)); await tester.drag(customDotControl.first, Offset(10, 10)); }); expect(completer.isCompleted, isTrue); }, ); testWidgets( 'dot control is still visible and available when only fixArea is set true', (tester) async { // to ensure callback is called final completer = Completer(); final widget = withMaterial( Crop( image: testImage, onCropped: (value) {}, onMoved: (_, __) { if (!completer.isCompleted) { completer.complete(); } }, fixCropRect: true, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 4)); await tester.pumpAndSettle(); final dotControl = find.byType(DotControl); expect(dotControl, findsNWidgets(4)); await tester.drag(dotControl.first, Offset(10, 10)); }); expect(completer.isCompleted, isTrue); }, ); testWidgets( 'dot control is not movable if fixArea and interactive are both set true', (tester) async { // to ensure callback is only called when initialized var calledCount = 0; final widget = withMaterial( Crop( image: testImage, onCropped: (value) {}, onMoved: (_, __) { calledCount++; }, fixCropRect: true, interactive: true, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 4)); await tester.pumpAndSettle(); // dot control is still visible final dotControl = find.byType(DotControl); expect(dotControl, findsNWidgets(4)); await tester.drag(dotControl.first, Offset(10, 10)); }); expect(calledCount, 1); }, ); testWidgets( 'custom FormatDetector is called if given to Crop constructor', (tester) async { // to ensure callback is called final completer = Completer(); final widget = withMaterial( Crop( image: testImage, onCropped: (value) {}, formatDetector: (data) { completer.complete(); return ImageFormat.png; }, ), ); await tester.runAsync(() async { await tester.pumpWidget(widget); // wait for parsing image await Future.delayed(const Duration(seconds: 4)); }); expect(completer.isCompleted, isTrue); }, ); }); } ================================================ FILE: test/widget/helper.dart ================================================ import 'package:crop_your_image/src/logic/cropper/image_cropper.dart'; import 'package:flutter/material.dart'; Widget withMaterial(Widget widget) { return MaterialApp( home: Scaffold( // TODO(chooyan-eng): fix error on cropping if image is not large enough comparing to viewport // body: SizedBox.expand(child: widget), body: SizedBox(width: 300, height: 300, child: widget), ), ); } /// [ImageCropper] that always fails class FailureCropper extends ImageCropper { @override CircleCropper get circleCropper => throw UnimplementedError(); @override RectCropper get rectCropper => throw UnimplementedError(); @override RectValidator get rectValidator => throw Exception(); } ================================================ FILE: test/widget/history_state_test.dart ================================================ import 'package:crop_your_image/crop_your_image.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:crop_your_image/src/widget/crop_editor_view_state.dart'; import 'package:crop_your_image/src/widget/history_state.dart'; void main() { final defaultViewportSize = Size(360, 200); final defaultImageSize = Size(800, 600); late HistoryState historyState; late List historyChangedCalls; setUp(() { historyChangedCalls = []; historyState = HistoryState( onHistoryChanged: (history) => historyChangedCalls.add(history), ); }); ReadyCropEditorViewState createViewState({double scale = 1.0}) { return ReadyCropEditorViewState.prepared( defaultImageSize, viewportSize: defaultViewportSize, scale: scale, aspectRatio: null, withCircleUi: false, ); } test('initial state has empty history', () { expect(historyState.history, isEmpty); expect(historyState.redoHistory, isEmpty); }); test('pushHistory adds state and clears redo history', () { final state1 = createViewState(scale: 1.0); final state2 = createViewState(scale: 1.5); historyState.pushHistory(state1); historyState.pushHistory(state2); expect(historyState.history.length, 2); expect(historyState.redoHistory, isEmpty); expect(historyChangedCalls, [ (undoCount: 1, redoCount: 0), (undoCount: 2, redoCount: 0), ]); }); test('requestUndo returns last state and moves it to redo history', () { final state1 = createViewState(scale: 1.0); final state2 = createViewState(scale: 1.5); historyState.pushHistory(state1); historyState.pushHistory(state2); final undoState = historyState.requestUndo(createViewState()); expect(undoState, state2); expect(historyState.history.length, 1); expect(historyState.redoHistory.length, 1); expect(historyChangedCalls, [ (undoCount: 1, redoCount: 0), (undoCount: 2, redoCount: 0), (undoCount: 1, redoCount: 1), ]); }); test('requestUndo returns null when history is empty', () { final undoState = historyState.requestUndo(createViewState(scale: 1.0)); expect(undoState, null); expect(historyState.history, isEmpty); expect(historyState.redoHistory, isEmpty); expect(historyChangedCalls, isEmpty); }); test('requestRedo returns last redo state and moves it to history', () { final state1 = createViewState(scale: 1.0); final state2 = createViewState(scale: 1.5); historyState.pushHistory(state1); historyState.pushHistory(state2); final current = createViewState(); historyState.requestUndo(current); // add current to redo history final redoState = historyState.requestRedo(current); expect(redoState, current); expect(historyState.history.length, 2); expect(historyState.redoHistory, isEmpty); expect(historyChangedCalls, [ (undoCount: 1, redoCount: 0), (undoCount: 2, redoCount: 0), (undoCount: 1, redoCount: 1), (undoCount: 2, redoCount: 0), ]); }); test('requestRedo returns null when redo history is empty', () { final redoState = historyState.requestRedo(createViewState()); expect(redoState, null); expect(historyState.history, isEmpty); expect(historyState.redoHistory, isEmpty); expect(historyChangedCalls, isEmpty); }); test('pushing new state clears redo history', () { final state1 = createViewState(scale: 1.0); final state2 = createViewState(scale: 1.5); final state3 = createViewState(scale: 2.0); historyState.pushHistory(state1); historyState.pushHistory(state2); historyState.requestUndo(createViewState()); // Move state2 to redo history historyState.pushHistory(state3); // Should clear redo history expect(historyState.history.length, 2); expect(historyState.redoHistory, isEmpty); expect(historyChangedCalls, [ (undoCount: 1, redoCount: 0), (undoCount: 2, redoCount: 0), (undoCount: 1, redoCount: 1), (undoCount: 2, redoCount: 0), ]); }); } ================================================ FILE: test/widget/rect_crop_area_clipper_test.dart ================================================ import 'package:crop_your_image/src/widget/rect_crop_area_clipper.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('shouldReclip is always true', () { final oldClipper = CropAreaClipper(Rect.fromLTWH(50, 50, 100, 100), 0); final clipper = CropAreaClipper(Rect.fromLTWH(50, 50, 100, 100), 0); expect(clipper.shouldReclip(oldClipper), true); }); group('when viewport is 200 x 200', () { final viewportSize = 200.0; testWidgets( 'CropAreaClipper clips center with 100x100 size of rectangular shape' 'if passing Rect.fromLTWH(50, 50, 100, 100)', (WidgetTester tester) async { await tester.pumpWidget( _ViewportWidget( size: viewportSize, targetWidget: RepaintBoundary( child: ClipPath( clipper: CropAreaClipper(Rect.fromLTWH(50, 50, 100, 100), 0), child: ColoredBox( color: Colors.grey, ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile( 'rect_crop_area_clipper.viewportSize200x200.crop_center.png', ), ); }, ); testWidgets( 'CropAreaClipper clips center with 100x100 size of rectangular shape with rounded corners' 'if passing Rect.fromLTWH(50, 50, 100, 100) and radius: 20', (WidgetTester tester) async { await tester.pumpWidget( _ViewportWidget( size: viewportSize, targetWidget: RepaintBoundary( child: ClipPath( clipper: CropAreaClipper(Rect.fromLTWH(50, 50, 100, 100), 20), child: ColoredBox( color: Colors.grey, ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile( 'rect_crop_area_clipper.viewportSize200x200.crop_center_radius20.png', ), ); }, ); }); } class _ViewportWidget extends StatelessWidget { const _ViewportWidget({ required this.size, required this.targetWidget, }); final double size; final RepaintBoundary targetWidget; @override Widget build(BuildContext context) { return Center( child: SizedBox( width: size, height: size, child: targetWidget, ), ); } }